blob: a9c772aa9e41f430788dff5a868940b33fc60c25 [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 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
Antoine Pitroub5218772010-05-21 09:56:06 +0000116/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */
117#if OPENSSL_VERSION_NUMBER >= 0x009080dfL
118# define HAVE_SSL_CTX_CLEAR_OPTIONS
119#else
120# undef HAVE_SSL_CTX_CLEAR_OPTIONS
121#endif
122
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000124 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000125 SSL_CTX *ctx;
126} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127
Antoine Pitrou152efa22010-05-16 18:19:27 +0000128typedef struct {
129 PyObject_HEAD
130 PyObject *Socket; /* weakref to socket on which we're layered */
131 SSL *ssl;
132 X509 *peer_cert;
133 int shutdown_seen_zero;
134} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Antoine Pitrou152efa22010-05-16 18:19:27 +0000136static PyTypeObject PySSLContext_Type;
137static PyTypeObject PySSLSocket_Type;
138
139static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
140static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000141static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000142 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000143static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
144static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000145
Antoine Pitrou152efa22010-05-16 18:19:27 +0000146#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
147#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000149typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000150 SOCKET_IS_NONBLOCKING,
151 SOCKET_IS_BLOCKING,
152 SOCKET_HAS_TIMED_OUT,
153 SOCKET_HAS_BEEN_CLOSED,
154 SOCKET_TOO_LARGE_FOR_SELECT,
155 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000156} timeout_state;
157
Thomas Woutersed03b412007-08-28 21:37:11 +0000158/* Wrap error strings with filename and line # */
159#define STRINGIFY1(x) #x
160#define STRINGIFY2(x) STRINGIFY1(x)
161#define ERRSTR1(x,y,z) (x ":" y ": " z)
162#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
163
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164/* XXX It might be helpful to augment the error message generated
165 below with the name of the SSL function that generated the error.
166 I expect it's obvious most of the time.
167*/
168
169static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000170PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000171{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000172 PyObject *v;
173 char buf[2048];
174 char *errstr;
175 int err;
176 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000178 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 if (obj->ssl != NULL) {
181 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000183 switch (err) {
184 case SSL_ERROR_ZERO_RETURN:
185 errstr = "TLS/SSL connection has been closed";
186 p = PY_SSL_ERROR_ZERO_RETURN;
187 break;
188 case SSL_ERROR_WANT_READ:
189 errstr = "The operation did not complete (read)";
190 p = PY_SSL_ERROR_WANT_READ;
191 break;
192 case SSL_ERROR_WANT_WRITE:
193 p = PY_SSL_ERROR_WANT_WRITE;
194 errstr = "The operation did not complete (write)";
195 break;
196 case SSL_ERROR_WANT_X509_LOOKUP:
197 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000198 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 break;
200 case SSL_ERROR_WANT_CONNECT:
201 p = PY_SSL_ERROR_WANT_CONNECT;
202 errstr = "The operation did not complete (connect)";
203 break;
204 case SSL_ERROR_SYSCALL:
205 {
206 unsigned long e = ERR_get_error();
207 if (e == 0) {
208 PySocketSockObject *s
209 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
210 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000211 p = PY_SSL_ERROR_EOF;
212 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000214 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000215 ERR_clear_error();
Antoine Pitrou525807b2010-05-12 14:05:24 +0000216 return s->errorhandler();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000217 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000218 p = PY_SSL_ERROR_SYSCALL;
219 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 }
221 } else {
222 p = PY_SSL_ERROR_SYSCALL;
223 /* XXX Protected by global interpreter lock */
224 errstr = ERR_error_string(e, NULL);
225 }
226 break;
227 }
228 case SSL_ERROR_SSL:
229 {
230 unsigned long e = ERR_get_error();
231 p = PY_SSL_ERROR_SSL;
232 if (e != 0)
233 /* XXX Protected by global interpreter lock */
234 errstr = ERR_error_string(e, NULL);
235 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000236 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000237 }
238 break;
239 }
240 default:
241 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
242 errstr = "Invalid error code";
243 }
244 } else {
245 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
246 }
247 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000248 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000249 v = Py_BuildValue("(is)", p, buf);
250 if (v != NULL) {
251 PyErr_SetObject(PySSLErrorObject, v);
252 Py_DECREF(v);
253 }
254 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000255}
256
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000257static PyObject *
258_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000260 char buf[2048];
261 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000263 if (errstr == NULL) {
264 errcode = ERR_peek_last_error();
265 errstr = ERR_error_string(errcode, NULL);
266 }
267 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000268 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000269 v = Py_BuildValue("(is)", errcode, buf);
270 if (v != NULL) {
271 PyErr_SetObject(PySSLErrorObject, v);
272 Py_DECREF(v);
273 }
274 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275}
276
Antoine Pitrou152efa22010-05-16 18:19:27 +0000277static PySSLSocket *
278newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
279 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000281 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000282
Antoine Pitrou152efa22010-05-16 18:19:27 +0000283 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 if (self == NULL)
285 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 self->peer_cert = NULL;
288 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000289 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000291 /* Make sure the SSL error state is initialized */
292 (void) ERR_get_state();
293 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000298 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000299#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000300 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000301#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 /* If the socket is in non-blocking mode or timeout mode, set the BIO
304 * to non-blocking mode (blocking is the default)
305 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000307 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
308 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
309 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000311 PySSL_BEGIN_ALLOW_THREADS
312 if (socket_type == PY_SSL_CLIENT)
313 SSL_set_connect_state(self->ssl);
314 else
315 SSL_set_accept_state(self->ssl);
316 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000317
Antoine Pitrou152efa22010-05-16 18:19:27 +0000318 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000320}
321
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000322/* SSL object methods */
323
Antoine Pitrou152efa22010-05-16 18:19:27 +0000324static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000325{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000326 int ret;
327 int err;
328 int sockstate, nonblocking;
329 PySocketSockObject *sock
330 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000332 if (((PyObject*)sock) == Py_None) {
333 _setSSLError("Underlying socket connection gone",
334 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
335 return NULL;
336 }
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000338 /* just in case the blocking state of the socket has been changed */
339 nonblocking = (sock->sock_timeout >= 0.0);
340 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
341 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000343 /* Actually negotiate SSL connection */
344 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
345 sockstate = 0;
346 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000347 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000348 ret = SSL_do_handshake(self->ssl);
349 err = SSL_get_error(self->ssl, ret);
350 PySSL_END_ALLOW_THREADS
351 if(PyErr_CheckSignals()) {
352 return NULL;
353 }
354 if (err == SSL_ERROR_WANT_READ) {
355 sockstate = check_socket_and_wait_for_timeout(sock, 0);
356 } else if (err == SSL_ERROR_WANT_WRITE) {
357 sockstate = check_socket_and_wait_for_timeout(sock, 1);
358 } else {
359 sockstate = SOCKET_OPERATION_OK;
360 }
361 if (sockstate == SOCKET_HAS_TIMED_OUT) {
362 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000363 ERRSTR("The handshake operation timed out"));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000364 return NULL;
365 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
366 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000367 ERRSTR("Underlying socket has been closed."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 return NULL;
369 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
370 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000371 ERRSTR("Underlying socket too large for select()."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 return NULL;
373 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
374 break;
375 }
376 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
377 if (ret < 1)
378 return PySSL_SetError(self, ret, __FILE__, __LINE__);
379 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 if (self->peer_cert)
382 X509_free (self->peer_cert);
383 PySSL_BEGIN_ALLOW_THREADS
384 self->peer_cert = SSL_get_peer_certificate(self->ssl);
385 PySSL_END_ALLOW_THREADS
386
387 Py_INCREF(Py_None);
388 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000389}
390
Thomas Woutersed03b412007-08-28 21:37:11 +0000391static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000392_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 char namebuf[X509_NAME_MAXLEN];
395 int buflen;
396 PyObject *name_obj;
397 PyObject *value_obj;
398 PyObject *attr;
399 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
402 if (buflen < 0) {
403 _setSSLError(NULL, 0, __FILE__, __LINE__);
404 goto fail;
405 }
406 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
407 if (name_obj == NULL)
408 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
411 if (buflen < 0) {
412 _setSSLError(NULL, 0, __FILE__, __LINE__);
413 Py_DECREF(name_obj);
414 goto fail;
415 }
416 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000417 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 OPENSSL_free(valuebuf);
419 if (value_obj == NULL) {
420 Py_DECREF(name_obj);
421 goto fail;
422 }
423 attr = PyTuple_New(2);
424 if (attr == NULL) {
425 Py_DECREF(name_obj);
426 Py_DECREF(value_obj);
427 goto fail;
428 }
429 PyTuple_SET_ITEM(attr, 0, name_obj);
430 PyTuple_SET_ITEM(attr, 1, value_obj);
431 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000432
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000435}
436
437static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000439{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000440 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
441 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
442 PyObject *rdnt;
443 PyObject *attr = NULL; /* tuple to hold an attribute */
444 int entry_count = X509_NAME_entry_count(xname);
445 X509_NAME_ENTRY *entry;
446 ASN1_OBJECT *name;
447 ASN1_STRING *value;
448 int index_counter;
449 int rdn_level = -1;
450 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 dn = PyList_New(0);
453 if (dn == NULL)
454 return NULL;
455 /* now create another tuple to hold the top-level RDN */
456 rdn = PyList_New(0);
457 if (rdn == NULL)
458 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 for (index_counter = 0;
461 index_counter < entry_count;
462 index_counter++)
463 {
464 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 /* check to see if we've gotten to a new RDN */
467 if (rdn_level >= 0) {
468 if (rdn_level != entry->set) {
469 /* yes, new RDN */
470 /* add old RDN to DN */
471 rdnt = PyList_AsTuple(rdn);
472 Py_DECREF(rdn);
473 if (rdnt == NULL)
474 goto fail0;
475 retcode = PyList_Append(dn, rdnt);
476 Py_DECREF(rdnt);
477 if (retcode < 0)
478 goto fail0;
479 /* create new RDN */
480 rdn = PyList_New(0);
481 if (rdn == NULL)
482 goto fail0;
483 }
484 }
485 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 /* now add this attribute to the current RDN */
488 name = X509_NAME_ENTRY_get_object(entry);
489 value = X509_NAME_ENTRY_get_data(entry);
490 attr = _create_tuple_for_attribute(name, value);
491 /*
492 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
493 entry->set,
494 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
495 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
496 */
497 if (attr == NULL)
498 goto fail1;
499 retcode = PyList_Append(rdn, attr);
500 Py_DECREF(attr);
501 if (retcode < 0)
502 goto fail1;
503 }
504 /* now, there's typically a dangling RDN */
505 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
506 rdnt = PyList_AsTuple(rdn);
507 Py_DECREF(rdn);
508 if (rdnt == NULL)
509 goto fail0;
510 retcode = PyList_Append(dn, rdnt);
511 Py_DECREF(rdnt);
512 if (retcode < 0)
513 goto fail0;
514 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* convert list to tuple */
517 rdnt = PyList_AsTuple(dn);
518 Py_DECREF(dn);
519 if (rdnt == NULL)
520 return NULL;
521 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
523 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525
526 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 Py_XDECREF(dn);
528 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529}
530
531static PyObject *
532_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 /* this code follows the procedure outlined in
535 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
536 function to extract the STACK_OF(GENERAL_NAME),
537 then iterates through the stack to add the
538 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 int i, j;
541 PyObject *peer_alt_names = Py_None;
542 PyObject *v, *t;
543 X509_EXTENSION *ext = NULL;
544 GENERAL_NAMES *names = NULL;
545 GENERAL_NAME *name;
546 X509V3_EXT_METHOD *method;
547 BIO *biobuf = NULL;
548 char buf[2048];
549 char *vptr;
550 int len;
551 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000552#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000554#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000555 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000556#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 if (certificate == NULL)
559 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 /* get a memory buffer */
562 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 i = 0;
565 while ((i = X509_get_ext_by_NID(
566 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 if (peer_alt_names == Py_None) {
569 peer_alt_names = PyList_New(0);
570 if (peer_alt_names == NULL)
571 goto fail;
572 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 /* now decode the altName */
575 ext = X509_get_ext(certificate, i);
576 if(!(method = X509V3_EXT_get(ext))) {
577 PyErr_SetString
578 (PySSLErrorObject,
579 ERRSTR("No method for internalizing subjectAltName!"));
580 goto fail;
581 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 p = ext->value->data;
584 if (method->it)
585 names = (GENERAL_NAMES*)
586 (ASN1_item_d2i(NULL,
587 &p,
588 ext->value->length,
589 ASN1_ITEM_ptr(method->it)));
590 else
591 names = (GENERAL_NAMES*)
592 (method->d2i(NULL,
593 &p,
594 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 name = sk_GENERAL_NAME_value(names, j);
601 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 /* we special-case DirName as a tuple of
604 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 t = PyTuple_New(2);
607 if (t == NULL) {
608 goto fail;
609 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 v = PyUnicode_FromString("DirName");
612 if (v == NULL) {
613 Py_DECREF(t);
614 goto fail;
615 }
616 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 v = _create_tuple_for_X509_NAME (name->d.dirn);
619 if (v == NULL) {
620 Py_DECREF(t);
621 goto fail;
622 }
623 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 (void) BIO_reset(biobuf);
630 GENERAL_NAME_print(biobuf, name);
631 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
632 if (len < 0) {
633 _setSSLError(NULL, 0, __FILE__, __LINE__);
634 goto fail;
635 }
636 vptr = strchr(buf, ':');
637 if (vptr == NULL)
638 goto fail;
639 t = PyTuple_New(2);
640 if (t == NULL)
641 goto fail;
642 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
643 if (v == NULL) {
644 Py_DECREF(t);
645 goto fail;
646 }
647 PyTuple_SET_ITEM(t, 0, v);
648 v = PyUnicode_FromStringAndSize((vptr + 1),
649 (len - (vptr - buf + 1)));
650 if (v == NULL) {
651 Py_DECREF(t);
652 goto fail;
653 }
654 PyTuple_SET_ITEM(t, 1, v);
655 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 if (PyList_Append(peer_alt_names, t) < 0) {
660 Py_DECREF(t);
661 goto fail;
662 }
663 Py_DECREF(t);
664 }
665 }
666 BIO_free(biobuf);
667 if (peer_alt_names != Py_None) {
668 v = PyList_AsTuple(peer_alt_names);
669 Py_DECREF(peer_alt_names);
670 return v;
671 } else {
672 return peer_alt_names;
673 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000674
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
676 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 if (biobuf != NULL)
678 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 if (peer_alt_names != Py_None) {
681 Py_XDECREF(peer_alt_names);
682 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685}
686
687static PyObject *
688_decode_certificate (X509 *certificate, int verbose) {
689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 PyObject *retval = NULL;
691 BIO *biobuf = NULL;
692 PyObject *peer;
693 PyObject *peer_alt_names = NULL;
694 PyObject *issuer;
695 PyObject *version;
696 PyObject *sn_obj;
697 ASN1_INTEGER *serialNumber;
698 char buf[2048];
699 int len;
700 ASN1_TIME *notBefore, *notAfter;
701 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000703 retval = PyDict_New();
704 if (retval == NULL)
705 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 peer = _create_tuple_for_X509_NAME(
708 X509_get_subject_name(certificate));
709 if (peer == NULL)
710 goto fail0;
711 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
712 Py_DECREF(peer);
713 goto fail0;
714 }
715 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 if (verbose) {
718 issuer = _create_tuple_for_X509_NAME(
719 X509_get_issuer_name(certificate));
720 if (issuer == NULL)
721 goto fail0;
722 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
723 Py_DECREF(issuer);
724 goto fail0;
725 }
726 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000727
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 version = PyLong_FromLong(X509_get_version(certificate) + 1);
729 if (PyDict_SetItemString(retval, "version", version) < 0) {
730 Py_DECREF(version);
731 goto fail0;
732 }
733 Py_DECREF(version);
734 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 /* get a memory buffer */
737 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000738
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 (void) BIO_reset(biobuf);
742 serialNumber = X509_get_serialNumber(certificate);
743 /* should not exceed 20 octets, 160 bits, so buf is big enough */
744 i2a_ASN1_INTEGER(biobuf, serialNumber);
745 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
746 if (len < 0) {
747 _setSSLError(NULL, 0, __FILE__, __LINE__);
748 goto fail1;
749 }
750 sn_obj = PyUnicode_FromStringAndSize(buf, len);
751 if (sn_obj == NULL)
752 goto fail1;
753 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
754 Py_DECREF(sn_obj);
755 goto fail1;
756 }
757 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 (void) BIO_reset(biobuf);
760 notBefore = X509_get_notBefore(certificate);
761 ASN1_TIME_print(biobuf, notBefore);
762 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
763 if (len < 0) {
764 _setSSLError(NULL, 0, __FILE__, __LINE__);
765 goto fail1;
766 }
767 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
768 if (pnotBefore == NULL)
769 goto fail1;
770 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
771 Py_DECREF(pnotBefore);
772 goto fail1;
773 }
774 Py_DECREF(pnotBefore);
775 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000776
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 (void) BIO_reset(biobuf);
778 notAfter = X509_get_notAfter(certificate);
779 ASN1_TIME_print(biobuf, notAfter);
780 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
781 if (len < 0) {
782 _setSSLError(NULL, 0, __FILE__, __LINE__);
783 goto fail1;
784 }
785 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
786 if (pnotAfter == NULL)
787 goto fail1;
788 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
789 Py_DECREF(pnotAfter);
790 goto fail1;
791 }
792 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 peer_alt_names = _get_peer_alt_names(certificate);
797 if (peer_alt_names == NULL)
798 goto fail1;
799 else if (peer_alt_names != Py_None) {
800 if (PyDict_SetItemString(retval, "subjectAltName",
801 peer_alt_names) < 0) {
802 Py_DECREF(peer_alt_names);
803 goto fail1;
804 }
805 Py_DECREF(peer_alt_names);
806 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 BIO_free(biobuf);
809 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000810
811 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 if (biobuf != NULL)
813 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000814 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 Py_XDECREF(retval);
816 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000817}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000818
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
820static PyObject *
821PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000824 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 X509 *x=NULL;
826 BIO *cert;
827 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Victor Stinner3800e1e2010-05-16 21:23:48 +0000829 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
830 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 if ((cert=BIO_new(BIO_s_file())) == NULL) {
834 PyErr_SetString(PySSLErrorObject,
835 "Can't malloc memory to read file");
836 goto fail0;
837 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Victor Stinner3800e1e2010-05-16 21:23:48 +0000839 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 PyErr_SetString(PySSLErrorObject,
841 "Can't open file");
842 goto fail0;
843 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
846 if (x == NULL) {
847 PyErr_SetString(PySSLErrorObject,
848 "Error decoding PEM-encoded file");
849 goto fail0;
850 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853
854 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000855 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 if (cert != NULL) BIO_free(cert);
857 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000858}
859
860
861static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000862PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 PyObject *retval = NULL;
865 int len;
866 int verification;
867 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
870 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 if (!self->peer_cert)
873 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 if (PyObject_IsTrue(binary_mode)) {
876 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 bytes_buf = NULL;
881 len = i2d_X509(self->peer_cert, &bytes_buf);
882 if (len < 0) {
883 PySSL_SetError(self, len, __FILE__, __LINE__);
884 return NULL;
885 }
886 /* this is actually an immutable bytes sequence */
887 retval = PyBytes_FromStringAndSize
888 ((const char *) bytes_buf, len);
889 OPENSSL_free(bytes_buf);
890 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000893 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 if ((verification & SSL_VERIFY_PEER) == 0)
895 return PyDict_New();
896 else
897 return _decode_certificate (self->peer_cert, 0);
898 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899}
900
901PyDoc_STRVAR(PySSL_peercert_doc,
902"peer_certificate([der=False]) -> certificate\n\
903\n\
904Returns the certificate for the peer. If no certificate was provided,\n\
905returns None. If a certificate was provided, but not validated, returns\n\
906an empty dictionary. Otherwise returns a dict containing information\n\
907about the peer certificate.\n\
908\n\
909If the optional argument is True, returns a DER-encoded copy of the\n\
910peer certificate, or None if no certificate was provided. This will\n\
911return the certificate even if it wasn't validated.");
912
Antoine Pitrou152efa22010-05-16 18:19:27 +0000913static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 PyObject *retval, *v;
916 SSL_CIPHER *current;
917 char *cipher_name;
918 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 if (self->ssl == NULL)
921 return Py_None;
922 current = SSL_get_current_cipher(self->ssl);
923 if (current == NULL)
924 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 retval = PyTuple_New(3);
927 if (retval == NULL)
928 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 cipher_name = (char *) SSL_CIPHER_get_name(current);
931 if (cipher_name == NULL) {
932 PyTuple_SET_ITEM(retval, 0, Py_None);
933 } else {
934 v = PyUnicode_FromString(cipher_name);
935 if (v == NULL)
936 goto fail0;
937 PyTuple_SET_ITEM(retval, 0, v);
938 }
939 cipher_protocol = SSL_CIPHER_get_version(current);
940 if (cipher_protocol == NULL) {
941 PyTuple_SET_ITEM(retval, 1, Py_None);
942 } else {
943 v = PyUnicode_FromString(cipher_protocol);
944 if (v == NULL)
945 goto fail0;
946 PyTuple_SET_ITEM(retval, 1, v);
947 }
948 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
949 if (v == NULL)
950 goto fail0;
951 PyTuple_SET_ITEM(retval, 2, v);
952 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000953
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 Py_DECREF(retval);
956 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957}
958
Antoine Pitrou152efa22010-05-16 18:19:27 +0000959static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000960{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 if (self->peer_cert) /* Possible not to have one? */
962 X509_free (self->peer_cert);
963 if (self->ssl)
964 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 Py_XDECREF(self->Socket);
966 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000967}
968
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000969/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000970 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000971 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000972 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000973
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000974static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000975check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000976{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 fd_set fds;
978 struct timeval tv;
979 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 /* Nothing to do unless we're in timeout mode (not non-blocking) */
982 if (s->sock_timeout < 0.0)
983 return SOCKET_IS_BLOCKING;
984 else if (s->sock_timeout == 0.0)
985 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 /* Guard against closed socket */
988 if (s->sock_fd < 0)
989 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 /* Prefer poll, if available, since you can poll() any fd
992 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000993#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 {
995 struct pollfd pollfd;
996 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 pollfd.fd = s->sock_fd;
999 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* s->sock_timeout is in seconds, timeout in ms */
1002 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1003 PySSL_BEGIN_ALLOW_THREADS
1004 rc = poll(&pollfd, 1, timeout);
1005 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 goto normal_return;
1008 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009#endif
1010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001012#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 if (s->sock_fd >= FD_SETSIZE)
1014 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001015#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 /* Construct the arguments to select */
1018 tv.tv_sec = (int)s->sock_timeout;
1019 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1020 FD_ZERO(&fds);
1021 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 /* See if the socket is ready */
1024 PySSL_BEGIN_ALLOW_THREADS
1025 if (writing)
1026 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1027 else
1028 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1029 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001030
Bill Janssen6e027db2007-11-15 22:23:56 +00001031#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001032normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001033#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1035 (when we are able to write or when there's something to read) */
1036 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001037}
1038
Antoine Pitrou152efa22010-05-16 18:19:27 +00001039static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001040{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 Py_buffer buf;
1042 int len;
1043 int sockstate;
1044 int err;
1045 int nonblocking;
1046 PySocketSockObject *sock
1047 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 if (((PyObject*)sock) == Py_None) {
1050 _setSSLError("Underlying socket connection gone",
1051 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1052 return NULL;
1053 }
1054
1055 if (!PyArg_ParseTuple(args, "y*:write", &buf))
1056 return NULL;
1057
1058 /* just in case the blocking state of the socket has been changed */
1059 nonblocking = (sock->sock_timeout >= 0.0);
1060 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1061 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1062
1063 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1064 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1065 PyErr_SetString(PySSLErrorObject,
1066 "The write operation timed out");
1067 goto error;
1068 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1069 PyErr_SetString(PySSLErrorObject,
1070 "Underlying socket has been closed.");
1071 goto error;
1072 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1073 PyErr_SetString(PySSLErrorObject,
1074 "Underlying socket too large for select().");
1075 goto error;
1076 }
1077 do {
1078 err = 0;
1079 PySSL_BEGIN_ALLOW_THREADS
1080 len = SSL_write(self->ssl, buf.buf, buf.len);
1081 err = SSL_get_error(self->ssl, len);
1082 PySSL_END_ALLOW_THREADS
1083 if (PyErr_CheckSignals()) {
1084 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001085 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001087 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001089 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 } else {
1091 sockstate = SOCKET_OPERATION_OK;
1092 }
1093 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1094 PyErr_SetString(PySSLErrorObject,
1095 "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_IS_NONBLOCKING) {
1102 break;
1103 }
1104 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 PyBuffer_Release(&buf);
1107 if (len > 0)
1108 return PyLong_FromLong(len);
1109 else
1110 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001111
1112error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 PyBuffer_Release(&buf);
1114 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001115}
1116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001117PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001118"write(s) -> len\n\
1119\n\
1120Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001121of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001122
Antoine Pitrou152efa22010-05-16 18:19:27 +00001123static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001124{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 PySSL_BEGIN_ALLOW_THREADS
1128 count = SSL_pending(self->ssl);
1129 PySSL_END_ALLOW_THREADS
1130 if (count < 0)
1131 return PySSL_SetError(self, count, __FILE__, __LINE__);
1132 else
1133 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001134}
1135
1136PyDoc_STRVAR(PySSL_SSLpending_doc,
1137"pending() -> count\n\
1138\n\
1139Returns the number of already decrypted bytes available for read,\n\
1140pending on the connection.\n");
1141
Antoine Pitrou152efa22010-05-16 18:19:27 +00001142static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001143{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 PyObject *dest = NULL;
1145 Py_buffer buf;
1146 int buf_passed = 0;
1147 int count = -1;
1148 char *mem;
1149 /* XXX this should use Py_ssize_t */
1150 int len = 1024;
1151 int sockstate;
1152 int err;
1153 int nonblocking;
1154 PySocketSockObject *sock
1155 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 if (((PyObject*)sock) == Py_None) {
1158 _setSSLError("Underlying socket connection gone",
1159 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1160 return NULL;
1161 }
1162
1163 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1164 return NULL;
1165 if ((dest == NULL) || (dest == Py_None)) {
1166 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1167 return NULL;
1168 mem = PyByteArray_AS_STRING(dest);
1169 } else if (PyLong_Check(dest)) {
1170 len = PyLong_AS_LONG(dest);
1171 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1172 return NULL;
1173 mem = PyByteArray_AS_STRING(dest);
1174 } else {
1175 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1176 return NULL;
1177 mem = buf.buf;
1178 len = buf.len;
1179 if ((count > 0) && (count <= len))
1180 len = count;
1181 buf_passed = 1;
1182 }
1183
1184 /* just in case the blocking state of the socket has been changed */
1185 nonblocking = (sock->sock_timeout >= 0.0);
1186 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1187 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1188
1189 /* first check if there are bytes ready to be read */
1190 PySSL_BEGIN_ALLOW_THREADS
1191 count = SSL_pending(self->ssl);
1192 PySSL_END_ALLOW_THREADS
1193
1194 if (!count) {
1195 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1196 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1197 PyErr_SetString(PySSLErrorObject,
1198 "The read operation timed out");
1199 goto error;
1200 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1201 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001202 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 goto error;
1204 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1205 count = 0;
1206 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001207 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 }
1209 do {
1210 err = 0;
1211 PySSL_BEGIN_ALLOW_THREADS
1212 count = SSL_read(self->ssl, mem, len);
1213 err = SSL_get_error(self->ssl, count);
1214 PySSL_END_ALLOW_THREADS
1215 if (PyErr_CheckSignals())
1216 goto error;
1217 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001218 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001220 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1222 (SSL_get_shutdown(self->ssl) ==
1223 SSL_RECEIVED_SHUTDOWN))
1224 {
1225 count = 0;
1226 goto done;
1227 } else {
1228 sockstate = SOCKET_OPERATION_OK;
1229 }
1230 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1231 PyErr_SetString(PySSLErrorObject,
1232 "The read operation timed out");
1233 goto error;
1234 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1235 break;
1236 }
1237 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1238 if (count <= 0) {
1239 PySSL_SetError(self, count, __FILE__, __LINE__);
1240 goto error;
1241 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001242 done:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 if (!buf_passed) {
1244 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1245 Py_DECREF(dest);
1246 return res;
1247 } else {
1248 PyBuffer_Release(&buf);
1249 return PyLong_FromLong(count);
1250 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001251 error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 if (!buf_passed) {
1253 Py_DECREF(dest);
1254 } else {
1255 PyBuffer_Release(&buf);
1256 }
1257 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001258}
1259
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001260PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001261"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001262\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001263Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001264
Antoine Pitrou152efa22010-05-16 18:19:27 +00001265static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001266{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 int err, ssl_err, sockstate, nonblocking;
1268 int zeros = 0;
1269 PySocketSockObject *sock
1270 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 /* Guard against closed socket */
1273 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1274 _setSSLError("Underlying socket connection gone",
1275 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1276 return NULL;
1277 }
1278
1279 /* Just in case the blocking state of the socket has been changed */
1280 nonblocking = (sock->sock_timeout >= 0.0);
1281 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1282 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1283
1284 while (1) {
1285 PySSL_BEGIN_ALLOW_THREADS
1286 /* Disable read-ahead so that unwrap can work correctly.
1287 * Otherwise OpenSSL might read in too much data,
1288 * eating clear text data that happens to be
1289 * transmitted after the SSL shutdown.
1290 * Should be safe to call repeatedly everytime this
1291 * function is used and the shutdown_seen_zero != 0
1292 * condition is met.
1293 */
1294 if (self->shutdown_seen_zero)
1295 SSL_set_read_ahead(self->ssl, 0);
1296 err = SSL_shutdown(self->ssl);
1297 PySSL_END_ALLOW_THREADS
1298 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1299 if (err > 0)
1300 break;
1301 if (err == 0) {
1302 /* Don't loop endlessly; instead preserve legacy
1303 behaviour of trying SSL_shutdown() only twice.
1304 This looks necessary for OpenSSL < 0.9.8m */
1305 if (++zeros > 1)
1306 break;
1307 /* Shutdown was sent, now try receiving */
1308 self->shutdown_seen_zero = 1;
1309 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001310 }
1311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 /* Possibly retry shutdown until timeout or failure */
1313 ssl_err = SSL_get_error(self->ssl, err);
1314 if (ssl_err == SSL_ERROR_WANT_READ)
1315 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1316 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1317 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1318 else
1319 break;
1320 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1321 if (ssl_err == SSL_ERROR_WANT_READ)
1322 PyErr_SetString(PySSLErrorObject,
1323 "The read operation timed out");
1324 else
1325 PyErr_SetString(PySSLErrorObject,
1326 "The write operation timed out");
1327 return NULL;
1328 }
1329 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1330 PyErr_SetString(PySSLErrorObject,
1331 "Underlying socket too large for select().");
1332 return NULL;
1333 }
1334 else if (sockstate != SOCKET_OPERATION_OK)
1335 /* Retain the SSL error code */
1336 break;
1337 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 if (err < 0)
1340 return PySSL_SetError(self, err, __FILE__, __LINE__);
1341 else {
1342 Py_INCREF(sock);
1343 return (PyObject *) sock;
1344 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001345}
1346
1347PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1348"shutdown(s) -> socket\n\
1349\n\
1350Does the SSL shutdown handshake with the remote end, and returns\n\
1351the underlying socket object.");
1352
1353
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1356 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1357 PySSL_SSLwrite_doc},
1358 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1359 PySSL_SSLread_doc},
1360 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1361 PySSL_SSLpending_doc},
1362 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1363 PySSL_peercert_doc},
1364 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1365 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1366 PySSL_SSLshutdown_doc},
1367 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001368};
1369
Antoine Pitrou152efa22010-05-16 18:19:27 +00001370static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001372 "_ssl._SSLSocket", /*tp_name*/
1373 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 0, /*tp_itemsize*/
1375 /* methods */
1376 (destructor)PySSL_dealloc, /*tp_dealloc*/
1377 0, /*tp_print*/
1378 0, /*tp_getattr*/
1379 0, /*tp_setattr*/
1380 0, /*tp_reserved*/
1381 0, /*tp_repr*/
1382 0, /*tp_as_number*/
1383 0, /*tp_as_sequence*/
1384 0, /*tp_as_mapping*/
1385 0, /*tp_hash*/
1386 0, /*tp_call*/
1387 0, /*tp_str*/
1388 0, /*tp_getattro*/
1389 0, /*tp_setattro*/
1390 0, /*tp_as_buffer*/
1391 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1392 0, /*tp_doc*/
1393 0, /*tp_traverse*/
1394 0, /*tp_clear*/
1395 0, /*tp_richcompare*/
1396 0, /*tp_weaklistoffset*/
1397 0, /*tp_iter*/
1398 0, /*tp_iternext*/
1399 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400};
1401
Antoine Pitrou152efa22010-05-16 18:19:27 +00001402
1403/*
1404 * _SSLContext objects
1405 */
1406
1407static PyObject *
1408context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1409{
1410 char *kwlist[] = {"protocol", NULL};
1411 PySSLContext *self;
1412 int proto_version = PY_SSL_VERSION_SSL23;
1413 SSL_CTX *ctx = NULL;
1414
1415 if (!PyArg_ParseTupleAndKeywords(
1416 args, kwds, "i:_SSLContext", kwlist,
1417 &proto_version))
1418 return NULL;
1419
1420 PySSL_BEGIN_ALLOW_THREADS
1421 if (proto_version == PY_SSL_VERSION_TLS1)
1422 ctx = SSL_CTX_new(TLSv1_method());
1423 else if (proto_version == PY_SSL_VERSION_SSL3)
1424 ctx = SSL_CTX_new(SSLv3_method());
1425 else if (proto_version == PY_SSL_VERSION_SSL2)
1426 ctx = SSL_CTX_new(SSLv2_method());
1427 else if (proto_version == PY_SSL_VERSION_SSL23)
1428 ctx = SSL_CTX_new(SSLv23_method());
1429 else
1430 proto_version = -1;
1431 PySSL_END_ALLOW_THREADS
1432
1433 if (proto_version == -1) {
1434 PyErr_SetString(PyExc_ValueError,
1435 "invalid protocol version");
1436 return NULL;
1437 }
1438 if (ctx == NULL) {
1439 PyErr_SetString(PySSLErrorObject,
1440 "failed to allocate SSL context");
1441 return NULL;
1442 }
1443
1444 assert(type != NULL && type->tp_alloc != NULL);
1445 self = (PySSLContext *) type->tp_alloc(type, 0);
1446 if (self == NULL) {
1447 SSL_CTX_free(ctx);
1448 return NULL;
1449 }
1450 self->ctx = ctx;
1451 /* Defaults */
1452 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1453 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1454
1455 return (PyObject *)self;
1456}
1457
1458static void
1459context_dealloc(PySSLContext *self)
1460{
1461 SSL_CTX_free(self->ctx);
1462 Py_TYPE(self)->tp_free(self);
1463}
1464
1465static PyObject *
1466set_ciphers(PySSLContext *self, PyObject *args)
1467{
1468 int ret;
1469 const char *cipherlist;
1470
1471 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1472 return NULL;
1473 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1474 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001475 /* Clearing the error queue is necessary on some OpenSSL versions,
1476 otherwise the error will be reported again when another SSL call
1477 is done. */
1478 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001479 PyErr_SetString(PySSLErrorObject,
1480 "No cipher can be selected.");
1481 return NULL;
1482 }
1483 Py_RETURN_NONE;
1484}
1485
1486static PyObject *
1487get_verify_mode(PySSLContext *self, void *c)
1488{
1489 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1490 case SSL_VERIFY_NONE:
1491 return PyLong_FromLong(PY_SSL_CERT_NONE);
1492 case SSL_VERIFY_PEER:
1493 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1494 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1495 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1496 }
1497 PyErr_SetString(PySSLErrorObject,
1498 "invalid return value from SSL_CTX_get_verify_mode");
1499 return NULL;
1500}
1501
1502static int
1503set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1504{
1505 int n, mode;
1506 if (!PyArg_Parse(arg, "i", &n))
1507 return -1;
1508 if (n == PY_SSL_CERT_NONE)
1509 mode = SSL_VERIFY_NONE;
1510 else if (n == PY_SSL_CERT_OPTIONAL)
1511 mode = SSL_VERIFY_PEER;
1512 else if (n == PY_SSL_CERT_REQUIRED)
1513 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1514 else {
1515 PyErr_SetString(PyExc_ValueError,
1516 "invalid value for verify_mode");
1517 return -1;
1518 }
1519 SSL_CTX_set_verify(self->ctx, mode, NULL);
1520 return 0;
1521}
1522
1523static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001524get_options(PySSLContext *self, void *c)
1525{
1526 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1527}
1528
1529static int
1530set_options(PySSLContext *self, PyObject *arg, void *c)
1531{
1532 long new_opts, opts, set, clear;
1533 if (!PyArg_Parse(arg, "l", &new_opts))
1534 return -1;
1535 opts = SSL_CTX_get_options(self->ctx);
1536 clear = opts & ~new_opts;
1537 set = ~opts & new_opts;
1538 if (clear) {
1539#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1540 SSL_CTX_clear_options(self->ctx, clear);
1541#else
1542 PyErr_SetString(PyExc_ValueError,
1543 "can't clear options before OpenSSL 0.9.8m");
1544 return -1;
1545#endif
1546 }
1547 if (set)
1548 SSL_CTX_set_options(self->ctx, set);
1549 return 0;
1550}
1551
1552static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001553load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1554{
1555 char *kwlist[] = {"certfile", "keyfile", NULL};
1556 PyObject *certfile, *keyfile = NULL;
1557 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1558 int r;
1559
1560 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1561 "O|O:load_cert_chain", kwlist,
1562 &certfile, &keyfile))
1563 return NULL;
1564 if (keyfile == Py_None)
1565 keyfile = NULL;
1566 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1567 PyErr_SetString(PyExc_TypeError,
1568 "certfile should be a valid filesystem path");
1569 return NULL;
1570 }
1571 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1572 PyErr_SetString(PyExc_TypeError,
1573 "keyfile should be a valid filesystem path");
1574 goto error;
1575 }
1576 PySSL_BEGIN_ALLOW_THREADS
1577 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1578 PyBytes_AS_STRING(certfile_bytes));
1579 PySSL_END_ALLOW_THREADS
1580 if (r != 1) {
1581 _setSSLError(NULL, 0, __FILE__, __LINE__);
1582 goto error;
1583 }
1584 PySSL_BEGIN_ALLOW_THREADS
1585 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1586 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1587 SSL_FILETYPE_PEM);
1588 PySSL_END_ALLOW_THREADS
1589 Py_XDECREF(keyfile_bytes);
1590 Py_XDECREF(certfile_bytes);
1591 if (r != 1) {
1592 _setSSLError(NULL, 0, __FILE__, __LINE__);
1593 return NULL;
1594 }
1595 PySSL_BEGIN_ALLOW_THREADS
1596 r = SSL_CTX_check_private_key(self->ctx);
1597 PySSL_END_ALLOW_THREADS
1598 if (r != 1) {
1599 _setSSLError(NULL, 0, __FILE__, __LINE__);
1600 return NULL;
1601 }
1602 Py_RETURN_NONE;
1603
1604error:
1605 Py_XDECREF(keyfile_bytes);
1606 Py_XDECREF(certfile_bytes);
1607 return NULL;
1608}
1609
1610static PyObject *
1611load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1612{
1613 char *kwlist[] = {"cafile", "capath", NULL};
1614 PyObject *cafile = NULL, *capath = NULL;
1615 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1616 const char *cafile_buf = NULL, *capath_buf = NULL;
1617 int r;
1618
1619 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1620 "|OO:load_verify_locations", kwlist,
1621 &cafile, &capath))
1622 return NULL;
1623 if (cafile == Py_None)
1624 cafile = NULL;
1625 if (capath == Py_None)
1626 capath = NULL;
1627 if (cafile == NULL && capath == NULL) {
1628 PyErr_SetString(PyExc_TypeError,
1629 "cafile and capath cannot be both omitted");
1630 return NULL;
1631 }
1632 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1633 PyErr_SetString(PyExc_TypeError,
1634 "cafile should be a valid filesystem path");
1635 return NULL;
1636 }
1637 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1638 Py_DECREF(cafile_bytes);
1639 PyErr_SetString(PyExc_TypeError,
1640 "capath should be a valid filesystem path");
1641 return NULL;
1642 }
1643 if (cafile)
1644 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1645 if (capath)
1646 capath_buf = PyBytes_AS_STRING(capath_bytes);
1647 PySSL_BEGIN_ALLOW_THREADS
1648 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1649 PySSL_END_ALLOW_THREADS
1650 Py_XDECREF(cafile_bytes);
1651 Py_XDECREF(capath_bytes);
1652 if (r != 1) {
1653 _setSSLError(NULL, 0, __FILE__, __LINE__);
1654 return NULL;
1655 }
1656 Py_RETURN_NONE;
1657}
1658
1659static PyObject *
1660context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1661{
1662 char *kwlist[] = {"sock", "server_side", NULL};
1663 PySocketSockObject *sock;
1664 int server_side = 0;
1665
1666 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1667 PySocketModule.Sock_Type,
1668 &sock, &server_side))
1669 return NULL;
1670
1671 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1672}
1673
1674static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001675 {"options", (getter) get_options,
1676 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001677 {"verify_mode", (getter) get_verify_mode,
1678 (setter) set_verify_mode, NULL},
1679 {NULL}, /* sentinel */
1680};
1681
1682static struct PyMethodDef context_methods[] = {
1683 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1684 METH_VARARGS | METH_KEYWORDS, NULL},
1685 {"set_ciphers", (PyCFunction) set_ciphers,
1686 METH_VARARGS, NULL},
1687 {"load_cert_chain", (PyCFunction) load_cert_chain,
1688 METH_VARARGS | METH_KEYWORDS, NULL},
1689 {"load_verify_locations", (PyCFunction) load_verify_locations,
1690 METH_VARARGS | METH_KEYWORDS, NULL},
1691 {NULL, NULL} /* sentinel */
1692};
1693
1694static PyTypeObject PySSLContext_Type = {
1695 PyVarObject_HEAD_INIT(NULL, 0)
1696 "_ssl._SSLContext", /*tp_name*/
1697 sizeof(PySSLContext), /*tp_basicsize*/
1698 0, /*tp_itemsize*/
1699 (destructor)context_dealloc, /*tp_dealloc*/
1700 0, /*tp_print*/
1701 0, /*tp_getattr*/
1702 0, /*tp_setattr*/
1703 0, /*tp_reserved*/
1704 0, /*tp_repr*/
1705 0, /*tp_as_number*/
1706 0, /*tp_as_sequence*/
1707 0, /*tp_as_mapping*/
1708 0, /*tp_hash*/
1709 0, /*tp_call*/
1710 0, /*tp_str*/
1711 0, /*tp_getattro*/
1712 0, /*tp_setattro*/
1713 0, /*tp_as_buffer*/
1714 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1715 0, /*tp_doc*/
1716 0, /*tp_traverse*/
1717 0, /*tp_clear*/
1718 0, /*tp_richcompare*/
1719 0, /*tp_weaklistoffset*/
1720 0, /*tp_iter*/
1721 0, /*tp_iternext*/
1722 context_methods, /*tp_methods*/
1723 0, /*tp_members*/
1724 context_getsetlist, /*tp_getset*/
1725 0, /*tp_base*/
1726 0, /*tp_dict*/
1727 0, /*tp_descr_get*/
1728 0, /*tp_descr_set*/
1729 0, /*tp_dictoffset*/
1730 0, /*tp_init*/
1731 0, /*tp_alloc*/
1732 context_new, /*tp_new*/
1733};
1734
1735
1736
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001737#ifdef HAVE_OPENSSL_RAND
1738
1739/* helper routines for seeding the SSL PRNG */
1740static PyObject *
1741PySSL_RAND_add(PyObject *self, PyObject *args)
1742{
1743 char *buf;
1744 int len;
1745 double entropy;
1746
1747 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001748 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001749 RAND_add(buf, len, entropy);
1750 Py_INCREF(Py_None);
1751 return Py_None;
1752}
1753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001754PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001755"RAND_add(string, entropy)\n\
1756\n\
1757Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001759
1760static PyObject *
1761PySSL_RAND_status(PyObject *self)
1762{
Christian Heimes217cfd12007-12-02 14:31:20 +00001763 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001764}
1765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001766PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001767"RAND_status() -> 0 or 1\n\
1768\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001769Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1770It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1771using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772
1773static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001774PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001775{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001776 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001777 int bytes;
1778
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001779 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1780 PyUnicode_FSConverter, &path))
1781 return NULL;
1782
1783 bytes = RAND_egd(PyBytes_AsString(path));
1784 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001785 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001786 PyErr_SetString(PySSLErrorObject,
1787 "EGD connection failed or EGD did not return "
1788 "enough data to seed the PRNG");
1789 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001790 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001791 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001792}
1793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001795"RAND_egd(path) -> bytes\n\
1796\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001797Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1798Returns number of bytes read. Raises SSLError if connection to EGD\n\
1799fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001800
1801#endif
1802
Bill Janssen40a0f662008-08-12 16:56:25 +00001803
1804
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001805/* List of functions exported by this module. */
1806
1807static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 {"_test_decode_cert", PySSL_test_decode_certificate,
1809 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001810#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1812 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001813 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 PySSL_RAND_egd_doc},
1815 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1816 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001817#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001819};
1820
1821
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001822#ifdef WITH_THREAD
1823
1824/* an implementation of OpenSSL threading operations in terms
1825 of the Python C thread library */
1826
1827static PyThread_type_lock *_ssl_locks = NULL;
1828
1829static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001831}
1832
Bill Janssen6e027db2007-11-15 22:23:56 +00001833static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 (int mode, int n, const char *file, int line) {
1835 /* this function is needed to perform locking on shared data
1836 structures. (Note that OpenSSL uses a number of global data
1837 structures that will be implicitly shared whenever multiple
1838 threads use OpenSSL.) Multi-threaded applications will
1839 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 locking_function() must be able to handle up to
1842 CRYPTO_num_locks() different mutex locks. It sets the n-th
1843 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 file and line are the file number of the function setting the
1846 lock. They can be useful for debugging.
1847 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 if ((_ssl_locks == NULL) ||
1850 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1851 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001852
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 if (mode & CRYPTO_LOCK) {
1854 PyThread_acquire_lock(_ssl_locks[n], 1);
1855 } else {
1856 PyThread_release_lock(_ssl_locks[n]);
1857 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001858}
1859
1860static int _setup_ssl_threads(void) {
1861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 if (_ssl_locks == NULL) {
1865 _ssl_locks_count = CRYPTO_num_locks();
1866 _ssl_locks = (PyThread_type_lock *)
1867 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1868 if (_ssl_locks == NULL)
1869 return 0;
1870 memset(_ssl_locks, 0,
1871 sizeof(PyThread_type_lock) * _ssl_locks_count);
1872 for (i = 0; i < _ssl_locks_count; i++) {
1873 _ssl_locks[i] = PyThread_allocate_lock();
1874 if (_ssl_locks[i] == NULL) {
1875 unsigned int j;
1876 for (j = 0; j < i; j++) {
1877 PyThread_free_lock(_ssl_locks[j]);
1878 }
1879 free(_ssl_locks);
1880 return 0;
1881 }
1882 }
1883 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1884 CRYPTO_set_id_callback(_ssl_thread_id_function);
1885 }
1886 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887}
1888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001892"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001893for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001894
Martin v. Löwis1a214512008-06-11 05:26:20 +00001895
1896static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001897 PyModuleDef_HEAD_INIT,
1898 "_ssl",
1899 module_doc,
1900 -1,
1901 PySSL_methods,
1902 NULL,
1903 NULL,
1904 NULL,
1905 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001906};
1907
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001908PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001909PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001910{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 PyObject *m, *d, *r;
1912 unsigned long libver;
1913 unsigned int major, minor, fix, patch, status;
1914 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001915
Antoine Pitrou152efa22010-05-16 18:19:27 +00001916 if (PyType_Ready(&PySSLContext_Type) < 0)
1917 return NULL;
1918 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 m = PyModule_Create(&_sslmodule);
1922 if (m == NULL)
1923 return NULL;
1924 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 /* Load _socket module and its C API */
1927 socket_api = PySocketModule_ImportModuleAndAPI();
1928 if (!socket_api)
1929 return NULL;
1930 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 /* Init OpenSSL */
1933 SSL_load_error_strings();
1934 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001935#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 /* note that this will start threading if not already started */
1937 if (!_setup_ssl_threads()) {
1938 return NULL;
1939 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001940#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 /* Add symbols to module dict */
1944 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1945 PySocketModule.error,
1946 NULL);
1947 if (PySSLErrorObject == NULL)
1948 return NULL;
1949 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1950 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001951 if (PyDict_SetItemString(d, "_SSLContext",
1952 (PyObject *)&PySSLContext_Type) != 0)
1953 return NULL;
1954 if (PyDict_SetItemString(d, "_SSLSocket",
1955 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 return NULL;
1957 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1958 PY_SSL_ERROR_ZERO_RETURN);
1959 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1960 PY_SSL_ERROR_WANT_READ);
1961 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1962 PY_SSL_ERROR_WANT_WRITE);
1963 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1964 PY_SSL_ERROR_WANT_X509_LOOKUP);
1965 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1966 PY_SSL_ERROR_SYSCALL);
1967 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1968 PY_SSL_ERROR_SSL);
1969 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1970 PY_SSL_ERROR_WANT_CONNECT);
1971 /* non ssl.h errorcodes */
1972 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1973 PY_SSL_ERROR_EOF);
1974 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1975 PY_SSL_ERROR_INVALID_ERROR_CODE);
1976 /* cert requirements */
1977 PyModule_AddIntConstant(m, "CERT_NONE",
1978 PY_SSL_CERT_NONE);
1979 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1980 PY_SSL_CERT_OPTIONAL);
1981 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1982 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 /* protocol versions */
1985 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1986 PY_SSL_VERSION_SSL2);
1987 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1988 PY_SSL_VERSION_SSL3);
1989 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1990 PY_SSL_VERSION_SSL23);
1991 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1992 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001993
Antoine Pitroub5218772010-05-21 09:56:06 +00001994 /* protocol options */
1995 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
1996 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
1997 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
1998 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
1999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 /* OpenSSL version */
2001 /* SSLeay() gives us the version of the library linked against,
2002 which could be different from the headers version.
2003 */
2004 libver = SSLeay();
2005 r = PyLong_FromUnsignedLong(libver);
2006 if (r == NULL)
2007 return NULL;
2008 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2009 return NULL;
2010 status = libver & 0xF;
2011 libver >>= 4;
2012 patch = libver & 0xFF;
2013 libver >>= 8;
2014 fix = libver & 0xFF;
2015 libver >>= 8;
2016 minor = libver & 0xFF;
2017 libver >>= 8;
2018 major = libver & 0xFF;
2019 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2020 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2021 return NULL;
2022 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2023 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2024 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002027}