blob: 1a367f2275394af2b93b22d3bfeab6488974fca8 [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"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000022 PyThreadState *_save = NULL; \
23 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000039 /* these mirror ssl.h */
40 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
42 PY_SSL_ERROR_WANT_READ,
43 PY_SSL_ERROR_WANT_WRITE,
44 PY_SSL_ERROR_WANT_X509_LOOKUP,
45 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN,
47 PY_SSL_ERROR_WANT_CONNECT,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
51 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000052};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020066#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000067 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020068#endif
69 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000070 PY_SSL_VERSION_SSL23,
71 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000072};
73
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000074/* Include symbols from _socket module */
75#include "socketmodule.h"
76
Benjamin Petersonb173f782009-05-05 22:31:58 +000077static PySocketModule_APIObject PySocketModule;
78
Thomas Woutersed03b412007-08-28 21:37:11 +000079#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080#include <poll.h>
81#elif defined(HAVE_SYS_POLL_H)
82#include <sys/poll.h>
83#endif
84
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000085/* Include OpenSSL header files */
86#include "openssl/rsa.h"
87#include "openssl/crypto.h"
88#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000089#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090#include "openssl/pem.h"
91#include "openssl/ssl.h"
92#include "openssl/err.h"
93#include "openssl/rand.h"
94
95/* SSL error object */
96static PyObject *PySSLErrorObject;
97
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098#ifdef WITH_THREAD
99
100/* serves as a flag to see whether we've initialized the SSL thread support. */
101/* 0 means no, greater than 0 means yes */
102
103static unsigned int _ssl_locks_count = 0;
104
105#endif /* def WITH_THREAD */
106
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107/* SSL socket object */
108
109#define X509_NAME_MAXLEN 256
110
111/* RAND_* APIs got added to OpenSSL in 0.9.5 */
112#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
113# define HAVE_OPENSSL_RAND 1
114#else
115# undef HAVE_OPENSSL_RAND
116#endif
117
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000118/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
119 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
120 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
121#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000122# define HAVE_SSL_CTX_CLEAR_OPTIONS
123#else
124# undef HAVE_SSL_CTX_CLEAR_OPTIONS
125#endif
126
Antoine Pitroud6494802011-07-21 01:11:30 +0200127/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
128 * older SSL, but let's be safe */
129#define PySSL_CB_MAXLEN 128
130
131/* SSL_get_finished got added to OpenSSL in 0.9.5 */
132#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
133# define HAVE_OPENSSL_FINISHED 1
134#else
135# define HAVE_OPENSSL_FINISHED 0
136#endif
137
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000138typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000140 SSL_CTX *ctx;
141} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000142
Antoine Pitrou152efa22010-05-16 18:19:27 +0000143typedef struct {
144 PyObject_HEAD
145 PyObject *Socket; /* weakref to socket on which we're layered */
146 SSL *ssl;
147 X509 *peer_cert;
148 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200149 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000150} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000151
Antoine Pitrou152efa22010-05-16 18:19:27 +0000152static PyTypeObject PySSLContext_Type;
153static PyTypeObject PySSLSocket_Type;
154
155static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
156static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000157static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000158 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000159static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
160static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161
Antoine Pitrou152efa22010-05-16 18:19:27 +0000162#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
163#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000165typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000166 SOCKET_IS_NONBLOCKING,
167 SOCKET_IS_BLOCKING,
168 SOCKET_HAS_TIMED_OUT,
169 SOCKET_HAS_BEEN_CLOSED,
170 SOCKET_TOO_LARGE_FOR_SELECT,
171 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000172} timeout_state;
173
Thomas Woutersed03b412007-08-28 21:37:11 +0000174/* Wrap error strings with filename and line # */
175#define STRINGIFY1(x) #x
176#define STRINGIFY2(x) STRINGIFY1(x)
177#define ERRSTR1(x,y,z) (x ":" y ": " z)
178#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
179
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000180/* XXX It might be helpful to augment the error message generated
181 below with the name of the SSL function that generated the error.
182 I expect it's obvious most of the time.
183*/
184
185static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000187{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000188 PyObject *v;
189 char buf[2048];
190 char *errstr;
191 int err;
192 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000194 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000196 if (obj->ssl != NULL) {
197 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 switch (err) {
200 case SSL_ERROR_ZERO_RETURN:
201 errstr = "TLS/SSL connection has been closed";
202 p = PY_SSL_ERROR_ZERO_RETURN;
203 break;
204 case SSL_ERROR_WANT_READ:
205 errstr = "The operation did not complete (read)";
206 p = PY_SSL_ERROR_WANT_READ;
207 break;
208 case SSL_ERROR_WANT_WRITE:
209 p = PY_SSL_ERROR_WANT_WRITE;
210 errstr = "The operation did not complete (write)";
211 break;
212 case SSL_ERROR_WANT_X509_LOOKUP:
213 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000214 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 break;
216 case SSL_ERROR_WANT_CONNECT:
217 p = PY_SSL_ERROR_WANT_CONNECT;
218 errstr = "The operation did not complete (connect)";
219 break;
220 case SSL_ERROR_SYSCALL:
221 {
222 unsigned long e = ERR_get_error();
223 if (e == 0) {
224 PySocketSockObject *s
225 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
226 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000227 p = PY_SSL_ERROR_EOF;
228 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000230 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000231 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000232 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000233 v = s->errorhandler();
234 Py_DECREF(s);
235 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000237 p = PY_SSL_ERROR_SYSCALL;
238 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000239 }
240 } else {
241 p = PY_SSL_ERROR_SYSCALL;
242 /* XXX Protected by global interpreter lock */
243 errstr = ERR_error_string(e, NULL);
244 }
245 break;
246 }
247 case SSL_ERROR_SSL:
248 {
249 unsigned long e = ERR_get_error();
250 p = PY_SSL_ERROR_SSL;
251 if (e != 0)
252 /* XXX Protected by global interpreter lock */
253 errstr = ERR_error_string(e, NULL);
254 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000255 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000256 }
257 break;
258 }
259 default:
260 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
261 errstr = "Invalid error code";
262 }
263 } else {
264 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
265 }
266 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000267 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 v = Py_BuildValue("(is)", p, buf);
269 if (v != NULL) {
270 PyErr_SetObject(PySSLErrorObject, v);
271 Py_DECREF(v);
272 }
273 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000274}
275
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000276static PyObject *
277_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000279 char buf[2048];
280 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000282 if (errstr == NULL) {
283 errcode = ERR_peek_last_error();
284 errstr = ERR_error_string(errcode, NULL);
285 }
286 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000287 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000288 v = Py_BuildValue("(is)", errcode, buf);
289 if (v != NULL) {
290 PyErr_SetObject(PySSLErrorObject, v);
291 Py_DECREF(v);
292 }
293 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000294}
295
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296static PySSLSocket *
297newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000298 enum py_ssl_server_or_client socket_type,
299 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000300{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000302
Antoine Pitrou152efa22010-05-16 18:19:27 +0000303 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 if (self == NULL)
305 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000307 self->peer_cert = NULL;
308 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000311 /* Make sure the SSL error state is initialized */
312 (void) ERR_get_state();
313 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000315 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000316 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000317 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000318 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000319#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000321#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000322
Antoine Pitroud5323212010-10-22 18:19:07 +0000323#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
324 if (server_hostname != NULL)
325 SSL_set_tlsext_host_name(self->ssl, server_hostname);
326#endif
327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000328 /* If the socket is in non-blocking mode or timeout mode, set the BIO
329 * to non-blocking mode (blocking is the default)
330 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000331 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000332 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
333 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
334 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 PySSL_BEGIN_ALLOW_THREADS
337 if (socket_type == PY_SSL_CLIENT)
338 SSL_set_connect_state(self->ssl);
339 else
340 SSL_set_accept_state(self->ssl);
341 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000342
Antoine Pitroud6494802011-07-21 01:11:30 +0200343 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000344 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000345 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346}
347
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000348/* SSL object methods */
349
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000351{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 int ret;
353 int err;
354 int sockstate, nonblocking;
355 PySocketSockObject *sock
356 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000358 if (((PyObject*)sock) == Py_None) {
359 _setSSLError("Underlying socket connection gone",
360 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
361 return NULL;
362 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000363 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000365 /* just in case the blocking state of the socket has been changed */
366 nonblocking = (sock->sock_timeout >= 0.0);
367 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
368 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000370 /* Actually negotiate SSL connection */
371 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000373 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 ret = SSL_do_handshake(self->ssl);
375 err = SSL_get_error(self->ssl, ret);
376 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000377 if (PyErr_CheckSignals())
378 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 if (err == SSL_ERROR_WANT_READ) {
380 sockstate = check_socket_and_wait_for_timeout(sock, 0);
381 } else if (err == SSL_ERROR_WANT_WRITE) {
382 sockstate = check_socket_and_wait_for_timeout(sock, 1);
383 } else {
384 sockstate = SOCKET_OPERATION_OK;
385 }
386 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000387 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000388 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000389 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
391 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000392 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000393 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
395 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000396 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000397 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000398 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
399 break;
400 }
401 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000402 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 if (ret < 1)
404 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 if (self->peer_cert)
407 X509_free (self->peer_cert);
408 PySSL_BEGIN_ALLOW_THREADS
409 self->peer_cert = SSL_get_peer_certificate(self->ssl);
410 PySSL_END_ALLOW_THREADS
411
412 Py_INCREF(Py_None);
413 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000414
415error:
416 Py_DECREF(sock);
417 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000418}
419
Thomas Woutersed03b412007-08-28 21:37:11 +0000420static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000423 char namebuf[X509_NAME_MAXLEN];
424 int buflen;
425 PyObject *name_obj;
426 PyObject *value_obj;
427 PyObject *attr;
428 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000430 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
431 if (buflen < 0) {
432 _setSSLError(NULL, 0, __FILE__, __LINE__);
433 goto fail;
434 }
435 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
436 if (name_obj == NULL)
437 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
440 if (buflen < 0) {
441 _setSSLError(NULL, 0, __FILE__, __LINE__);
442 Py_DECREF(name_obj);
443 goto fail;
444 }
445 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000446 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 OPENSSL_free(valuebuf);
448 if (value_obj == NULL) {
449 Py_DECREF(name_obj);
450 goto fail;
451 }
452 attr = PyTuple_New(2);
453 if (attr == NULL) {
454 Py_DECREF(name_obj);
455 Py_DECREF(value_obj);
456 goto fail;
457 }
458 PyTuple_SET_ITEM(attr, 0, name_obj);
459 PyTuple_SET_ITEM(attr, 1, value_obj);
460 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000461
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000464}
465
466static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000468{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
470 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
471 PyObject *rdnt;
472 PyObject *attr = NULL; /* tuple to hold an attribute */
473 int entry_count = X509_NAME_entry_count(xname);
474 X509_NAME_ENTRY *entry;
475 ASN1_OBJECT *name;
476 ASN1_STRING *value;
477 int index_counter;
478 int rdn_level = -1;
479 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 dn = PyList_New(0);
482 if (dn == NULL)
483 return NULL;
484 /* now create another tuple to hold the top-level RDN */
485 rdn = PyList_New(0);
486 if (rdn == NULL)
487 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 for (index_counter = 0;
490 index_counter < entry_count;
491 index_counter++)
492 {
493 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000494
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 /* check to see if we've gotten to a new RDN */
496 if (rdn_level >= 0) {
497 if (rdn_level != entry->set) {
498 /* yes, new RDN */
499 /* add old RDN to DN */
500 rdnt = PyList_AsTuple(rdn);
501 Py_DECREF(rdn);
502 if (rdnt == NULL)
503 goto fail0;
504 retcode = PyList_Append(dn, rdnt);
505 Py_DECREF(rdnt);
506 if (retcode < 0)
507 goto fail0;
508 /* create new RDN */
509 rdn = PyList_New(0);
510 if (rdn == NULL)
511 goto fail0;
512 }
513 }
514 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* now add this attribute to the current RDN */
517 name = X509_NAME_ENTRY_get_object(entry);
518 value = X509_NAME_ENTRY_get_data(entry);
519 attr = _create_tuple_for_attribute(name, value);
520 /*
521 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
522 entry->set,
523 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
524 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
525 */
526 if (attr == NULL)
527 goto fail1;
528 retcode = PyList_Append(rdn, attr);
529 Py_DECREF(attr);
530 if (retcode < 0)
531 goto fail1;
532 }
533 /* now, there's typically a dangling RDN */
534 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
535 rdnt = PyList_AsTuple(rdn);
536 Py_DECREF(rdn);
537 if (rdnt == NULL)
538 goto fail0;
539 retcode = PyList_Append(dn, rdnt);
540 Py_DECREF(rdnt);
541 if (retcode < 0)
542 goto fail0;
543 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 /* convert list to tuple */
546 rdnt = PyList_AsTuple(dn);
547 Py_DECREF(dn);
548 if (rdnt == NULL)
549 return NULL;
550 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551
552 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
555 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 Py_XDECREF(dn);
557 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558}
559
560static PyObject *
561_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 /* this code follows the procedure outlined in
564 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
565 function to extract the STACK_OF(GENERAL_NAME),
566 then iterates through the stack to add the
567 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 int i, j;
570 PyObject *peer_alt_names = Py_None;
571 PyObject *v, *t;
572 X509_EXTENSION *ext = NULL;
573 GENERAL_NAMES *names = NULL;
574 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000575 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 BIO *biobuf = NULL;
577 char buf[2048];
578 char *vptr;
579 int len;
580 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000581#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000583#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000585#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 if (certificate == NULL)
588 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 /* get a memory buffer */
591 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 i = 0;
594 while ((i = X509_get_ext_by_NID(
595 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 if (peer_alt_names == Py_None) {
598 peer_alt_names = PyList_New(0);
599 if (peer_alt_names == NULL)
600 goto fail;
601 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 /* now decode the altName */
604 ext = X509_get_ext(certificate, i);
605 if(!(method = X509V3_EXT_get(ext))) {
606 PyErr_SetString
607 (PySSLErrorObject,
608 ERRSTR("No method for internalizing subjectAltName!"));
609 goto fail;
610 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 p = ext->value->data;
613 if (method->it)
614 names = (GENERAL_NAMES*)
615 (ASN1_item_d2i(NULL,
616 &p,
617 ext->value->length,
618 ASN1_ITEM_ptr(method->it)));
619 else
620 names = (GENERAL_NAMES*)
621 (method->d2i(NULL,
622 &p,
623 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 name = sk_GENERAL_NAME_value(names, j);
630 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 /* we special-case DirName as a tuple of
633 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 t = PyTuple_New(2);
636 if (t == NULL) {
637 goto fail;
638 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 v = PyUnicode_FromString("DirName");
641 if (v == NULL) {
642 Py_DECREF(t);
643 goto fail;
644 }
645 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 v = _create_tuple_for_X509_NAME (name->d.dirn);
648 if (v == NULL) {
649 Py_DECREF(t);
650 goto fail;
651 }
652 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 (void) BIO_reset(biobuf);
659 GENERAL_NAME_print(biobuf, name);
660 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
661 if (len < 0) {
662 _setSSLError(NULL, 0, __FILE__, __LINE__);
663 goto fail;
664 }
665 vptr = strchr(buf, ':');
666 if (vptr == NULL)
667 goto fail;
668 t = PyTuple_New(2);
669 if (t == NULL)
670 goto fail;
671 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
672 if (v == NULL) {
673 Py_DECREF(t);
674 goto fail;
675 }
676 PyTuple_SET_ITEM(t, 0, v);
677 v = PyUnicode_FromStringAndSize((vptr + 1),
678 (len - (vptr - buf + 1)));
679 if (v == NULL) {
680 Py_DECREF(t);
681 goto fail;
682 }
683 PyTuple_SET_ITEM(t, 1, v);
684 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 if (PyList_Append(peer_alt_names, t) < 0) {
689 Py_DECREF(t);
690 goto fail;
691 }
692 Py_DECREF(t);
693 }
694 }
695 BIO_free(biobuf);
696 if (peer_alt_names != Py_None) {
697 v = PyList_AsTuple(peer_alt_names);
698 Py_DECREF(peer_alt_names);
699 return v;
700 } else {
701 return peer_alt_names;
702 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000703
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704
705 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 if (biobuf != NULL)
707 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 if (peer_alt_names != Py_None) {
710 Py_XDECREF(peer_alt_names);
711 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714}
715
716static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000717_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 PyObject *retval = NULL;
720 BIO *biobuf = NULL;
721 PyObject *peer;
722 PyObject *peer_alt_names = NULL;
723 PyObject *issuer;
724 PyObject *version;
725 PyObject *sn_obj;
726 ASN1_INTEGER *serialNumber;
727 char buf[2048];
728 int len;
729 ASN1_TIME *notBefore, *notAfter;
730 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 retval = PyDict_New();
733 if (retval == NULL)
734 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 peer = _create_tuple_for_X509_NAME(
737 X509_get_subject_name(certificate));
738 if (peer == NULL)
739 goto fail0;
740 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
741 Py_DECREF(peer);
742 goto fail0;
743 }
744 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000745
Antoine Pitroufb046912010-11-09 20:21:19 +0000746 issuer = _create_tuple_for_X509_NAME(
747 X509_get_issuer_name(certificate));
748 if (issuer == NULL)
749 goto fail0;
750 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000752 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000754 Py_DECREF(issuer);
755
756 version = PyLong_FromLong(X509_get_version(certificate) + 1);
757 if (PyDict_SetItemString(retval, "version", version) < 0) {
758 Py_DECREF(version);
759 goto fail0;
760 }
761 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 /* get a memory buffer */
764 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000765
Antoine Pitroufb046912010-11-09 20:21:19 +0000766 (void) BIO_reset(biobuf);
767 serialNumber = X509_get_serialNumber(certificate);
768 /* should not exceed 20 octets, 160 bits, so buf is big enough */
769 i2a_ASN1_INTEGER(biobuf, serialNumber);
770 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
771 if (len < 0) {
772 _setSSLError(NULL, 0, __FILE__, __LINE__);
773 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000775 sn_obj = PyUnicode_FromStringAndSize(buf, len);
776 if (sn_obj == NULL)
777 goto fail1;
778 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
779 Py_DECREF(sn_obj);
780 goto fail1;
781 }
782 Py_DECREF(sn_obj);
783
784 (void) BIO_reset(biobuf);
785 notBefore = X509_get_notBefore(certificate);
786 ASN1_TIME_print(biobuf, notBefore);
787 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
788 if (len < 0) {
789 _setSSLError(NULL, 0, __FILE__, __LINE__);
790 goto fail1;
791 }
792 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
793 if (pnotBefore == NULL)
794 goto fail1;
795 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
796 Py_DECREF(pnotBefore);
797 goto fail1;
798 }
799 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 (void) BIO_reset(biobuf);
802 notAfter = X509_get_notAfter(certificate);
803 ASN1_TIME_print(biobuf, notAfter);
804 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
805 if (len < 0) {
806 _setSSLError(NULL, 0, __FILE__, __LINE__);
807 goto fail1;
808 }
809 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
810 if (pnotAfter == NULL)
811 goto fail1;
812 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
813 Py_DECREF(pnotAfter);
814 goto fail1;
815 }
816 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 peer_alt_names = _get_peer_alt_names(certificate);
821 if (peer_alt_names == NULL)
822 goto fail1;
823 else if (peer_alt_names != Py_None) {
824 if (PyDict_SetItemString(retval, "subjectAltName",
825 peer_alt_names) < 0) {
826 Py_DECREF(peer_alt_names);
827 goto fail1;
828 }
829 Py_DECREF(peer_alt_names);
830 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 BIO_free(biobuf);
833 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000834
835 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 if (biobuf != NULL)
837 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000838 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 Py_XDECREF(retval);
840 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000841}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000842
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
844static PyObject *
845PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000848 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 X509 *x=NULL;
850 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroufb046912010-11-09 20:21:19 +0000852 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
853 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 if ((cert=BIO_new(BIO_s_file())) == NULL) {
857 PyErr_SetString(PySSLErrorObject,
858 "Can't malloc memory to read file");
859 goto fail0;
860 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Victor Stinner3800e1e2010-05-16 21:23:48 +0000862 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 PyErr_SetString(PySSLErrorObject,
864 "Can't open file");
865 goto fail0;
866 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
869 if (x == NULL) {
870 PyErr_SetString(PySSLErrorObject,
871 "Error decoding PEM-encoded file");
872 goto fail0;
873 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000874
Antoine Pitroufb046912010-11-09 20:21:19 +0000875 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000876 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
878 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000879 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 if (cert != NULL) BIO_free(cert);
881 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882}
883
884
885static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000886PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 PyObject *retval = NULL;
889 int len;
890 int verification;
891 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
894 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 if (!self->peer_cert)
897 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 if (PyObject_IsTrue(binary_mode)) {
900 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 bytes_buf = NULL;
905 len = i2d_X509(self->peer_cert, &bytes_buf);
906 if (len < 0) {
907 PySSL_SetError(self, len, __FILE__, __LINE__);
908 return NULL;
909 }
910 /* this is actually an immutable bytes sequence */
911 retval = PyBytes_FromStringAndSize
912 ((const char *) bytes_buf, len);
913 OPENSSL_free(bytes_buf);
914 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000917 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 if ((verification & SSL_VERIFY_PEER) == 0)
919 return PyDict_New();
920 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000921 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923}
924
925PyDoc_STRVAR(PySSL_peercert_doc,
926"peer_certificate([der=False]) -> certificate\n\
927\n\
928Returns the certificate for the peer. If no certificate was provided,\n\
929returns None. If a certificate was provided, but not validated, returns\n\
930an empty dictionary. Otherwise returns a dict containing information\n\
931about the peer certificate.\n\
932\n\
933If the optional argument is True, returns a DER-encoded copy of the\n\
934peer certificate, or None if no certificate was provided. This will\n\
935return the certificate even if it wasn't validated.");
936
Antoine Pitrou152efa22010-05-16 18:19:27 +0000937static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000940 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 char *cipher_name;
942 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000945 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 current = SSL_get_current_cipher(self->ssl);
947 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000948 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 retval = PyTuple_New(3);
951 if (retval == NULL)
952 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 cipher_name = (char *) SSL_CIPHER_get_name(current);
955 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000956 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 PyTuple_SET_ITEM(retval, 0, Py_None);
958 } else {
959 v = PyUnicode_FromString(cipher_name);
960 if (v == NULL)
961 goto fail0;
962 PyTuple_SET_ITEM(retval, 0, v);
963 }
964 cipher_protocol = SSL_CIPHER_get_version(current);
965 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000966 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 PyTuple_SET_ITEM(retval, 1, Py_None);
968 } else {
969 v = PyUnicode_FromString(cipher_protocol);
970 if (v == NULL)
971 goto fail0;
972 PyTuple_SET_ITEM(retval, 1, v);
973 }
974 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
975 if (v == NULL)
976 goto fail0;
977 PyTuple_SET_ITEM(retval, 2, v);
978 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000979
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 Py_DECREF(retval);
982 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983}
984
Antoine Pitrou152efa22010-05-16 18:19:27 +0000985static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000986{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 if (self->peer_cert) /* Possible not to have one? */
988 X509_free (self->peer_cert);
989 if (self->ssl)
990 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 Py_XDECREF(self->Socket);
992 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000993}
994
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000995/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000996 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000997 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000998 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000999
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001000static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001001check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001002{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 fd_set fds;
1004 struct timeval tv;
1005 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1008 if (s->sock_timeout < 0.0)
1009 return SOCKET_IS_BLOCKING;
1010 else if (s->sock_timeout == 0.0)
1011 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 /* Guard against closed socket */
1014 if (s->sock_fd < 0)
1015 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 /* Prefer poll, if available, since you can poll() any fd
1018 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 {
1021 struct pollfd pollfd;
1022 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 pollfd.fd = s->sock_fd;
1025 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 /* s->sock_timeout is in seconds, timeout in ms */
1028 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1029 PySSL_BEGIN_ALLOW_THREADS
1030 rc = poll(&pollfd, 1, timeout);
1031 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 goto normal_return;
1034 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001035#endif
1036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001038#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 if (s->sock_fd >= FD_SETSIZE)
1040 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001041#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 /* Construct the arguments to select */
1044 tv.tv_sec = (int)s->sock_timeout;
1045 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1046 FD_ZERO(&fds);
1047 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 /* See if the socket is ready */
1050 PySSL_BEGIN_ALLOW_THREADS
1051 if (writing)
1052 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1053 else
1054 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1055 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001056
Bill Janssen6e027db2007-11-15 22:23:56 +00001057#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001059#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1061 (when we are able to write or when there's something to read) */
1062 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001063}
1064
Antoine Pitrou152efa22010-05-16 18:19:27 +00001065static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001066{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 Py_buffer buf;
1068 int len;
1069 int sockstate;
1070 int err;
1071 int nonblocking;
1072 PySocketSockObject *sock
1073 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001074
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 if (((PyObject*)sock) == Py_None) {
1076 _setSSLError("Underlying socket connection gone",
1077 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1078 return NULL;
1079 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001080 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001082 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1083 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001085 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086
1087 /* just in case the blocking state of the socket has been changed */
1088 nonblocking = (sock->sock_timeout >= 0.0);
1089 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1090 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1091
1092 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1093 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001094 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 "The write operation timed out");
1096 goto error;
1097 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1098 PyErr_SetString(PySSLErrorObject,
1099 "Underlying socket has been closed.");
1100 goto error;
1101 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1102 PyErr_SetString(PySSLErrorObject,
1103 "Underlying socket too large for select().");
1104 goto error;
1105 }
1106 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 PySSL_BEGIN_ALLOW_THREADS
1108 len = SSL_write(self->ssl, buf.buf, buf.len);
1109 err = SSL_get_error(self->ssl, len);
1110 PySSL_END_ALLOW_THREADS
1111 if (PyErr_CheckSignals()) {
1112 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001113 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001115 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001117 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 } else {
1119 sockstate = SOCKET_OPERATION_OK;
1120 }
1121 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001122 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 "The write operation timed out");
1124 goto error;
1125 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1126 PyErr_SetString(PySSLErrorObject,
1127 "Underlying socket has been closed.");
1128 goto error;
1129 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1130 break;
1131 }
1132 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001133
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001134 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 PyBuffer_Release(&buf);
1136 if (len > 0)
1137 return PyLong_FromLong(len);
1138 else
1139 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001140
1141error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001142 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 PyBuffer_Release(&buf);
1144 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001145}
1146
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001147PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001148"write(s) -> len\n\
1149\n\
1150Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001151of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001152
Antoine Pitrou152efa22010-05-16 18:19:27 +00001153static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001154{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 PySSL_BEGIN_ALLOW_THREADS
1158 count = SSL_pending(self->ssl);
1159 PySSL_END_ALLOW_THREADS
1160 if (count < 0)
1161 return PySSL_SetError(self, count, __FILE__, __LINE__);
1162 else
1163 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001164}
1165
1166PyDoc_STRVAR(PySSL_SSLpending_doc,
1167"pending() -> count\n\
1168\n\
1169Returns the number of already decrypted bytes available for read,\n\
1170pending on the connection.\n");
1171
Antoine Pitrou152efa22010-05-16 18:19:27 +00001172static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001173{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 PyObject *dest = NULL;
1175 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001177 int len, count;
1178 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 int sockstate;
1180 int err;
1181 int nonblocking;
1182 PySocketSockObject *sock
1183 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 if (((PyObject*)sock) == Py_None) {
1186 _setSSLError("Underlying socket connection gone",
1187 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1188 return NULL;
1189 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001190 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001192 buf.obj = NULL;
1193 buf.buf = NULL;
1194 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001195 goto error;
1196
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001197 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1198 dest = PyBytes_FromStringAndSize(NULL, len);
1199 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001200 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001201 mem = PyBytes_AS_STRING(dest);
1202 }
1203 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001205 mem = buf.buf;
1206 if (len <= 0 || len > buf.len) {
1207 len = (int) buf.len;
1208 if (buf.len != len) {
1209 PyErr_SetString(PyExc_OverflowError,
1210 "maximum length can't fit in a C 'int'");
1211 goto error;
1212 }
1213 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 }
1215
1216 /* just in case the blocking state of the socket has been changed */
1217 nonblocking = (sock->sock_timeout >= 0.0);
1218 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1219 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1220
1221 /* first check if there are bytes ready to be read */
1222 PySSL_BEGIN_ALLOW_THREADS
1223 count = SSL_pending(self->ssl);
1224 PySSL_END_ALLOW_THREADS
1225
1226 if (!count) {
1227 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1228 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001229 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 "The read operation timed out");
1231 goto error;
1232 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1233 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001234 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 goto error;
1236 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1237 count = 0;
1238 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001239 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 }
1241 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 PySSL_BEGIN_ALLOW_THREADS
1243 count = SSL_read(self->ssl, mem, len);
1244 err = SSL_get_error(self->ssl, count);
1245 PySSL_END_ALLOW_THREADS
1246 if (PyErr_CheckSignals())
1247 goto error;
1248 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001249 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001251 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1253 (SSL_get_shutdown(self->ssl) ==
1254 SSL_RECEIVED_SHUTDOWN))
1255 {
1256 count = 0;
1257 goto done;
1258 } else {
1259 sockstate = SOCKET_OPERATION_OK;
1260 }
1261 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001262 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 "The read operation timed out");
1264 goto error;
1265 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1266 break;
1267 }
1268 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1269 if (count <= 0) {
1270 PySSL_SetError(self, count, __FILE__, __LINE__);
1271 goto error;
1272 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001273
1274done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001275 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001277 _PyBytes_Resize(&dest, count);
1278 return dest;
1279 }
1280 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 PyBuffer_Release(&buf);
1282 return PyLong_FromLong(count);
1283 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001284
1285error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001286 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001287 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001288 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001289 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001292}
1293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001294PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001295"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001296\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001297Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001298
Antoine Pitrou152efa22010-05-16 18:19:27 +00001299static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001300{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 int err, ssl_err, sockstate, nonblocking;
1302 int zeros = 0;
1303 PySocketSockObject *sock
1304 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001306 /* Guard against closed socket */
1307 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1308 _setSSLError("Underlying socket connection gone",
1309 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1310 return NULL;
1311 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001312 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313
1314 /* Just in case the blocking state of the socket has been changed */
1315 nonblocking = (sock->sock_timeout >= 0.0);
1316 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1317 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1318
1319 while (1) {
1320 PySSL_BEGIN_ALLOW_THREADS
1321 /* Disable read-ahead so that unwrap can work correctly.
1322 * Otherwise OpenSSL might read in too much data,
1323 * eating clear text data that happens to be
1324 * transmitted after the SSL shutdown.
1325 * Should be safe to call repeatedly everytime this
1326 * function is used and the shutdown_seen_zero != 0
1327 * condition is met.
1328 */
1329 if (self->shutdown_seen_zero)
1330 SSL_set_read_ahead(self->ssl, 0);
1331 err = SSL_shutdown(self->ssl);
1332 PySSL_END_ALLOW_THREADS
1333 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1334 if (err > 0)
1335 break;
1336 if (err == 0) {
1337 /* Don't loop endlessly; instead preserve legacy
1338 behaviour of trying SSL_shutdown() only twice.
1339 This looks necessary for OpenSSL < 0.9.8m */
1340 if (++zeros > 1)
1341 break;
1342 /* Shutdown was sent, now try receiving */
1343 self->shutdown_seen_zero = 1;
1344 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001345 }
1346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 /* Possibly retry shutdown until timeout or failure */
1348 ssl_err = SSL_get_error(self->ssl, err);
1349 if (ssl_err == SSL_ERROR_WANT_READ)
1350 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1351 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1352 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1353 else
1354 break;
1355 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1356 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001357 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 "The read operation timed out");
1359 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001360 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001362 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 }
1364 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1365 PyErr_SetString(PySSLErrorObject,
1366 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001367 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 }
1369 else if (sockstate != SOCKET_OPERATION_OK)
1370 /* Retain the SSL error code */
1371 break;
1372 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001373
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001374 if (err < 0) {
1375 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001378 else
1379 /* It's already INCREF'ed */
1380 return (PyObject *) sock;
1381
1382error:
1383 Py_DECREF(sock);
1384 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001385}
1386
1387PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1388"shutdown(s) -> socket\n\
1389\n\
1390Does the SSL shutdown handshake with the remote end, and returns\n\
1391the underlying socket object.");
1392
Antoine Pitroud6494802011-07-21 01:11:30 +02001393#if HAVE_OPENSSL_FINISHED
1394static PyObject *
1395PySSL_tls_unique_cb(PySSLSocket *self)
1396{
1397 PyObject *retval = NULL;
1398 char buf[PySSL_CB_MAXLEN];
1399 int len;
1400
1401 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1402 /* if session is resumed XOR we are the client */
1403 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1404 }
1405 else {
1406 /* if a new session XOR we are the server */
1407 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1408 }
1409
1410 /* It cannot be negative in current OpenSSL version as of July 2011 */
1411 assert(len >= 0);
1412 if (len == 0)
1413 Py_RETURN_NONE;
1414
1415 retval = PyBytes_FromStringAndSize(buf, len);
1416
1417 return retval;
1418}
1419
1420PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1421"tls_unique_cb() -> bytes\n\
1422\n\
1423Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1424\n\
1425If the TLS handshake is not yet complete, None is returned");
1426
1427#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001428
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001429static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1431 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1432 PySSL_SSLwrite_doc},
1433 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1434 PySSL_SSLread_doc},
1435 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1436 PySSL_SSLpending_doc},
1437 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1438 PySSL_peercert_doc},
1439 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1440 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1441 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001442#if HAVE_OPENSSL_FINISHED
1443 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1444 PySSL_tls_unique_cb_doc},
1445#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001447};
1448
Antoine Pitrou152efa22010-05-16 18:19:27 +00001449static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001450 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001451 "_ssl._SSLSocket", /*tp_name*/
1452 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 0, /*tp_itemsize*/
1454 /* methods */
1455 (destructor)PySSL_dealloc, /*tp_dealloc*/
1456 0, /*tp_print*/
1457 0, /*tp_getattr*/
1458 0, /*tp_setattr*/
1459 0, /*tp_reserved*/
1460 0, /*tp_repr*/
1461 0, /*tp_as_number*/
1462 0, /*tp_as_sequence*/
1463 0, /*tp_as_mapping*/
1464 0, /*tp_hash*/
1465 0, /*tp_call*/
1466 0, /*tp_str*/
1467 0, /*tp_getattro*/
1468 0, /*tp_setattro*/
1469 0, /*tp_as_buffer*/
1470 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1471 0, /*tp_doc*/
1472 0, /*tp_traverse*/
1473 0, /*tp_clear*/
1474 0, /*tp_richcompare*/
1475 0, /*tp_weaklistoffset*/
1476 0, /*tp_iter*/
1477 0, /*tp_iternext*/
1478 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479};
1480
Antoine Pitrou152efa22010-05-16 18:19:27 +00001481
1482/*
1483 * _SSLContext objects
1484 */
1485
1486static PyObject *
1487context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1488{
1489 char *kwlist[] = {"protocol", NULL};
1490 PySSLContext *self;
1491 int proto_version = PY_SSL_VERSION_SSL23;
1492 SSL_CTX *ctx = NULL;
1493
1494 if (!PyArg_ParseTupleAndKeywords(
1495 args, kwds, "i:_SSLContext", kwlist,
1496 &proto_version))
1497 return NULL;
1498
1499 PySSL_BEGIN_ALLOW_THREADS
1500 if (proto_version == PY_SSL_VERSION_TLS1)
1501 ctx = SSL_CTX_new(TLSv1_method());
1502 else if (proto_version == PY_SSL_VERSION_SSL3)
1503 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001504#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001505 else if (proto_version == PY_SSL_VERSION_SSL2)
1506 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001507#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001508 else if (proto_version == PY_SSL_VERSION_SSL23)
1509 ctx = SSL_CTX_new(SSLv23_method());
1510 else
1511 proto_version = -1;
1512 PySSL_END_ALLOW_THREADS
1513
1514 if (proto_version == -1) {
1515 PyErr_SetString(PyExc_ValueError,
1516 "invalid protocol version");
1517 return NULL;
1518 }
1519 if (ctx == NULL) {
1520 PyErr_SetString(PySSLErrorObject,
1521 "failed to allocate SSL context");
1522 return NULL;
1523 }
1524
1525 assert(type != NULL && type->tp_alloc != NULL);
1526 self = (PySSLContext *) type->tp_alloc(type, 0);
1527 if (self == NULL) {
1528 SSL_CTX_free(ctx);
1529 return NULL;
1530 }
1531 self->ctx = ctx;
1532 /* Defaults */
1533 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1534 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1535
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001536#define SID_CTX "Python"
1537 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1538 sizeof(SID_CTX));
1539#undef SID_CTX
1540
Antoine Pitrou152efa22010-05-16 18:19:27 +00001541 return (PyObject *)self;
1542}
1543
1544static void
1545context_dealloc(PySSLContext *self)
1546{
1547 SSL_CTX_free(self->ctx);
1548 Py_TYPE(self)->tp_free(self);
1549}
1550
1551static PyObject *
1552set_ciphers(PySSLContext *self, PyObject *args)
1553{
1554 int ret;
1555 const char *cipherlist;
1556
1557 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1558 return NULL;
1559 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1560 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001561 /* Clearing the error queue is necessary on some OpenSSL versions,
1562 otherwise the error will be reported again when another SSL call
1563 is done. */
1564 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001565 PyErr_SetString(PySSLErrorObject,
1566 "No cipher can be selected.");
1567 return NULL;
1568 }
1569 Py_RETURN_NONE;
1570}
1571
1572static PyObject *
1573get_verify_mode(PySSLContext *self, void *c)
1574{
1575 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1576 case SSL_VERIFY_NONE:
1577 return PyLong_FromLong(PY_SSL_CERT_NONE);
1578 case SSL_VERIFY_PEER:
1579 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1580 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1581 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1582 }
1583 PyErr_SetString(PySSLErrorObject,
1584 "invalid return value from SSL_CTX_get_verify_mode");
1585 return NULL;
1586}
1587
1588static int
1589set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1590{
1591 int n, mode;
1592 if (!PyArg_Parse(arg, "i", &n))
1593 return -1;
1594 if (n == PY_SSL_CERT_NONE)
1595 mode = SSL_VERIFY_NONE;
1596 else if (n == PY_SSL_CERT_OPTIONAL)
1597 mode = SSL_VERIFY_PEER;
1598 else if (n == PY_SSL_CERT_REQUIRED)
1599 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1600 else {
1601 PyErr_SetString(PyExc_ValueError,
1602 "invalid value for verify_mode");
1603 return -1;
1604 }
1605 SSL_CTX_set_verify(self->ctx, mode, NULL);
1606 return 0;
1607}
1608
1609static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001610get_options(PySSLContext *self, void *c)
1611{
1612 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1613}
1614
1615static int
1616set_options(PySSLContext *self, PyObject *arg, void *c)
1617{
1618 long new_opts, opts, set, clear;
1619 if (!PyArg_Parse(arg, "l", &new_opts))
1620 return -1;
1621 opts = SSL_CTX_get_options(self->ctx);
1622 clear = opts & ~new_opts;
1623 set = ~opts & new_opts;
1624 if (clear) {
1625#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1626 SSL_CTX_clear_options(self->ctx, clear);
1627#else
1628 PyErr_SetString(PyExc_ValueError,
1629 "can't clear options before OpenSSL 0.9.8m");
1630 return -1;
1631#endif
1632 }
1633 if (set)
1634 SSL_CTX_set_options(self->ctx, set);
1635 return 0;
1636}
1637
1638static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001639load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1640{
1641 char *kwlist[] = {"certfile", "keyfile", NULL};
1642 PyObject *certfile, *keyfile = NULL;
1643 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1644 int r;
1645
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001646 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001647 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001648 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1649 "O|O:load_cert_chain", kwlist,
1650 &certfile, &keyfile))
1651 return NULL;
1652 if (keyfile == Py_None)
1653 keyfile = NULL;
1654 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1655 PyErr_SetString(PyExc_TypeError,
1656 "certfile should be a valid filesystem path");
1657 return NULL;
1658 }
1659 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1660 PyErr_SetString(PyExc_TypeError,
1661 "keyfile should be a valid filesystem path");
1662 goto error;
1663 }
1664 PySSL_BEGIN_ALLOW_THREADS
1665 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1666 PyBytes_AS_STRING(certfile_bytes));
1667 PySSL_END_ALLOW_THREADS
1668 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001669 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001670 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001671 PyErr_SetFromErrno(PyExc_IOError);
1672 }
1673 else {
1674 _setSSLError(NULL, 0, __FILE__, __LINE__);
1675 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001676 goto error;
1677 }
1678 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001679 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001680 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1681 SSL_FILETYPE_PEM);
1682 PySSL_END_ALLOW_THREADS
1683 Py_XDECREF(keyfile_bytes);
1684 Py_XDECREF(certfile_bytes);
1685 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001686 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001687 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001688 PyErr_SetFromErrno(PyExc_IOError);
1689 }
1690 else {
1691 _setSSLError(NULL, 0, __FILE__, __LINE__);
1692 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001693 return NULL;
1694 }
1695 PySSL_BEGIN_ALLOW_THREADS
1696 r = SSL_CTX_check_private_key(self->ctx);
1697 PySSL_END_ALLOW_THREADS
1698 if (r != 1) {
1699 _setSSLError(NULL, 0, __FILE__, __LINE__);
1700 return NULL;
1701 }
1702 Py_RETURN_NONE;
1703
1704error:
1705 Py_XDECREF(keyfile_bytes);
1706 Py_XDECREF(certfile_bytes);
1707 return NULL;
1708}
1709
1710static PyObject *
1711load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1712{
1713 char *kwlist[] = {"cafile", "capath", NULL};
1714 PyObject *cafile = NULL, *capath = NULL;
1715 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1716 const char *cafile_buf = NULL, *capath_buf = NULL;
1717 int r;
1718
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001719 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001720 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1721 "|OO:load_verify_locations", kwlist,
1722 &cafile, &capath))
1723 return NULL;
1724 if (cafile == Py_None)
1725 cafile = NULL;
1726 if (capath == Py_None)
1727 capath = NULL;
1728 if (cafile == NULL && capath == NULL) {
1729 PyErr_SetString(PyExc_TypeError,
1730 "cafile and capath cannot be both omitted");
1731 return NULL;
1732 }
1733 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1734 PyErr_SetString(PyExc_TypeError,
1735 "cafile should be a valid filesystem path");
1736 return NULL;
1737 }
1738 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001739 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001740 PyErr_SetString(PyExc_TypeError,
1741 "capath should be a valid filesystem path");
1742 return NULL;
1743 }
1744 if (cafile)
1745 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1746 if (capath)
1747 capath_buf = PyBytes_AS_STRING(capath_bytes);
1748 PySSL_BEGIN_ALLOW_THREADS
1749 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1750 PySSL_END_ALLOW_THREADS
1751 Py_XDECREF(cafile_bytes);
1752 Py_XDECREF(capath_bytes);
1753 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001754 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001755 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001756 PyErr_SetFromErrno(PyExc_IOError);
1757 }
1758 else {
1759 _setSSLError(NULL, 0, __FILE__, __LINE__);
1760 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001761 return NULL;
1762 }
1763 Py_RETURN_NONE;
1764}
1765
1766static PyObject *
1767context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1768{
Antoine Pitroud5323212010-10-22 18:19:07 +00001769 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001770 PySocketSockObject *sock;
1771 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001772 char *hostname = NULL;
1773 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001774
Antoine Pitroud5323212010-10-22 18:19:07 +00001775 /* server_hostname is either None (or absent), or to be encoded
1776 using the idna encoding. */
1777 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001778 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001779 &sock, &server_side,
1780 Py_TYPE(Py_None), &hostname_obj)) {
1781 PyErr_Clear();
1782 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1783 PySocketModule.Sock_Type,
1784 &sock, &server_side,
1785 "idna", &hostname))
1786 return NULL;
1787#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1788 PyMem_Free(hostname);
1789 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1790 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001792#endif
1793 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794
Antoine Pitroud5323212010-10-22 18:19:07 +00001795 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1796 hostname);
1797 if (hostname != NULL)
1798 PyMem_Free(hostname);
1799 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001800}
1801
Antoine Pitroub0182c82010-10-12 20:09:02 +00001802static PyObject *
1803session_stats(PySSLContext *self, PyObject *unused)
1804{
1805 int r;
1806 PyObject *value, *stats = PyDict_New();
1807 if (!stats)
1808 return NULL;
1809
1810#define ADD_STATS(SSL_NAME, KEY_NAME) \
1811 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1812 if (value == NULL) \
1813 goto error; \
1814 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1815 Py_DECREF(value); \
1816 if (r < 0) \
1817 goto error;
1818
1819 ADD_STATS(number, "number");
1820 ADD_STATS(connect, "connect");
1821 ADD_STATS(connect_good, "connect_good");
1822 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1823 ADD_STATS(accept, "accept");
1824 ADD_STATS(accept_good, "accept_good");
1825 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1826 ADD_STATS(accept, "accept");
1827 ADD_STATS(hits, "hits");
1828 ADD_STATS(misses, "misses");
1829 ADD_STATS(timeouts, "timeouts");
1830 ADD_STATS(cache_full, "cache_full");
1831
1832#undef ADD_STATS
1833
1834 return stats;
1835
1836error:
1837 Py_DECREF(stats);
1838 return NULL;
1839}
1840
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001841static PyObject *
1842set_default_verify_paths(PySSLContext *self, PyObject *unused)
1843{
1844 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1845 _setSSLError(NULL, 0, __FILE__, __LINE__);
1846 return NULL;
1847 }
1848 Py_RETURN_NONE;
1849}
1850
Antoine Pitrou152efa22010-05-16 18:19:27 +00001851static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001852 {"options", (getter) get_options,
1853 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001854 {"verify_mode", (getter) get_verify_mode,
1855 (setter) set_verify_mode, NULL},
1856 {NULL}, /* sentinel */
1857};
1858
1859static struct PyMethodDef context_methods[] = {
1860 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1861 METH_VARARGS | METH_KEYWORDS, NULL},
1862 {"set_ciphers", (PyCFunction) set_ciphers,
1863 METH_VARARGS, NULL},
1864 {"load_cert_chain", (PyCFunction) load_cert_chain,
1865 METH_VARARGS | METH_KEYWORDS, NULL},
1866 {"load_verify_locations", (PyCFunction) load_verify_locations,
1867 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001868 {"session_stats", (PyCFunction) session_stats,
1869 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001870 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1871 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001872 {NULL, NULL} /* sentinel */
1873};
1874
1875static PyTypeObject PySSLContext_Type = {
1876 PyVarObject_HEAD_INIT(NULL, 0)
1877 "_ssl._SSLContext", /*tp_name*/
1878 sizeof(PySSLContext), /*tp_basicsize*/
1879 0, /*tp_itemsize*/
1880 (destructor)context_dealloc, /*tp_dealloc*/
1881 0, /*tp_print*/
1882 0, /*tp_getattr*/
1883 0, /*tp_setattr*/
1884 0, /*tp_reserved*/
1885 0, /*tp_repr*/
1886 0, /*tp_as_number*/
1887 0, /*tp_as_sequence*/
1888 0, /*tp_as_mapping*/
1889 0, /*tp_hash*/
1890 0, /*tp_call*/
1891 0, /*tp_str*/
1892 0, /*tp_getattro*/
1893 0, /*tp_setattro*/
1894 0, /*tp_as_buffer*/
1895 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1896 0, /*tp_doc*/
1897 0, /*tp_traverse*/
1898 0, /*tp_clear*/
1899 0, /*tp_richcompare*/
1900 0, /*tp_weaklistoffset*/
1901 0, /*tp_iter*/
1902 0, /*tp_iternext*/
1903 context_methods, /*tp_methods*/
1904 0, /*tp_members*/
1905 context_getsetlist, /*tp_getset*/
1906 0, /*tp_base*/
1907 0, /*tp_dict*/
1908 0, /*tp_descr_get*/
1909 0, /*tp_descr_set*/
1910 0, /*tp_dictoffset*/
1911 0, /*tp_init*/
1912 0, /*tp_alloc*/
1913 context_new, /*tp_new*/
1914};
1915
1916
1917
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001918#ifdef HAVE_OPENSSL_RAND
1919
1920/* helper routines for seeding the SSL PRNG */
1921static PyObject *
1922PySSL_RAND_add(PyObject *self, PyObject *args)
1923{
1924 char *buf;
1925 int len;
1926 double entropy;
1927
1928 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001929 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001930 RAND_add(buf, len, entropy);
1931 Py_INCREF(Py_None);
1932 return Py_None;
1933}
1934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001935PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001936"RAND_add(string, entropy)\n\
1937\n\
1938Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001939bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001940
1941static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02001942PySSL_RAND(int len, int pseudo)
1943{
1944 int ok;
1945 PyObject *bytes;
1946 unsigned long err;
1947 const char *errstr;
1948 PyObject *v;
1949
1950 bytes = PyBytes_FromStringAndSize(NULL, len);
1951 if (bytes == NULL)
1952 return NULL;
1953 if (pseudo) {
1954 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
1955 if (ok == 0 || ok == 1)
1956 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
1957 }
1958 else {
1959 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
1960 if (ok == 1)
1961 return bytes;
1962 }
1963 Py_DECREF(bytes);
1964
1965 err = ERR_get_error();
1966 errstr = ERR_reason_error_string(err);
1967 v = Py_BuildValue("(ks)", err, errstr);
1968 if (v != NULL) {
1969 PyErr_SetObject(PySSLErrorObject, v);
1970 Py_DECREF(v);
1971 }
1972 return NULL;
1973}
1974
1975static PyObject *
1976PySSL_RAND_bytes(PyObject *self, PyObject *args)
1977{
1978 int len;
1979 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
1980 return NULL;
1981 return PySSL_RAND(len, 0);
1982}
1983
1984PyDoc_STRVAR(PySSL_RAND_bytes_doc,
1985"RAND_bytes(n) -> bytes\n\
1986\n\
1987Generate n cryptographically strong pseudo-random bytes.");
1988
1989static PyObject *
1990PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
1991{
1992 int len;
1993 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
1994 return NULL;
1995 return PySSL_RAND(len, 1);
1996}
1997
1998PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
1999"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2000\n\
2001Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2002generated are cryptographically strong.");
2003
2004static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002005PySSL_RAND_status(PyObject *self)
2006{
Christian Heimes217cfd12007-12-02 14:31:20 +00002007 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002008}
2009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002010PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002011"RAND_status() -> 0 or 1\n\
2012\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002013Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2014It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2015using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002016
2017static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002018PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002019{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002020 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002021 int bytes;
2022
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002023 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2024 PyUnicode_FSConverter, &path))
2025 return NULL;
2026
2027 bytes = RAND_egd(PyBytes_AsString(path));
2028 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002029 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002030 PyErr_SetString(PySSLErrorObject,
2031 "EGD connection failed or EGD did not return "
2032 "enough data to seed the PRNG");
2033 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002034 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002035 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002036}
2037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002038PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002039"RAND_egd(path) -> bytes\n\
2040\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002041Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2042Returns number of bytes read. Raises SSLError if connection to EGD\n\
2043fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002044
2045#endif
2046
Bill Janssen40a0f662008-08-12 16:56:25 +00002047
2048
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002049/* List of functions exported by this module. */
2050
2051static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 {"_test_decode_cert", PySSL_test_decode_certificate,
2053 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002054#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2056 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002057 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2058 PySSL_RAND_bytes_doc},
2059 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2060 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002061 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002062 PySSL_RAND_egd_doc},
2063 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2064 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002065#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002067};
2068
2069
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002070#ifdef WITH_THREAD
2071
2072/* an implementation of OpenSSL threading operations in terms
2073 of the Python C thread library */
2074
2075static PyThread_type_lock *_ssl_locks = NULL;
2076
2077static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002079}
2080
Bill Janssen6e027db2007-11-15 22:23:56 +00002081static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 (int mode, int n, const char *file, int line) {
2083 /* this function is needed to perform locking on shared data
2084 structures. (Note that OpenSSL uses a number of global data
2085 structures that will be implicitly shared whenever multiple
2086 threads use OpenSSL.) Multi-threaded applications will
2087 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 locking_function() must be able to handle up to
2090 CRYPTO_num_locks() different mutex locks. It sets the n-th
2091 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 file and line are the file number of the function setting the
2094 lock. They can be useful for debugging.
2095 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 if ((_ssl_locks == NULL) ||
2098 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2099 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002100
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002101 if (mode & CRYPTO_LOCK) {
2102 PyThread_acquire_lock(_ssl_locks[n], 1);
2103 } else {
2104 PyThread_release_lock(_ssl_locks[n]);
2105 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002106}
2107
2108static int _setup_ssl_threads(void) {
2109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002110 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002112 if (_ssl_locks == NULL) {
2113 _ssl_locks_count = CRYPTO_num_locks();
2114 _ssl_locks = (PyThread_type_lock *)
2115 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2116 if (_ssl_locks == NULL)
2117 return 0;
2118 memset(_ssl_locks, 0,
2119 sizeof(PyThread_type_lock) * _ssl_locks_count);
2120 for (i = 0; i < _ssl_locks_count; i++) {
2121 _ssl_locks[i] = PyThread_allocate_lock();
2122 if (_ssl_locks[i] == NULL) {
2123 unsigned int j;
2124 for (j = 0; j < i; j++) {
2125 PyThread_free_lock(_ssl_locks[j]);
2126 }
2127 free(_ssl_locks);
2128 return 0;
2129 }
2130 }
2131 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2132 CRYPTO_set_id_callback(_ssl_thread_id_function);
2133 }
2134 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002135}
2136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002139PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002140"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002141for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002142
Martin v. Löwis1a214512008-06-11 05:26:20 +00002143
2144static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 PyModuleDef_HEAD_INIT,
2146 "_ssl",
2147 module_doc,
2148 -1,
2149 PySSL_methods,
2150 NULL,
2151 NULL,
2152 NULL,
2153 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002154};
2155
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002156
2157static void
2158parse_openssl_version(unsigned long libver,
2159 unsigned int *major, unsigned int *minor,
2160 unsigned int *fix, unsigned int *patch,
2161 unsigned int *status)
2162{
2163 *status = libver & 0xF;
2164 libver >>= 4;
2165 *patch = libver & 0xFF;
2166 libver >>= 8;
2167 *fix = libver & 0xFF;
2168 libver >>= 8;
2169 *minor = libver & 0xFF;
2170 libver >>= 8;
2171 *major = libver & 0xFF;
2172}
2173
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002174PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002175PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002176{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 PyObject *m, *d, *r;
2178 unsigned long libver;
2179 unsigned int major, minor, fix, patch, status;
2180 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002181
Antoine Pitrou152efa22010-05-16 18:19:27 +00002182 if (PyType_Ready(&PySSLContext_Type) < 0)
2183 return NULL;
2184 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002187 m = PyModule_Create(&_sslmodule);
2188 if (m == NULL)
2189 return NULL;
2190 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 /* Load _socket module and its C API */
2193 socket_api = PySocketModule_ImportModuleAndAPI();
2194 if (!socket_api)
2195 return NULL;
2196 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 /* Init OpenSSL */
2199 SSL_load_error_strings();
2200 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002201#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 /* note that this will start threading if not already started */
2203 if (!_setup_ssl_threads()) {
2204 return NULL;
2205 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002206#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 /* Add symbols to module dict */
2210 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2211 PySocketModule.error,
2212 NULL);
2213 if (PySSLErrorObject == NULL)
2214 return NULL;
2215 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2216 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217 if (PyDict_SetItemString(d, "_SSLContext",
2218 (PyObject *)&PySSLContext_Type) != 0)
2219 return NULL;
2220 if (PyDict_SetItemString(d, "_SSLSocket",
2221 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 return NULL;
2223 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2224 PY_SSL_ERROR_ZERO_RETURN);
2225 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2226 PY_SSL_ERROR_WANT_READ);
2227 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2228 PY_SSL_ERROR_WANT_WRITE);
2229 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2230 PY_SSL_ERROR_WANT_X509_LOOKUP);
2231 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2232 PY_SSL_ERROR_SYSCALL);
2233 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2234 PY_SSL_ERROR_SSL);
2235 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2236 PY_SSL_ERROR_WANT_CONNECT);
2237 /* non ssl.h errorcodes */
2238 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2239 PY_SSL_ERROR_EOF);
2240 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2241 PY_SSL_ERROR_INVALID_ERROR_CODE);
2242 /* cert requirements */
2243 PyModule_AddIntConstant(m, "CERT_NONE",
2244 PY_SSL_CERT_NONE);
2245 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2246 PY_SSL_CERT_OPTIONAL);
2247 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2248 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002251#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2253 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002254#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2256 PY_SSL_VERSION_SSL3);
2257 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2258 PY_SSL_VERSION_SSL23);
2259 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2260 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002261
Antoine Pitroub5218772010-05-21 09:56:06 +00002262 /* protocol options */
2263 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2264 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2265 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2266 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2267
Antoine Pitroud5323212010-10-22 18:19:07 +00002268#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2269 r = Py_True;
2270#else
2271 r = Py_False;
2272#endif
2273 Py_INCREF(r);
2274 PyModule_AddObject(m, "HAS_SNI", r);
2275
Antoine Pitroud6494802011-07-21 01:11:30 +02002276#if HAVE_OPENSSL_FINISHED
2277 r = Py_True;
2278#else
2279 r = Py_False;
2280#endif
2281 Py_INCREF(r);
2282 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 /* OpenSSL version */
2285 /* SSLeay() gives us the version of the library linked against,
2286 which could be different from the headers version.
2287 */
2288 libver = SSLeay();
2289 r = PyLong_FromUnsignedLong(libver);
2290 if (r == NULL)
2291 return NULL;
2292 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2293 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002294 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2296 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2297 return NULL;
2298 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2299 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2300 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002301
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002302 libver = OPENSSL_VERSION_NUMBER;
2303 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2304 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2305 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2306 return NULL;
2307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002309}