blob: 690d0be647cc17fd30caa8a31203cb56eb2adaa1 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000079/* Include symbols from _socket module */
80#include "socketmodule.h"
81
Benjamin Petersonb173f782009-05-05 22:31:58 +000082static PySocketModule_APIObject PySocketModule;
83
Thomas Woutersed03b412007-08-28 21:37:11 +000084#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085#include <poll.h>
86#elif defined(HAVE_SYS_POLL_H)
87#include <sys/poll.h>
88#endif
89
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090/* Include OpenSSL header files */
91#include "openssl/rsa.h"
92#include "openssl/crypto.h"
93#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000095#include "openssl/pem.h"
96#include "openssl/ssl.h"
97#include "openssl/err.h"
98#include "openssl/rand.h"
99
100/* SSL error object */
101static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200102static PyObject *PySSLZeroReturnErrorObject;
103static PyObject *PySSLWantReadErrorObject;
104static PyObject *PySSLWantWriteErrorObject;
105static PyObject *PySSLSyscallErrorObject;
106static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108#ifdef WITH_THREAD
109
110/* serves as a flag to see whether we've initialized the SSL thread support. */
111/* 0 means no, greater than 0 means yes */
112
113static unsigned int _ssl_locks_count = 0;
114
115#endif /* def WITH_THREAD */
116
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000117/* SSL socket object */
118
119#define X509_NAME_MAXLEN 256
120
121/* RAND_* APIs got added to OpenSSL in 0.9.5 */
122#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
123# define HAVE_OPENSSL_RAND 1
124#else
125# undef HAVE_OPENSSL_RAND
126#endif
127
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000128/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
129 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
130 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
131#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000132# define HAVE_SSL_CTX_CLEAR_OPTIONS
133#else
134# undef HAVE_SSL_CTX_CLEAR_OPTIONS
135#endif
136
Antoine Pitroud6494802011-07-21 01:11:30 +0200137/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
138 * older SSL, but let's be safe */
139#define PySSL_CB_MAXLEN 128
140
141/* SSL_get_finished got added to OpenSSL in 0.9.5 */
142#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
143# define HAVE_OPENSSL_FINISHED 1
144#else
145# define HAVE_OPENSSL_FINISHED 0
146#endif
147
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100148/* ECDH support got added to OpenSSL in 0.9.8 */
149#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
150# define OPENSSL_NO_ECDH
151#endif
152
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100153/* compression support got added to OpenSSL in 0.9.8 */
154#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
155# define OPENSSL_NO_COMP
156#endif
157
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100158
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000159typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000160 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000161 SSL_CTX *ctx;
162} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000163
Antoine Pitrou152efa22010-05-16 18:19:27 +0000164typedef struct {
165 PyObject_HEAD
166 PyObject *Socket; /* weakref to socket on which we're layered */
167 SSL *ssl;
168 X509 *peer_cert;
169 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200170 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000171} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000172
Antoine Pitrou152efa22010-05-16 18:19:27 +0000173static PyTypeObject PySSLContext_Type;
174static PyTypeObject PySSLSocket_Type;
175
176static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
177static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000178static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000179 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000180static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
181static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000182
Antoine Pitrou152efa22010-05-16 18:19:27 +0000183#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
184#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000185
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000186typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000187 SOCKET_IS_NONBLOCKING,
188 SOCKET_IS_BLOCKING,
189 SOCKET_HAS_TIMED_OUT,
190 SOCKET_HAS_BEEN_CLOSED,
191 SOCKET_TOO_LARGE_FOR_SELECT,
192 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000193} timeout_state;
194
Thomas Woutersed03b412007-08-28 21:37:11 +0000195/* Wrap error strings with filename and line # */
196#define STRINGIFY1(x) #x
197#define STRINGIFY2(x) STRINGIFY1(x)
198#define ERRSTR1(x,y,z) (x ":" y ": " z)
199#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
200
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000201/* XXX It might be helpful to augment the error message generated
202 below with the name of the SSL function that generated the error.
203 I expect it's obvious most of the time.
204*/
205
206static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000207PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000208{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 PyObject *v;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200210 PyObject *type = PySSLErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 char buf[2048];
212 char *errstr;
213 int err;
214 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000216 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000218 if (obj->ssl != NULL) {
219 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000221 switch (err) {
222 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200223 errstr = "TLS/SSL connection has been closed (EOF)";
224 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 p = PY_SSL_ERROR_ZERO_RETURN;
226 break;
227 case SSL_ERROR_WANT_READ:
228 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200229 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000230 p = PY_SSL_ERROR_WANT_READ;
231 break;
232 case SSL_ERROR_WANT_WRITE:
233 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200234 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000235 errstr = "The operation did not complete (write)";
236 break;
237 case SSL_ERROR_WANT_X509_LOOKUP:
238 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000239 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000240 break;
241 case SSL_ERROR_WANT_CONNECT:
242 p = PY_SSL_ERROR_WANT_CONNECT;
243 errstr = "The operation did not complete (connect)";
244 break;
245 case SSL_ERROR_SYSCALL:
246 {
247 unsigned long e = ERR_get_error();
248 if (e == 0) {
249 PySocketSockObject *s
250 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
251 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000252 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200253 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000254 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000255 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000256 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000257 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000258 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000259 v = s->errorhandler();
260 Py_DECREF(s);
261 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000262 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000263 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200264 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000265 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 }
267 } else {
268 p = PY_SSL_ERROR_SYSCALL;
269 /* XXX Protected by global interpreter lock */
270 errstr = ERR_error_string(e, NULL);
271 }
272 break;
273 }
274 case SSL_ERROR_SSL:
275 {
276 unsigned long e = ERR_get_error();
277 p = PY_SSL_ERROR_SSL;
278 if (e != 0)
279 /* XXX Protected by global interpreter lock */
280 errstr = ERR_error_string(e, NULL);
281 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000282 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000283 }
284 break;
285 }
286 default:
287 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
288 errstr = "Invalid error code";
289 }
290 } else {
291 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
292 }
293 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000294 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 v = Py_BuildValue("(is)", p, buf);
296 if (v != NULL) {
Antoine Pitrou41032a62011-10-27 23:56:55 +0200297 PyErr_SetObject(type, v);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 Py_DECREF(v);
299 }
300 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000301}
302
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303static PyObject *
304_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 char buf[2048];
307 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 if (errstr == NULL) {
310 errcode = ERR_peek_last_error();
311 errstr = ERR_error_string(errcode, NULL);
312 }
313 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000314 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000315 v = Py_BuildValue("(is)", errcode, buf);
316 if (v != NULL) {
317 PyErr_SetObject(PySSLErrorObject, v);
318 Py_DECREF(v);
319 }
320 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000321}
322
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323static PySSLSocket *
324newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000325 enum py_ssl_server_or_client socket_type,
326 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000327{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000328 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000329
Antoine Pitrou152efa22010-05-16 18:19:27 +0000330 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 if (self == NULL)
332 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000334 self->peer_cert = NULL;
335 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000338 /* Make sure the SSL error state is initialized */
339 (void) ERR_get_state();
340 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000343 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000345 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000346#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000348#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000349
Antoine Pitroud5323212010-10-22 18:19:07 +0000350#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
351 if (server_hostname != NULL)
352 SSL_set_tlsext_host_name(self->ssl, server_hostname);
353#endif
354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000355 /* If the socket is in non-blocking mode or timeout mode, set the BIO
356 * to non-blocking mode (blocking is the default)
357 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000358 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
360 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
361 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000363 PySSL_BEGIN_ALLOW_THREADS
364 if (socket_type == PY_SSL_CLIENT)
365 SSL_set_connect_state(self->ssl);
366 else
367 SSL_set_accept_state(self->ssl);
368 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000369
Antoine Pitroud6494802011-07-21 01:11:30 +0200370 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000371 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000373}
374
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375/* SSL object methods */
376
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 int ret;
380 int err;
381 int sockstate, nonblocking;
382 PySocketSockObject *sock
383 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 if (((PyObject*)sock) == Py_None) {
386 _setSSLError("Underlying socket connection gone",
387 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
388 return NULL;
389 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000390 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 /* just in case the blocking state of the socket has been changed */
393 nonblocking = (sock->sock_timeout >= 0.0);
394 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
395 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 /* Actually negotiate SSL connection */
398 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000400 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 ret = SSL_do_handshake(self->ssl);
402 err = SSL_get_error(self->ssl, ret);
403 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000404 if (PyErr_CheckSignals())
405 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 if (err == SSL_ERROR_WANT_READ) {
407 sockstate = check_socket_and_wait_for_timeout(sock, 0);
408 } else if (err == SSL_ERROR_WANT_WRITE) {
409 sockstate = check_socket_and_wait_for_timeout(sock, 1);
410 } else {
411 sockstate = SOCKET_OPERATION_OK;
412 }
413 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000414 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000415 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000416 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
418 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000420 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
422 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
426 break;
427 }
428 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000429 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000430 if (ret < 1)
431 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 if (self->peer_cert)
434 X509_free (self->peer_cert);
435 PySSL_BEGIN_ALLOW_THREADS
436 self->peer_cert = SSL_get_peer_certificate(self->ssl);
437 PySSL_END_ALLOW_THREADS
438
439 Py_INCREF(Py_None);
440 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000441
442error:
443 Py_DECREF(sock);
444 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000445}
446
Thomas Woutersed03b412007-08-28 21:37:11 +0000447static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000448_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 char namebuf[X509_NAME_MAXLEN];
451 int buflen;
452 PyObject *name_obj;
453 PyObject *value_obj;
454 PyObject *attr;
455 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000456
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
458 if (buflen < 0) {
459 _setSSLError(NULL, 0, __FILE__, __LINE__);
460 goto fail;
461 }
462 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
463 if (name_obj == NULL)
464 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
467 if (buflen < 0) {
468 _setSSLError(NULL, 0, __FILE__, __LINE__);
469 Py_DECREF(name_obj);
470 goto fail;
471 }
472 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000473 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000474 OPENSSL_free(valuebuf);
475 if (value_obj == NULL) {
476 Py_DECREF(name_obj);
477 goto fail;
478 }
479 attr = PyTuple_New(2);
480 if (attr == NULL) {
481 Py_DECREF(name_obj);
482 Py_DECREF(value_obj);
483 goto fail;
484 }
485 PyTuple_SET_ITEM(attr, 0, name_obj);
486 PyTuple_SET_ITEM(attr, 1, value_obj);
487 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000488
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000489 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000491}
492
493static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000494_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000495{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
497 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
498 PyObject *rdnt;
499 PyObject *attr = NULL; /* tuple to hold an attribute */
500 int entry_count = X509_NAME_entry_count(xname);
501 X509_NAME_ENTRY *entry;
502 ASN1_OBJECT *name;
503 ASN1_STRING *value;
504 int index_counter;
505 int rdn_level = -1;
506 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 dn = PyList_New(0);
509 if (dn == NULL)
510 return NULL;
511 /* now create another tuple to hold the top-level RDN */
512 rdn = PyList_New(0);
513 if (rdn == NULL)
514 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 for (index_counter = 0;
517 index_counter < entry_count;
518 index_counter++)
519 {
520 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 /* check to see if we've gotten to a new RDN */
523 if (rdn_level >= 0) {
524 if (rdn_level != entry->set) {
525 /* yes, new RDN */
526 /* add old RDN to DN */
527 rdnt = PyList_AsTuple(rdn);
528 Py_DECREF(rdn);
529 if (rdnt == NULL)
530 goto fail0;
531 retcode = PyList_Append(dn, rdnt);
532 Py_DECREF(rdnt);
533 if (retcode < 0)
534 goto fail0;
535 /* create new RDN */
536 rdn = PyList_New(0);
537 if (rdn == NULL)
538 goto fail0;
539 }
540 }
541 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 /* now add this attribute to the current RDN */
544 name = X509_NAME_ENTRY_get_object(entry);
545 value = X509_NAME_ENTRY_get_data(entry);
546 attr = _create_tuple_for_attribute(name, value);
547 /*
548 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
549 entry->set,
550 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
551 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
552 */
553 if (attr == NULL)
554 goto fail1;
555 retcode = PyList_Append(rdn, attr);
556 Py_DECREF(attr);
557 if (retcode < 0)
558 goto fail1;
559 }
560 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100561 if (rdn != NULL) {
562 if (PyList_GET_SIZE(rdn) > 0) {
563 rdnt = PyList_AsTuple(rdn);
564 Py_DECREF(rdn);
565 if (rdnt == NULL)
566 goto fail0;
567 retcode = PyList_Append(dn, rdnt);
568 Py_DECREF(rdnt);
569 if (retcode < 0)
570 goto fail0;
571 }
572 else {
573 Py_DECREF(rdn);
574 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 /* convert list to tuple */
578 rdnt = PyList_AsTuple(dn);
579 Py_DECREF(dn);
580 if (rdnt == NULL)
581 return NULL;
582 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
584 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586
587 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 Py_XDECREF(dn);
589 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590}
591
592static PyObject *
593_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 /* this code follows the procedure outlined in
596 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
597 function to extract the STACK_OF(GENERAL_NAME),
598 then iterates through the stack to add the
599 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000601 int i, j;
602 PyObject *peer_alt_names = Py_None;
603 PyObject *v, *t;
604 X509_EXTENSION *ext = NULL;
605 GENERAL_NAMES *names = NULL;
606 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000607 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 BIO *biobuf = NULL;
609 char buf[2048];
610 char *vptr;
611 int len;
612 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000613#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000615#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000617#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 if (certificate == NULL)
620 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 /* get a memory buffer */
623 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200625 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 while ((i = X509_get_ext_by_NID(
627 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 if (peer_alt_names == Py_None) {
630 peer_alt_names = PyList_New(0);
631 if (peer_alt_names == NULL)
632 goto fail;
633 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 /* now decode the altName */
636 ext = X509_get_ext(certificate, i);
637 if(!(method = X509V3_EXT_get(ext))) {
638 PyErr_SetString
639 (PySSLErrorObject,
640 ERRSTR("No method for internalizing subjectAltName!"));
641 goto fail;
642 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 p = ext->value->data;
645 if (method->it)
646 names = (GENERAL_NAMES*)
647 (ASN1_item_d2i(NULL,
648 &p,
649 ext->value->length,
650 ASN1_ITEM_ptr(method->it)));
651 else
652 names = (GENERAL_NAMES*)
653 (method->d2i(NULL,
654 &p,
655 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 name = sk_GENERAL_NAME_value(names, j);
662 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 /* we special-case DirName as a tuple of
665 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 t = PyTuple_New(2);
668 if (t == NULL) {
669 goto fail;
670 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 v = PyUnicode_FromString("DirName");
673 if (v == NULL) {
674 Py_DECREF(t);
675 goto fail;
676 }
677 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 v = _create_tuple_for_X509_NAME (name->d.dirn);
680 if (v == NULL) {
681 Py_DECREF(t);
682 goto fail;
683 }
684 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 (void) BIO_reset(biobuf);
691 GENERAL_NAME_print(biobuf, name);
692 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
693 if (len < 0) {
694 _setSSLError(NULL, 0, __FILE__, __LINE__);
695 goto fail;
696 }
697 vptr = strchr(buf, ':');
698 if (vptr == NULL)
699 goto fail;
700 t = PyTuple_New(2);
701 if (t == NULL)
702 goto fail;
703 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
704 if (v == NULL) {
705 Py_DECREF(t);
706 goto fail;
707 }
708 PyTuple_SET_ITEM(t, 0, v);
709 v = PyUnicode_FromStringAndSize((vptr + 1),
710 (len - (vptr - buf + 1)));
711 if (v == NULL) {
712 Py_DECREF(t);
713 goto fail;
714 }
715 PyTuple_SET_ITEM(t, 1, v);
716 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 if (PyList_Append(peer_alt_names, t) < 0) {
721 Py_DECREF(t);
722 goto fail;
723 }
724 Py_DECREF(t);
725 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100726 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 }
728 BIO_free(biobuf);
729 if (peer_alt_names != Py_None) {
730 v = PyList_AsTuple(peer_alt_names);
731 Py_DECREF(peer_alt_names);
732 return v;
733 } else {
734 return peer_alt_names;
735 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000736
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
738 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 if (biobuf != NULL)
740 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 if (peer_alt_names != Py_None) {
743 Py_XDECREF(peer_alt_names);
744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747}
748
749static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000750_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 PyObject *retval = NULL;
753 BIO *biobuf = NULL;
754 PyObject *peer;
755 PyObject *peer_alt_names = NULL;
756 PyObject *issuer;
757 PyObject *version;
758 PyObject *sn_obj;
759 ASN1_INTEGER *serialNumber;
760 char buf[2048];
761 int len;
762 ASN1_TIME *notBefore, *notAfter;
763 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 retval = PyDict_New();
766 if (retval == NULL)
767 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 peer = _create_tuple_for_X509_NAME(
770 X509_get_subject_name(certificate));
771 if (peer == NULL)
772 goto fail0;
773 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
774 Py_DECREF(peer);
775 goto fail0;
776 }
777 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000778
Antoine Pitroufb046912010-11-09 20:21:19 +0000779 issuer = _create_tuple_for_X509_NAME(
780 X509_get_issuer_name(certificate));
781 if (issuer == NULL)
782 goto fail0;
783 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000785 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000787 Py_DECREF(issuer);
788
789 version = PyLong_FromLong(X509_get_version(certificate) + 1);
790 if (PyDict_SetItemString(retval, "version", version) < 0) {
791 Py_DECREF(version);
792 goto fail0;
793 }
794 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 /* get a memory buffer */
797 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000798
Antoine Pitroufb046912010-11-09 20:21:19 +0000799 (void) BIO_reset(biobuf);
800 serialNumber = X509_get_serialNumber(certificate);
801 /* should not exceed 20 octets, 160 bits, so buf is big enough */
802 i2a_ASN1_INTEGER(biobuf, serialNumber);
803 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
804 if (len < 0) {
805 _setSSLError(NULL, 0, __FILE__, __LINE__);
806 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000808 sn_obj = PyUnicode_FromStringAndSize(buf, len);
809 if (sn_obj == NULL)
810 goto fail1;
811 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
812 Py_DECREF(sn_obj);
813 goto fail1;
814 }
815 Py_DECREF(sn_obj);
816
817 (void) BIO_reset(biobuf);
818 notBefore = X509_get_notBefore(certificate);
819 ASN1_TIME_print(biobuf, notBefore);
820 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
821 if (len < 0) {
822 _setSSLError(NULL, 0, __FILE__, __LINE__);
823 goto fail1;
824 }
825 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
826 if (pnotBefore == NULL)
827 goto fail1;
828 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
829 Py_DECREF(pnotBefore);
830 goto fail1;
831 }
832 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 (void) BIO_reset(biobuf);
835 notAfter = X509_get_notAfter(certificate);
836 ASN1_TIME_print(biobuf, notAfter);
837 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
838 if (len < 0) {
839 _setSSLError(NULL, 0, __FILE__, __LINE__);
840 goto fail1;
841 }
842 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
843 if (pnotAfter == NULL)
844 goto fail1;
845 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
846 Py_DECREF(pnotAfter);
847 goto fail1;
848 }
849 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000852
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 peer_alt_names = _get_peer_alt_names(certificate);
854 if (peer_alt_names == NULL)
855 goto fail1;
856 else if (peer_alt_names != Py_None) {
857 if (PyDict_SetItemString(retval, "subjectAltName",
858 peer_alt_names) < 0) {
859 Py_DECREF(peer_alt_names);
860 goto fail1;
861 }
862 Py_DECREF(peer_alt_names);
863 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 BIO_free(biobuf);
866 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000867
868 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 if (biobuf != NULL)
870 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000871 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 Py_XDECREF(retval);
873 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000874}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000875
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
877static PyObject *
878PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000881 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 X509 *x=NULL;
883 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroufb046912010-11-09 20:21:19 +0000885 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
886 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 if ((cert=BIO_new(BIO_s_file())) == NULL) {
890 PyErr_SetString(PySSLErrorObject,
891 "Can't malloc memory to read file");
892 goto fail0;
893 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Victor Stinner3800e1e2010-05-16 21:23:48 +0000895 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 PyErr_SetString(PySSLErrorObject,
897 "Can't open file");
898 goto fail0;
899 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
902 if (x == NULL) {
903 PyErr_SetString(PySSLErrorObject,
904 "Error decoding PEM-encoded file");
905 goto fail0;
906 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroufb046912010-11-09 20:21:19 +0000908 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000909 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000910
911 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000912 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 if (cert != NULL) BIO_free(cert);
914 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915}
916
917
918static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000919PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 PyObject *retval = NULL;
922 int len;
923 int verification;
924 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
927 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 if (!self->peer_cert)
930 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 if (PyObject_IsTrue(binary_mode)) {
933 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 bytes_buf = NULL;
938 len = i2d_X509(self->peer_cert, &bytes_buf);
939 if (len < 0) {
940 PySSL_SetError(self, len, __FILE__, __LINE__);
941 return NULL;
942 }
943 /* this is actually an immutable bytes sequence */
944 retval = PyBytes_FromStringAndSize
945 ((const char *) bytes_buf, len);
946 OPENSSL_free(bytes_buf);
947 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000950 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 if ((verification & SSL_VERIFY_PEER) == 0)
952 return PyDict_New();
953 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000954 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956}
957
958PyDoc_STRVAR(PySSL_peercert_doc,
959"peer_certificate([der=False]) -> certificate\n\
960\n\
961Returns the certificate for the peer. If no certificate was provided,\n\
962returns None. If a certificate was provided, but not validated, returns\n\
963an empty dictionary. Otherwise returns a dict containing information\n\
964about the peer certificate.\n\
965\n\
966If the optional argument is True, returns a DER-encoded copy of the\n\
967peer certificate, or None if no certificate was provided. This will\n\
968return the certificate even if it wasn't validated.");
969
Antoine Pitrou152efa22010-05-16 18:19:27 +0000970static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000973 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 char *cipher_name;
975 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000978 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 current = SSL_get_current_cipher(self->ssl);
980 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000981 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 retval = PyTuple_New(3);
984 if (retval == NULL)
985 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 cipher_name = (char *) SSL_CIPHER_get_name(current);
988 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000989 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 PyTuple_SET_ITEM(retval, 0, Py_None);
991 } else {
992 v = PyUnicode_FromString(cipher_name);
993 if (v == NULL)
994 goto fail0;
995 PyTuple_SET_ITEM(retval, 0, v);
996 }
997 cipher_protocol = SSL_CIPHER_get_version(current);
998 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000999 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 PyTuple_SET_ITEM(retval, 1, Py_None);
1001 } else {
1002 v = PyUnicode_FromString(cipher_protocol);
1003 if (v == NULL)
1004 goto fail0;
1005 PyTuple_SET_ITEM(retval, 1, v);
1006 }
1007 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1008 if (v == NULL)
1009 goto fail0;
1010 PyTuple_SET_ITEM(retval, 2, v);
1011 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001012
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001013 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 Py_DECREF(retval);
1015 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001016}
1017
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001018static PyObject *PySSL_compression(PySSLSocket *self) {
1019#ifdef OPENSSL_NO_COMP
1020 Py_RETURN_NONE;
1021#else
1022 const COMP_METHOD *comp_method;
1023 const char *short_name;
1024
1025 if (self->ssl == NULL)
1026 Py_RETURN_NONE;
1027 comp_method = SSL_get_current_compression(self->ssl);
1028 if (comp_method == NULL || comp_method->type == NID_undef)
1029 Py_RETURN_NONE;
1030 short_name = OBJ_nid2sn(comp_method->type);
1031 if (short_name == NULL)
1032 Py_RETURN_NONE;
1033 return PyUnicode_DecodeFSDefault(short_name);
1034#endif
1035}
1036
Antoine Pitrou152efa22010-05-16 18:19:27 +00001037static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001038{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 if (self->peer_cert) /* Possible not to have one? */
1040 X509_free (self->peer_cert);
1041 if (self->ssl)
1042 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 Py_XDECREF(self->Socket);
1044 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001045}
1046
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001047/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001048 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001049 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001050 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001051
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001052static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001053check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001054{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 fd_set fds;
1056 struct timeval tv;
1057 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1060 if (s->sock_timeout < 0.0)
1061 return SOCKET_IS_BLOCKING;
1062 else if (s->sock_timeout == 0.0)
1063 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 /* Guard against closed socket */
1066 if (s->sock_fd < 0)
1067 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 /* Prefer poll, if available, since you can poll() any fd
1070 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001071#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 {
1073 struct pollfd pollfd;
1074 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 pollfd.fd = s->sock_fd;
1077 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 /* s->sock_timeout is in seconds, timeout in ms */
1080 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1081 PySSL_BEGIN_ALLOW_THREADS
1082 rc = poll(&pollfd, 1, timeout);
1083 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 goto normal_return;
1086 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001087#endif
1088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001090 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 /* Construct the arguments to select */
1094 tv.tv_sec = (int)s->sock_timeout;
1095 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1096 FD_ZERO(&fds);
1097 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001098
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 /* See if the socket is ready */
1100 PySSL_BEGIN_ALLOW_THREADS
1101 if (writing)
1102 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1103 else
1104 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1105 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001106
Bill Janssen6e027db2007-11-15 22:23:56 +00001107#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001108normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001109#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1111 (when we are able to write or when there's something to read) */
1112 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001113}
1114
Antoine Pitrou152efa22010-05-16 18:19:27 +00001115static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001116{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 Py_buffer buf;
1118 int len;
1119 int sockstate;
1120 int err;
1121 int nonblocking;
1122 PySocketSockObject *sock
1123 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 if (((PyObject*)sock) == Py_None) {
1126 _setSSLError("Underlying socket connection gone",
1127 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1128 return NULL;
1129 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001130 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001132 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1133 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001135 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136
1137 /* just in case the blocking state of the socket has been changed */
1138 nonblocking = (sock->sock_timeout >= 0.0);
1139 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1140 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1141
1142 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1143 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001144 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 "The write operation timed out");
1146 goto error;
1147 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1148 PyErr_SetString(PySSLErrorObject,
1149 "Underlying socket has been closed.");
1150 goto error;
1151 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1152 PyErr_SetString(PySSLErrorObject,
1153 "Underlying socket too large for select().");
1154 goto error;
1155 }
1156 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 PySSL_BEGIN_ALLOW_THREADS
1158 len = SSL_write(self->ssl, buf.buf, buf.len);
1159 err = SSL_get_error(self->ssl, len);
1160 PySSL_END_ALLOW_THREADS
1161 if (PyErr_CheckSignals()) {
1162 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001163 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001165 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001167 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 } else {
1169 sockstate = SOCKET_OPERATION_OK;
1170 }
1171 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001172 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 "The write operation timed out");
1174 goto error;
1175 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1176 PyErr_SetString(PySSLErrorObject,
1177 "Underlying socket has been closed.");
1178 goto error;
1179 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1180 break;
1181 }
1182 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001183
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001184 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 PyBuffer_Release(&buf);
1186 if (len > 0)
1187 return PyLong_FromLong(len);
1188 else
1189 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001190
1191error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001192 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 PyBuffer_Release(&buf);
1194 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001195}
1196
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001197PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001198"write(s) -> len\n\
1199\n\
1200Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001201of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001202
Antoine Pitrou152efa22010-05-16 18:19:27 +00001203static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001204{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 PySSL_BEGIN_ALLOW_THREADS
1208 count = SSL_pending(self->ssl);
1209 PySSL_END_ALLOW_THREADS
1210 if (count < 0)
1211 return PySSL_SetError(self, count, __FILE__, __LINE__);
1212 else
1213 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001214}
1215
1216PyDoc_STRVAR(PySSL_SSLpending_doc,
1217"pending() -> count\n\
1218\n\
1219Returns the number of already decrypted bytes available for read,\n\
1220pending on the connection.\n");
1221
Antoine Pitrou152efa22010-05-16 18:19:27 +00001222static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001223{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 PyObject *dest = NULL;
1225 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001227 int len, count;
1228 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 int sockstate;
1230 int err;
1231 int nonblocking;
1232 PySocketSockObject *sock
1233 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 if (((PyObject*)sock) == Py_None) {
1236 _setSSLError("Underlying socket connection gone",
1237 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1238 return NULL;
1239 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001240 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001242 buf.obj = NULL;
1243 buf.buf = NULL;
1244 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001245 goto error;
1246
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001247 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1248 dest = PyBytes_FromStringAndSize(NULL, len);
1249 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001250 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001251 mem = PyBytes_AS_STRING(dest);
1252 }
1253 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001255 mem = buf.buf;
1256 if (len <= 0 || len > buf.len) {
1257 len = (int) buf.len;
1258 if (buf.len != len) {
1259 PyErr_SetString(PyExc_OverflowError,
1260 "maximum length can't fit in a C 'int'");
1261 goto error;
1262 }
1263 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 }
1265
1266 /* just in case the blocking state of the socket has been changed */
1267 nonblocking = (sock->sock_timeout >= 0.0);
1268 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1269 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1270
1271 /* first check if there are bytes ready to be read */
1272 PySSL_BEGIN_ALLOW_THREADS
1273 count = SSL_pending(self->ssl);
1274 PySSL_END_ALLOW_THREADS
1275
1276 if (!count) {
1277 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1278 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001279 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 "The read operation timed out");
1281 goto error;
1282 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1283 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001284 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 goto error;
1286 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1287 count = 0;
1288 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001289 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 }
1291 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 PySSL_BEGIN_ALLOW_THREADS
1293 count = SSL_read(self->ssl, mem, len);
1294 err = SSL_get_error(self->ssl, count);
1295 PySSL_END_ALLOW_THREADS
1296 if (PyErr_CheckSignals())
1297 goto error;
1298 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001299 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001301 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1303 (SSL_get_shutdown(self->ssl) ==
1304 SSL_RECEIVED_SHUTDOWN))
1305 {
1306 count = 0;
1307 goto done;
1308 } else {
1309 sockstate = SOCKET_OPERATION_OK;
1310 }
1311 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001312 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 "The read operation timed out");
1314 goto error;
1315 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1316 break;
1317 }
1318 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1319 if (count <= 0) {
1320 PySSL_SetError(self, count, __FILE__, __LINE__);
1321 goto error;
1322 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001323
1324done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001325 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001327 _PyBytes_Resize(&dest, count);
1328 return dest;
1329 }
1330 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 PyBuffer_Release(&buf);
1332 return PyLong_FromLong(count);
1333 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001334
1335error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001336 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001337 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001338 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001339 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001342}
1343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001344PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001345"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001346\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001347Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001348
Antoine Pitrou152efa22010-05-16 18:19:27 +00001349static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001350{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 int err, ssl_err, sockstate, nonblocking;
1352 int zeros = 0;
1353 PySocketSockObject *sock
1354 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 /* Guard against closed socket */
1357 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1358 _setSSLError("Underlying socket connection gone",
1359 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1360 return NULL;
1361 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001362 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363
1364 /* Just in case the blocking state of the socket has been changed */
1365 nonblocking = (sock->sock_timeout >= 0.0);
1366 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1367 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1368
1369 while (1) {
1370 PySSL_BEGIN_ALLOW_THREADS
1371 /* Disable read-ahead so that unwrap can work correctly.
1372 * Otherwise OpenSSL might read in too much data,
1373 * eating clear text data that happens to be
1374 * transmitted after the SSL shutdown.
1375 * Should be safe to call repeatedly everytime this
1376 * function is used and the shutdown_seen_zero != 0
1377 * condition is met.
1378 */
1379 if (self->shutdown_seen_zero)
1380 SSL_set_read_ahead(self->ssl, 0);
1381 err = SSL_shutdown(self->ssl);
1382 PySSL_END_ALLOW_THREADS
1383 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1384 if (err > 0)
1385 break;
1386 if (err == 0) {
1387 /* Don't loop endlessly; instead preserve legacy
1388 behaviour of trying SSL_shutdown() only twice.
1389 This looks necessary for OpenSSL < 0.9.8m */
1390 if (++zeros > 1)
1391 break;
1392 /* Shutdown was sent, now try receiving */
1393 self->shutdown_seen_zero = 1;
1394 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001395 }
1396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 /* Possibly retry shutdown until timeout or failure */
1398 ssl_err = SSL_get_error(self->ssl, err);
1399 if (ssl_err == SSL_ERROR_WANT_READ)
1400 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1401 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1402 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1403 else
1404 break;
1405 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1406 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001407 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 "The read operation timed out");
1409 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001410 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001412 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 }
1414 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1415 PyErr_SetString(PySSLErrorObject,
1416 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001417 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 }
1419 else if (sockstate != SOCKET_OPERATION_OK)
1420 /* Retain the SSL error code */
1421 break;
1422 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001423
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001424 if (err < 0) {
1425 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001428 else
1429 /* It's already INCREF'ed */
1430 return (PyObject *) sock;
1431
1432error:
1433 Py_DECREF(sock);
1434 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001435}
1436
1437PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1438"shutdown(s) -> socket\n\
1439\n\
1440Does the SSL shutdown handshake with the remote end, and returns\n\
1441the underlying socket object.");
1442
Antoine Pitroud6494802011-07-21 01:11:30 +02001443#if HAVE_OPENSSL_FINISHED
1444static PyObject *
1445PySSL_tls_unique_cb(PySSLSocket *self)
1446{
1447 PyObject *retval = NULL;
1448 char buf[PySSL_CB_MAXLEN];
1449 int len;
1450
1451 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1452 /* if session is resumed XOR we are the client */
1453 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1454 }
1455 else {
1456 /* if a new session XOR we are the server */
1457 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1458 }
1459
1460 /* It cannot be negative in current OpenSSL version as of July 2011 */
1461 assert(len >= 0);
1462 if (len == 0)
1463 Py_RETURN_NONE;
1464
1465 retval = PyBytes_FromStringAndSize(buf, len);
1466
1467 return retval;
1468}
1469
1470PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1471"tls_unique_cb() -> bytes\n\
1472\n\
1473Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1474\n\
1475If the TLS handshake is not yet complete, None is returned");
1476
1477#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001478
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1481 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1482 PySSL_SSLwrite_doc},
1483 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1484 PySSL_SSLread_doc},
1485 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1486 PySSL_SSLpending_doc},
1487 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1488 PySSL_peercert_doc},
1489 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001490 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1492 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001493#if HAVE_OPENSSL_FINISHED
1494 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1495 PySSL_tls_unique_cb_doc},
1496#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001498};
1499
Antoine Pitrou152efa22010-05-16 18:19:27 +00001500static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001502 "_ssl._SSLSocket", /*tp_name*/
1503 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 0, /*tp_itemsize*/
1505 /* methods */
1506 (destructor)PySSL_dealloc, /*tp_dealloc*/
1507 0, /*tp_print*/
1508 0, /*tp_getattr*/
1509 0, /*tp_setattr*/
1510 0, /*tp_reserved*/
1511 0, /*tp_repr*/
1512 0, /*tp_as_number*/
1513 0, /*tp_as_sequence*/
1514 0, /*tp_as_mapping*/
1515 0, /*tp_hash*/
1516 0, /*tp_call*/
1517 0, /*tp_str*/
1518 0, /*tp_getattro*/
1519 0, /*tp_setattro*/
1520 0, /*tp_as_buffer*/
1521 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1522 0, /*tp_doc*/
1523 0, /*tp_traverse*/
1524 0, /*tp_clear*/
1525 0, /*tp_richcompare*/
1526 0, /*tp_weaklistoffset*/
1527 0, /*tp_iter*/
1528 0, /*tp_iternext*/
1529 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001530};
1531
Antoine Pitrou152efa22010-05-16 18:19:27 +00001532
1533/*
1534 * _SSLContext objects
1535 */
1536
1537static PyObject *
1538context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1539{
1540 char *kwlist[] = {"protocol", NULL};
1541 PySSLContext *self;
1542 int proto_version = PY_SSL_VERSION_SSL23;
1543 SSL_CTX *ctx = NULL;
1544
1545 if (!PyArg_ParseTupleAndKeywords(
1546 args, kwds, "i:_SSLContext", kwlist,
1547 &proto_version))
1548 return NULL;
1549
1550 PySSL_BEGIN_ALLOW_THREADS
1551 if (proto_version == PY_SSL_VERSION_TLS1)
1552 ctx = SSL_CTX_new(TLSv1_method());
1553 else if (proto_version == PY_SSL_VERSION_SSL3)
1554 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001555#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001556 else if (proto_version == PY_SSL_VERSION_SSL2)
1557 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001558#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001559 else if (proto_version == PY_SSL_VERSION_SSL23)
1560 ctx = SSL_CTX_new(SSLv23_method());
1561 else
1562 proto_version = -1;
1563 PySSL_END_ALLOW_THREADS
1564
1565 if (proto_version == -1) {
1566 PyErr_SetString(PyExc_ValueError,
1567 "invalid protocol version");
1568 return NULL;
1569 }
1570 if (ctx == NULL) {
1571 PyErr_SetString(PySSLErrorObject,
1572 "failed to allocate SSL context");
1573 return NULL;
1574 }
1575
1576 assert(type != NULL && type->tp_alloc != NULL);
1577 self = (PySSLContext *) type->tp_alloc(type, 0);
1578 if (self == NULL) {
1579 SSL_CTX_free(ctx);
1580 return NULL;
1581 }
1582 self->ctx = ctx;
1583 /* Defaults */
1584 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001585 SSL_CTX_set_options(self->ctx,
1586 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001587
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001588#define SID_CTX "Python"
1589 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1590 sizeof(SID_CTX));
1591#undef SID_CTX
1592
Antoine Pitrou152efa22010-05-16 18:19:27 +00001593 return (PyObject *)self;
1594}
1595
1596static void
1597context_dealloc(PySSLContext *self)
1598{
1599 SSL_CTX_free(self->ctx);
1600 Py_TYPE(self)->tp_free(self);
1601}
1602
1603static PyObject *
1604set_ciphers(PySSLContext *self, PyObject *args)
1605{
1606 int ret;
1607 const char *cipherlist;
1608
1609 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1610 return NULL;
1611 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1612 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001613 /* Clearing the error queue is necessary on some OpenSSL versions,
1614 otherwise the error will be reported again when another SSL call
1615 is done. */
1616 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001617 PyErr_SetString(PySSLErrorObject,
1618 "No cipher can be selected.");
1619 return NULL;
1620 }
1621 Py_RETURN_NONE;
1622}
1623
1624static PyObject *
1625get_verify_mode(PySSLContext *self, void *c)
1626{
1627 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1628 case SSL_VERIFY_NONE:
1629 return PyLong_FromLong(PY_SSL_CERT_NONE);
1630 case SSL_VERIFY_PEER:
1631 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1632 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1633 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1634 }
1635 PyErr_SetString(PySSLErrorObject,
1636 "invalid return value from SSL_CTX_get_verify_mode");
1637 return NULL;
1638}
1639
1640static int
1641set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1642{
1643 int n, mode;
1644 if (!PyArg_Parse(arg, "i", &n))
1645 return -1;
1646 if (n == PY_SSL_CERT_NONE)
1647 mode = SSL_VERIFY_NONE;
1648 else if (n == PY_SSL_CERT_OPTIONAL)
1649 mode = SSL_VERIFY_PEER;
1650 else if (n == PY_SSL_CERT_REQUIRED)
1651 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1652 else {
1653 PyErr_SetString(PyExc_ValueError,
1654 "invalid value for verify_mode");
1655 return -1;
1656 }
1657 SSL_CTX_set_verify(self->ctx, mode, NULL);
1658 return 0;
1659}
1660
1661static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001662get_options(PySSLContext *self, void *c)
1663{
1664 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1665}
1666
1667static int
1668set_options(PySSLContext *self, PyObject *arg, void *c)
1669{
1670 long new_opts, opts, set, clear;
1671 if (!PyArg_Parse(arg, "l", &new_opts))
1672 return -1;
1673 opts = SSL_CTX_get_options(self->ctx);
1674 clear = opts & ~new_opts;
1675 set = ~opts & new_opts;
1676 if (clear) {
1677#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1678 SSL_CTX_clear_options(self->ctx, clear);
1679#else
1680 PyErr_SetString(PyExc_ValueError,
1681 "can't clear options before OpenSSL 0.9.8m");
1682 return -1;
1683#endif
1684 }
1685 if (set)
1686 SSL_CTX_set_options(self->ctx, set);
1687 return 0;
1688}
1689
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001690typedef struct {
1691 PyThreadState *thread_state;
1692 PyObject *callable;
1693 char *password;
1694 Py_ssize_t size;
1695 int error;
1696} _PySSLPasswordInfo;
1697
1698static int
1699_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1700 const char *bad_type_error)
1701{
1702 /* Set the password and size fields of a _PySSLPasswordInfo struct
1703 from a unicode, bytes, or byte array object.
1704 The password field will be dynamically allocated and must be freed
1705 by the caller */
1706 PyObject *password_bytes = NULL;
1707 const char *data = NULL;
1708 Py_ssize_t size;
1709
1710 if (PyUnicode_Check(password)) {
1711 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1712 if (!password_bytes) {
1713 goto error;
1714 }
1715 data = PyBytes_AS_STRING(password_bytes);
1716 size = PyBytes_GET_SIZE(password_bytes);
1717 } else if (PyBytes_Check(password)) {
1718 data = PyBytes_AS_STRING(password);
1719 size = PyBytes_GET_SIZE(password);
1720 } else if (PyByteArray_Check(password)) {
1721 data = PyByteArray_AS_STRING(password);
1722 size = PyByteArray_GET_SIZE(password);
1723 } else {
1724 PyErr_SetString(PyExc_TypeError, bad_type_error);
1725 goto error;
1726 }
1727
1728 free(pw_info->password);
1729 pw_info->password = malloc(size);
1730 if (!pw_info->password) {
1731 PyErr_SetString(PyExc_MemoryError,
1732 "unable to allocate password buffer");
1733 goto error;
1734 }
1735 memcpy(pw_info->password, data, size);
1736 pw_info->size = size;
1737
1738 Py_XDECREF(password_bytes);
1739 return 1;
1740
1741error:
1742 Py_XDECREF(password_bytes);
1743 return 0;
1744}
1745
1746static int
1747_password_callback(char *buf, int size, int rwflag, void *userdata)
1748{
1749 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1750 PyObject *fn_ret = NULL;
1751
1752 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1753
1754 if (pw_info->callable) {
1755 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1756 if (!fn_ret) {
1757 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1758 core python API, so we could use it to add a frame here */
1759 goto error;
1760 }
1761
1762 if (!_pwinfo_set(pw_info, fn_ret,
1763 "password callback must return a string")) {
1764 goto error;
1765 }
1766 Py_CLEAR(fn_ret);
1767 }
1768
1769 if (pw_info->size > size) {
1770 PyErr_Format(PyExc_ValueError,
1771 "password cannot be longer than %d bytes", size);
1772 goto error;
1773 }
1774
1775 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1776 memcpy(buf, pw_info->password, pw_info->size);
1777 return pw_info->size;
1778
1779error:
1780 Py_XDECREF(fn_ret);
1781 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1782 pw_info->error = 1;
1783 return -1;
1784}
1785
Antoine Pitroub5218772010-05-21 09:56:06 +00001786static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001787load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1788{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001789 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1790 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001792 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1793 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1794 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001795 int r;
1796
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001797 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001798 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001799 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001800 "O|OO:load_cert_chain", kwlist,
1801 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802 return NULL;
1803 if (keyfile == Py_None)
1804 keyfile = NULL;
1805 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1806 PyErr_SetString(PyExc_TypeError,
1807 "certfile should be a valid filesystem path");
1808 return NULL;
1809 }
1810 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1811 PyErr_SetString(PyExc_TypeError,
1812 "keyfile should be a valid filesystem path");
1813 goto error;
1814 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001815 if (password && password != Py_None) {
1816 if (PyCallable_Check(password)) {
1817 pw_info.callable = password;
1818 } else if (!_pwinfo_set(&pw_info, password,
1819 "password should be a string or callable")) {
1820 goto error;
1821 }
1822 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1823 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1824 }
1825 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001826 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1827 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001828 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001829 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001830 if (pw_info.error) {
1831 ERR_clear_error();
1832 /* the password callback has already set the error information */
1833 }
1834 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001835 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001836 PyErr_SetFromErrno(PyExc_IOError);
1837 }
1838 else {
1839 _setSSLError(NULL, 0, __FILE__, __LINE__);
1840 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001841 goto error;
1842 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001843 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001844 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001845 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1846 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001847 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1848 Py_CLEAR(keyfile_bytes);
1849 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001850 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001851 if (pw_info.error) {
1852 ERR_clear_error();
1853 /* the password callback has already set the error information */
1854 }
1855 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001856 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001857 PyErr_SetFromErrno(PyExc_IOError);
1858 }
1859 else {
1860 _setSSLError(NULL, 0, __FILE__, __LINE__);
1861 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001862 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001863 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001864 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001865 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001866 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001867 if (r != 1) {
1868 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001869 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001870 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001871 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1872 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1873 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001874 Py_RETURN_NONE;
1875
1876error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001877 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1878 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1879 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001880 Py_XDECREF(keyfile_bytes);
1881 Py_XDECREF(certfile_bytes);
1882 return NULL;
1883}
1884
1885static PyObject *
1886load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1887{
1888 char *kwlist[] = {"cafile", "capath", NULL};
1889 PyObject *cafile = NULL, *capath = NULL;
1890 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1891 const char *cafile_buf = NULL, *capath_buf = NULL;
1892 int r;
1893
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001894 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001895 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1896 "|OO:load_verify_locations", kwlist,
1897 &cafile, &capath))
1898 return NULL;
1899 if (cafile == Py_None)
1900 cafile = NULL;
1901 if (capath == Py_None)
1902 capath = NULL;
1903 if (cafile == NULL && capath == NULL) {
1904 PyErr_SetString(PyExc_TypeError,
1905 "cafile and capath cannot be both omitted");
1906 return NULL;
1907 }
1908 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1909 PyErr_SetString(PyExc_TypeError,
1910 "cafile should be a valid filesystem path");
1911 return NULL;
1912 }
1913 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001914 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915 PyErr_SetString(PyExc_TypeError,
1916 "capath should be a valid filesystem path");
1917 return NULL;
1918 }
1919 if (cafile)
1920 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1921 if (capath)
1922 capath_buf = PyBytes_AS_STRING(capath_bytes);
1923 PySSL_BEGIN_ALLOW_THREADS
1924 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1925 PySSL_END_ALLOW_THREADS
1926 Py_XDECREF(cafile_bytes);
1927 Py_XDECREF(capath_bytes);
1928 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001929 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001930 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001931 PyErr_SetFromErrno(PyExc_IOError);
1932 }
1933 else {
1934 _setSSLError(NULL, 0, __FILE__, __LINE__);
1935 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001936 return NULL;
1937 }
1938 Py_RETURN_NONE;
1939}
1940
1941static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001942load_dh_params(PySSLContext *self, PyObject *filepath)
1943{
1944 FILE *f;
1945 DH *dh;
1946
1947 f = _Py_fopen(filepath, "rb");
1948 if (f == NULL) {
1949 if (!PyErr_Occurred())
1950 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1951 return NULL;
1952 }
1953 errno = 0;
1954 PySSL_BEGIN_ALLOW_THREADS
1955 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
1956 PySSL_END_ALLOW_THREADS
1957 if (dh == NULL) {
1958 if (errno != 0) {
1959 ERR_clear_error();
1960 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1961 }
1962 else {
1963 _setSSLError(NULL, 0, __FILE__, __LINE__);
1964 }
1965 return NULL;
1966 }
1967 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
1968 _setSSLError(NULL, 0, __FILE__, __LINE__);
1969 DH_free(dh);
1970 Py_RETURN_NONE;
1971}
1972
1973static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001974context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1975{
Antoine Pitroud5323212010-10-22 18:19:07 +00001976 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001977 PySocketSockObject *sock;
1978 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001979 char *hostname = NULL;
1980 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001981
Antoine Pitroud5323212010-10-22 18:19:07 +00001982 /* server_hostname is either None (or absent), or to be encoded
1983 using the idna encoding. */
1984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001985 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001986 &sock, &server_side,
1987 Py_TYPE(Py_None), &hostname_obj)) {
1988 PyErr_Clear();
1989 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1990 PySocketModule.Sock_Type,
1991 &sock, &server_side,
1992 "idna", &hostname))
1993 return NULL;
1994#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1995 PyMem_Free(hostname);
1996 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1997 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001998 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001999#endif
2000 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002001
Antoine Pitroud5323212010-10-22 18:19:07 +00002002 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2003 hostname);
2004 if (hostname != NULL)
2005 PyMem_Free(hostname);
2006 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002007}
2008
Antoine Pitroub0182c82010-10-12 20:09:02 +00002009static PyObject *
2010session_stats(PySSLContext *self, PyObject *unused)
2011{
2012 int r;
2013 PyObject *value, *stats = PyDict_New();
2014 if (!stats)
2015 return NULL;
2016
2017#define ADD_STATS(SSL_NAME, KEY_NAME) \
2018 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2019 if (value == NULL) \
2020 goto error; \
2021 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2022 Py_DECREF(value); \
2023 if (r < 0) \
2024 goto error;
2025
2026 ADD_STATS(number, "number");
2027 ADD_STATS(connect, "connect");
2028 ADD_STATS(connect_good, "connect_good");
2029 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2030 ADD_STATS(accept, "accept");
2031 ADD_STATS(accept_good, "accept_good");
2032 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2033 ADD_STATS(accept, "accept");
2034 ADD_STATS(hits, "hits");
2035 ADD_STATS(misses, "misses");
2036 ADD_STATS(timeouts, "timeouts");
2037 ADD_STATS(cache_full, "cache_full");
2038
2039#undef ADD_STATS
2040
2041 return stats;
2042
2043error:
2044 Py_DECREF(stats);
2045 return NULL;
2046}
2047
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002048static PyObject *
2049set_default_verify_paths(PySSLContext *self, PyObject *unused)
2050{
2051 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2052 _setSSLError(NULL, 0, __FILE__, __LINE__);
2053 return NULL;
2054 }
2055 Py_RETURN_NONE;
2056}
2057
Antoine Pitrou501da612011-12-21 09:27:41 +01002058#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002059static PyObject *
2060set_ecdh_curve(PySSLContext *self, PyObject *name)
2061{
2062 PyObject *name_bytes;
2063 int nid;
2064 EC_KEY *key;
2065
2066 if (!PyUnicode_FSConverter(name, &name_bytes))
2067 return NULL;
2068 assert(PyBytes_Check(name_bytes));
2069 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2070 Py_DECREF(name_bytes);
2071 if (nid == 0) {
2072 PyErr_Format(PyExc_ValueError,
2073 "unknown elliptic curve name %R", name);
2074 return NULL;
2075 }
2076 key = EC_KEY_new_by_curve_name(nid);
2077 if (key == NULL) {
2078 _setSSLError(NULL, 0, __FILE__, __LINE__);
2079 return NULL;
2080 }
2081 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2082 EC_KEY_free(key);
2083 Py_RETURN_NONE;
2084}
Antoine Pitrou501da612011-12-21 09:27:41 +01002085#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002086
Antoine Pitrou152efa22010-05-16 18:19:27 +00002087static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002088 {"options", (getter) get_options,
2089 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002090 {"verify_mode", (getter) get_verify_mode,
2091 (setter) set_verify_mode, NULL},
2092 {NULL}, /* sentinel */
2093};
2094
2095static struct PyMethodDef context_methods[] = {
2096 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2097 METH_VARARGS | METH_KEYWORDS, NULL},
2098 {"set_ciphers", (PyCFunction) set_ciphers,
2099 METH_VARARGS, NULL},
2100 {"load_cert_chain", (PyCFunction) load_cert_chain,
2101 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002102 {"load_dh_params", (PyCFunction) load_dh_params,
2103 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104 {"load_verify_locations", (PyCFunction) load_verify_locations,
2105 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002106 {"session_stats", (PyCFunction) session_stats,
2107 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002108 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2109 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002110#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002111 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2112 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002113#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002114 {NULL, NULL} /* sentinel */
2115};
2116
2117static PyTypeObject PySSLContext_Type = {
2118 PyVarObject_HEAD_INIT(NULL, 0)
2119 "_ssl._SSLContext", /*tp_name*/
2120 sizeof(PySSLContext), /*tp_basicsize*/
2121 0, /*tp_itemsize*/
2122 (destructor)context_dealloc, /*tp_dealloc*/
2123 0, /*tp_print*/
2124 0, /*tp_getattr*/
2125 0, /*tp_setattr*/
2126 0, /*tp_reserved*/
2127 0, /*tp_repr*/
2128 0, /*tp_as_number*/
2129 0, /*tp_as_sequence*/
2130 0, /*tp_as_mapping*/
2131 0, /*tp_hash*/
2132 0, /*tp_call*/
2133 0, /*tp_str*/
2134 0, /*tp_getattro*/
2135 0, /*tp_setattro*/
2136 0, /*tp_as_buffer*/
2137 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2138 0, /*tp_doc*/
2139 0, /*tp_traverse*/
2140 0, /*tp_clear*/
2141 0, /*tp_richcompare*/
2142 0, /*tp_weaklistoffset*/
2143 0, /*tp_iter*/
2144 0, /*tp_iternext*/
2145 context_methods, /*tp_methods*/
2146 0, /*tp_members*/
2147 context_getsetlist, /*tp_getset*/
2148 0, /*tp_base*/
2149 0, /*tp_dict*/
2150 0, /*tp_descr_get*/
2151 0, /*tp_descr_set*/
2152 0, /*tp_dictoffset*/
2153 0, /*tp_init*/
2154 0, /*tp_alloc*/
2155 context_new, /*tp_new*/
2156};
2157
2158
2159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002160#ifdef HAVE_OPENSSL_RAND
2161
2162/* helper routines for seeding the SSL PRNG */
2163static PyObject *
2164PySSL_RAND_add(PyObject *self, PyObject *args)
2165{
2166 char *buf;
2167 int len;
2168 double entropy;
2169
2170 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002171 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002172 RAND_add(buf, len, entropy);
2173 Py_INCREF(Py_None);
2174 return Py_None;
2175}
2176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002177PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002178"RAND_add(string, entropy)\n\
2179\n\
2180Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002181bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002182
2183static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002184PySSL_RAND(int len, int pseudo)
2185{
2186 int ok;
2187 PyObject *bytes;
2188 unsigned long err;
2189 const char *errstr;
2190 PyObject *v;
2191
2192 bytes = PyBytes_FromStringAndSize(NULL, len);
2193 if (bytes == NULL)
2194 return NULL;
2195 if (pseudo) {
2196 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2197 if (ok == 0 || ok == 1)
2198 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2199 }
2200 else {
2201 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2202 if (ok == 1)
2203 return bytes;
2204 }
2205 Py_DECREF(bytes);
2206
2207 err = ERR_get_error();
2208 errstr = ERR_reason_error_string(err);
2209 v = Py_BuildValue("(ks)", err, errstr);
2210 if (v != NULL) {
2211 PyErr_SetObject(PySSLErrorObject, v);
2212 Py_DECREF(v);
2213 }
2214 return NULL;
2215}
2216
2217static PyObject *
2218PySSL_RAND_bytes(PyObject *self, PyObject *args)
2219{
2220 int len;
2221 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2222 return NULL;
2223 return PySSL_RAND(len, 0);
2224}
2225
2226PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2227"RAND_bytes(n) -> bytes\n\
2228\n\
2229Generate n cryptographically strong pseudo-random bytes.");
2230
2231static PyObject *
2232PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2233{
2234 int len;
2235 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2236 return NULL;
2237 return PySSL_RAND(len, 1);
2238}
2239
2240PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2241"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2242\n\
2243Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2244generated are cryptographically strong.");
2245
2246static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002247PySSL_RAND_status(PyObject *self)
2248{
Christian Heimes217cfd12007-12-02 14:31:20 +00002249 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002250}
2251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002252PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002253"RAND_status() -> 0 or 1\n\
2254\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002255Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2256It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2257using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002258
2259static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002260PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002261{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002262 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002263 int bytes;
2264
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002265 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2266 PyUnicode_FSConverter, &path))
2267 return NULL;
2268
2269 bytes = RAND_egd(PyBytes_AsString(path));
2270 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002271 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002272 PyErr_SetString(PySSLErrorObject,
2273 "EGD connection failed or EGD did not return "
2274 "enough data to seed the PRNG");
2275 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002276 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002277 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002278}
2279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002280PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002281"RAND_egd(path) -> bytes\n\
2282\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002283Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2284Returns number of bytes read. Raises SSLError if connection to EGD\n\
2285fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002286
2287#endif
2288
Bill Janssen40a0f662008-08-12 16:56:25 +00002289
2290
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291/* List of functions exported by this module. */
2292
2293static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 {"_test_decode_cert", PySSL_test_decode_certificate,
2295 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002296#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2298 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002299 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2300 PySSL_RAND_bytes_doc},
2301 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2302 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002303 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 PySSL_RAND_egd_doc},
2305 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2306 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002307#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002309};
2310
2311
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002312#ifdef WITH_THREAD
2313
2314/* an implementation of OpenSSL threading operations in terms
2315 of the Python C thread library */
2316
2317static PyThread_type_lock *_ssl_locks = NULL;
2318
2319static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002321}
2322
Bill Janssen6e027db2007-11-15 22:23:56 +00002323static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 (int mode, int n, const char *file, int line) {
2325 /* this function is needed to perform locking on shared data
2326 structures. (Note that OpenSSL uses a number of global data
2327 structures that will be implicitly shared whenever multiple
2328 threads use OpenSSL.) Multi-threaded applications will
2329 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 locking_function() must be able to handle up to
2332 CRYPTO_num_locks() different mutex locks. It sets the n-th
2333 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 file and line are the file number of the function setting the
2336 lock. They can be useful for debugging.
2337 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 if ((_ssl_locks == NULL) ||
2340 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2341 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 if (mode & CRYPTO_LOCK) {
2344 PyThread_acquire_lock(_ssl_locks[n], 1);
2345 } else {
2346 PyThread_release_lock(_ssl_locks[n]);
2347 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348}
2349
2350static int _setup_ssl_threads(void) {
2351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 if (_ssl_locks == NULL) {
2355 _ssl_locks_count = CRYPTO_num_locks();
2356 _ssl_locks = (PyThread_type_lock *)
2357 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2358 if (_ssl_locks == NULL)
2359 return 0;
2360 memset(_ssl_locks, 0,
2361 sizeof(PyThread_type_lock) * _ssl_locks_count);
2362 for (i = 0; i < _ssl_locks_count; i++) {
2363 _ssl_locks[i] = PyThread_allocate_lock();
2364 if (_ssl_locks[i] == NULL) {
2365 unsigned int j;
2366 for (j = 0; j < i; j++) {
2367 PyThread_free_lock(_ssl_locks[j]);
2368 }
2369 free(_ssl_locks);
2370 return 0;
2371 }
2372 }
2373 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2374 CRYPTO_set_id_callback(_ssl_thread_id_function);
2375 }
2376 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002377}
2378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002379#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002380
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002381PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002382"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002383for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002384
Martin v. Löwis1a214512008-06-11 05:26:20 +00002385
2386static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 PyModuleDef_HEAD_INIT,
2388 "_ssl",
2389 module_doc,
2390 -1,
2391 PySSL_methods,
2392 NULL,
2393 NULL,
2394 NULL,
2395 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002396};
2397
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002398
2399static void
2400parse_openssl_version(unsigned long libver,
2401 unsigned int *major, unsigned int *minor,
2402 unsigned int *fix, unsigned int *patch,
2403 unsigned int *status)
2404{
2405 *status = libver & 0xF;
2406 libver >>= 4;
2407 *patch = libver & 0xFF;
2408 libver >>= 8;
2409 *fix = libver & 0xFF;
2410 libver >>= 8;
2411 *minor = libver & 0xFF;
2412 libver >>= 8;
2413 *major = libver & 0xFF;
2414}
2415
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002416PyDoc_STRVAR(SSLError_doc,
2417"An error occurred in the SSL implementation.");
2418
Antoine Pitrou41032a62011-10-27 23:56:55 +02002419PyDoc_STRVAR(SSLZeroReturnError_doc,
2420"SSL/TLS session closed cleanly.");
2421
2422PyDoc_STRVAR(SSLWantReadError_doc,
2423"Non-blocking SSL socket needs to read more data\n"
2424"before the requested operation can be completed.");
2425
2426PyDoc_STRVAR(SSLWantWriteError_doc,
2427"Non-blocking SSL socket needs to write more data\n"
2428"before the requested operation can be completed.");
2429
2430PyDoc_STRVAR(SSLSyscallError_doc,
2431"System error when attempting SSL operation.");
2432
2433PyDoc_STRVAR(SSLEOFError_doc,
2434"SSL/TLS connection terminated abruptly.");
2435
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002436
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002437PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002438PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002439{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 PyObject *m, *d, *r;
2441 unsigned long libver;
2442 unsigned int major, minor, fix, patch, status;
2443 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002444
Antoine Pitrou152efa22010-05-16 18:19:27 +00002445 if (PyType_Ready(&PySSLContext_Type) < 0)
2446 return NULL;
2447 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 m = PyModule_Create(&_sslmodule);
2451 if (m == NULL)
2452 return NULL;
2453 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 /* Load _socket module and its C API */
2456 socket_api = PySocketModule_ImportModuleAndAPI();
2457 if (!socket_api)
2458 return NULL;
2459 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 /* Init OpenSSL */
2462 SSL_load_error_strings();
2463 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 /* note that this will start threading if not already started */
2466 if (!_setup_ssl_threads()) {
2467 return NULL;
2468 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002469#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002473 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2474 SSLError_doc,
2475 PyExc_OSError,
2476 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 if (PySSLErrorObject == NULL)
2478 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002479 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2480 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2481 PySSLErrorObject, NULL);
2482 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2483 "ssl.SSLWantReadError", SSLWantReadError_doc,
2484 PySSLErrorObject, NULL);
2485 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2486 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2487 PySSLErrorObject, NULL);
2488 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2489 "ssl.SSLSyscallError", SSLSyscallError_doc,
2490 PySSLErrorObject, NULL);
2491 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2492 "ssl.SSLEOFError", SSLEOFError_doc,
2493 PySSLErrorObject, NULL);
2494 if (PySSLZeroReturnErrorObject == NULL
2495 || PySSLWantReadErrorObject == NULL
2496 || PySSLWantWriteErrorObject == NULL
2497 || PySSLSyscallErrorObject == NULL
2498 || PySSLEOFErrorObject == NULL)
2499 return NULL;
2500 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2501 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2502 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2503 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2504 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2505 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002507 if (PyDict_SetItemString(d, "_SSLContext",
2508 (PyObject *)&PySSLContext_Type) != 0)
2509 return NULL;
2510 if (PyDict_SetItemString(d, "_SSLSocket",
2511 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002512 return NULL;
2513 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2514 PY_SSL_ERROR_ZERO_RETURN);
2515 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2516 PY_SSL_ERROR_WANT_READ);
2517 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2518 PY_SSL_ERROR_WANT_WRITE);
2519 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2520 PY_SSL_ERROR_WANT_X509_LOOKUP);
2521 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2522 PY_SSL_ERROR_SYSCALL);
2523 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2524 PY_SSL_ERROR_SSL);
2525 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2526 PY_SSL_ERROR_WANT_CONNECT);
2527 /* non ssl.h errorcodes */
2528 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2529 PY_SSL_ERROR_EOF);
2530 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2531 PY_SSL_ERROR_INVALID_ERROR_CODE);
2532 /* cert requirements */
2533 PyModule_AddIntConstant(m, "CERT_NONE",
2534 PY_SSL_CERT_NONE);
2535 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2536 PY_SSL_CERT_OPTIONAL);
2537 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2538 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002541#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2543 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002544#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2546 PY_SSL_VERSION_SSL3);
2547 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2548 PY_SSL_VERSION_SSL23);
2549 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2550 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002551
Antoine Pitroub5218772010-05-21 09:56:06 +00002552 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002553 PyModule_AddIntConstant(m, "OP_ALL",
2554 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002555 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2556 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2557 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002558 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2559 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002560 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002561#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002562 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002563#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002564#ifdef SSL_OP_NO_COMPRESSION
2565 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2566 SSL_OP_NO_COMPRESSION);
2567#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002568
Antoine Pitroud5323212010-10-22 18:19:07 +00002569#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2570 r = Py_True;
2571#else
2572 r = Py_False;
2573#endif
2574 Py_INCREF(r);
2575 PyModule_AddObject(m, "HAS_SNI", r);
2576
Antoine Pitroud6494802011-07-21 01:11:30 +02002577#if HAVE_OPENSSL_FINISHED
2578 r = Py_True;
2579#else
2580 r = Py_False;
2581#endif
2582 Py_INCREF(r);
2583 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2584
Antoine Pitrou501da612011-12-21 09:27:41 +01002585#ifdef OPENSSL_NO_ECDH
2586 r = Py_False;
2587#else
2588 r = Py_True;
2589#endif
2590 Py_INCREF(r);
2591 PyModule_AddObject(m, "HAS_ECDH", r);
2592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 /* OpenSSL version */
2594 /* SSLeay() gives us the version of the library linked against,
2595 which could be different from the headers version.
2596 */
2597 libver = SSLeay();
2598 r = PyLong_FromUnsignedLong(libver);
2599 if (r == NULL)
2600 return NULL;
2601 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2602 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002603 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2605 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2606 return NULL;
2607 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2608 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2609 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002610
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002611 libver = OPENSSL_VERSION_NUMBER;
2612 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2613 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2614 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2615 return NULL;
2616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002618}