blob: ed4bbfd6d35ad9b43a2cde74a28ec4bfdb1bab5a [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
108enum py_ssl_error {
109 /* these mirror ssl.h */
110 PY_SSL_ERROR_NONE,
111 PY_SSL_ERROR_SSL,
112 PY_SSL_ERROR_WANT_READ,
113 PY_SSL_ERROR_WANT_WRITE,
114 PY_SSL_ERROR_WANT_X509_LOOKUP,
115 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
116 PY_SSL_ERROR_ZERO_RETURN,
117 PY_SSL_ERROR_WANT_CONNECT,
118 /* start of non ssl.h errorcodes */
119 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
120 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
121 PY_SSL_ERROR_INVALID_ERROR_CODE
122};
123
124enum py_ssl_server_or_client {
125 PY_SSL_CLIENT,
126 PY_SSL_SERVER
127};
128
129enum py_ssl_cert_requirements {
130 PY_SSL_CERT_NONE,
131 PY_SSL_CERT_OPTIONAL,
132 PY_SSL_CERT_REQUIRED
133};
134
135enum py_ssl_version {
136 PY_SSL_VERSION_SSL2,
137 PY_SSL_VERSION_SSL3=1,
138 PY_SSL_VERSION_SSL23,
139#if HAVE_TLSv1_2
140 PY_SSL_VERSION_TLS1,
141 PY_SSL_VERSION_TLS1_1,
142 PY_SSL_VERSION_TLS1_2
143#else
144 PY_SSL_VERSION_TLS1
145#endif
146};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147
Bill Janssen98d19da2007-09-10 21:51:02 +0000148#ifdef WITH_THREAD
149
150/* serves as a flag to see whether we've initialized the SSL thread support. */
151/* 0 means no, greater than 0 means yes */
152
153static unsigned int _ssl_locks_count = 0;
154
155#endif /* def WITH_THREAD */
156
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157/* SSL socket object */
158
159#define X509_NAME_MAXLEN 256
160
161/* RAND_* APIs got added to OpenSSL in 0.9.5 */
162#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
163# define HAVE_OPENSSL_RAND 1
164#else
165# undef HAVE_OPENSSL_RAND
166#endif
167
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500168/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
169 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
170 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
171#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
172# define HAVE_SSL_CTX_CLEAR_OPTIONS
173#else
174# undef HAVE_SSL_CTX_CLEAR_OPTIONS
175#endif
176
177/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
178 * older SSL, but let's be safe */
179#define PySSL_CB_MAXLEN 128
180
181/* SSL_get_finished got added to OpenSSL in 0.9.5 */
182#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
183# define HAVE_OPENSSL_FINISHED 1
184#else
185# define HAVE_OPENSSL_FINISHED 0
186#endif
187
188/* ECDH support got added to OpenSSL in 0.9.8 */
189#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
190# define OPENSSL_NO_ECDH
191#endif
192
193/* compression support got added to OpenSSL in 0.9.8 */
194#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
195# define OPENSSL_NO_COMP
196#endif
197
198/* X509_VERIFY_PARAM got added to OpenSSL in 0.9.8 */
199#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
200# define HAVE_OPENSSL_VERIFY_PARAM
201#endif
202
203
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000204typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000205 PyObject_HEAD
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500206 SSL_CTX *ctx;
207#ifdef OPENSSL_NPN_NEGOTIATED
208 char *npn_protocols;
209 int npn_protocols_len;
210#endif
211#ifndef OPENSSL_NO_TLSEXT
212 PyObject *set_hostname;
213#endif
214 int check_hostname;
215} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000216
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500217typedef struct {
218 PyObject_HEAD
219 PySocketSockObject *Socket;
220 PyObject *ssl_sock;
221 SSL *ssl;
222 PySSLContext *ctx; /* weakref to SSL context */
223 X509 *peer_cert;
224 char shutdown_seen_zero;
225 char handshake_done;
226 enum py_ssl_server_or_client socket_type;
227} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000228
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500229static PyTypeObject PySSLContext_Type;
230static PyTypeObject PySSLSocket_Type;
231
232static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
233static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000234static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000235 int writing);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500236static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
237static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500239#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
240#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000241
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000243 SOCKET_IS_NONBLOCKING,
244 SOCKET_IS_BLOCKING,
245 SOCKET_HAS_TIMED_OUT,
246 SOCKET_HAS_BEEN_CLOSED,
247 SOCKET_TOO_LARGE_FOR_SELECT,
248 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000249} timeout_state;
250
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000251/* Wrap error strings with filename and line # */
252#define STRINGIFY1(x) #x
253#define STRINGIFY2(x) STRINGIFY1(x)
254#define ERRSTR1(x,y,z) (x ":" y ": " z)
255#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
256
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500257
258/*
259 * SSL errors.
260 */
261
262PyDoc_STRVAR(SSLError_doc,
263"An error occurred in the SSL implementation.");
264
265PyDoc_STRVAR(SSLZeroReturnError_doc,
266"SSL/TLS session closed cleanly.");
267
268PyDoc_STRVAR(SSLWantReadError_doc,
269"Non-blocking SSL socket needs to read more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLWantWriteError_doc,
273"Non-blocking SSL socket needs to write more data\n"
274"before the requested operation can be completed.");
275
276PyDoc_STRVAR(SSLSyscallError_doc,
277"System error when attempting SSL operation.");
278
279PyDoc_STRVAR(SSLEOFError_doc,
280"SSL/TLS connection terminated abruptly.");
281
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000282
283static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500284SSLError_str(PyEnvironmentErrorObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000285{
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500286 if (self->strerror != NULL) {
287 Py_INCREF(self->strerror);
288 return self->strerror;
289 }
290 else
291 return PyObject_Str(self->args);
292}
293
294static void
295fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
296 int lineno, unsigned long errcode)
297{
298 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
299 PyObject *init_value, *msg, *key;
300
301 if (errcode != 0) {
302 int lib, reason;
303
304 lib = ERR_GET_LIB(errcode);
305 reason = ERR_GET_REASON(errcode);
306 key = Py_BuildValue("ii", lib, reason);
307 if (key == NULL)
308 goto fail;
309 reason_obj = PyDict_GetItem(err_codes_to_names, key);
310 Py_DECREF(key);
311 if (reason_obj == NULL) {
312 /* XXX if reason < 100, it might reflect a library number (!!) */
313 PyErr_Clear();
314 }
315 key = PyLong_FromLong(lib);
316 if (key == NULL)
317 goto fail;
318 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
319 Py_DECREF(key);
320 if (lib_obj == NULL) {
321 PyErr_Clear();
322 }
323 if (errstr == NULL)
324 errstr = ERR_reason_error_string(errcode);
325 }
326 if (errstr == NULL)
327 errstr = "unknown error";
328
329 if (reason_obj && lib_obj)
330 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
331 lib_obj, reason_obj, errstr, lineno);
332 else if (lib_obj)
333 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
334 lib_obj, errstr, lineno);
335 else
336 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
337 if (msg == NULL)
338 goto fail;
339
340 init_value = Py_BuildValue("iN", ssl_errno, msg);
341 if (init_value == NULL)
342 goto fail;
343
344 err_value = PyObject_CallObject(type, init_value);
345 Py_DECREF(init_value);
346 if (err_value == NULL)
347 goto fail;
348
349 if (reason_obj == NULL)
350 reason_obj = Py_None;
351 if (PyObject_SetAttrString(err_value, "reason", reason_obj))
352 goto fail;
353 if (lib_obj == NULL)
354 lib_obj = Py_None;
355 if (PyObject_SetAttrString(err_value, "library", lib_obj))
356 goto fail;
357 PyErr_SetObject(type, err_value);
358fail:
359 Py_XDECREF(err_value);
360}
361
362static PyObject *
363PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
364{
365 PyObject *type = PySSLErrorObject;
366 char *errstr = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000367 int err;
368 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500369 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000370
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000371 assert(ret <= 0);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500372 e = ERR_peek_last_error();
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000373
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000374 if (obj->ssl != NULL) {
375 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000376
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000377 switch (err) {
378 case SSL_ERROR_ZERO_RETURN:
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500379 errstr = "TLS/SSL connection has been closed (EOF)";
380 type = PySSLZeroReturnErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000381 p = PY_SSL_ERROR_ZERO_RETURN;
382 break;
383 case SSL_ERROR_WANT_READ:
384 errstr = "The operation did not complete (read)";
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500385 type = PySSLWantReadErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000386 p = PY_SSL_ERROR_WANT_READ;
387 break;
388 case SSL_ERROR_WANT_WRITE:
389 p = PY_SSL_ERROR_WANT_WRITE;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500390 type = PySSLWantWriteErrorObject;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000391 errstr = "The operation did not complete (write)";
392 break;
393 case SSL_ERROR_WANT_X509_LOOKUP:
394 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000395 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000396 break;
397 case SSL_ERROR_WANT_CONNECT:
398 p = PY_SSL_ERROR_WANT_CONNECT;
399 errstr = "The operation did not complete (connect)";
400 break;
401 case SSL_ERROR_SYSCALL:
402 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000403 if (e == 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500404 PySocketSockObject *s = obj->Socket;
405 if (ret == 0) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000406 p = PY_SSL_ERROR_EOF;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500407 type = PySSLEOFErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000408 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000409 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000410 /* underlying BIO reported an I/O error */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500411 Py_INCREF(s);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000412 ERR_clear_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500413 s->errorhandler();
414 Py_DECREF(s);
415 return NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000416 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000417 p = PY_SSL_ERROR_SYSCALL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500418 type = PySSLSyscallErrorObject;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000419 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000420 }
421 } else {
422 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000423 }
424 break;
425 }
426 case SSL_ERROR_SSL:
427 {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000428 p = PY_SSL_ERROR_SSL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500429 if (e == 0)
430 /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000431 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000432 break;
433 }
434 default:
435 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
436 errstr = "Invalid error code";
437 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000438 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500439 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000440 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000441 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000442}
443
Bill Janssen98d19da2007-09-10 21:51:02 +0000444static PyObject *
445_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
446
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500447 if (errstr == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000448 errcode = ERR_peek_last_error();
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500449 else
450 errcode = 0;
451 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000452 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000453 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000454}
455
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500456/*
457 * SSL objects
458 */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000459
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500460static PySSLSocket *
461newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
462 enum py_ssl_server_or_client socket_type,
463 char *server_hostname, PyObject *ssl_sock)
464{
465 PySSLSocket *self;
466 SSL_CTX *ctx = sslctx->ctx;
467 long mode;
468
469 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000470 if (self == NULL)
471 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500472
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000473 self->peer_cert = NULL;
474 self->ssl = NULL;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000475 self->Socket = NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500476 self->ssl_sock = NULL;
477 self->ctx = sslctx;
Antoine Pitrou87c99a02013-09-29 19:52:45 +0200478 self->shutdown_seen_zero = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500479 self->handshake_done = 0;
480 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000482 /* Make sure the SSL error state is initialized */
483 (void) ERR_get_state();
484 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000485
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000486 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500487 self->ssl = SSL_new(ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000488 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500489 SSL_set_app_data(self->ssl,self);
490 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
491 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou92719c52010-04-09 20:38:39 +0000492#ifdef SSL_MODE_AUTO_RETRY
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500493 mode |= SSL_MODE_AUTO_RETRY;
494#endif
495 SSL_set_mode(self->ssl, mode);
496
497#if HAVE_SNI
498 if (server_hostname != NULL)
499 SSL_set_tlsext_host_name(self->ssl, server_hostname);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000500#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000501
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000502 /* If the socket is in non-blocking mode or timeout mode, set the BIO
503 * to non-blocking mode (blocking is the default)
504 */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500505 if (sock->sock_timeout >= 0.0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000506 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
507 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
508 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000509
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000510 PySSL_BEGIN_ALLOW_THREADS
511 if (socket_type == PY_SSL_CLIENT)
512 SSL_set_connect_state(self->ssl);
513 else
514 SSL_set_accept_state(self->ssl);
515 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000516
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500517 self->socket_type = socket_type;
518 self->Socket = sock;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000519 Py_INCREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500520 self->ssl_sock = PyWeakref_NewRef(ssl_sock, NULL);
521 if (self->ssl_sock == NULL) {
522 Py_DECREF(self);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000523 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500524 }
525 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000526}
527
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528
529/* SSL object methods */
530
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500531static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +0000532{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000533 int ret;
534 int err;
535 int sockstate, nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500536 PySocketSockObject *sock = self->Socket;
537
538 Py_INCREF(sock);
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000539
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000540 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500541 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000542 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
543 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000544
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000545 /* Actually negotiate SSL connection */
546 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
547 do {
548 PySSL_BEGIN_ALLOW_THREADS
549 ret = SSL_do_handshake(self->ssl);
550 err = SSL_get_error(self->ssl, ret);
551 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500552 if (PyErr_CheckSignals())
553 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000554 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500555 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000556 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500557 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000558 } else {
559 sockstate = SOCKET_OPERATION_OK;
560 }
561 if (sockstate == SOCKET_HAS_TIMED_OUT) {
562 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000563 ERRSTR("The handshake operation timed out"));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500564 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000565 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
566 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000567 ERRSTR("Underlying socket has been closed."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500568 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000569 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
570 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000571 ERRSTR("Underlying socket too large for select()."));
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500572 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000573 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
574 break;
575 }
576 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500577 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000578 if (ret < 1)
579 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000580
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000581 if (self->peer_cert)
582 X509_free (self->peer_cert);
583 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500584 self->peer_cert = SSL_get_peer_certificate(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000585 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500586 self->handshake_done = 1;
Bill Janssen934b16d2008-06-28 22:19:33 +0000587
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000588 Py_INCREF(Py_None);
589 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000590
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500591error:
592 Py_DECREF(sock);
593 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000594}
595
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000596static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000597_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 char namebuf[X509_NAME_MAXLEN];
600 int buflen;
601 PyObject *name_obj;
602 PyObject *value_obj;
603 PyObject *attr;
604 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000605
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000606 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
607 if (buflen < 0) {
608 _setSSLError(NULL, 0, __FILE__, __LINE__);
609 goto fail;
610 }
611 name_obj = PyString_FromStringAndSize(namebuf, buflen);
612 if (name_obj == NULL)
613 goto fail;
614
615 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
616 if (buflen < 0) {
617 _setSSLError(NULL, 0, __FILE__, __LINE__);
618 Py_DECREF(name_obj);
619 goto fail;
620 }
621 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000622 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000623 OPENSSL_free(valuebuf);
624 if (value_obj == NULL) {
625 Py_DECREF(name_obj);
626 goto fail;
627 }
628 attr = PyTuple_New(2);
629 if (attr == NULL) {
630 Py_DECREF(name_obj);
631 Py_DECREF(value_obj);
632 goto fail;
633 }
634 PyTuple_SET_ITEM(attr, 0, name_obj);
635 PyTuple_SET_ITEM(attr, 1, value_obj);
636 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000637
Bill Janssen98d19da2007-09-10 21:51:02 +0000638 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000639 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000640}
641
642static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000643_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000644{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000645 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
646 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
647 PyObject *rdnt;
648 PyObject *attr = NULL; /* tuple to hold an attribute */
649 int entry_count = X509_NAME_entry_count(xname);
650 X509_NAME_ENTRY *entry;
651 ASN1_OBJECT *name;
652 ASN1_STRING *value;
653 int index_counter;
654 int rdn_level = -1;
655 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000656
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000657 dn = PyList_New(0);
658 if (dn == NULL)
659 return NULL;
660 /* now create another tuple to hold the top-level RDN */
661 rdn = PyList_New(0);
662 if (rdn == NULL)
663 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000664
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000665 for (index_counter = 0;
666 index_counter < entry_count;
667 index_counter++)
668 {
669 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000670
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000671 /* check to see if we've gotten to a new RDN */
672 if (rdn_level >= 0) {
673 if (rdn_level != entry->set) {
674 /* yes, new RDN */
675 /* add old RDN to DN */
676 rdnt = PyList_AsTuple(rdn);
677 Py_DECREF(rdn);
678 if (rdnt == NULL)
679 goto fail0;
680 retcode = PyList_Append(dn, rdnt);
681 Py_DECREF(rdnt);
682 if (retcode < 0)
683 goto fail0;
684 /* create new RDN */
685 rdn = PyList_New(0);
686 if (rdn == NULL)
687 goto fail0;
688 }
689 }
690 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000691
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000692 /* now add this attribute to the current RDN */
693 name = X509_NAME_ENTRY_get_object(entry);
694 value = X509_NAME_ENTRY_get_data(entry);
695 attr = _create_tuple_for_attribute(name, value);
696 /*
697 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
698 entry->set,
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500699 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
700 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000701 */
702 if (attr == NULL)
703 goto fail1;
704 retcode = PyList_Append(rdn, attr);
705 Py_DECREF(attr);
706 if (retcode < 0)
707 goto fail1;
708 }
709 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100710 if (rdn != NULL) {
711 if (PyList_GET_SIZE(rdn) > 0) {
712 rdnt = PyList_AsTuple(rdn);
713 Py_DECREF(rdn);
714 if (rdnt == NULL)
715 goto fail0;
716 retcode = PyList_Append(dn, rdnt);
717 Py_DECREF(rdnt);
718 if (retcode < 0)
719 goto fail0;
720 }
721 else {
722 Py_DECREF(rdn);
723 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000724 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000725
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000726 /* convert list to tuple */
727 rdnt = PyList_AsTuple(dn);
728 Py_DECREF(dn);
729 if (rdnt == NULL)
730 return NULL;
731 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000732
733 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000734 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000735
736 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000737 Py_XDECREF(dn);
738 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000739}
740
741static PyObject *
742_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000743
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000744 /* this code follows the procedure outlined in
745 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
746 function to extract the STACK_OF(GENERAL_NAME),
747 then iterates through the stack to add the
748 names. */
749
750 int i, j;
751 PyObject *peer_alt_names = Py_None;
Christian Heimesed9884b2013-09-05 16:04:35 +0200752 PyObject *v = NULL, *t;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000753 X509_EXTENSION *ext = NULL;
754 GENERAL_NAMES *names = NULL;
755 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000756 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000757 BIO *biobuf = NULL;
758 char buf[2048];
759 char *vptr;
760 int len;
761 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000762#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000763 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000764#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000765 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000766#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000767
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000768 if (certificate == NULL)
769 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000770
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000771 /* get a memory buffer */
772 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000773
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200774 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000775 while ((i = X509_get_ext_by_NID(
776 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000777
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000778 if (peer_alt_names == Py_None) {
779 peer_alt_names = PyList_New(0);
780 if (peer_alt_names == NULL)
781 goto fail;
782 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000783
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000784 /* now decode the altName */
785 ext = X509_get_ext(certificate, i);
786 if(!(method = X509V3_EXT_get(ext))) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500787 PyErr_SetString
788 (PySSLErrorObject,
789 ERRSTR("No method for internalizing subjectAltName!"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000790 goto fail;
791 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000792
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000793 p = ext->value->data;
794 if (method->it)
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500795 names = (GENERAL_NAMES*)
796 (ASN1_item_d2i(NULL,
797 &p,
798 ext->value->length,
799 ASN1_ITEM_ptr(method->it)));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000800 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500801 names = (GENERAL_NAMES*)
802 (method->d2i(NULL,
803 &p,
804 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000805
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000806 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000807 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200808 int gntype;
809 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000810
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000811 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200812 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200813 switch (gntype) {
814 case GEN_DIRNAME:
815 /* we special-case DirName as a tuple of
816 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000817
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000818 t = PyTuple_New(2);
819 if (t == NULL) {
820 goto fail;
821 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000822
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000823 v = PyString_FromString("DirName");
824 if (v == NULL) {
825 Py_DECREF(t);
826 goto fail;
827 }
828 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000829
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000830 v = _create_tuple_for_X509_NAME (name->d.dirn);
831 if (v == NULL) {
832 Py_DECREF(t);
833 goto fail;
834 }
835 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200836 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000837
Christian Heimes88b174c2013-08-17 00:54:47 +0200838 case GEN_EMAIL:
839 case GEN_DNS:
840 case GEN_URI:
841 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
842 correctly, CVE-2013-4238 */
843 t = PyTuple_New(2);
844 if (t == NULL)
845 goto fail;
846 switch (gntype) {
847 case GEN_EMAIL:
848 v = PyString_FromString("email");
849 as = name->d.rfc822Name;
850 break;
851 case GEN_DNS:
852 v = PyString_FromString("DNS");
853 as = name->d.dNSName;
854 break;
855 case GEN_URI:
856 v = PyString_FromString("URI");
857 as = name->d.uniformResourceIdentifier;
858 break;
859 }
860 if (v == NULL) {
861 Py_DECREF(t);
862 goto fail;
863 }
864 PyTuple_SET_ITEM(t, 0, v);
865 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
866 ASN1_STRING_length(as));
867 if (v == NULL) {
868 Py_DECREF(t);
869 goto fail;
870 }
871 PyTuple_SET_ITEM(t, 1, v);
872 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000873
Christian Heimes88b174c2013-08-17 00:54:47 +0200874 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000875 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200876 switch (gntype) {
877 /* check for new general name type */
878 case GEN_OTHERNAME:
879 case GEN_X400:
880 case GEN_EDIPARTY:
881 case GEN_IPADD:
882 case GEN_RID:
883 break;
884 default:
885 if (PyErr_Warn(PyExc_RuntimeWarning,
886 "Unknown general name type") == -1) {
887 goto fail;
888 }
889 break;
890 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000891 (void) BIO_reset(biobuf);
892 GENERAL_NAME_print(biobuf, name);
893 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
894 if (len < 0) {
895 _setSSLError(NULL, 0, __FILE__, __LINE__);
896 goto fail;
897 }
898 vptr = strchr(buf, ':');
899 if (vptr == NULL)
900 goto fail;
901 t = PyTuple_New(2);
902 if (t == NULL)
903 goto fail;
904 v = PyString_FromStringAndSize(buf, (vptr - buf));
905 if (v == NULL) {
906 Py_DECREF(t);
907 goto fail;
908 }
909 PyTuple_SET_ITEM(t, 0, v);
910 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
911 if (v == NULL) {
912 Py_DECREF(t);
913 goto fail;
914 }
915 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200916 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000917 }
918
919 /* and add that rendering to the list */
920
921 if (PyList_Append(peer_alt_names, t) < 0) {
922 Py_DECREF(t);
923 goto fail;
924 }
925 Py_DECREF(t);
926 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +0100927 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000928 }
929 BIO_free(biobuf);
930 if (peer_alt_names != Py_None) {
931 v = PyList_AsTuple(peer_alt_names);
932 Py_DECREF(peer_alt_names);
933 return v;
934 } else {
935 return peer_alt_names;
936 }
937
Bill Janssen98d19da2007-09-10 21:51:02 +0000938
939 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000940 if (biobuf != NULL)
941 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000942
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000943 if (peer_alt_names != Py_None) {
944 Py_XDECREF(peer_alt_names);
945 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000946
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000947 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000948}
949
950static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -0500951_get_aia_uri(X509 *certificate, int nid) {
952 PyObject *lst = NULL, *ostr = NULL;
953 int i, result;
954 AUTHORITY_INFO_ACCESS *info;
955
956 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
957 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
958 return Py_None;
959 }
960
961 if ((lst = PyList_New(0)) == NULL) {
962 goto fail;
963 }
964
965 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
966 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
967 ASN1_IA5STRING *uri;
968
969 if ((OBJ_obj2nid(ad->method) != nid) ||
970 (ad->location->type != GEN_URI)) {
971 continue;
972 }
973 uri = ad->location->d.uniformResourceIdentifier;
974 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
975 uri->length);
976 if (ostr == NULL) {
977 goto fail;
978 }
979 result = PyList_Append(lst, ostr);
980 Py_DECREF(ostr);
981 if (result < 0) {
982 goto fail;
983 }
984 }
985 AUTHORITY_INFO_ACCESS_free(info);
986
987 /* convert to tuple or None */
988 if (PyList_Size(lst) == 0) {
989 Py_DECREF(lst);
990 return Py_None;
991 } else {
992 PyObject *tup;
993 tup = PyList_AsTuple(lst);
994 Py_DECREF(lst);
995 return tup;
996 }
997
998 fail:
999 AUTHORITY_INFO_ACCESS_free(info);
1000 Py_XDECREF(lst);
1001 return NULL;
1002}
1003
1004static PyObject *
1005_get_crl_dp(X509 *certificate) {
1006 STACK_OF(DIST_POINT) *dps;
1007 int i, j, result;
1008 PyObject *lst;
1009
1010#if OPENSSL_VERSION_NUMBER < 0x10001000L
1011 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1012 NULL, NULL);
1013#else
1014 /* Calls x509v3_cache_extensions and sets up crldp */
1015 X509_check_ca(certificate);
1016 dps = certificate->crldp;
1017#endif
1018
1019 if (dps == NULL) {
1020 return Py_None;
1021 }
1022
1023 if ((lst = PyList_New(0)) == NULL) {
1024 return NULL;
1025 }
1026
1027 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1028 DIST_POINT *dp;
1029 STACK_OF(GENERAL_NAME) *gns;
1030
1031 dp = sk_DIST_POINT_value(dps, i);
1032 gns = dp->distpoint->name.fullname;
1033
1034 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1035 GENERAL_NAME *gn;
1036 ASN1_IA5STRING *uri;
1037 PyObject *ouri;
1038
1039 gn = sk_GENERAL_NAME_value(gns, j);
1040 if (gn->type != GEN_URI) {
1041 continue;
1042 }
1043 uri = gn->d.uniformResourceIdentifier;
1044 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1045 uri->length);
1046 if (ouri == NULL) {
1047 Py_DECREF(lst);
1048 return NULL;
1049 }
1050 result = PyList_Append(lst, ouri);
1051 Py_DECREF(ouri);
1052 if (result < 0) {
1053 Py_DECREF(lst);
1054 return NULL;
1055 }
1056 }
1057 }
1058 /* convert to tuple or None */
1059 if (PyList_Size(lst) == 0) {
1060 Py_DECREF(lst);
1061 return Py_None;
1062 } else {
1063 PyObject *tup;
1064 tup = PyList_AsTuple(lst);
1065 Py_DECREF(lst);
1066 return tup;
1067 }
1068}
1069
1070static PyObject *
1071_decode_certificate(X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001072
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001073 PyObject *retval = NULL;
1074 BIO *biobuf = NULL;
1075 PyObject *peer;
1076 PyObject *peer_alt_names = NULL;
1077 PyObject *issuer;
1078 PyObject *version;
1079 PyObject *sn_obj;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001080 PyObject *obj;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001081 ASN1_INTEGER *serialNumber;
1082 char buf[2048];
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001083 int len, result;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001084 ASN1_TIME *notBefore, *notAfter;
1085 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001086
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001087 retval = PyDict_New();
1088 if (retval == NULL)
1089 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001090
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001091 peer = _create_tuple_for_X509_NAME(
1092 X509_get_subject_name(certificate));
1093 if (peer == NULL)
1094 goto fail0;
1095 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1096 Py_DECREF(peer);
1097 goto fail0;
1098 }
1099 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001100
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001101 issuer = _create_tuple_for_X509_NAME(
1102 X509_get_issuer_name(certificate));
1103 if (issuer == NULL)
1104 goto fail0;
1105 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001106 Py_DECREF(issuer);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001107 goto fail0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001108 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001109 Py_DECREF(issuer);
1110
1111 version = PyLong_FromLong(X509_get_version(certificate) + 1);
1112 if (version == NULL)
1113 goto fail0;
1114 if (PyDict_SetItemString(retval, "version", version) < 0) {
1115 Py_DECREF(version);
1116 goto fail0;
1117 }
1118 Py_DECREF(version);
Bill Janssen98d19da2007-09-10 21:51:02 +00001119
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001120 /* get a memory buffer */
1121 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001122
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001123 (void) BIO_reset(biobuf);
1124 serialNumber = X509_get_serialNumber(certificate);
1125 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1126 i2a_ASN1_INTEGER(biobuf, serialNumber);
1127 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1128 if (len < 0) {
1129 _setSSLError(NULL, 0, __FILE__, __LINE__);
1130 goto fail1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001131 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001132 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1133 if (sn_obj == NULL)
1134 goto fail1;
1135 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1136 Py_DECREF(sn_obj);
1137 goto fail1;
1138 }
1139 Py_DECREF(sn_obj);
1140
1141 (void) BIO_reset(biobuf);
1142 notBefore = X509_get_notBefore(certificate);
1143 ASN1_TIME_print(biobuf, notBefore);
1144 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1145 if (len < 0) {
1146 _setSSLError(NULL, 0, __FILE__, __LINE__);
1147 goto fail1;
1148 }
1149 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1150 if (pnotBefore == NULL)
1151 goto fail1;
1152 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1153 Py_DECREF(pnotBefore);
1154 goto fail1;
1155 }
1156 Py_DECREF(pnotBefore);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001157
1158 (void) BIO_reset(biobuf);
1159 notAfter = X509_get_notAfter(certificate);
1160 ASN1_TIME_print(biobuf, notAfter);
1161 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1162 if (len < 0) {
1163 _setSSLError(NULL, 0, __FILE__, __LINE__);
1164 goto fail1;
1165 }
1166 pnotAfter = PyString_FromStringAndSize(buf, len);
1167 if (pnotAfter == NULL)
1168 goto fail1;
1169 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1170 Py_DECREF(pnotAfter);
1171 goto fail1;
1172 }
1173 Py_DECREF(pnotAfter);
1174
1175 /* Now look for subjectAltName */
1176
1177 peer_alt_names = _get_peer_alt_names(certificate);
1178 if (peer_alt_names == NULL)
1179 goto fail1;
1180 else if (peer_alt_names != Py_None) {
1181 if (PyDict_SetItemString(retval, "subjectAltName",
1182 peer_alt_names) < 0) {
1183 Py_DECREF(peer_alt_names);
1184 goto fail1;
1185 }
1186 Py_DECREF(peer_alt_names);
1187 }
1188
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001189 /* Authority Information Access: OCSP URIs */
1190 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1191 if (obj == NULL) {
1192 goto fail1;
1193 } else if (obj != Py_None) {
1194 result = PyDict_SetItemString(retval, "OCSP", obj);
1195 Py_DECREF(obj);
1196 if (result < 0) {
1197 goto fail1;
1198 }
1199 }
1200
1201 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1202 if (obj == NULL) {
1203 goto fail1;
1204 } else if (obj != Py_None) {
1205 result = PyDict_SetItemString(retval, "caIssuers", obj);
1206 Py_DECREF(obj);
1207 if (result < 0) {
1208 goto fail1;
1209 }
1210 }
1211
1212 /* CDP (CRL distribution points) */
1213 obj = _get_crl_dp(certificate);
1214 if (obj == NULL) {
1215 goto fail1;
1216 } else if (obj != Py_None) {
1217 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1218 Py_DECREF(obj);
1219 if (result < 0) {
1220 goto fail1;
1221 }
1222 }
1223
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001224 BIO_free(biobuf);
1225 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001226
1227 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001228 if (biobuf != NULL)
1229 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001230 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001231 Py_XDECREF(retval);
1232 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001233}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001234
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001235static PyObject *
1236_certificate_to_der(X509 *certificate)
1237{
1238 unsigned char *bytes_buf = NULL;
1239 int len;
1240 PyObject *retval;
1241
1242 bytes_buf = NULL;
1243 len = i2d_X509(certificate, &bytes_buf);
1244 if (len < 0) {
1245 _setSSLError(NULL, 0, __FILE__, __LINE__);
1246 return NULL;
1247 }
1248 /* this is actually an immutable bytes sequence */
1249 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1250 OPENSSL_free(bytes_buf);
1251 return retval;
1252}
Bill Janssen98d19da2007-09-10 21:51:02 +00001253
1254static PyObject *
1255PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1256
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001257 PyObject *retval = NULL;
1258 char *filename = NULL;
1259 X509 *x=NULL;
1260 BIO *cert;
Bill Janssen98d19da2007-09-10 21:51:02 +00001261
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001262 if (!PyArg_ParseTuple(args, "s:test_decode_certificate", &filename))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001263 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001264
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001265 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001266 PyErr_SetString(PySSLErrorObject,
1267 "Can't malloc memory to read file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001268 goto fail0;
1269 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001270
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001271 if (BIO_read_filename(cert,filename) <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001272 PyErr_SetString(PySSLErrorObject,
1273 "Can't open file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001274 goto fail0;
1275 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001276
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001277 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1278 if (x == NULL) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001279 PyErr_SetString(PySSLErrorObject,
1280 "Error decoding PEM-encoded file");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001281 goto fail0;
1282 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001283
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001284 retval = _decode_certificate(x);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001285 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001286
1287 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001288
1289 if (cert != NULL) BIO_free(cert);
1290 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001291}
1292
1293
1294static PyObject *
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001295PySSL_peercert(PySSLSocket *self, PyObject *args)
Bill Janssen98d19da2007-09-10 21:51:02 +00001296{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001297 int verification;
1298 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001299 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001300
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001301 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1302 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001303
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001304 if (!self->handshake_done) {
1305 PyErr_SetString(PyExc_ValueError,
1306 "handshake not done yet");
1307 return NULL;
1308 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001309 if (!self->peer_cert)
1310 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001311
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001312 b = PyObject_IsTrue(binary_mode);
1313 if (b < 0)
1314 return NULL;
1315 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001316 /* return cert in DER-encoded format */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001317 return _certificate_to_der(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001318 } else {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001319 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001320 if ((verification & SSL_VERIFY_PEER) == 0)
1321 return PyDict_New();
1322 else
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001323 return _decode_certificate(self->peer_cert);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001324 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001325}
1326
1327PyDoc_STRVAR(PySSL_peercert_doc,
1328"peer_certificate([der=False]) -> certificate\n\
1329\n\
1330Returns the certificate for the peer. If no certificate was provided,\n\
1331returns None. If a certificate was provided, but not validated, returns\n\
1332an empty dictionary. Otherwise returns a dict containing information\n\
1333about the peer certificate.\n\
1334\n\
1335If the optional argument is True, returns a DER-encoded copy of the\n\
1336peer certificate, or None if no certificate was provided. This will\n\
1337return the certificate even if it wasn't validated.");
1338
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001339static PyObject *PySSL_cipher (PySSLSocket *self) {
Bill Janssen98d19da2007-09-10 21:51:02 +00001340
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001341 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001342 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001343 char *cipher_name;
1344 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001345
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001346 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001347 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001348 current = SSL_get_current_cipher(self->ssl);
1349 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001350 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001351
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001352 retval = PyTuple_New(3);
1353 if (retval == NULL)
1354 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001355
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001356 cipher_name = (char *) SSL_CIPHER_get_name(current);
1357 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001358 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001359 PyTuple_SET_ITEM(retval, 0, Py_None);
1360 } else {
1361 v = PyString_FromString(cipher_name);
1362 if (v == NULL)
1363 goto fail0;
1364 PyTuple_SET_ITEM(retval, 0, v);
1365 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001366 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001367 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001368 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001369 PyTuple_SET_ITEM(retval, 1, Py_None);
1370 } else {
1371 v = PyString_FromString(cipher_protocol);
1372 if (v == NULL)
1373 goto fail0;
1374 PyTuple_SET_ITEM(retval, 1, v);
1375 }
1376 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1377 if (v == NULL)
1378 goto fail0;
1379 PyTuple_SET_ITEM(retval, 2, v);
1380 return retval;
1381
Bill Janssen98d19da2007-09-10 21:51:02 +00001382 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001383 Py_DECREF(retval);
1384 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001385}
1386
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001387#ifdef OPENSSL_NPN_NEGOTIATED
1388static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1389 const unsigned char *out;
1390 unsigned int outlen;
1391
1392 SSL_get0_next_proto_negotiated(self->ssl,
1393 &out, &outlen);
1394
1395 if (out == NULL)
1396 Py_RETURN_NONE;
1397 return PyUnicode_FromStringAndSize((char *) out, outlen);
1398}
1399#endif
1400
1401static PyObject *PySSL_compression(PySSLSocket *self) {
1402#ifdef OPENSSL_NO_COMP
1403 Py_RETURN_NONE;
1404#else
1405 const COMP_METHOD *comp_method;
1406 const char *short_name;
1407
1408 if (self->ssl == NULL)
1409 Py_RETURN_NONE;
1410 comp_method = SSL_get_current_compression(self->ssl);
1411 if (comp_method == NULL || comp_method->type == NID_undef)
1412 Py_RETURN_NONE;
1413 short_name = OBJ_nid2sn(comp_method->type);
1414 if (short_name == NULL)
1415 Py_RETURN_NONE;
1416 return PyBytes_FromString(short_name);
1417#endif
1418}
1419
1420static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1421 Py_INCREF(self->ctx);
1422 return self->ctx;
1423}
1424
1425static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1426 void *closure) {
1427
1428 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1429#if !HAVE_SNI
1430 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1431 "context is not supported by your OpenSSL library");
1432 return -1;
1433#else
1434 Py_INCREF(value);
1435 Py_DECREF(self->ctx);
1436 self->ctx = (PySSLContext *) value;
1437 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1438#endif
1439 } else {
1440 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1441 return -1;
1442 }
1443
1444 return 0;
1445}
1446
1447PyDoc_STRVAR(PySSL_set_context_doc,
1448"_setter_context(ctx)\n\
1449\
1450This changes the context associated with the SSLSocket. This is typically\n\
1451used from within a callback function set by the set_servername_callback\n\
1452on the SSLContext to change the certificate information associated with the\n\
1453SSLSocket before the cryptographic exchange handshake messages\n");
1454
1455
1456
1457static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001458{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001459 if (self->peer_cert) /* Possible not to have one? */
1460 X509_free (self->peer_cert);
1461 if (self->ssl)
1462 SSL_free(self->ssl);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001463 Py_XDECREF(self->Socket);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001464 Py_XDECREF(self->ssl_sock);
1465 Py_XDECREF(self->ctx);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001466 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001467}
1468
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001469/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001470 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001471 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001472 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001473
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001474static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001475check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001476{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001477 fd_set fds;
1478 struct timeval tv;
1479 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001480
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001481 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1482 if (s->sock_timeout < 0.0)
1483 return SOCKET_IS_BLOCKING;
1484 else if (s->sock_timeout == 0.0)
1485 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001486
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001487 /* Guard against closed socket */
1488 if (s->sock_fd < 0)
1489 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001490
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001491 /* Prefer poll, if available, since you can poll() any fd
1492 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001493#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001494 {
1495 struct pollfd pollfd;
1496 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001497
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001498 pollfd.fd = s->sock_fd;
1499 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001500
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001501 /* s->sock_timeout is in seconds, timeout in ms */
1502 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1503 PySSL_BEGIN_ALLOW_THREADS
1504 rc = poll(&pollfd, 1, timeout);
1505 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001506
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001507 goto normal_return;
1508 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001509#endif
1510
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001511 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001512 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001513 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001514
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001515 /* Construct the arguments to select */
1516 tv.tv_sec = (int)s->sock_timeout;
1517 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1518 FD_ZERO(&fds);
1519 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001520
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001521 /* See if the socket is ready */
1522 PySSL_BEGIN_ALLOW_THREADS
1523 if (writing)
1524 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1525 else
1526 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1527 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001528
Bill Janssen934b16d2008-06-28 22:19:33 +00001529#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001530normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001531#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001532 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1533 (when we are able to write or when there's something to read) */
1534 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001535}
1536
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001537static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001538{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001539 Py_buffer buf;
1540 int len;
1541 int sockstate;
1542 int err;
1543 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001544 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001545
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001546 Py_INCREF(sock);
1547
1548 if (!PyArg_ParseTuple(args, "s*:write", &buf)) {
1549 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001550 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001551 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001552
Victor Stinnerc1a44262013-06-25 00:48:02 +02001553 if (buf.len > INT_MAX) {
1554 PyErr_Format(PyExc_OverflowError,
1555 "string longer than %d bytes", INT_MAX);
1556 goto error;
1557 }
1558
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001559 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001560 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001563
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001564 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001565 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1566 PyErr_SetString(PySSLErrorObject,
1567 "The write operation timed out");
1568 goto error;
1569 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1570 PyErr_SetString(PySSLErrorObject,
1571 "Underlying socket has been closed.");
1572 goto error;
1573 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1574 PyErr_SetString(PySSLErrorObject,
1575 "Underlying socket too large for select().");
1576 goto error;
1577 }
1578 do {
1579 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001580 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001581 err = SSL_get_error(self->ssl, len);
1582 PySSL_END_ALLOW_THREADS
1583 if (PyErr_CheckSignals()) {
1584 goto error;
1585 }
1586 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001587 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001588 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001589 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001590 } else {
1591 sockstate = SOCKET_OPERATION_OK;
1592 }
1593 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1594 PyErr_SetString(PySSLErrorObject,
1595 "The write operation timed out");
1596 goto error;
1597 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1598 PyErr_SetString(PySSLErrorObject,
1599 "Underlying socket has been closed.");
1600 goto error;
1601 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1602 break;
1603 }
1604 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001605
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001606 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001607 PyBuffer_Release(&buf);
1608 if (len > 0)
1609 return PyInt_FromLong(len);
1610 else
1611 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001612
1613error:
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001614 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001615 PyBuffer_Release(&buf);
1616 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001617}
1618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620"write(s) -> len\n\
1621\n\
1622Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001623of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001624
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001625static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001626{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001627 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001628
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001629 PySSL_BEGIN_ALLOW_THREADS
1630 count = SSL_pending(self->ssl);
1631 PySSL_END_ALLOW_THREADS
1632 if (count < 0)
1633 return PySSL_SetError(self, count, __FILE__, __LINE__);
1634 else
1635 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001636}
1637
1638PyDoc_STRVAR(PySSL_SSLpending_doc,
1639"pending() -> count\n\
1640\n\
1641Returns the number of already decrypted bytes available for read,\n\
1642pending on the connection.\n");
1643
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001644static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001645{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001646 PyObject *dest = NULL;
1647 Py_buffer buf;
1648 char *mem;
1649 int len, count;
1650 int buf_passed = 0;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001651 int sockstate;
1652 int err;
1653 int nonblocking;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001654 PySocketSockObject *sock = self->Socket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001655
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001656 Py_INCREF(sock);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001657
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001658 buf.obj = NULL;
1659 buf.buf = NULL;
1660 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
1661 goto error;
1662
1663 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1664 dest = PyBytes_FromStringAndSize(NULL, len);
1665 if (dest == NULL)
1666 goto error;
1667 mem = PyBytes_AS_STRING(dest);
1668 }
1669 else {
1670 buf_passed = 1;
1671 mem = buf.buf;
1672 if (len <= 0 || len > buf.len) {
1673 len = (int) buf.len;
1674 if (buf.len != len) {
1675 PyErr_SetString(PyExc_OverflowError,
1676 "maximum length can't fit in a C 'int'");
1677 goto error;
1678 }
1679 }
1680 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001681
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001682 /* just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001683 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001684 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1685 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001686
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001687 /* first check if there are bytes ready to be read */
1688 PySSL_BEGIN_ALLOW_THREADS
1689 count = SSL_pending(self->ssl);
1690 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001691
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001692 if (!count) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001693 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001694 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1695 PyErr_SetString(PySSLErrorObject,
1696 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001697 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001698 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1699 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001700 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001701 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001702 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001703 count = 0;
1704 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001705 }
1706 }
1707 do {
1708 PySSL_BEGIN_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001709 count = SSL_read(self->ssl, mem, len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001710 err = SSL_get_error(self->ssl, count);
1711 PySSL_END_ALLOW_THREADS
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001712 if (PyErr_CheckSignals())
1713 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001714 if (err == SSL_ERROR_WANT_READ) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001715 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001716 } else if (err == SSL_ERROR_WANT_WRITE) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001717 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001718 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1719 (SSL_get_shutdown(self->ssl) ==
1720 SSL_RECEIVED_SHUTDOWN))
1721 {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001722 count = 0;
1723 goto done;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001724 } else {
1725 sockstate = SOCKET_OPERATION_OK;
1726 }
1727 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1728 PyErr_SetString(PySSLErrorObject,
1729 "The read operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001730 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001731 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1732 break;
1733 }
1734 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1735 if (count <= 0) {
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001736 PySSL_SetError(self, count, __FILE__, __LINE__);
1737 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001738 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001739
1740done:
1741 Py_DECREF(sock);
1742 if (!buf_passed) {
1743 _PyBytes_Resize(&dest, count);
1744 return dest;
1745 }
1746 else {
1747 PyBuffer_Release(&buf);
1748 return PyLong_FromLong(count);
1749 }
1750
1751error:
1752 Py_DECREF(sock);
1753 if (!buf_passed)
1754 Py_XDECREF(dest);
1755 else
1756 PyBuffer_Release(&buf);
1757 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758}
1759
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001760PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001761"read([len]) -> string\n\
1762\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001763Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001764
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001765static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen934b16d2008-06-28 22:19:33 +00001766{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001767 int err, ssl_err, sockstate, nonblocking;
1768 int zeros = 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001769 PySocketSockObject *sock = self->Socket;
Bill Janssen934b16d2008-06-28 22:19:33 +00001770
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001771 /* Guard against closed socket */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001772 if (sock->sock_fd < 0) {
1773 _setSSLError("Underlying socket connection gone",
1774 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001775 return NULL;
1776 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001777 Py_INCREF(sock);
Bill Janssen934b16d2008-06-28 22:19:33 +00001778
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001779 /* Just in case the blocking state of the socket has been changed */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001780 nonblocking = (sock->sock_timeout >= 0.0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001781 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1782 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001783
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001784 while (1) {
1785 PySSL_BEGIN_ALLOW_THREADS
1786 /* Disable read-ahead so that unwrap can work correctly.
1787 * Otherwise OpenSSL might read in too much data,
1788 * eating clear text data that happens to be
1789 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001790 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001791 * function is used and the shutdown_seen_zero != 0
1792 * condition is met.
1793 */
1794 if (self->shutdown_seen_zero)
1795 SSL_set_read_ahead(self->ssl, 0);
1796 err = SSL_shutdown(self->ssl);
1797 PySSL_END_ALLOW_THREADS
1798 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1799 if (err > 0)
1800 break;
1801 if (err == 0) {
1802 /* Don't loop endlessly; instead preserve legacy
1803 behaviour of trying SSL_shutdown() only twice.
1804 This looks necessary for OpenSSL < 0.9.8m */
1805 if (++zeros > 1)
1806 break;
1807 /* Shutdown was sent, now try receiving */
1808 self->shutdown_seen_zero = 1;
1809 continue;
1810 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001811
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001812 /* Possibly retry shutdown until timeout or failure */
1813 ssl_err = SSL_get_error(self->ssl, err);
1814 if (ssl_err == SSL_ERROR_WANT_READ)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001815 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001816 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001817 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001818 else
1819 break;
1820 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1821 if (ssl_err == SSL_ERROR_WANT_READ)
1822 PyErr_SetString(PySSLErrorObject,
1823 "The read operation timed out");
1824 else
1825 PyErr_SetString(PySSLErrorObject,
1826 "The write operation timed out");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001827 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001828 }
1829 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1830 PyErr_SetString(PySSLErrorObject,
1831 "Underlying socket too large for select().");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001832 goto error;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001833 }
1834 else if (sockstate != SOCKET_OPERATION_OK)
1835 /* Retain the SSL error code */
1836 break;
1837 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001838
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001839 if (err < 0) {
1840 Py_DECREF(sock);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001841 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001842 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001843 else
1844 /* It's already INCREF'ed */
1845 return (PyObject *) sock;
1846
1847error:
1848 Py_DECREF(sock);
1849 return NULL;
Bill Janssen934b16d2008-06-28 22:19:33 +00001850}
1851
1852PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1853"shutdown(s) -> socket\n\
1854\n\
1855Does the SSL shutdown handshake with the remote end, and returns\n\
1856the underlying socket object.");
1857
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001858#if HAVE_OPENSSL_FINISHED
1859static PyObject *
1860PySSL_tls_unique_cb(PySSLSocket *self)
1861{
1862 PyObject *retval = NULL;
1863 char buf[PySSL_CB_MAXLEN];
1864 size_t len;
1865
1866 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1867 /* if session is resumed XOR we are the client */
1868 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1869 }
1870 else {
1871 /* if a new session XOR we are the server */
1872 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1873 }
1874
1875 /* It cannot be negative in current OpenSSL version as of July 2011 */
1876 if (len == 0)
1877 Py_RETURN_NONE;
1878
1879 retval = PyBytes_FromStringAndSize(buf, len);
1880
1881 return retval;
1882}
1883
1884PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1885"tls_unique_cb() -> bytes\n\
1886\n\
1887Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1888\n\
1889If the TLS handshake is not yet complete, None is returned");
1890
1891#endif /* HAVE_OPENSSL_FINISHED */
1892
1893static PyGetSetDef ssl_getsetlist[] = {
1894 {"context", (getter) PySSL_get_context,
1895 (setter) PySSL_set_context, PySSL_set_context_doc},
1896 {NULL}, /* sentinel */
1897};
1898
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001899static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001900 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1901 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1902 PySSL_SSLwrite_doc},
1903 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1904 PySSL_SSLread_doc},
1905 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1906 PySSL_SSLpending_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001907 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1908 PySSL_peercert_doc},
1909 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001910#ifdef OPENSSL_NPN_NEGOTIATED
1911 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1912#endif
1913 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001914 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1915 PySSL_SSLshutdown_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001916#if HAVE_OPENSSL_FINISHED
1917 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1918 PySSL_tls_unique_cb_doc},
1919#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001920 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001921};
1922
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001923static PyTypeObject PySSLSocket_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001924 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001925 "_ssl._SSLSocket", /*tp_name*/
1926 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001927 0, /*tp_itemsize*/
1928 /* methods */
1929 (destructor)PySSL_dealloc, /*tp_dealloc*/
1930 0, /*tp_print*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001931 0, /*tp_getattr*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001932 0, /*tp_setattr*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001933 0, /*tp_reserved*/
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001934 0, /*tp_repr*/
1935 0, /*tp_as_number*/
1936 0, /*tp_as_sequence*/
1937 0, /*tp_as_mapping*/
1938 0, /*tp_hash*/
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001939 0, /*tp_call*/
1940 0, /*tp_str*/
1941 0, /*tp_getattro*/
1942 0, /*tp_setattro*/
1943 0, /*tp_as_buffer*/
1944 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1945 0, /*tp_doc*/
1946 0, /*tp_traverse*/
1947 0, /*tp_clear*/
1948 0, /*tp_richcompare*/
1949 0, /*tp_weaklistoffset*/
1950 0, /*tp_iter*/
1951 0, /*tp_iternext*/
1952 PySSLMethods, /*tp_methods*/
1953 0, /*tp_members*/
1954 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001955};
1956
Benjamin Petersondaeb9252014-08-20 14:14:50 -05001957
1958/*
1959 * _SSLContext objects
1960 */
1961
1962static PyObject *
1963context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1964{
1965 char *kwlist[] = {"protocol", NULL};
1966 PySSLContext *self;
1967 int proto_version = PY_SSL_VERSION_SSL23;
1968 long options;
1969 SSL_CTX *ctx = NULL;
1970
1971 if (!PyArg_ParseTupleAndKeywords(
1972 args, kwds, "i:_SSLContext", kwlist,
1973 &proto_version))
1974 return NULL;
1975
1976 PySSL_BEGIN_ALLOW_THREADS
1977 if (proto_version == PY_SSL_VERSION_TLS1)
1978 ctx = SSL_CTX_new(TLSv1_method());
1979#if HAVE_TLSv1_2
1980 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1981 ctx = SSL_CTX_new(TLSv1_1_method());
1982 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1983 ctx = SSL_CTX_new(TLSv1_2_method());
1984#endif
1985 else if (proto_version == PY_SSL_VERSION_SSL3)
1986 ctx = SSL_CTX_new(SSLv3_method());
1987#ifndef OPENSSL_NO_SSL2
1988 else if (proto_version == PY_SSL_VERSION_SSL2)
1989 ctx = SSL_CTX_new(SSLv2_method());
1990#endif
1991 else if (proto_version == PY_SSL_VERSION_SSL23)
1992 ctx = SSL_CTX_new(SSLv23_method());
1993 else
1994 proto_version = -1;
1995 PySSL_END_ALLOW_THREADS
1996
1997 if (proto_version == -1) {
1998 PyErr_SetString(PyExc_ValueError,
1999 "invalid protocol version");
2000 return NULL;
2001 }
2002 if (ctx == NULL) {
2003 PyErr_SetString(PySSLErrorObject,
2004 "failed to allocate SSL context");
2005 return NULL;
2006 }
2007
2008 assert(type != NULL && type->tp_alloc != NULL);
2009 self = (PySSLContext *) type->tp_alloc(type, 0);
2010 if (self == NULL) {
2011 SSL_CTX_free(ctx);
2012 return NULL;
2013 }
2014 self->ctx = ctx;
2015#ifdef OPENSSL_NPN_NEGOTIATED
2016 self->npn_protocols = NULL;
2017#endif
2018#ifndef OPENSSL_NO_TLSEXT
2019 self->set_hostname = NULL;
2020#endif
2021 /* Don't check host name by default */
2022 self->check_hostname = 0;
2023 /* Defaults */
2024 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
2025 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2026 if (proto_version != PY_SSL_VERSION_SSL2)
2027 options |= SSL_OP_NO_SSLv2;
2028 SSL_CTX_set_options(self->ctx, options);
2029
2030#ifndef OPENSSL_NO_ECDH
2031 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2032 prime256v1 by default. This is Apache mod_ssl's initialization
2033 policy, so we should be safe. */
2034#if defined(SSL_CTX_set_ecdh_auto)
2035 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2036#else
2037 {
2038 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2039 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2040 EC_KEY_free(key);
2041 }
2042#endif
2043#endif
2044
2045#define SID_CTX "Python"
2046 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2047 sizeof(SID_CTX));
2048#undef SID_CTX
2049
2050 return (PyObject *)self;
2051}
2052
2053static int
2054context_traverse(PySSLContext *self, visitproc visit, void *arg)
2055{
2056#ifndef OPENSSL_NO_TLSEXT
2057 Py_VISIT(self->set_hostname);
2058#endif
2059 return 0;
2060}
2061
2062static int
2063context_clear(PySSLContext *self)
2064{
2065#ifndef OPENSSL_NO_TLSEXT
2066 Py_CLEAR(self->set_hostname);
2067#endif
2068 return 0;
2069}
2070
2071static void
2072context_dealloc(PySSLContext *self)
2073{
2074 context_clear(self);
2075 SSL_CTX_free(self->ctx);
2076#ifdef OPENSSL_NPN_NEGOTIATED
2077 PyMem_Free(self->npn_protocols);
2078#endif
2079 Py_TYPE(self)->tp_free(self);
2080}
2081
2082static PyObject *
2083set_ciphers(PySSLContext *self, PyObject *args)
2084{
2085 int ret;
2086 const char *cipherlist;
2087
2088 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2089 return NULL;
2090 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2091 if (ret == 0) {
2092 /* Clearing the error queue is necessary on some OpenSSL versions,
2093 otherwise the error will be reported again when another SSL call
2094 is done. */
2095 ERR_clear_error();
2096 PyErr_SetString(PySSLErrorObject,
2097 "No cipher can be selected.");
2098 return NULL;
2099 }
2100 Py_RETURN_NONE;
2101}
2102
2103#ifdef OPENSSL_NPN_NEGOTIATED
2104/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2105static int
2106_advertiseNPN_cb(SSL *s,
2107 const unsigned char **data, unsigned int *len,
2108 void *args)
2109{
2110 PySSLContext *ssl_ctx = (PySSLContext *) args;
2111
2112 if (ssl_ctx->npn_protocols == NULL) {
2113 *data = (unsigned char *) "";
2114 *len = 0;
2115 } else {
2116 *data = (unsigned char *) ssl_ctx->npn_protocols;
2117 *len = ssl_ctx->npn_protocols_len;
2118 }
2119
2120 return SSL_TLSEXT_ERR_OK;
2121}
2122/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2123static int
2124_selectNPN_cb(SSL *s,
2125 unsigned char **out, unsigned char *outlen,
2126 const unsigned char *server, unsigned int server_len,
2127 void *args)
2128{
2129 PySSLContext *ssl_ctx = (PySSLContext *) args;
2130
2131 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2132 int client_len;
2133
2134 if (client == NULL) {
2135 client = (unsigned char *) "";
2136 client_len = 0;
2137 } else {
2138 client_len = ssl_ctx->npn_protocols_len;
2139 }
2140
2141 SSL_select_next_proto(out, outlen,
2142 server, server_len,
2143 client, client_len);
2144
2145 return SSL_TLSEXT_ERR_OK;
2146}
2147#endif
2148
2149static PyObject *
2150_set_npn_protocols(PySSLContext *self, PyObject *args)
2151{
2152#ifdef OPENSSL_NPN_NEGOTIATED
2153 Py_buffer protos;
2154
2155 if (!PyArg_ParseTuple(args, "s*:set_npn_protocols", &protos))
2156 return NULL;
2157
2158 if (self->npn_protocols != NULL) {
2159 PyMem_Free(self->npn_protocols);
2160 }
2161
2162 self->npn_protocols = PyMem_Malloc(protos.len);
2163 if (self->npn_protocols == NULL) {
2164 PyBuffer_Release(&protos);
2165 return PyErr_NoMemory();
2166 }
2167 memcpy(self->npn_protocols, protos.buf, protos.len);
2168 self->npn_protocols_len = (int) protos.len;
2169
2170 /* set both server and client callbacks, because the context can
2171 * be used to create both types of sockets */
2172 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2173 _advertiseNPN_cb,
2174 self);
2175 SSL_CTX_set_next_proto_select_cb(self->ctx,
2176 _selectNPN_cb,
2177 self);
2178
2179 PyBuffer_Release(&protos);
2180 Py_RETURN_NONE;
2181#else
2182 PyErr_SetString(PyExc_NotImplementedError,
2183 "The NPN extension requires OpenSSL 1.0.1 or later.");
2184 return NULL;
2185#endif
2186}
2187
2188static PyObject *
2189get_verify_mode(PySSLContext *self, void *c)
2190{
2191 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2192 case SSL_VERIFY_NONE:
2193 return PyLong_FromLong(PY_SSL_CERT_NONE);
2194 case SSL_VERIFY_PEER:
2195 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2196 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2197 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2198 }
2199 PyErr_SetString(PySSLErrorObject,
2200 "invalid return value from SSL_CTX_get_verify_mode");
2201 return NULL;
2202}
2203
2204static int
2205set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2206{
2207 int n, mode;
2208 if (!PyArg_Parse(arg, "i", &n))
2209 return -1;
2210 if (n == PY_SSL_CERT_NONE)
2211 mode = SSL_VERIFY_NONE;
2212 else if (n == PY_SSL_CERT_OPTIONAL)
2213 mode = SSL_VERIFY_PEER;
2214 else if (n == PY_SSL_CERT_REQUIRED)
2215 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2216 else {
2217 PyErr_SetString(PyExc_ValueError,
2218 "invalid value for verify_mode");
2219 return -1;
2220 }
2221 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2222 PyErr_SetString(PyExc_ValueError,
2223 "Cannot set verify_mode to CERT_NONE when "
2224 "check_hostname is enabled.");
2225 return -1;
2226 }
2227 SSL_CTX_set_verify(self->ctx, mode, NULL);
2228 return 0;
2229}
2230
2231#ifdef HAVE_OPENSSL_VERIFY_PARAM
2232static PyObject *
2233get_verify_flags(PySSLContext *self, void *c)
2234{
2235 X509_STORE *store;
2236 unsigned long flags;
2237
2238 store = SSL_CTX_get_cert_store(self->ctx);
2239 flags = X509_VERIFY_PARAM_get_flags(store->param);
2240 return PyLong_FromUnsignedLong(flags);
2241}
2242
2243static int
2244set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2245{
2246 X509_STORE *store;
2247 unsigned long new_flags, flags, set, clear;
2248
2249 if (!PyArg_Parse(arg, "k", &new_flags))
2250 return -1;
2251 store = SSL_CTX_get_cert_store(self->ctx);
2252 flags = X509_VERIFY_PARAM_get_flags(store->param);
2253 clear = flags & ~new_flags;
2254 set = ~flags & new_flags;
2255 if (clear) {
2256 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2257 _setSSLError(NULL, 0, __FILE__, __LINE__);
2258 return -1;
2259 }
2260 }
2261 if (set) {
2262 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2263 _setSSLError(NULL, 0, __FILE__, __LINE__);
2264 return -1;
2265 }
2266 }
2267 return 0;
2268}
2269#endif
2270
2271static PyObject *
2272get_options(PySSLContext *self, void *c)
2273{
2274 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2275}
2276
2277static int
2278set_options(PySSLContext *self, PyObject *arg, void *c)
2279{
2280 long new_opts, opts, set, clear;
2281 if (!PyArg_Parse(arg, "l", &new_opts))
2282 return -1;
2283 opts = SSL_CTX_get_options(self->ctx);
2284 clear = opts & ~new_opts;
2285 set = ~opts & new_opts;
2286 if (clear) {
2287#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2288 SSL_CTX_clear_options(self->ctx, clear);
2289#else
2290 PyErr_SetString(PyExc_ValueError,
2291 "can't clear options before OpenSSL 0.9.8m");
2292 return -1;
2293#endif
2294 }
2295 if (set)
2296 SSL_CTX_set_options(self->ctx, set);
2297 return 0;
2298}
2299
2300static PyObject *
2301get_check_hostname(PySSLContext *self, void *c)
2302{
2303 return PyBool_FromLong(self->check_hostname);
2304}
2305
2306static int
2307set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2308{
2309 PyObject *py_check_hostname;
2310 int check_hostname;
2311 if (!PyArg_Parse(arg, "O", &py_check_hostname))
2312 return -1;
2313
2314 check_hostname = PyObject_IsTrue(py_check_hostname);
2315 if (check_hostname < 0)
2316 return -1;
2317 if (check_hostname &&
2318 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2319 PyErr_SetString(PyExc_ValueError,
2320 "check_hostname needs a SSL context with either "
2321 "CERT_OPTIONAL or CERT_REQUIRED");
2322 return -1;
2323 }
2324 self->check_hostname = check_hostname;
2325 return 0;
2326}
2327
2328
2329typedef struct {
2330 PyThreadState *thread_state;
2331 PyObject *callable;
2332 char *password;
2333 int size;
2334 int error;
2335} _PySSLPasswordInfo;
2336
2337static int
2338_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2339 const char *bad_type_error)
2340{
2341 /* Set the password and size fields of a _PySSLPasswordInfo struct
2342 from a unicode, bytes, or byte array object.
2343 The password field will be dynamically allocated and must be freed
2344 by the caller */
2345 PyObject *password_bytes = NULL;
2346 const char *data = NULL;
2347 Py_ssize_t size;
2348
2349 if (PyUnicode_Check(password)) {
2350 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2351 if (!password_bytes) {
2352 goto error;
2353 }
2354 data = PyBytes_AS_STRING(password_bytes);
2355 size = PyBytes_GET_SIZE(password_bytes);
2356 } else if (PyBytes_Check(password)) {
2357 data = PyBytes_AS_STRING(password);
2358 size = PyBytes_GET_SIZE(password);
2359 } else if (PyByteArray_Check(password)) {
2360 data = PyByteArray_AS_STRING(password);
2361 size = PyByteArray_GET_SIZE(password);
2362 } else {
2363 PyErr_SetString(PyExc_TypeError, bad_type_error);
2364 goto error;
2365 }
2366
2367 if (size > (Py_ssize_t)INT_MAX) {
2368 PyErr_Format(PyExc_ValueError,
2369 "password cannot be longer than %d bytes", INT_MAX);
2370 goto error;
2371 }
2372
2373 PyMem_Free(pw_info->password);
2374 pw_info->password = PyMem_Malloc(size);
2375 if (!pw_info->password) {
2376 PyErr_SetString(PyExc_MemoryError,
2377 "unable to allocate password buffer");
2378 goto error;
2379 }
2380 memcpy(pw_info->password, data, size);
2381 pw_info->size = (int)size;
2382
2383 Py_XDECREF(password_bytes);
2384 return 1;
2385
2386error:
2387 Py_XDECREF(password_bytes);
2388 return 0;
2389}
2390
2391static int
2392_password_callback(char *buf, int size, int rwflag, void *userdata)
2393{
2394 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2395 PyObject *fn_ret = NULL;
2396
2397 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2398
2399 if (pw_info->callable) {
2400 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2401 if (!fn_ret) {
2402 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2403 core python API, so we could use it to add a frame here */
2404 goto error;
2405 }
2406
2407 if (!_pwinfo_set(pw_info, fn_ret,
2408 "password callback must return a string")) {
2409 goto error;
2410 }
2411 Py_CLEAR(fn_ret);
2412 }
2413
2414 if (pw_info->size > size) {
2415 PyErr_Format(PyExc_ValueError,
2416 "password cannot be longer than %d bytes", size);
2417 goto error;
2418 }
2419
2420 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2421 memcpy(buf, pw_info->password, pw_info->size);
2422 return pw_info->size;
2423
2424error:
2425 Py_XDECREF(fn_ret);
2426 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2427 pw_info->error = 1;
2428 return -1;
2429}
2430
2431static PyObject *
2432load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2433{
2434 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2435 PyObject *password = NULL;
2436 char *certfile_bytes = NULL, *keyfile_bytes = NULL;
2437 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2438 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2439 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
2440 int r;
2441
2442 errno = 0;
2443 ERR_clear_error();
2444 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2445 "et|etO:load_cert_chain", kwlist,
2446 Py_FileSystemDefaultEncoding, &certfile_bytes,
2447 Py_FileSystemDefaultEncoding, &keyfile_bytes,
2448 &password))
2449 return NULL;
2450 if (password && password != Py_None) {
2451 if (PyCallable_Check(password)) {
2452 pw_info.callable = password;
2453 } else if (!_pwinfo_set(&pw_info, password,
2454 "password should be a string or callable")) {
2455 goto error;
2456 }
2457 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2458 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2459 }
2460 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2461 r = SSL_CTX_use_certificate_chain_file(self->ctx, certfile_bytes);
2462 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2463 if (r != 1) {
2464 if (pw_info.error) {
2465 ERR_clear_error();
2466 /* the password callback has already set the error information */
2467 }
2468 else if (errno != 0) {
2469 ERR_clear_error();
2470 PyErr_SetFromErrno(PyExc_IOError);
2471 }
2472 else {
2473 _setSSLError(NULL, 0, __FILE__, __LINE__);
2474 }
2475 goto error;
2476 }
2477 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2478 r = SSL_CTX_use_PrivateKey_file(self->ctx,
2479 keyfile_bytes ? keyfile_bytes : certfile_bytes,
2480 SSL_FILETYPE_PEM);
2481 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2482 if (r != 1) {
2483 if (pw_info.error) {
2484 ERR_clear_error();
2485 /* the password callback has already set the error information */
2486 }
2487 else if (errno != 0) {
2488 ERR_clear_error();
2489 PyErr_SetFromErrno(PyExc_IOError);
2490 }
2491 else {
2492 _setSSLError(NULL, 0, __FILE__, __LINE__);
2493 }
2494 goto error;
2495 }
2496 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
2497 r = SSL_CTX_check_private_key(self->ctx);
2498 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2499 if (r != 1) {
2500 _setSSLError(NULL, 0, __FILE__, __LINE__);
2501 goto error;
2502 }
2503 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2504 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2505 PyMem_Free(pw_info.password);
2506 Py_RETURN_NONE;
2507
2508error:
2509 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2510 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2511 PyMem_Free(pw_info.password);
2512 PyMem_Free(keyfile_bytes);
2513 PyMem_Free(certfile_bytes);
2514 return NULL;
2515}
2516
2517/* internal helper function, returns -1 on error
2518 */
2519static int
2520_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2521 int filetype)
2522{
2523 BIO *biobuf = NULL;
2524 X509_STORE *store;
2525 int retval = 0, err, loaded = 0;
2526
2527 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2528
2529 if (len <= 0) {
2530 PyErr_SetString(PyExc_ValueError,
2531 "Empty certificate data");
2532 return -1;
2533 } else if (len > INT_MAX) {
2534 PyErr_SetString(PyExc_OverflowError,
2535 "Certificate data is too long.");
2536 return -1;
2537 }
2538
2539 biobuf = BIO_new_mem_buf(data, (int)len);
2540 if (biobuf == NULL) {
2541 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2542 return -1;
2543 }
2544
2545 store = SSL_CTX_get_cert_store(self->ctx);
2546 assert(store != NULL);
2547
2548 while (1) {
2549 X509 *cert = NULL;
2550 int r;
2551
2552 if (filetype == SSL_FILETYPE_ASN1) {
2553 cert = d2i_X509_bio(biobuf, NULL);
2554 } else {
2555 cert = PEM_read_bio_X509(biobuf, NULL,
2556 self->ctx->default_passwd_callback,
2557 self->ctx->default_passwd_callback_userdata);
2558 }
2559 if (cert == NULL) {
2560 break;
2561 }
2562 r = X509_STORE_add_cert(store, cert);
2563 X509_free(cert);
2564 if (!r) {
2565 err = ERR_peek_last_error();
2566 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2567 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2568 /* cert already in hash table, not an error */
2569 ERR_clear_error();
2570 } else {
2571 break;
2572 }
2573 }
2574 loaded++;
2575 }
2576
2577 err = ERR_peek_last_error();
2578 if ((filetype == SSL_FILETYPE_ASN1) &&
2579 (loaded > 0) &&
2580 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2581 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2582 /* EOF ASN1 file, not an error */
2583 ERR_clear_error();
2584 retval = 0;
2585 } else if ((filetype == SSL_FILETYPE_PEM) &&
2586 (loaded > 0) &&
2587 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2588 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2589 /* EOF PEM file, not an error */
2590 ERR_clear_error();
2591 retval = 0;
2592 } else {
2593 _setSSLError(NULL, 0, __FILE__, __LINE__);
2594 retval = -1;
2595 }
2596
2597 BIO_free(biobuf);
2598 return retval;
2599}
2600
2601
2602static PyObject *
2603load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2604{
2605 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2606 PyObject *cadata = NULL, *cafile = NULL, *capath = NULL;
2607 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2608 const char *cafile_buf = NULL, *capath_buf = NULL;
2609 int r = 0, ok = 1;
2610
2611 errno = 0;
2612 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2613 "|OOO:load_verify_locations", kwlist,
2614 &cafile, &capath, &cadata))
2615 return NULL;
2616
2617 if (cafile == Py_None)
2618 cafile = NULL;
2619 if (capath == Py_None)
2620 capath = NULL;
2621 if (cadata == Py_None)
2622 cadata = NULL;
2623
2624 if (cafile == NULL && capath == NULL && cadata == NULL) {
2625 PyErr_SetString(PyExc_TypeError,
2626 "cafile, capath and cadata cannot be all omitted");
2627 goto error;
2628 }
2629
2630 if (cafile) {
2631 cafile_bytes = PyString_AsEncodedObject(
2632 cafile, Py_FileSystemDefaultEncoding, "strict");
2633 if (!cafile_bytes) {
2634 goto error;
2635 }
2636 }
2637 if (capath) {
2638 capath_bytes = PyString_AsEncodedObject(
2639 capath, Py_FileSystemDefaultEncoding, "strict");
2640 if (!capath_bytes) {
2641 goto error;
2642 }
2643 }
2644
2645 /* validata cadata type and load cadata */
2646 if (cadata) {
2647 Py_buffer buf;
2648 PyObject *cadata_ascii = NULL;
2649
2650 if (!PyUnicode_Check(cadata) && PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2651 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2652 PyBuffer_Release(&buf);
2653 PyErr_SetString(PyExc_TypeError,
2654 "cadata should be a contiguous buffer with "
2655 "a single dimension");
2656 goto error;
2657 }
2658 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2659 PyBuffer_Release(&buf);
2660 if (r == -1) {
2661 goto error;
2662 }
2663 } else {
2664 PyErr_Clear();
2665 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2666 if (cadata_ascii == NULL) {
2667 PyErr_SetString(PyExc_TypeError,
2668 "cadata should be a ASCII string or a "
2669 "bytes-like object");
2670 goto error;
2671 }
2672 r = _add_ca_certs(self,
2673 PyBytes_AS_STRING(cadata_ascii),
2674 PyBytes_GET_SIZE(cadata_ascii),
2675 SSL_FILETYPE_PEM);
2676 Py_DECREF(cadata_ascii);
2677 if (r == -1) {
2678 goto error;
2679 }
2680 }
2681 }
2682
2683 /* load cafile or capath */
2684 if (cafile_bytes || capath_bytes) {
2685 if (cafile)
2686 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2687 if (capath)
2688 capath_buf = PyBytes_AS_STRING(capath_bytes);
2689 PySSL_BEGIN_ALLOW_THREADS
2690 r = SSL_CTX_load_verify_locations(
2691 self->ctx,
2692 cafile_buf,
2693 capath_buf);
2694 PySSL_END_ALLOW_THREADS
2695 if (r != 1) {
2696 ok = 0;
2697 if (errno != 0) {
2698 ERR_clear_error();
2699 PyErr_SetFromErrno(PyExc_IOError);
2700 }
2701 else {
2702 _setSSLError(NULL, 0, __FILE__, __LINE__);
2703 }
2704 goto error;
2705 }
2706 }
2707 goto end;
2708
2709 error:
2710 ok = 0;
2711 end:
2712 Py_XDECREF(cafile_bytes);
2713 Py_XDECREF(capath_bytes);
2714 if (ok) {
2715 Py_RETURN_NONE;
2716 } else {
2717 return NULL;
2718 }
2719}
2720
2721static PyObject *
2722load_dh_params(PySSLContext *self, PyObject *filepath)
2723{
2724 BIO *bio;
2725 DH *dh;
2726 char *path = PyBytes_AsString(filepath);
2727 if (!path) {
2728 return NULL;
2729 }
2730
2731 bio = BIO_new_file(path, "r");
2732 if (bio == NULL) {
2733 ERR_clear_error();
2734 PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, filepath);
2735 return NULL;
2736 }
2737 errno = 0;
2738 PySSL_BEGIN_ALLOW_THREADS
2739 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2740 BIO_free(bio);
2741 PySSL_END_ALLOW_THREADS
2742 if (dh == NULL) {
2743 if (errno != 0) {
2744 ERR_clear_error();
2745 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2746 }
2747 else {
2748 _setSSLError(NULL, 0, __FILE__, __LINE__);
2749 }
2750 return NULL;
2751 }
2752 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2753 _setSSLError(NULL, 0, __FILE__, __LINE__);
2754 DH_free(dh);
2755 Py_RETURN_NONE;
2756}
2757
2758static PyObject *
2759context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2760{
2761 char *kwlist[] = {"sock", "server_side", "server_hostname", "ssl_sock", NULL};
2762 PySocketSockObject *sock;
2763 int server_side = 0;
2764 char *hostname = NULL;
2765 PyObject *hostname_obj, *ssl_sock = Py_None, *res;
2766
2767 /* server_hostname is either None (or absent), or to be encoded
2768 using the idna encoding. */
2769 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!O:_wrap_socket", kwlist,
2770 PySocketModule.Sock_Type,
2771 &sock, &server_side,
2772 Py_TYPE(Py_None), &hostname_obj,
2773 &ssl_sock)) {
2774 PyErr_Clear();
2775 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet|O:_wrap_socket", kwlist,
2776 PySocketModule.Sock_Type,
2777 &sock, &server_side,
2778 "idna", &hostname, &ssl_sock))
2779 return NULL;
2780#if !HAVE_SNI
2781 PyMem_Free(hostname);
2782 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2783 "by your OpenSSL library");
2784 return NULL;
2785#endif
2786 }
2787
2788 res = (PyObject *) newPySSLSocket(self, sock, server_side,
2789 hostname, ssl_sock);
2790 if (hostname != NULL)
2791 PyMem_Free(hostname);
2792 return res;
2793}
2794
2795static PyObject *
2796session_stats(PySSLContext *self, PyObject *unused)
2797{
2798 int r;
2799 PyObject *value, *stats = PyDict_New();
2800 if (!stats)
2801 return NULL;
2802
2803#define ADD_STATS(SSL_NAME, KEY_NAME) \
2804 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2805 if (value == NULL) \
2806 goto error; \
2807 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2808 Py_DECREF(value); \
2809 if (r < 0) \
2810 goto error;
2811
2812 ADD_STATS(number, "number");
2813 ADD_STATS(connect, "connect");
2814 ADD_STATS(connect_good, "connect_good");
2815 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2816 ADD_STATS(accept, "accept");
2817 ADD_STATS(accept_good, "accept_good");
2818 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2819 ADD_STATS(accept, "accept");
2820 ADD_STATS(hits, "hits");
2821 ADD_STATS(misses, "misses");
2822 ADD_STATS(timeouts, "timeouts");
2823 ADD_STATS(cache_full, "cache_full");
2824
2825#undef ADD_STATS
2826
2827 return stats;
2828
2829error:
2830 Py_DECREF(stats);
2831 return NULL;
2832}
2833
2834static PyObject *
2835set_default_verify_paths(PySSLContext *self, PyObject *unused)
2836{
2837 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2838 _setSSLError(NULL, 0, __FILE__, __LINE__);
2839 return NULL;
2840 }
2841 Py_RETURN_NONE;
2842}
2843
2844#ifndef OPENSSL_NO_ECDH
2845static PyObject *
2846set_ecdh_curve(PySSLContext *self, PyObject *name)
2847{
2848 char *name_bytes;
2849 int nid;
2850 EC_KEY *key;
2851
2852 name_bytes = PyBytes_AsString(name);
2853 if (!name_bytes) {
2854 return NULL;
2855 }
2856 nid = OBJ_sn2nid(name_bytes);
2857 if (nid == 0) {
2858 PyErr_Format(PyExc_ValueError,
2859 "unknown elliptic curve name %R", name);
2860 return NULL;
2861 }
2862 key = EC_KEY_new_by_curve_name(nid);
2863 if (key == NULL) {
2864 _setSSLError(NULL, 0, __FILE__, __LINE__);
2865 return NULL;
2866 }
2867 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2868 EC_KEY_free(key);
2869 Py_RETURN_NONE;
2870}
2871#endif
2872
2873#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
2874static int
2875_servername_callback(SSL *s, int *al, void *args)
2876{
2877 int ret;
2878 PySSLContext *ssl_ctx = (PySSLContext *) args;
2879 PySSLSocket *ssl;
2880 PyObject *servername_o;
2881 PyObject *servername_idna;
2882 PyObject *result;
2883 /* The high-level ssl.SSLSocket object */
2884 PyObject *ssl_socket;
2885 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2886#ifdef WITH_THREAD
2887 PyGILState_STATE gstate = PyGILState_Ensure();
2888#endif
2889
2890 if (ssl_ctx->set_hostname == NULL) {
2891 /* remove race condition in this the call back while if removing the
2892 * callback is in progress */
2893#ifdef WITH_THREAD
2894 PyGILState_Release(gstate);
2895#endif
2896 return SSL_TLSEXT_ERR_OK;
2897 }
2898
2899 ssl = SSL_get_app_data(s);
2900 assert(PySSLSocket_Check(ssl));
2901 ssl_socket = PyWeakref_GetObject(ssl->ssl_sock);
2902 Py_INCREF(ssl_socket);
2903 if (ssl_socket == Py_None) {
2904 goto error;
2905 }
2906
2907 if (servername == NULL) {
2908 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2909 Py_None, ssl_ctx, NULL);
2910 }
2911 else {
2912 servername_o = PyBytes_FromString(servername);
2913 if (servername_o == NULL) {
2914 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2915 goto error;
2916 }
2917 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2918 if (servername_idna == NULL) {
2919 PyErr_WriteUnraisable(servername_o);
2920 Py_DECREF(servername_o);
2921 goto error;
2922 }
2923 Py_DECREF(servername_o);
2924 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2925 servername_idna, ssl_ctx, NULL);
2926 Py_DECREF(servername_idna);
2927 }
2928 Py_DECREF(ssl_socket);
2929
2930 if (result == NULL) {
2931 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2932 *al = SSL_AD_HANDSHAKE_FAILURE;
2933 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2934 }
2935 else {
2936 if (result != Py_None) {
2937 *al = (int) PyLong_AsLong(result);
2938 if (PyErr_Occurred()) {
2939 PyErr_WriteUnraisable(result);
2940 *al = SSL_AD_INTERNAL_ERROR;
2941 }
2942 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2943 }
2944 else {
2945 ret = SSL_TLSEXT_ERR_OK;
2946 }
2947 Py_DECREF(result);
2948 }
2949
2950#ifdef WITH_THREAD
2951 PyGILState_Release(gstate);
2952#endif
2953 return ret;
2954
2955error:
2956 Py_DECREF(ssl_socket);
2957 *al = SSL_AD_INTERNAL_ERROR;
2958 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2959#ifdef WITH_THREAD
2960 PyGILState_Release(gstate);
2961#endif
2962 return ret;
2963}
2964#endif
2965
2966PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2967"set_servername_callback(method)\n\
2968\n\
2969This sets a callback that will be called when a server name is provided by\n\
2970the SSL/TLS client in the SNI extension.\n\
2971\n\
2972If the argument is None then the callback is disabled. The method is called\n\
2973with the SSLSocket, the server name as a string, and the SSLContext object.\n\
2974See RFC 6066 for details of the SNI extension.");
2975
2976static PyObject *
2977set_servername_callback(PySSLContext *self, PyObject *args)
2978{
2979#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
2980 PyObject *cb;
2981
2982 if (!PyArg_ParseTuple(args, "O", &cb))
2983 return NULL;
2984
2985 Py_CLEAR(self->set_hostname);
2986 if (cb == Py_None) {
2987 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2988 }
2989 else {
2990 if (!PyCallable_Check(cb)) {
2991 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2992 PyErr_SetString(PyExc_TypeError,
2993 "not a callable object");
2994 return NULL;
2995 }
2996 Py_INCREF(cb);
2997 self->set_hostname = cb;
2998 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2999 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3000 }
3001 Py_RETURN_NONE;
3002#else
3003 PyErr_SetString(PyExc_NotImplementedError,
3004 "The TLS extension servername callback, "
3005 "SSL_CTX_set_tlsext_servername_callback, "
3006 "is not in the current OpenSSL library.");
3007 return NULL;
3008#endif
3009}
3010
3011PyDoc_STRVAR(PySSL_get_stats_doc,
3012"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3013\n\
3014Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3015CA extension and certificate revocation lists inside the context's cert\n\
3016store.\n\
3017NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3018been used at least once.");
3019
3020static PyObject *
3021cert_store_stats(PySSLContext *self)
3022{
3023 X509_STORE *store;
3024 X509_OBJECT *obj;
3025 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3026
3027 store = SSL_CTX_get_cert_store(self->ctx);
3028 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3029 obj = sk_X509_OBJECT_value(store->objs, i);
3030 switch (obj->type) {
3031 case X509_LU_X509:
3032 x509++;
3033 if (X509_check_ca(obj->data.x509)) {
3034 ca++;
3035 }
3036 break;
3037 case X509_LU_CRL:
3038 crl++;
3039 break;
3040 case X509_LU_PKEY:
3041 pkey++;
3042 break;
3043 default:
3044 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3045 * As far as I can tell they are internal states and never
3046 * stored in a cert store */
3047 break;
3048 }
3049 }
3050 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3051 "x509_ca", ca);
3052}
3053
3054PyDoc_STRVAR(PySSL_get_ca_certs_doc,
3055"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
3056\n\
3057Returns a list of dicts with information of loaded CA certs. If the\n\
3058optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3059NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3060been used at least once.");
3061
3062static PyObject *
3063get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
3064{
3065 char *kwlist[] = {"binary_form", NULL};
3066 X509_STORE *store;
3067 PyObject *ci = NULL, *rlist = NULL, *py_binary_mode = Py_False;
3068 int i;
3069 int binary_mode = 0;
3070
3071 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:get_ca_certs",
3072 kwlist, &py_binary_mode)) {
3073 return NULL;
3074 }
3075 binary_mode = PyObject_IsTrue(py_binary_mode);
3076 if (binary_mode < 0) {
3077 return NULL;
3078 }
3079
3080 if ((rlist = PyList_New(0)) == NULL) {
3081 return NULL;
3082 }
3083
3084 store = SSL_CTX_get_cert_store(self->ctx);
3085 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3086 X509_OBJECT *obj;
3087 X509 *cert;
3088
3089 obj = sk_X509_OBJECT_value(store->objs, i);
3090 if (obj->type != X509_LU_X509) {
3091 /* not a x509 cert */
3092 continue;
3093 }
3094 /* CA for any purpose */
3095 cert = obj->data.x509;
3096 if (!X509_check_ca(cert)) {
3097 continue;
3098 }
3099 if (binary_mode) {
3100 ci = _certificate_to_der(cert);
3101 } else {
3102 ci = _decode_certificate(cert);
3103 }
3104 if (ci == NULL) {
3105 goto error;
3106 }
3107 if (PyList_Append(rlist, ci) == -1) {
3108 goto error;
3109 }
3110 Py_CLEAR(ci);
3111 }
3112 return rlist;
3113
3114 error:
3115 Py_XDECREF(ci);
3116 Py_XDECREF(rlist);
3117 return NULL;
3118}
3119
3120
3121static PyGetSetDef context_getsetlist[] = {
3122 {"check_hostname", (getter) get_check_hostname,
3123 (setter) set_check_hostname, NULL},
3124 {"options", (getter) get_options,
3125 (setter) set_options, NULL},
3126#ifdef HAVE_OPENSSL_VERIFY_PARAM
3127 {"verify_flags", (getter) get_verify_flags,
3128 (setter) set_verify_flags, NULL},
3129#endif
3130 {"verify_mode", (getter) get_verify_mode,
3131 (setter) set_verify_mode, NULL},
3132 {NULL}, /* sentinel */
3133};
3134
3135static struct PyMethodDef context_methods[] = {
3136 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3137 METH_VARARGS | METH_KEYWORDS, NULL},
3138 {"set_ciphers", (PyCFunction) set_ciphers,
3139 METH_VARARGS, NULL},
3140 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3141 METH_VARARGS, NULL},
3142 {"load_cert_chain", (PyCFunction) load_cert_chain,
3143 METH_VARARGS | METH_KEYWORDS, NULL},
3144 {"load_dh_params", (PyCFunction) load_dh_params,
3145 METH_O, NULL},
3146 {"load_verify_locations", (PyCFunction) load_verify_locations,
3147 METH_VARARGS | METH_KEYWORDS, NULL},
3148 {"session_stats", (PyCFunction) session_stats,
3149 METH_NOARGS, NULL},
3150 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3151 METH_NOARGS, NULL},
3152#ifndef OPENSSL_NO_ECDH
3153 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3154 METH_O, NULL},
3155#endif
3156 {"set_servername_callback", (PyCFunction) set_servername_callback,
3157 METH_VARARGS, PySSL_set_servername_callback_doc},
3158 {"cert_store_stats", (PyCFunction) cert_store_stats,
3159 METH_NOARGS, PySSL_get_stats_doc},
3160 {"get_ca_certs", (PyCFunction) get_ca_certs,
3161 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
3162 {NULL, NULL} /* sentinel */
3163};
3164
3165static PyTypeObject PySSLContext_Type = {
3166 PyVarObject_HEAD_INIT(NULL, 0)
3167 "_ssl._SSLContext", /*tp_name*/
3168 sizeof(PySSLContext), /*tp_basicsize*/
3169 0, /*tp_itemsize*/
3170 (destructor)context_dealloc, /*tp_dealloc*/
3171 0, /*tp_print*/
3172 0, /*tp_getattr*/
3173 0, /*tp_setattr*/
3174 0, /*tp_reserved*/
3175 0, /*tp_repr*/
3176 0, /*tp_as_number*/
3177 0, /*tp_as_sequence*/
3178 0, /*tp_as_mapping*/
3179 0, /*tp_hash*/
3180 0, /*tp_call*/
3181 0, /*tp_str*/
3182 0, /*tp_getattro*/
3183 0, /*tp_setattro*/
3184 0, /*tp_as_buffer*/
3185 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
3186 0, /*tp_doc*/
3187 (traverseproc) context_traverse, /*tp_traverse*/
3188 (inquiry) context_clear, /*tp_clear*/
3189 0, /*tp_richcompare*/
3190 0, /*tp_weaklistoffset*/
3191 0, /*tp_iter*/
3192 0, /*tp_iternext*/
3193 context_methods, /*tp_methods*/
3194 0, /*tp_members*/
3195 context_getsetlist, /*tp_getset*/
3196 0, /*tp_base*/
3197 0, /*tp_dict*/
3198 0, /*tp_descr_get*/
3199 0, /*tp_descr_set*/
3200 0, /*tp_dictoffset*/
3201 0, /*tp_init*/
3202 0, /*tp_alloc*/
3203 context_new, /*tp_new*/
3204};
3205
3206
3207
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003208#ifdef HAVE_OPENSSL_RAND
3209
3210/* helper routines for seeding the SSL PRNG */
3211static PyObject *
3212PySSL_RAND_add(PyObject *self, PyObject *args)
3213{
3214 char *buf;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003215 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003216 double entropy;
3217
3218 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003219 return NULL;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003220 do {
3221 if (len >= INT_MAX) {
3222 written = INT_MAX;
3223 } else {
3224 written = len;
3225 }
3226 RAND_add(buf, (int)written, entropy);
3227 buf += written;
3228 len -= written;
3229 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003230 Py_INCREF(Py_None);
3231 return Py_None;
3232}
3233
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003234PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003235"RAND_add(string, entropy)\n\
3236\n\
3237Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003238bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003239
3240static PyObject *
3241PySSL_RAND_status(PyObject *self)
3242{
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003243 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003244}
3245
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003246PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003247"RAND_status() -> 0 or 1\n\
3248\n\
3249Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3250It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003251using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003252
3253static PyObject *
3254PySSL_RAND_egd(PyObject *self, PyObject *arg)
3255{
3256 int bytes;
3257
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003258 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003259 return PyErr_Format(PyExc_TypeError,
3260 "RAND_egd() expected string, found %s",
3261 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003262 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003263 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00003264 PyErr_SetString(PySSLErrorObject,
3265 "EGD connection failed or EGD did not return "
3266 "enough data to seed the PRNG");
3267 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003268 }
3269 return PyInt_FromLong(bytes);
3270}
3271
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003272PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003273"RAND_egd(path) -> bytes\n\
3274\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00003275Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3276Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02003277fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003278
Christian Heimes0d604cf2013-08-21 13:26:05 +02003279#endif /* HAVE_OPENSSL_RAND */
3280
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003281
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003282PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3283"get_default_verify_paths() -> tuple\n\
3284\n\
3285Return search paths and environment vars that are used by SSLContext's\n\
3286set_default_verify_paths() to load default CAs. The values are\n\
3287'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3288
3289static PyObject *
3290PySSL_get_default_verify_paths(PyObject *self)
3291{
3292 PyObject *ofile_env = NULL;
3293 PyObject *ofile = NULL;
3294 PyObject *odir_env = NULL;
3295 PyObject *odir = NULL;
3296
3297#define convert(info, target) { \
3298 const char *tmp = (info); \
3299 target = NULL; \
3300 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3301 else { target = PyBytes_FromString(tmp); } \
3302 if (!target) goto error; \
3303 } while(0)
3304
3305 convert(X509_get_default_cert_file_env(), ofile_env);
3306 convert(X509_get_default_cert_file(), ofile);
3307 convert(X509_get_default_cert_dir_env(), odir_env);
3308 convert(X509_get_default_cert_dir(), odir);
3309#undef convert
3310
3311 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
3312
3313 error:
3314 Py_XDECREF(ofile_env);
3315 Py_XDECREF(ofile);
3316 Py_XDECREF(odir_env);
3317 Py_XDECREF(odir);
3318 return NULL;
3319}
3320
3321static PyObject*
3322asn1obj2py(ASN1_OBJECT *obj)
3323{
3324 int nid;
3325 const char *ln, *sn;
3326 char buf[100];
3327 Py_ssize_t buflen;
3328
3329 nid = OBJ_obj2nid(obj);
3330 if (nid == NID_undef) {
3331 PyErr_Format(PyExc_ValueError, "Unknown object");
3332 return NULL;
3333 }
3334 sn = OBJ_nid2sn(nid);
3335 ln = OBJ_nid2ln(nid);
3336 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3337 if (buflen < 0) {
3338 _setSSLError(NULL, 0, __FILE__, __LINE__);
3339 return NULL;
3340 }
3341 if (buflen) {
3342 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3343 } else {
3344 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3345 }
3346}
3347
3348PyDoc_STRVAR(PySSL_txt2obj_doc,
3349"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3350\n\
3351Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3352objects are looked up by OID. With name=True short and long name are also\n\
3353matched.");
3354
3355static PyObject*
3356PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3357{
3358 char *kwlist[] = {"txt", "name", NULL};
3359 PyObject *result = NULL;
3360 char *txt;
3361 PyObject *pyname = Py_None;
3362 int name = 0;
3363 ASN1_OBJECT *obj;
3364
3365 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:txt2obj",
3366 kwlist, &txt, &pyname)) {
3367 return NULL;
3368 }
3369 name = PyObject_IsTrue(pyname);
3370 if (name < 0)
3371 return NULL;
3372 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3373 if (obj == NULL) {
3374 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
3375 return NULL;
3376 }
3377 result = asn1obj2py(obj);
3378 ASN1_OBJECT_free(obj);
3379 return result;
3380}
3381
3382PyDoc_STRVAR(PySSL_nid2obj_doc,
3383"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3384\n\
3385Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3386
3387static PyObject*
3388PySSL_nid2obj(PyObject *self, PyObject *args)
3389{
3390 PyObject *result = NULL;
3391 int nid;
3392 ASN1_OBJECT *obj;
3393
3394 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3395 return NULL;
3396 }
3397 if (nid < NID_undef) {
3398 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
3399 return NULL;
3400 }
3401 obj = OBJ_nid2obj(nid);
3402 if (obj == NULL) {
3403 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
3404 return NULL;
3405 }
3406 result = asn1obj2py(obj);
3407 ASN1_OBJECT_free(obj);
3408 return result;
3409}
3410
3411#ifdef _MSC_VER
3412
3413static PyObject*
3414certEncodingType(DWORD encodingType)
3415{
3416 static PyObject *x509_asn = NULL;
3417 static PyObject *pkcs_7_asn = NULL;
3418
3419 if (x509_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003420 x509_asn = PyString_InternFromString("x509_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003421 if (x509_asn == NULL)
3422 return NULL;
3423 }
3424 if (pkcs_7_asn == NULL) {
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003425 pkcs_7_asn = PyString_InternFromString("pkcs_7_asn");
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003426 if (pkcs_7_asn == NULL)
3427 return NULL;
3428 }
3429 switch(encodingType) {
3430 case X509_ASN_ENCODING:
3431 Py_INCREF(x509_asn);
3432 return x509_asn;
3433 case PKCS_7_ASN_ENCODING:
3434 Py_INCREF(pkcs_7_asn);
3435 return pkcs_7_asn;
3436 default:
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003437 return PyInt_FromLong(encodingType);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003438 }
3439}
3440
3441static PyObject*
3442parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3443{
3444 CERT_ENHKEY_USAGE *usage;
3445 DWORD size, error, i;
3446 PyObject *retval;
3447
3448 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3449 error = GetLastError();
3450 if (error == CRYPT_E_NOT_FOUND) {
3451 Py_RETURN_TRUE;
3452 }
3453 return PyErr_SetFromWindowsErr(error);
3454 }
3455
3456 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3457 if (usage == NULL) {
3458 return PyErr_NoMemory();
3459 }
3460
3461 /* Now get the actual enhanced usage property */
3462 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3463 PyMem_Free(usage);
3464 error = GetLastError();
3465 if (error == CRYPT_E_NOT_FOUND) {
3466 Py_RETURN_TRUE;
3467 }
3468 return PyErr_SetFromWindowsErr(error);
3469 }
3470 retval = PySet_New(NULL);
3471 if (retval == NULL) {
3472 goto error;
3473 }
3474 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3475 if (usage->rgpszUsageIdentifier[i]) {
3476 PyObject *oid;
3477 int err;
Benjamin Petersoncbb144a2014-08-20 14:25:32 -05003478 oid = PyString_FromString(usage->rgpszUsageIdentifier[i]);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003479 if (oid == NULL) {
3480 Py_CLEAR(retval);
3481 goto error;
3482 }
3483 err = PySet_Add(retval, oid);
3484 Py_DECREF(oid);
3485 if (err == -1) {
3486 Py_CLEAR(retval);
3487 goto error;
3488 }
3489 }
3490 }
3491 error:
3492 PyMem_Free(usage);
3493 return retval;
3494}
3495
3496PyDoc_STRVAR(PySSL_enum_certificates_doc,
3497"enum_certificates(store_name) -> []\n\
3498\n\
3499Retrieve certificates from Windows' cert store. store_name may be one of\n\
3500'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3501The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
3502encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3503PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
3504boolean True.");
3505
3506static PyObject *
3507PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
3508{
3509 char *kwlist[] = {"store_name", NULL};
3510 char *store_name;
3511 HCERTSTORE hStore = NULL;
3512 PCCERT_CONTEXT pCertCtx = NULL;
3513 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
3514 PyObject *result = NULL;
3515
3516 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
3517 kwlist, &store_name)) {
3518 return NULL;
3519 }
3520 result = PyList_New(0);
3521 if (result == NULL) {
3522 return NULL;
3523 }
3524 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3525 if (hStore == NULL) {
3526 Py_DECREF(result);
3527 return PyErr_SetFromWindowsErr(GetLastError());
3528 }
3529
3530 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3531 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3532 pCertCtx->cbCertEncoded);
3533 if (!cert) {
3534 Py_CLEAR(result);
3535 break;
3536 }
3537 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
3538 Py_CLEAR(result);
3539 break;
3540 }
3541 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
3542 if (keyusage == Py_True) {
3543 Py_DECREF(keyusage);
3544 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
3545 }
3546 if (keyusage == NULL) {
3547 Py_CLEAR(result);
3548 break;
3549 }
3550 if ((tup = PyTuple_New(3)) == NULL) {
3551 Py_CLEAR(result);
3552 break;
3553 }
3554 PyTuple_SET_ITEM(tup, 0, cert);
3555 cert = NULL;
3556 PyTuple_SET_ITEM(tup, 1, enc);
3557 enc = NULL;
3558 PyTuple_SET_ITEM(tup, 2, keyusage);
3559 keyusage = NULL;
3560 if (PyList_Append(result, tup) < 0) {
3561 Py_CLEAR(result);
3562 break;
3563 }
3564 Py_CLEAR(tup);
3565 }
3566 if (pCertCtx) {
3567 /* loop ended with an error, need to clean up context manually */
3568 CertFreeCertificateContext(pCertCtx);
3569 }
3570
3571 /* In error cases cert, enc and tup may not be NULL */
3572 Py_XDECREF(cert);
3573 Py_XDECREF(enc);
3574 Py_XDECREF(keyusage);
3575 Py_XDECREF(tup);
3576
3577 if (!CertCloseStore(hStore, 0)) {
3578 /* This error case might shadow another exception.*/
3579 Py_XDECREF(result);
3580 return PyErr_SetFromWindowsErr(GetLastError());
3581 }
3582 return result;
3583}
3584
3585PyDoc_STRVAR(PySSL_enum_crls_doc,
3586"enum_crls(store_name) -> []\n\
3587\n\
3588Retrieve CRLs from Windows' cert store. store_name may be one of\n\
3589'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3590The function returns a list of (bytes, encoding_type) tuples. The\n\
3591encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3592PKCS_7_ASN_ENCODING.");
3593
3594static PyObject *
3595PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
3596{
3597 char *kwlist[] = {"store_name", NULL};
3598 char *store_name;
3599 HCERTSTORE hStore = NULL;
3600 PCCRL_CONTEXT pCrlCtx = NULL;
3601 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
3602 PyObject *result = NULL;
3603
3604 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
3605 kwlist, &store_name)) {
3606 return NULL;
3607 }
3608 result = PyList_New(0);
3609 if (result == NULL) {
3610 return NULL;
3611 }
3612 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
3613 if (hStore == NULL) {
3614 Py_DECREF(result);
3615 return PyErr_SetFromWindowsErr(GetLastError());
3616 }
3617
3618 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3619 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3620 pCrlCtx->cbCrlEncoded);
3621 if (!crl) {
3622 Py_CLEAR(result);
3623 break;
3624 }
3625 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
3626 Py_CLEAR(result);
3627 break;
3628 }
3629 if ((tup = PyTuple_New(2)) == NULL) {
3630 Py_CLEAR(result);
3631 break;
3632 }
3633 PyTuple_SET_ITEM(tup, 0, crl);
3634 crl = NULL;
3635 PyTuple_SET_ITEM(tup, 1, enc);
3636 enc = NULL;
3637
3638 if (PyList_Append(result, tup) < 0) {
3639 Py_CLEAR(result);
3640 break;
3641 }
3642 Py_CLEAR(tup);
3643 }
3644 if (pCrlCtx) {
3645 /* loop ended with an error, need to clean up context manually */
3646 CertFreeCRLContext(pCrlCtx);
3647 }
3648
3649 /* In error cases cert, enc and tup may not be NULL */
3650 Py_XDECREF(crl);
3651 Py_XDECREF(enc);
3652 Py_XDECREF(tup);
3653
3654 if (!CertCloseStore(hStore, 0)) {
3655 /* This error case might shadow another exception.*/
3656 Py_XDECREF(result);
3657 return PyErr_SetFromWindowsErr(GetLastError());
3658 }
3659 return result;
3660}
3661
3662#endif /* _MSC_VER */
3663
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003664/* List of functions exported by this module. */
3665
3666static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003667 {"_test_decode_cert", PySSL_test_decode_certificate,
3668 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003669#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003670 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3671 PySSL_RAND_add_doc},
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003672 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003673 PySSL_RAND_egd_doc},
3674 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3675 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003676#endif
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003677 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
3678 METH_NOARGS, PySSL_get_default_verify_paths_doc},
3679#ifdef _MSC_VER
3680 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
3681 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
3682 {"enum_crls", (PyCFunction)PySSL_enum_crls,
3683 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
3684#endif
3685 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3686 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3687 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3688 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003689 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003690};
3691
3692
Bill Janssen98d19da2007-09-10 21:51:02 +00003693#ifdef WITH_THREAD
3694
3695/* an implementation of OpenSSL threading operations in terms
3696 of the Python C thread library */
3697
3698static PyThread_type_lock *_ssl_locks = NULL;
3699
Christian Heimes10107812013-08-19 17:36:29 +02003700#if OPENSSL_VERSION_NUMBER >= 0x10000000
3701/* use new CRYPTO_THREADID API. */
3702static void
3703_ssl_threadid_callback(CRYPTO_THREADID *id)
3704{
3705 CRYPTO_THREADID_set_numeric(id,
3706 (unsigned long)PyThread_get_thread_ident());
3707}
3708#else
3709/* deprecated CRYPTO_set_id_callback() API. */
3710static unsigned long
3711_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003712 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00003713}
Christian Heimes10107812013-08-19 17:36:29 +02003714#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00003715
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003716static void _ssl_thread_locking_function
3717 (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003718 /* this function is needed to perform locking on shared data
3719 structures. (Note that OpenSSL uses a number of global data
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003720 structures that will be implicitly shared whenever multiple
3721 threads use OpenSSL.) Multi-threaded applications will
3722 crash at random if it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00003723
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003724 locking_function() must be able to handle up to
3725 CRYPTO_num_locks() different mutex locks. It sets the n-th
3726 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00003727
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003728 file and line are the file number of the function setting the
3729 lock. They can be useful for debugging.
3730 */
Bill Janssen98d19da2007-09-10 21:51:02 +00003731
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003732 if ((_ssl_locks == NULL) ||
3733 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3734 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00003735
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003736 if (mode & CRYPTO_LOCK) {
3737 PyThread_acquire_lock(_ssl_locks[n], 1);
3738 } else {
3739 PyThread_release_lock(_ssl_locks[n]);
3740 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003741}
3742
3743static int _setup_ssl_threads(void) {
3744
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003745 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00003746
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003747 if (_ssl_locks == NULL) {
3748 _ssl_locks_count = CRYPTO_num_locks();
3749 _ssl_locks = (PyThread_type_lock *)
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003750 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003751 if (_ssl_locks == NULL)
3752 return 0;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003753 memset(_ssl_locks, 0,
3754 sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003755 for (i = 0; i < _ssl_locks_count; i++) {
3756 _ssl_locks[i] = PyThread_allocate_lock();
3757 if (_ssl_locks[i] == NULL) {
3758 unsigned int j;
3759 for (j = 0; j < i; j++) {
3760 PyThread_free_lock(_ssl_locks[j]);
3761 }
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003762 PyMem_Free(_ssl_locks);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003763 return 0;
3764 }
3765 }
3766 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02003767#if OPENSSL_VERSION_NUMBER >= 0x10000000
3768 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3769#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003770 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02003771#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003772 }
3773 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00003774}
3775
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003776#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00003777
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003778PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003779"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003780for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003781
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003782
3783
3784
3785static void
3786parse_openssl_version(unsigned long libver,
3787 unsigned int *major, unsigned int *minor,
3788 unsigned int *fix, unsigned int *patch,
3789 unsigned int *status)
3790{
3791 *status = libver & 0xF;
3792 libver >>= 4;
3793 *patch = libver & 0xFF;
3794 libver >>= 8;
3795 *fix = libver & 0xFF;
3796 libver >>= 8;
3797 *minor = libver & 0xFF;
3798 libver >>= 8;
3799 *major = libver & 0xFF;
3800}
3801
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003802PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003803init_ssl(void)
3804{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003805 PyObject *m, *d, *r;
3806 unsigned long libver;
3807 unsigned int major, minor, fix, patch, status;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003808 struct py_ssl_error_code *errcode;
3809 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003810
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003811 if (PyType_Ready(&PySSLContext_Type) < 0)
3812 return;
3813 if (PyType_Ready(&PySSLSocket_Type) < 0)
3814 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003815
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003816 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
3817 if (m == NULL)
3818 return;
3819 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003820
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003821 /* Load _socket module and its C API */
3822 if (PySocketModule_ImportModuleAndAPI())
3823 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003824
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003825 /* Init OpenSSL */
3826 SSL_load_error_strings();
3827 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00003828#ifdef WITH_THREAD
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003829 /* note that this will start threading if not already started */
3830 if (!_setup_ssl_threads()) {
3831 return;
3832 }
Bill Janssen98d19da2007-09-10 21:51:02 +00003833#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003834 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003835
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003836 /* Add symbols to module dict */
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003837 PySSLErrorObject = PyErr_NewExceptionWithDoc(
3838 "ssl.SSLError", SSLError_doc,
3839 PySocketModule.error, NULL);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003840 if (PySSLErrorObject == NULL)
3841 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003842 ((PyTypeObject *)PySSLErrorObject)->tp_str = (reprfunc)SSLError_str;
3843
3844 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3845 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3846 PySSLErrorObject, NULL);
3847 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3848 "ssl.SSLWantReadError", SSLWantReadError_doc,
3849 PySSLErrorObject, NULL);
3850 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3851 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3852 PySSLErrorObject, NULL);
3853 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3854 "ssl.SSLSyscallError", SSLSyscallError_doc,
3855 PySSLErrorObject, NULL);
3856 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3857 "ssl.SSLEOFError", SSLEOFError_doc,
3858 PySSLErrorObject, NULL);
3859 if (PySSLZeroReturnErrorObject == NULL
3860 || PySSLWantReadErrorObject == NULL
3861 || PySSLWantWriteErrorObject == NULL
3862 || PySSLSyscallErrorObject == NULL
3863 || PySSLEOFErrorObject == NULL)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003864 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003865
3866 ((PyTypeObject *)PySSLZeroReturnErrorObject)->tp_str = (reprfunc)SSLError_str;
3867 ((PyTypeObject *)PySSLWantReadErrorObject)->tp_str = (reprfunc)SSLError_str;
3868 ((PyTypeObject *)PySSLWantWriteErrorObject)->tp_str = (reprfunc)SSLError_str;
3869 ((PyTypeObject *)PySSLSyscallErrorObject)->tp_str = (reprfunc)SSLError_str;
3870 ((PyTypeObject *)PySSLEOFErrorObject)->tp_str = (reprfunc)SSLError_str;
3871
3872 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3873 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3874 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3875 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3876 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3877 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
3878 return;
3879 if (PyDict_SetItemString(d, "_SSLContext",
3880 (PyObject *)&PySSLContext_Type) != 0)
3881 return;
3882 if (PyDict_SetItemString(d, "_SSLSocket",
3883 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003884 return;
3885 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3886 PY_SSL_ERROR_ZERO_RETURN);
3887 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3888 PY_SSL_ERROR_WANT_READ);
3889 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3890 PY_SSL_ERROR_WANT_WRITE);
3891 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3892 PY_SSL_ERROR_WANT_X509_LOOKUP);
3893 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3894 PY_SSL_ERROR_SYSCALL);
3895 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3896 PY_SSL_ERROR_SSL);
3897 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3898 PY_SSL_ERROR_WANT_CONNECT);
3899 /* non ssl.h errorcodes */
3900 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3901 PY_SSL_ERROR_EOF);
3902 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3903 PY_SSL_ERROR_INVALID_ERROR_CODE);
3904 /* cert requirements */
3905 PyModule_AddIntConstant(m, "CERT_NONE",
3906 PY_SSL_CERT_NONE);
3907 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3908 PY_SSL_CERT_OPTIONAL);
3909 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3910 PY_SSL_CERT_REQUIRED);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003911 /* CRL verification for verification_flags */
3912 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
3913 0);
3914 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
3915 X509_V_FLAG_CRL_CHECK);
3916 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
3917 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
3918 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
3919 X509_V_FLAG_X509_STRICT);
3920
3921 /* Alert Descriptions from ssl.h */
3922 /* note RESERVED constants no longer intended for use have been removed */
3923 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3924
3925#define ADD_AD_CONSTANT(s) \
3926 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3927 SSL_AD_##s)
3928
3929 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3930 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3931 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3932 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3933 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3934 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3935 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3936 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3937 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3938 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3939 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3940 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3941 ADD_AD_CONSTANT(UNKNOWN_CA);
3942 ADD_AD_CONSTANT(ACCESS_DENIED);
3943 ADD_AD_CONSTANT(DECODE_ERROR);
3944 ADD_AD_CONSTANT(DECRYPT_ERROR);
3945 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3946 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3947 ADD_AD_CONSTANT(INTERNAL_ERROR);
3948 ADD_AD_CONSTANT(USER_CANCELLED);
3949 ADD_AD_CONSTANT(NO_RENEGOTIATION);
3950 /* Not all constants are in old OpenSSL versions */
3951#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3952 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3953#endif
3954#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3955 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3956#endif
3957#ifdef SSL_AD_UNRECOGNIZED_NAME
3958 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3959#endif
3960#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3961 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3962#endif
3963#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3964 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3965#endif
3966#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3967 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3968#endif
3969
3970#undef ADD_AD_CONSTANT
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003971
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003972 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02003973#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003974 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3975 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02003976#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00003977 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3978 PY_SSL_VERSION_SSL3);
3979 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3980 PY_SSL_VERSION_SSL23);
3981 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3982 PY_SSL_VERSION_TLS1);
Benjamin Petersondaeb9252014-08-20 14:14:50 -05003983#if HAVE_TLSv1_2
3984 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3985 PY_SSL_VERSION_TLS1_1);
3986 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3987 PY_SSL_VERSION_TLS1_2);
3988#endif
3989
3990 /* protocol options */
3991 PyModule_AddIntConstant(m, "OP_ALL",
3992 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3993 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3994 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3995 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
3996#if HAVE_TLSv1_2
3997 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3998 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3999#endif
4000 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4001 SSL_OP_CIPHER_SERVER_PREFERENCE);
4002 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
4003#ifdef SSL_OP_SINGLE_ECDH_USE
4004 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
4005#endif
4006#ifdef SSL_OP_NO_COMPRESSION
4007 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4008 SSL_OP_NO_COMPRESSION);
4009#endif
4010
4011#if HAVE_SNI
4012 r = Py_True;
4013#else
4014 r = Py_False;
4015#endif
4016 Py_INCREF(r);
4017 PyModule_AddObject(m, "HAS_SNI", r);
4018
4019#if HAVE_OPENSSL_FINISHED
4020 r = Py_True;
4021#else
4022 r = Py_False;
4023#endif
4024 Py_INCREF(r);
4025 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4026
4027#ifdef OPENSSL_NO_ECDH
4028 r = Py_False;
4029#else
4030 r = Py_True;
4031#endif
4032 Py_INCREF(r);
4033 PyModule_AddObject(m, "HAS_ECDH", r);
4034
4035#ifdef OPENSSL_NPN_NEGOTIATED
4036 r = Py_True;
4037#else
4038 r = Py_False;
4039#endif
4040 Py_INCREF(r);
4041 PyModule_AddObject(m, "HAS_NPN", r);
4042
4043 /* Mappings for error codes */
4044 err_codes_to_names = PyDict_New();
4045 err_names_to_codes = PyDict_New();
4046 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4047 return;
4048 errcode = error_codes;
4049 while (errcode->mnemonic != NULL) {
4050 PyObject *mnemo, *key;
4051 mnemo = PyUnicode_FromString(errcode->mnemonic);
4052 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4053 if (mnemo == NULL || key == NULL)
4054 return;
4055 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4056 return;
4057 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4058 return;
4059 Py_DECREF(key);
4060 Py_DECREF(mnemo);
4061 errcode++;
4062 }
4063 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4064 return;
4065 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4066 return;
4067
4068 lib_codes_to_names = PyDict_New();
4069 if (lib_codes_to_names == NULL)
4070 return;
4071 libcode = library_codes;
4072 while (libcode->library != NULL) {
4073 PyObject *mnemo, *key;
4074 key = PyLong_FromLong(libcode->code);
4075 mnemo = PyUnicode_FromString(libcode->library);
4076 if (key == NULL || mnemo == NULL)
4077 return;
4078 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4079 return;
4080 Py_DECREF(key);
4081 Py_DECREF(mnemo);
4082 libcode++;
4083 }
4084 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4085 return;
Antoine Pitrouf9de5342010-04-05 21:35:07 +00004086
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004087 /* OpenSSL version */
4088 /* SSLeay() gives us the version of the library linked against,
4089 which could be different from the headers version.
4090 */
4091 libver = SSLeay();
4092 r = PyLong_FromUnsignedLong(libver);
4093 if (r == NULL)
4094 return;
4095 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4096 return;
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004097 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00004098 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4099 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4100 return;
4101 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
4102 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4103 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02004104
Benjamin Petersondaeb9252014-08-20 14:14:50 -05004105 libver = OPENSSL_VERSION_NUMBER;
4106 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4107 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4108 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4109 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004110}