blob: e4b6fedf194a9a263db4ad33ebc54c6249ae80d5 [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
116typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000117 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000118 SSL_CTX *ctx;
119} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000120
Antoine Pitrou152efa22010-05-16 18:19:27 +0000121typedef struct {
122 PyObject_HEAD
123 PyObject *Socket; /* weakref to socket on which we're layered */
124 SSL *ssl;
125 X509 *peer_cert;
126 int shutdown_seen_zero;
127} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000128
Antoine Pitrou152efa22010-05-16 18:19:27 +0000129static PyTypeObject PySSLContext_Type;
130static PyTypeObject PySSLSocket_Type;
131
132static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
133static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000134static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000135 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000136static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
137static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000138
Antoine Pitrou152efa22010-05-16 18:19:27 +0000139#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
140#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000141
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000142typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000143 SOCKET_IS_NONBLOCKING,
144 SOCKET_IS_BLOCKING,
145 SOCKET_HAS_TIMED_OUT,
146 SOCKET_HAS_BEEN_CLOSED,
147 SOCKET_TOO_LARGE_FOR_SELECT,
148 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000149} timeout_state;
150
Thomas Woutersed03b412007-08-28 21:37:11 +0000151/* Wrap error strings with filename and line # */
152#define STRINGIFY1(x) #x
153#define STRINGIFY2(x) STRINGIFY1(x)
154#define ERRSTR1(x,y,z) (x ":" y ": " z)
155#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
156
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157/* XXX It might be helpful to augment the error message generated
158 below with the name of the SSL function that generated the error.
159 I expect it's obvious most of the time.
160*/
161
162static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000163PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000165 PyObject *v;
166 char buf[2048];
167 char *errstr;
168 int err;
169 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000171 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000173 if (obj->ssl != NULL) {
174 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000176 switch (err) {
177 case SSL_ERROR_ZERO_RETURN:
178 errstr = "TLS/SSL connection has been closed";
179 p = PY_SSL_ERROR_ZERO_RETURN;
180 break;
181 case SSL_ERROR_WANT_READ:
182 errstr = "The operation did not complete (read)";
183 p = PY_SSL_ERROR_WANT_READ;
184 break;
185 case SSL_ERROR_WANT_WRITE:
186 p = PY_SSL_ERROR_WANT_WRITE;
187 errstr = "The operation did not complete (write)";
188 break;
189 case SSL_ERROR_WANT_X509_LOOKUP:
190 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000191 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000192 break;
193 case SSL_ERROR_WANT_CONNECT:
194 p = PY_SSL_ERROR_WANT_CONNECT;
195 errstr = "The operation did not complete (connect)";
196 break;
197 case SSL_ERROR_SYSCALL:
198 {
199 unsigned long e = ERR_get_error();
200 if (e == 0) {
201 PySocketSockObject *s
202 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
203 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000204 p = PY_SSL_ERROR_EOF;
205 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000207 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000208 ERR_clear_error();
Antoine Pitrou525807b2010-05-12 14:05:24 +0000209 return s->errorhandler();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000210 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000211 p = PY_SSL_ERROR_SYSCALL;
212 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 }
214 } else {
215 p = PY_SSL_ERROR_SYSCALL;
216 /* XXX Protected by global interpreter lock */
217 errstr = ERR_error_string(e, NULL);
218 }
219 break;
220 }
221 case SSL_ERROR_SSL:
222 {
223 unsigned long e = ERR_get_error();
224 p = PY_SSL_ERROR_SSL;
225 if (e != 0)
226 /* XXX Protected by global interpreter lock */
227 errstr = ERR_error_string(e, NULL);
228 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000229 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000230 }
231 break;
232 }
233 default:
234 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
235 errstr = "Invalid error code";
236 }
237 } else {
238 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
239 }
240 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000241 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000242 v = Py_BuildValue("(is)", p, buf);
243 if (v != NULL) {
244 PyErr_SetObject(PySSLErrorObject, v);
245 Py_DECREF(v);
246 }
247 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000248}
249
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000250static PyObject *
251_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
252
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000253 char buf[2048];
254 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000256 if (errstr == NULL) {
257 errcode = ERR_peek_last_error();
258 errstr = ERR_error_string(errcode, NULL);
259 }
260 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000261 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000262 v = Py_BuildValue("(is)", errcode, buf);
263 if (v != NULL) {
264 PyErr_SetObject(PySSLErrorObject, v);
265 Py_DECREF(v);
266 }
267 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000268}
269
Antoine Pitrou152efa22010-05-16 18:19:27 +0000270static PySSLSocket *
271newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
272 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000273{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000274 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000275
Antoine Pitrou152efa22010-05-16 18:19:27 +0000276 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000277 if (self == NULL)
278 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000280 self->peer_cert = NULL;
281 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000282 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 /* Make sure the SSL error state is initialized */
285 (void) ERR_get_state();
286 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000288 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000292#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000294#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000296 /* If the socket is in non-blocking mode or timeout mode, set the BIO
297 * to non-blocking mode (blocking is the default)
298 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000300 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
301 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
302 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 PySSL_BEGIN_ALLOW_THREADS
305 if (socket_type == PY_SSL_CLIENT)
306 SSL_set_connect_state(self->ssl);
307 else
308 SSL_set_accept_state(self->ssl);
309 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000310
Antoine Pitrou152efa22010-05-16 18:19:27 +0000311 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000312 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313}
314
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315/* SSL object methods */
316
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 int ret;
320 int err;
321 int sockstate, nonblocking;
322 PySocketSockObject *sock
323 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000324
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000325 if (((PyObject*)sock) == Py_None) {
326 _setSSLError("Underlying socket connection gone",
327 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
328 return NULL;
329 }
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 /* just in case the blocking state of the socket has been changed */
332 nonblocking = (sock->sock_timeout >= 0.0);
333 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
334 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 /* Actually negotiate SSL connection */
337 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
338 sockstate = 0;
339 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000340 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000341 ret = SSL_do_handshake(self->ssl);
342 err = SSL_get_error(self->ssl, ret);
343 PySSL_END_ALLOW_THREADS
344 if(PyErr_CheckSignals()) {
345 return NULL;
346 }
347 if (err == SSL_ERROR_WANT_READ) {
348 sockstate = check_socket_and_wait_for_timeout(sock, 0);
349 } else if (err == SSL_ERROR_WANT_WRITE) {
350 sockstate = check_socket_and_wait_for_timeout(sock, 1);
351 } else {
352 sockstate = SOCKET_OPERATION_OK;
353 }
354 if (sockstate == SOCKET_HAS_TIMED_OUT) {
355 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000356 ERRSTR("The handshake operation timed out"));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 return NULL;
358 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
359 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000360 ERRSTR("Underlying socket has been closed."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000361 return NULL;
362 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
363 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000364 ERRSTR("Underlying socket too large for select()."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000365 return NULL;
366 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
367 break;
368 }
369 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
370 if (ret < 1)
371 return PySSL_SetError(self, ret, __FILE__, __LINE__);
372 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 if (self->peer_cert)
375 X509_free (self->peer_cert);
376 PySSL_BEGIN_ALLOW_THREADS
377 self->peer_cert = SSL_get_peer_certificate(self->ssl);
378 PySSL_END_ALLOW_THREADS
379
380 Py_INCREF(Py_None);
381 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382}
383
Thomas Woutersed03b412007-08-28 21:37:11 +0000384static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 char namebuf[X509_NAME_MAXLEN];
388 int buflen;
389 PyObject *name_obj;
390 PyObject *value_obj;
391 PyObject *attr;
392 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
395 if (buflen < 0) {
396 _setSSLError(NULL, 0, __FILE__, __LINE__);
397 goto fail;
398 }
399 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
400 if (name_obj == NULL)
401 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
404 if (buflen < 0) {
405 _setSSLError(NULL, 0, __FILE__, __LINE__);
406 Py_DECREF(name_obj);
407 goto fail;
408 }
409 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000410 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 OPENSSL_free(valuebuf);
412 if (value_obj == NULL) {
413 Py_DECREF(name_obj);
414 goto fail;
415 }
416 attr = PyTuple_New(2);
417 if (attr == NULL) {
418 Py_DECREF(name_obj);
419 Py_DECREF(value_obj);
420 goto fail;
421 }
422 PyTuple_SET_ITEM(attr, 0, name_obj);
423 PyTuple_SET_ITEM(attr, 1, value_obj);
424 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000425
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000426 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000428}
429
430static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000432{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
434 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
435 PyObject *rdnt;
436 PyObject *attr = NULL; /* tuple to hold an attribute */
437 int entry_count = X509_NAME_entry_count(xname);
438 X509_NAME_ENTRY *entry;
439 ASN1_OBJECT *name;
440 ASN1_STRING *value;
441 int index_counter;
442 int rdn_level = -1;
443 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 dn = PyList_New(0);
446 if (dn == NULL)
447 return NULL;
448 /* now create another tuple to hold the top-level RDN */
449 rdn = PyList_New(0);
450 if (rdn == NULL)
451 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000453 for (index_counter = 0;
454 index_counter < entry_count;
455 index_counter++)
456 {
457 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 /* check to see if we've gotten to a new RDN */
460 if (rdn_level >= 0) {
461 if (rdn_level != entry->set) {
462 /* yes, new RDN */
463 /* add old RDN to DN */
464 rdnt = PyList_AsTuple(rdn);
465 Py_DECREF(rdn);
466 if (rdnt == NULL)
467 goto fail0;
468 retcode = PyList_Append(dn, rdnt);
469 Py_DECREF(rdnt);
470 if (retcode < 0)
471 goto fail0;
472 /* create new RDN */
473 rdn = PyList_New(0);
474 if (rdn == NULL)
475 goto fail0;
476 }
477 }
478 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000480 /* now add this attribute to the current RDN */
481 name = X509_NAME_ENTRY_get_object(entry);
482 value = X509_NAME_ENTRY_get_data(entry);
483 attr = _create_tuple_for_attribute(name, value);
484 /*
485 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
486 entry->set,
487 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
488 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
489 */
490 if (attr == NULL)
491 goto fail1;
492 retcode = PyList_Append(rdn, attr);
493 Py_DECREF(attr);
494 if (retcode < 0)
495 goto fail1;
496 }
497 /* now, there's typically a dangling RDN */
498 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
499 rdnt = PyList_AsTuple(rdn);
500 Py_DECREF(rdn);
501 if (rdnt == NULL)
502 goto fail0;
503 retcode = PyList_Append(dn, rdnt);
504 Py_DECREF(rdnt);
505 if (retcode < 0)
506 goto fail0;
507 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 /* convert list to tuple */
510 rdnt = PyList_AsTuple(dn);
511 Py_DECREF(dn);
512 if (rdnt == NULL)
513 return NULL;
514 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
516 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518
519 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 Py_XDECREF(dn);
521 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522}
523
524static PyObject *
525_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 /* this code follows the procedure outlined in
528 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
529 function to extract the STACK_OF(GENERAL_NAME),
530 then iterates through the stack to add the
531 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 int i, j;
534 PyObject *peer_alt_names = Py_None;
535 PyObject *v, *t;
536 X509_EXTENSION *ext = NULL;
537 GENERAL_NAMES *names = NULL;
538 GENERAL_NAME *name;
539 X509V3_EXT_METHOD *method;
540 BIO *biobuf = NULL;
541 char buf[2048];
542 char *vptr;
543 int len;
544 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000545#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000547#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000549#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 if (certificate == NULL)
552 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 /* get a memory buffer */
555 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000557 i = 0;
558 while ((i = X509_get_ext_by_NID(
559 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 if (peer_alt_names == Py_None) {
562 peer_alt_names = PyList_New(0);
563 if (peer_alt_names == NULL)
564 goto fail;
565 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 /* now decode the altName */
568 ext = X509_get_ext(certificate, i);
569 if(!(method = X509V3_EXT_get(ext))) {
570 PyErr_SetString
571 (PySSLErrorObject,
572 ERRSTR("No method for internalizing subjectAltName!"));
573 goto fail;
574 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 p = ext->value->data;
577 if (method->it)
578 names = (GENERAL_NAMES*)
579 (ASN1_item_d2i(NULL,
580 &p,
581 ext->value->length,
582 ASN1_ITEM_ptr(method->it)));
583 else
584 names = (GENERAL_NAMES*)
585 (method->d2i(NULL,
586 &p,
587 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 name = sk_GENERAL_NAME_value(names, j);
594 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 /* we special-case DirName as a tuple of
597 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 t = PyTuple_New(2);
600 if (t == NULL) {
601 goto fail;
602 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 v = PyUnicode_FromString("DirName");
605 if (v == NULL) {
606 Py_DECREF(t);
607 goto fail;
608 }
609 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 v = _create_tuple_for_X509_NAME (name->d.dirn);
612 if (v == NULL) {
613 Py_DECREF(t);
614 goto fail;
615 }
616 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 (void) BIO_reset(biobuf);
623 GENERAL_NAME_print(biobuf, name);
624 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
625 if (len < 0) {
626 _setSSLError(NULL, 0, __FILE__, __LINE__);
627 goto fail;
628 }
629 vptr = strchr(buf, ':');
630 if (vptr == NULL)
631 goto fail;
632 t = PyTuple_New(2);
633 if (t == NULL)
634 goto fail;
635 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
636 if (v == NULL) {
637 Py_DECREF(t);
638 goto fail;
639 }
640 PyTuple_SET_ITEM(t, 0, v);
641 v = PyUnicode_FromStringAndSize((vptr + 1),
642 (len - (vptr - buf + 1)));
643 if (v == NULL) {
644 Py_DECREF(t);
645 goto fail;
646 }
647 PyTuple_SET_ITEM(t, 1, v);
648 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000650 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 if (PyList_Append(peer_alt_names, t) < 0) {
653 Py_DECREF(t);
654 goto fail;
655 }
656 Py_DECREF(t);
657 }
658 }
659 BIO_free(biobuf);
660 if (peer_alt_names != Py_None) {
661 v = PyList_AsTuple(peer_alt_names);
662 Py_DECREF(peer_alt_names);
663 return v;
664 } else {
665 return peer_alt_names;
666 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000667
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
669 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 if (biobuf != NULL)
671 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 if (peer_alt_names != Py_None) {
674 Py_XDECREF(peer_alt_names);
675 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678}
679
680static PyObject *
681_decode_certificate (X509 *certificate, int verbose) {
682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 PyObject *retval = NULL;
684 BIO *biobuf = NULL;
685 PyObject *peer;
686 PyObject *peer_alt_names = NULL;
687 PyObject *issuer;
688 PyObject *version;
689 PyObject *sn_obj;
690 ASN1_INTEGER *serialNumber;
691 char buf[2048];
692 int len;
693 ASN1_TIME *notBefore, *notAfter;
694 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 retval = PyDict_New();
697 if (retval == NULL)
698 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 peer = _create_tuple_for_X509_NAME(
701 X509_get_subject_name(certificate));
702 if (peer == NULL)
703 goto fail0;
704 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
705 Py_DECREF(peer);
706 goto fail0;
707 }
708 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 if (verbose) {
711 issuer = _create_tuple_for_X509_NAME(
712 X509_get_issuer_name(certificate));
713 if (issuer == NULL)
714 goto fail0;
715 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
716 Py_DECREF(issuer);
717 goto fail0;
718 }
719 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 version = PyLong_FromLong(X509_get_version(certificate) + 1);
722 if (PyDict_SetItemString(retval, "version", version) < 0) {
723 Py_DECREF(version);
724 goto fail0;
725 }
726 Py_DECREF(version);
727 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 /* get a memory buffer */
730 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000733
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 (void) BIO_reset(biobuf);
735 serialNumber = X509_get_serialNumber(certificate);
736 /* should not exceed 20 octets, 160 bits, so buf is big enough */
737 i2a_ASN1_INTEGER(biobuf, serialNumber);
738 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
739 if (len < 0) {
740 _setSSLError(NULL, 0, __FILE__, __LINE__);
741 goto fail1;
742 }
743 sn_obj = PyUnicode_FromStringAndSize(buf, len);
744 if (sn_obj == NULL)
745 goto fail1;
746 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
747 Py_DECREF(sn_obj);
748 goto fail1;
749 }
750 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 (void) BIO_reset(biobuf);
753 notBefore = X509_get_notBefore(certificate);
754 ASN1_TIME_print(biobuf, notBefore);
755 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
756 if (len < 0) {
757 _setSSLError(NULL, 0, __FILE__, __LINE__);
758 goto fail1;
759 }
760 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
761 if (pnotBefore == NULL)
762 goto fail1;
763 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
764 Py_DECREF(pnotBefore);
765 goto fail1;
766 }
767 Py_DECREF(pnotBefore);
768 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 (void) BIO_reset(biobuf);
771 notAfter = X509_get_notAfter(certificate);
772 ASN1_TIME_print(biobuf, notAfter);
773 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
774 if (len < 0) {
775 _setSSLError(NULL, 0, __FILE__, __LINE__);
776 goto fail1;
777 }
778 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
779 if (pnotAfter == NULL)
780 goto fail1;
781 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
782 Py_DECREF(pnotAfter);
783 goto fail1;
784 }
785 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 peer_alt_names = _get_peer_alt_names(certificate);
790 if (peer_alt_names == NULL)
791 goto fail1;
792 else if (peer_alt_names != Py_None) {
793 if (PyDict_SetItemString(retval, "subjectAltName",
794 peer_alt_names) < 0) {
795 Py_DECREF(peer_alt_names);
796 goto fail1;
797 }
798 Py_DECREF(peer_alt_names);
799 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 BIO_free(biobuf);
802 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000803
804 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 if (biobuf != NULL)
806 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000807 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 Py_XDECREF(retval);
809 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000810}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000811
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812
813static PyObject *
814PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000817 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 X509 *x=NULL;
819 BIO *cert;
820 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Victor Stinner3800e1e2010-05-16 21:23:48 +0000822 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
823 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 if ((cert=BIO_new(BIO_s_file())) == NULL) {
827 PyErr_SetString(PySSLErrorObject,
828 "Can't malloc memory to read file");
829 goto fail0;
830 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Victor Stinner3800e1e2010-05-16 21:23:48 +0000832 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 PyErr_SetString(PySSLErrorObject,
834 "Can't open file");
835 goto fail0;
836 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
839 if (x == NULL) {
840 PyErr_SetString(PySSLErrorObject,
841 "Error decoding PEM-encoded file");
842 goto fail0;
843 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846
847 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000848 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 if (cert != NULL) BIO_free(cert);
850 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851}
852
853
854static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000855PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 PyObject *retval = NULL;
858 int len;
859 int verification;
860 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
863 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 if (!self->peer_cert)
866 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 if (PyObject_IsTrue(binary_mode)) {
869 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 bytes_buf = NULL;
874 len = i2d_X509(self->peer_cert, &bytes_buf);
875 if (len < 0) {
876 PySSL_SetError(self, len, __FILE__, __LINE__);
877 return NULL;
878 }
879 /* this is actually an immutable bytes sequence */
880 retval = PyBytes_FromStringAndSize
881 ((const char *) bytes_buf, len);
882 OPENSSL_free(bytes_buf);
883 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000886 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 if ((verification & SSL_VERIFY_PEER) == 0)
888 return PyDict_New();
889 else
890 return _decode_certificate (self->peer_cert, 0);
891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892}
893
894PyDoc_STRVAR(PySSL_peercert_doc,
895"peer_certificate([der=False]) -> certificate\n\
896\n\
897Returns the certificate for the peer. If no certificate was provided,\n\
898returns None. If a certificate was provided, but not validated, returns\n\
899an empty dictionary. Otherwise returns a dict containing information\n\
900about the peer certificate.\n\
901\n\
902If the optional argument is True, returns a DER-encoded copy of the\n\
903peer certificate, or None if no certificate was provided. This will\n\
904return the certificate even if it wasn't validated.");
905
Antoine Pitrou152efa22010-05-16 18:19:27 +0000906static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PyObject *retval, *v;
909 SSL_CIPHER *current;
910 char *cipher_name;
911 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 if (self->ssl == NULL)
914 return Py_None;
915 current = SSL_get_current_cipher(self->ssl);
916 if (current == NULL)
917 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 retval = PyTuple_New(3);
920 if (retval == NULL)
921 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 cipher_name = (char *) SSL_CIPHER_get_name(current);
924 if (cipher_name == NULL) {
925 PyTuple_SET_ITEM(retval, 0, Py_None);
926 } else {
927 v = PyUnicode_FromString(cipher_name);
928 if (v == NULL)
929 goto fail0;
930 PyTuple_SET_ITEM(retval, 0, v);
931 }
932 cipher_protocol = SSL_CIPHER_get_version(current);
933 if (cipher_protocol == NULL) {
934 PyTuple_SET_ITEM(retval, 1, Py_None);
935 } else {
936 v = PyUnicode_FromString(cipher_protocol);
937 if (v == NULL)
938 goto fail0;
939 PyTuple_SET_ITEM(retval, 1, v);
940 }
941 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
942 if (v == NULL)
943 goto fail0;
944 PyTuple_SET_ITEM(retval, 2, v);
945 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000946
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 Py_DECREF(retval);
949 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950}
951
Antoine Pitrou152efa22010-05-16 18:19:27 +0000952static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000953{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 if (self->peer_cert) /* Possible not to have one? */
955 X509_free (self->peer_cert);
956 if (self->ssl)
957 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 Py_XDECREF(self->Socket);
959 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000960}
961
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000962/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000963 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000964 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000965 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000966
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000967static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000968check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000969{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 fd_set fds;
971 struct timeval tv;
972 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 /* Nothing to do unless we're in timeout mode (not non-blocking) */
975 if (s->sock_timeout < 0.0)
976 return SOCKET_IS_BLOCKING;
977 else if (s->sock_timeout == 0.0)
978 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 /* Guard against closed socket */
981 if (s->sock_fd < 0)
982 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 /* Prefer poll, if available, since you can poll() any fd
985 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000986#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 {
988 struct pollfd pollfd;
989 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 pollfd.fd = s->sock_fd;
992 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 /* s->sock_timeout is in seconds, timeout in ms */
995 timeout = (int)(s->sock_timeout * 1000 + 0.5);
996 PySSL_BEGIN_ALLOW_THREADS
997 rc = poll(&pollfd, 1, timeout);
998 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 goto normal_return;
1001 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002#endif
1003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001005#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 if (s->sock_fd >= FD_SETSIZE)
1007 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001008#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 /* Construct the arguments to select */
1011 tv.tv_sec = (int)s->sock_timeout;
1012 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1013 FD_ZERO(&fds);
1014 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* See if the socket is ready */
1017 PySSL_BEGIN_ALLOW_THREADS
1018 if (writing)
1019 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1020 else
1021 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1022 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001023
Bill Janssen6e027db2007-11-15 22:23:56 +00001024#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001026#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1028 (when we are able to write or when there's something to read) */
1029 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001030}
1031
Antoine Pitrou152efa22010-05-16 18:19:27 +00001032static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001033{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 Py_buffer buf;
1035 int len;
1036 int sockstate;
1037 int err;
1038 int nonblocking;
1039 PySocketSockObject *sock
1040 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 if (((PyObject*)sock) == Py_None) {
1043 _setSSLError("Underlying socket connection gone",
1044 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1045 return NULL;
1046 }
1047
1048 if (!PyArg_ParseTuple(args, "y*:write", &buf))
1049 return NULL;
1050
1051 /* just in case the blocking state of the socket has been changed */
1052 nonblocking = (sock->sock_timeout >= 0.0);
1053 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1054 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1055
1056 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1057 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1058 PyErr_SetString(PySSLErrorObject,
1059 "The write operation timed out");
1060 goto error;
1061 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1062 PyErr_SetString(PySSLErrorObject,
1063 "Underlying socket has been closed.");
1064 goto error;
1065 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1066 PyErr_SetString(PySSLErrorObject,
1067 "Underlying socket too large for select().");
1068 goto error;
1069 }
1070 do {
1071 err = 0;
1072 PySSL_BEGIN_ALLOW_THREADS
1073 len = SSL_write(self->ssl, buf.buf, buf.len);
1074 err = SSL_get_error(self->ssl, len);
1075 PySSL_END_ALLOW_THREADS
1076 if (PyErr_CheckSignals()) {
1077 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001078 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001080 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001082 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 } else {
1084 sockstate = SOCKET_OPERATION_OK;
1085 }
1086 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1087 PyErr_SetString(PySSLErrorObject,
1088 "The write operation timed out");
1089 goto error;
1090 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1091 PyErr_SetString(PySSLErrorObject,
1092 "Underlying socket has been closed.");
1093 goto error;
1094 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1095 break;
1096 }
1097 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001098
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 PyBuffer_Release(&buf);
1100 if (len > 0)
1101 return PyLong_FromLong(len);
1102 else
1103 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001104
1105error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 PyBuffer_Release(&buf);
1107 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001108}
1109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001110PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001111"write(s) -> len\n\
1112\n\
1113Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001114of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001115
Antoine Pitrou152efa22010-05-16 18:19:27 +00001116static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001117{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 PySSL_BEGIN_ALLOW_THREADS
1121 count = SSL_pending(self->ssl);
1122 PySSL_END_ALLOW_THREADS
1123 if (count < 0)
1124 return PySSL_SetError(self, count, __FILE__, __LINE__);
1125 else
1126 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001127}
1128
1129PyDoc_STRVAR(PySSL_SSLpending_doc,
1130"pending() -> count\n\
1131\n\
1132Returns the number of already decrypted bytes available for read,\n\
1133pending on the connection.\n");
1134
Antoine Pitrou152efa22010-05-16 18:19:27 +00001135static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001136{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 PyObject *dest = NULL;
1138 Py_buffer buf;
1139 int buf_passed = 0;
1140 int count = -1;
1141 char *mem;
1142 /* XXX this should use Py_ssize_t */
1143 int len = 1024;
1144 int sockstate;
1145 int err;
1146 int nonblocking;
1147 PySocketSockObject *sock
1148 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 if (((PyObject*)sock) == Py_None) {
1151 _setSSLError("Underlying socket connection gone",
1152 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1153 return NULL;
1154 }
1155
1156 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1157 return NULL;
1158 if ((dest == NULL) || (dest == Py_None)) {
1159 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1160 return NULL;
1161 mem = PyByteArray_AS_STRING(dest);
1162 } else if (PyLong_Check(dest)) {
1163 len = PyLong_AS_LONG(dest);
1164 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1165 return NULL;
1166 mem = PyByteArray_AS_STRING(dest);
1167 } else {
1168 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1169 return NULL;
1170 mem = buf.buf;
1171 len = buf.len;
1172 if ((count > 0) && (count <= len))
1173 len = count;
1174 buf_passed = 1;
1175 }
1176
1177 /* just in case the blocking state of the socket has been changed */
1178 nonblocking = (sock->sock_timeout >= 0.0);
1179 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1180 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1181
1182 /* first check if there are bytes ready to be read */
1183 PySSL_BEGIN_ALLOW_THREADS
1184 count = SSL_pending(self->ssl);
1185 PySSL_END_ALLOW_THREADS
1186
1187 if (!count) {
1188 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1189 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1190 PyErr_SetString(PySSLErrorObject,
1191 "The read operation timed out");
1192 goto error;
1193 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1194 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001195 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 goto error;
1197 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1198 count = 0;
1199 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001200 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 }
1202 do {
1203 err = 0;
1204 PySSL_BEGIN_ALLOW_THREADS
1205 count = SSL_read(self->ssl, mem, len);
1206 err = SSL_get_error(self->ssl, count);
1207 PySSL_END_ALLOW_THREADS
1208 if (PyErr_CheckSignals())
1209 goto error;
1210 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001211 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001212 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001213 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1215 (SSL_get_shutdown(self->ssl) ==
1216 SSL_RECEIVED_SHUTDOWN))
1217 {
1218 count = 0;
1219 goto done;
1220 } else {
1221 sockstate = SOCKET_OPERATION_OK;
1222 }
1223 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1224 PyErr_SetString(PySSLErrorObject,
1225 "The read operation timed out");
1226 goto error;
1227 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1228 break;
1229 }
1230 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1231 if (count <= 0) {
1232 PySSL_SetError(self, count, __FILE__, __LINE__);
1233 goto error;
1234 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001235 done:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 if (!buf_passed) {
1237 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1238 Py_DECREF(dest);
1239 return res;
1240 } else {
1241 PyBuffer_Release(&buf);
1242 return PyLong_FromLong(count);
1243 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001244 error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 if (!buf_passed) {
1246 Py_DECREF(dest);
1247 } else {
1248 PyBuffer_Release(&buf);
1249 }
1250 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001254"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001257
Antoine Pitrou152efa22010-05-16 18:19:27 +00001258static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001259{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 int err, ssl_err, sockstate, nonblocking;
1261 int zeros = 0;
1262 PySocketSockObject *sock
1263 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 /* Guard against closed socket */
1266 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1267 _setSSLError("Underlying socket connection gone",
1268 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1269 return NULL;
1270 }
1271
1272 /* Just in case the blocking state of the socket has been changed */
1273 nonblocking = (sock->sock_timeout >= 0.0);
1274 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1275 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1276
1277 while (1) {
1278 PySSL_BEGIN_ALLOW_THREADS
1279 /* Disable read-ahead so that unwrap can work correctly.
1280 * Otherwise OpenSSL might read in too much data,
1281 * eating clear text data that happens to be
1282 * transmitted after the SSL shutdown.
1283 * Should be safe to call repeatedly everytime this
1284 * function is used and the shutdown_seen_zero != 0
1285 * condition is met.
1286 */
1287 if (self->shutdown_seen_zero)
1288 SSL_set_read_ahead(self->ssl, 0);
1289 err = SSL_shutdown(self->ssl);
1290 PySSL_END_ALLOW_THREADS
1291 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1292 if (err > 0)
1293 break;
1294 if (err == 0) {
1295 /* Don't loop endlessly; instead preserve legacy
1296 behaviour of trying SSL_shutdown() only twice.
1297 This looks necessary for OpenSSL < 0.9.8m */
1298 if (++zeros > 1)
1299 break;
1300 /* Shutdown was sent, now try receiving */
1301 self->shutdown_seen_zero = 1;
1302 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001303 }
1304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 /* Possibly retry shutdown until timeout or failure */
1306 ssl_err = SSL_get_error(self->ssl, err);
1307 if (ssl_err == SSL_ERROR_WANT_READ)
1308 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1309 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1310 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1311 else
1312 break;
1313 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1314 if (ssl_err == SSL_ERROR_WANT_READ)
1315 PyErr_SetString(PySSLErrorObject,
1316 "The read operation timed out");
1317 else
1318 PyErr_SetString(PySSLErrorObject,
1319 "The write operation timed out");
1320 return NULL;
1321 }
1322 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1323 PyErr_SetString(PySSLErrorObject,
1324 "Underlying socket too large for select().");
1325 return NULL;
1326 }
1327 else if (sockstate != SOCKET_OPERATION_OK)
1328 /* Retain the SSL error code */
1329 break;
1330 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 if (err < 0)
1333 return PySSL_SetError(self, err, __FILE__, __LINE__);
1334 else {
1335 Py_INCREF(sock);
1336 return (PyObject *) sock;
1337 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001338}
1339
1340PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1341"shutdown(s) -> socket\n\
1342\n\
1343Does the SSL shutdown handshake with the remote end, and returns\n\
1344the underlying socket object.");
1345
1346
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001347static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1349 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1350 PySSL_SSLwrite_doc},
1351 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1352 PySSL_SSLread_doc},
1353 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1354 PySSL_SSLpending_doc},
1355 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1356 PySSL_peercert_doc},
1357 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1358 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1359 PySSL_SSLshutdown_doc},
1360 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001361};
1362
Antoine Pitrou152efa22010-05-16 18:19:27 +00001363static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001365 "_ssl._SSLSocket", /*tp_name*/
1366 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 0, /*tp_itemsize*/
1368 /* methods */
1369 (destructor)PySSL_dealloc, /*tp_dealloc*/
1370 0, /*tp_print*/
1371 0, /*tp_getattr*/
1372 0, /*tp_setattr*/
1373 0, /*tp_reserved*/
1374 0, /*tp_repr*/
1375 0, /*tp_as_number*/
1376 0, /*tp_as_sequence*/
1377 0, /*tp_as_mapping*/
1378 0, /*tp_hash*/
1379 0, /*tp_call*/
1380 0, /*tp_str*/
1381 0, /*tp_getattro*/
1382 0, /*tp_setattro*/
1383 0, /*tp_as_buffer*/
1384 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1385 0, /*tp_doc*/
1386 0, /*tp_traverse*/
1387 0, /*tp_clear*/
1388 0, /*tp_richcompare*/
1389 0, /*tp_weaklistoffset*/
1390 0, /*tp_iter*/
1391 0, /*tp_iternext*/
1392 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001393};
1394
Antoine Pitrou152efa22010-05-16 18:19:27 +00001395
1396/*
1397 * _SSLContext objects
1398 */
1399
1400static PyObject *
1401context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1402{
1403 char *kwlist[] = {"protocol", NULL};
1404 PySSLContext *self;
1405 int proto_version = PY_SSL_VERSION_SSL23;
1406 SSL_CTX *ctx = NULL;
1407
1408 if (!PyArg_ParseTupleAndKeywords(
1409 args, kwds, "i:_SSLContext", kwlist,
1410 &proto_version))
1411 return NULL;
1412
1413 PySSL_BEGIN_ALLOW_THREADS
1414 if (proto_version == PY_SSL_VERSION_TLS1)
1415 ctx = SSL_CTX_new(TLSv1_method());
1416 else if (proto_version == PY_SSL_VERSION_SSL3)
1417 ctx = SSL_CTX_new(SSLv3_method());
1418 else if (proto_version == PY_SSL_VERSION_SSL2)
1419 ctx = SSL_CTX_new(SSLv2_method());
1420 else if (proto_version == PY_SSL_VERSION_SSL23)
1421 ctx = SSL_CTX_new(SSLv23_method());
1422 else
1423 proto_version = -1;
1424 PySSL_END_ALLOW_THREADS
1425
1426 if (proto_version == -1) {
1427 PyErr_SetString(PyExc_ValueError,
1428 "invalid protocol version");
1429 return NULL;
1430 }
1431 if (ctx == NULL) {
1432 PyErr_SetString(PySSLErrorObject,
1433 "failed to allocate SSL context");
1434 return NULL;
1435 }
1436
1437 assert(type != NULL && type->tp_alloc != NULL);
1438 self = (PySSLContext *) type->tp_alloc(type, 0);
1439 if (self == NULL) {
1440 SSL_CTX_free(ctx);
1441 return NULL;
1442 }
1443 self->ctx = ctx;
1444 /* Defaults */
1445 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1446 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1447
1448 return (PyObject *)self;
1449}
1450
1451static void
1452context_dealloc(PySSLContext *self)
1453{
1454 SSL_CTX_free(self->ctx);
1455 Py_TYPE(self)->tp_free(self);
1456}
1457
1458static PyObject *
1459set_ciphers(PySSLContext *self, PyObject *args)
1460{
1461 int ret;
1462 const char *cipherlist;
1463
1464 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1465 return NULL;
1466 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1467 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001468 /* Clearing the error queue is necessary on some OpenSSL versions,
1469 otherwise the error will be reported again when another SSL call
1470 is done. */
1471 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001472 PyErr_SetString(PySSLErrorObject,
1473 "No cipher can be selected.");
1474 return NULL;
1475 }
1476 Py_RETURN_NONE;
1477}
1478
1479static PyObject *
1480get_verify_mode(PySSLContext *self, void *c)
1481{
1482 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1483 case SSL_VERIFY_NONE:
1484 return PyLong_FromLong(PY_SSL_CERT_NONE);
1485 case SSL_VERIFY_PEER:
1486 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1487 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1488 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1489 }
1490 PyErr_SetString(PySSLErrorObject,
1491 "invalid return value from SSL_CTX_get_verify_mode");
1492 return NULL;
1493}
1494
1495static int
1496set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1497{
1498 int n, mode;
1499 if (!PyArg_Parse(arg, "i", &n))
1500 return -1;
1501 if (n == PY_SSL_CERT_NONE)
1502 mode = SSL_VERIFY_NONE;
1503 else if (n == PY_SSL_CERT_OPTIONAL)
1504 mode = SSL_VERIFY_PEER;
1505 else if (n == PY_SSL_CERT_REQUIRED)
1506 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1507 else {
1508 PyErr_SetString(PyExc_ValueError,
1509 "invalid value for verify_mode");
1510 return -1;
1511 }
1512 SSL_CTX_set_verify(self->ctx, mode, NULL);
1513 return 0;
1514}
1515
1516static PyObject *
1517load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1518{
1519 char *kwlist[] = {"certfile", "keyfile", NULL};
1520 PyObject *certfile, *keyfile = NULL;
1521 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1522 int r;
1523
1524 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1525 "O|O:load_cert_chain", kwlist,
1526 &certfile, &keyfile))
1527 return NULL;
1528 if (keyfile == Py_None)
1529 keyfile = NULL;
1530 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1531 PyErr_SetString(PyExc_TypeError,
1532 "certfile should be a valid filesystem path");
1533 return NULL;
1534 }
1535 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1536 PyErr_SetString(PyExc_TypeError,
1537 "keyfile should be a valid filesystem path");
1538 goto error;
1539 }
1540 PySSL_BEGIN_ALLOW_THREADS
1541 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1542 PyBytes_AS_STRING(certfile_bytes));
1543 PySSL_END_ALLOW_THREADS
1544 if (r != 1) {
1545 _setSSLError(NULL, 0, __FILE__, __LINE__);
1546 goto error;
1547 }
1548 PySSL_BEGIN_ALLOW_THREADS
1549 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1550 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1551 SSL_FILETYPE_PEM);
1552 PySSL_END_ALLOW_THREADS
1553 Py_XDECREF(keyfile_bytes);
1554 Py_XDECREF(certfile_bytes);
1555 if (r != 1) {
1556 _setSSLError(NULL, 0, __FILE__, __LINE__);
1557 return NULL;
1558 }
1559 PySSL_BEGIN_ALLOW_THREADS
1560 r = SSL_CTX_check_private_key(self->ctx);
1561 PySSL_END_ALLOW_THREADS
1562 if (r != 1) {
1563 _setSSLError(NULL, 0, __FILE__, __LINE__);
1564 return NULL;
1565 }
1566 Py_RETURN_NONE;
1567
1568error:
1569 Py_XDECREF(keyfile_bytes);
1570 Py_XDECREF(certfile_bytes);
1571 return NULL;
1572}
1573
1574static PyObject *
1575load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1576{
1577 char *kwlist[] = {"cafile", "capath", NULL};
1578 PyObject *cafile = NULL, *capath = NULL;
1579 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1580 const char *cafile_buf = NULL, *capath_buf = NULL;
1581 int r;
1582
1583 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1584 "|OO:load_verify_locations", kwlist,
1585 &cafile, &capath))
1586 return NULL;
1587 if (cafile == Py_None)
1588 cafile = NULL;
1589 if (capath == Py_None)
1590 capath = NULL;
1591 if (cafile == NULL && capath == NULL) {
1592 PyErr_SetString(PyExc_TypeError,
1593 "cafile and capath cannot be both omitted");
1594 return NULL;
1595 }
1596 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1597 PyErr_SetString(PyExc_TypeError,
1598 "cafile should be a valid filesystem path");
1599 return NULL;
1600 }
1601 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1602 Py_DECREF(cafile_bytes);
1603 PyErr_SetString(PyExc_TypeError,
1604 "capath should be a valid filesystem path");
1605 return NULL;
1606 }
1607 if (cafile)
1608 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1609 if (capath)
1610 capath_buf = PyBytes_AS_STRING(capath_bytes);
1611 PySSL_BEGIN_ALLOW_THREADS
1612 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1613 PySSL_END_ALLOW_THREADS
1614 Py_XDECREF(cafile_bytes);
1615 Py_XDECREF(capath_bytes);
1616 if (r != 1) {
1617 _setSSLError(NULL, 0, __FILE__, __LINE__);
1618 return NULL;
1619 }
1620 Py_RETURN_NONE;
1621}
1622
1623static PyObject *
1624context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1625{
1626 char *kwlist[] = {"sock", "server_side", NULL};
1627 PySocketSockObject *sock;
1628 int server_side = 0;
1629
1630 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1631 PySocketModule.Sock_Type,
1632 &sock, &server_side))
1633 return NULL;
1634
1635 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1636}
1637
1638static PyGetSetDef context_getsetlist[] = {
1639 {"verify_mode", (getter) get_verify_mode,
1640 (setter) set_verify_mode, NULL},
1641 {NULL}, /* sentinel */
1642};
1643
1644static struct PyMethodDef context_methods[] = {
1645 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1646 METH_VARARGS | METH_KEYWORDS, NULL},
1647 {"set_ciphers", (PyCFunction) set_ciphers,
1648 METH_VARARGS, NULL},
1649 {"load_cert_chain", (PyCFunction) load_cert_chain,
1650 METH_VARARGS | METH_KEYWORDS, NULL},
1651 {"load_verify_locations", (PyCFunction) load_verify_locations,
1652 METH_VARARGS | METH_KEYWORDS, NULL},
1653 {NULL, NULL} /* sentinel */
1654};
1655
1656static PyTypeObject PySSLContext_Type = {
1657 PyVarObject_HEAD_INIT(NULL, 0)
1658 "_ssl._SSLContext", /*tp_name*/
1659 sizeof(PySSLContext), /*tp_basicsize*/
1660 0, /*tp_itemsize*/
1661 (destructor)context_dealloc, /*tp_dealloc*/
1662 0, /*tp_print*/
1663 0, /*tp_getattr*/
1664 0, /*tp_setattr*/
1665 0, /*tp_reserved*/
1666 0, /*tp_repr*/
1667 0, /*tp_as_number*/
1668 0, /*tp_as_sequence*/
1669 0, /*tp_as_mapping*/
1670 0, /*tp_hash*/
1671 0, /*tp_call*/
1672 0, /*tp_str*/
1673 0, /*tp_getattro*/
1674 0, /*tp_setattro*/
1675 0, /*tp_as_buffer*/
1676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1677 0, /*tp_doc*/
1678 0, /*tp_traverse*/
1679 0, /*tp_clear*/
1680 0, /*tp_richcompare*/
1681 0, /*tp_weaklistoffset*/
1682 0, /*tp_iter*/
1683 0, /*tp_iternext*/
1684 context_methods, /*tp_methods*/
1685 0, /*tp_members*/
1686 context_getsetlist, /*tp_getset*/
1687 0, /*tp_base*/
1688 0, /*tp_dict*/
1689 0, /*tp_descr_get*/
1690 0, /*tp_descr_set*/
1691 0, /*tp_dictoffset*/
1692 0, /*tp_init*/
1693 0, /*tp_alloc*/
1694 context_new, /*tp_new*/
1695};
1696
1697
1698
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001699#ifdef HAVE_OPENSSL_RAND
1700
1701/* helper routines for seeding the SSL PRNG */
1702static PyObject *
1703PySSL_RAND_add(PyObject *self, PyObject *args)
1704{
1705 char *buf;
1706 int len;
1707 double entropy;
1708
1709 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001710 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001711 RAND_add(buf, len, entropy);
1712 Py_INCREF(Py_None);
1713 return Py_None;
1714}
1715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001716PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001717"RAND_add(string, entropy)\n\
1718\n\
1719Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001721
1722static PyObject *
1723PySSL_RAND_status(PyObject *self)
1724{
Christian Heimes217cfd12007-12-02 14:31:20 +00001725 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001726}
1727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001728PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001729"RAND_status() -> 0 or 1\n\
1730\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001731Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1732It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1733using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001734
1735static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001736PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001737{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001738 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001739 int bytes;
1740
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001741 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1742 PyUnicode_FSConverter, &path))
1743 return NULL;
1744
1745 bytes = RAND_egd(PyBytes_AsString(path));
1746 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001748 PyErr_SetString(PySSLErrorObject,
1749 "EGD connection failed or EGD did not return "
1750 "enough data to seed the PRNG");
1751 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001752 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001753 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754}
1755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001756PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001757"RAND_egd(path) -> bytes\n\
1758\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1760Returns number of bytes read. Raises SSLError if connection to EGD\n\
1761fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001762
1763#endif
1764
Bill Janssen40a0f662008-08-12 16:56:25 +00001765
1766
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001767/* List of functions exported by this module. */
1768
1769static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 {"_test_decode_cert", PySSL_test_decode_certificate,
1771 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001773 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1774 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001775 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 PySSL_RAND_egd_doc},
1777 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1778 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001779#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001781};
1782
1783
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001784#ifdef WITH_THREAD
1785
1786/* an implementation of OpenSSL threading operations in terms
1787 of the Python C thread library */
1788
1789static PyThread_type_lock *_ssl_locks = NULL;
1790
1791static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001793}
1794
Bill Janssen6e027db2007-11-15 22:23:56 +00001795static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 (int mode, int n, const char *file, int line) {
1797 /* this function is needed to perform locking on shared data
1798 structures. (Note that OpenSSL uses a number of global data
1799 structures that will be implicitly shared whenever multiple
1800 threads use OpenSSL.) Multi-threaded applications will
1801 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 locking_function() must be able to handle up to
1804 CRYPTO_num_locks() different mutex locks. It sets the n-th
1805 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 file and line are the file number of the function setting the
1808 lock. They can be useful for debugging.
1809 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 if ((_ssl_locks == NULL) ||
1812 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1813 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 if (mode & CRYPTO_LOCK) {
1816 PyThread_acquire_lock(_ssl_locks[n], 1);
1817 } else {
1818 PyThread_release_lock(_ssl_locks[n]);
1819 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001820}
1821
1822static int _setup_ssl_threads(void) {
1823
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 if (_ssl_locks == NULL) {
1827 _ssl_locks_count = CRYPTO_num_locks();
1828 _ssl_locks = (PyThread_type_lock *)
1829 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1830 if (_ssl_locks == NULL)
1831 return 0;
1832 memset(_ssl_locks, 0,
1833 sizeof(PyThread_type_lock) * _ssl_locks_count);
1834 for (i = 0; i < _ssl_locks_count; i++) {
1835 _ssl_locks[i] = PyThread_allocate_lock();
1836 if (_ssl_locks[i] == NULL) {
1837 unsigned int j;
1838 for (j = 0; j < i; j++) {
1839 PyThread_free_lock(_ssl_locks[j]);
1840 }
1841 free(_ssl_locks);
1842 return 0;
1843 }
1844 }
1845 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1846 CRYPTO_set_id_callback(_ssl_thread_id_function);
1847 }
1848 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001849}
1850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001852
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001853PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001854"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001855for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001856
Martin v. Löwis1a214512008-06-11 05:26:20 +00001857
1858static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 PyModuleDef_HEAD_INIT,
1860 "_ssl",
1861 module_doc,
1862 -1,
1863 PySSL_methods,
1864 NULL,
1865 NULL,
1866 NULL,
1867 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001868};
1869
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001870PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001871PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001872{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 PyObject *m, *d, *r;
1874 unsigned long libver;
1875 unsigned int major, minor, fix, patch, status;
1876 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001877
Antoine Pitrou152efa22010-05-16 18:19:27 +00001878 if (PyType_Ready(&PySSLContext_Type) < 0)
1879 return NULL;
1880 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001883 m = PyModule_Create(&_sslmodule);
1884 if (m == NULL)
1885 return NULL;
1886 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 /* Load _socket module and its C API */
1889 socket_api = PySocketModule_ImportModuleAndAPI();
1890 if (!socket_api)
1891 return NULL;
1892 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 /* Init OpenSSL */
1895 SSL_load_error_strings();
1896 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001897#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 /* note that this will start threading if not already started */
1899 if (!_setup_ssl_threads()) {
1900 return NULL;
1901 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001902#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 /* Add symbols to module dict */
1906 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1907 PySocketModule.error,
1908 NULL);
1909 if (PySSLErrorObject == NULL)
1910 return NULL;
1911 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1912 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001913 if (PyDict_SetItemString(d, "_SSLContext",
1914 (PyObject *)&PySSLContext_Type) != 0)
1915 return NULL;
1916 if (PyDict_SetItemString(d, "_SSLSocket",
1917 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 return NULL;
1919 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1920 PY_SSL_ERROR_ZERO_RETURN);
1921 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1922 PY_SSL_ERROR_WANT_READ);
1923 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1924 PY_SSL_ERROR_WANT_WRITE);
1925 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1926 PY_SSL_ERROR_WANT_X509_LOOKUP);
1927 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1928 PY_SSL_ERROR_SYSCALL);
1929 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1930 PY_SSL_ERROR_SSL);
1931 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1932 PY_SSL_ERROR_WANT_CONNECT);
1933 /* non ssl.h errorcodes */
1934 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1935 PY_SSL_ERROR_EOF);
1936 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1937 PY_SSL_ERROR_INVALID_ERROR_CODE);
1938 /* cert requirements */
1939 PyModule_AddIntConstant(m, "CERT_NONE",
1940 PY_SSL_CERT_NONE);
1941 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1942 PY_SSL_CERT_OPTIONAL);
1943 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1944 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 /* protocol versions */
1947 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1948 PY_SSL_VERSION_SSL2);
1949 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1950 PY_SSL_VERSION_SSL3);
1951 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1952 PY_SSL_VERSION_SSL23);
1953 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1954 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 /* OpenSSL version */
1957 /* SSLeay() gives us the version of the library linked against,
1958 which could be different from the headers version.
1959 */
1960 libver = SSLeay();
1961 r = PyLong_FromUnsignedLong(libver);
1962 if (r == NULL)
1963 return NULL;
1964 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1965 return NULL;
1966 status = libver & 0xF;
1967 libver >>= 4;
1968 patch = libver & 0xFF;
1969 libver >>= 8;
1970 fix = libver & 0xFF;
1971 libver >>= 8;
1972 minor = libver & 0xFF;
1973 libver >>= 8;
1974 major = libver & 0xFF;
1975 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1976 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1977 return NULL;
1978 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1979 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1980 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001983}