blob: 4aa1e2d6ec108e56b75ca567023c846141c1e2d2 [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 */
208 return s->errorhandler();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000210 p = PY_SSL_ERROR_SYSCALL;
211 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000212 }
213 } else {
214 p = PY_SSL_ERROR_SYSCALL;
215 /* XXX Protected by global interpreter lock */
216 errstr = ERR_error_string(e, NULL);
217 }
218 break;
219 }
220 case SSL_ERROR_SSL:
221 {
222 unsigned long e = ERR_get_error();
223 p = PY_SSL_ERROR_SSL;
224 if (e != 0)
225 /* XXX Protected by global interpreter lock */
226 errstr = ERR_error_string(e, NULL);
227 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000228 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 }
230 break;
231 }
232 default:
233 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
234 errstr = "Invalid error code";
235 }
236 } else {
237 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
238 }
239 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
240 v = Py_BuildValue("(is)", p, buf);
241 if (v != NULL) {
242 PyErr_SetObject(PySSLErrorObject, v);
243 Py_DECREF(v);
244 }
245 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000246}
247
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000248static PyObject *
249_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000251 char buf[2048];
252 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000254 if (errstr == NULL) {
255 errcode = ERR_peek_last_error();
256 errstr = ERR_error_string(errcode, NULL);
257 }
258 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
259 v = Py_BuildValue("(is)", errcode, buf);
260 if (v != NULL) {
261 PyErr_SetObject(PySSLErrorObject, v);
262 Py_DECREF(v);
263 }
264 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000265}
266
Antoine Pitrou152efa22010-05-16 18:19:27 +0000267static PySSLSocket *
268newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
269 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000270{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000271 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000272
Antoine Pitrou152efa22010-05-16 18:19:27 +0000273 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 if (self == NULL)
275 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000277 self->peer_cert = NULL;
278 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000279 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000281 /* Make sure the SSL error state is initialized */
282 (void) ERR_get_state();
283 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000285 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000289#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000291#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 /* If the socket is in non-blocking mode or timeout mode, set the BIO
294 * to non-blocking mode (blocking is the default)
295 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
298 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
299 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000301 PySSL_BEGIN_ALLOW_THREADS
302 if (socket_type == PY_SSL_CLIENT)
303 SSL_set_connect_state(self->ssl);
304 else
305 SSL_set_accept_state(self->ssl);
306 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000307
Antoine Pitrou152efa22010-05-16 18:19:27 +0000308 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310}
311
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000312/* SSL object methods */
313
Antoine Pitrou152efa22010-05-16 18:19:27 +0000314static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 int ret;
317 int err;
318 int sockstate, nonblocking;
319 PySocketSockObject *sock
320 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 if (((PyObject*)sock) == Py_None) {
323 _setSSLError("Underlying socket connection gone",
324 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
325 return NULL;
326 }
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000328 /* just in case the blocking state of the socket has been changed */
329 nonblocking = (sock->sock_timeout >= 0.0);
330 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
331 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000333 /* Actually negotiate SSL connection */
334 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
335 sockstate = 0;
336 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000337 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000338 ret = SSL_do_handshake(self->ssl);
339 err = SSL_get_error(self->ssl, ret);
340 PySSL_END_ALLOW_THREADS
341 if(PyErr_CheckSignals()) {
342 return NULL;
343 }
344 if (err == SSL_ERROR_WANT_READ) {
345 sockstate = check_socket_and_wait_for_timeout(sock, 0);
346 } else if (err == SSL_ERROR_WANT_WRITE) {
347 sockstate = check_socket_and_wait_for_timeout(sock, 1);
348 } else {
349 sockstate = SOCKET_OPERATION_OK;
350 }
351 if (sockstate == SOCKET_HAS_TIMED_OUT) {
352 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000353 ERRSTR("The handshake operation timed out"));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000354 return NULL;
355 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
356 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000357 ERRSTR("Underlying socket has been closed."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000358 return NULL;
359 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
360 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000361 ERRSTR("Underlying socket too large for select()."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000362 return NULL;
363 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
364 break;
365 }
366 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
367 if (ret < 1)
368 return PySSL_SetError(self, ret, __FILE__, __LINE__);
369 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000371 if (self->peer_cert)
372 X509_free (self->peer_cert);
373 PySSL_BEGIN_ALLOW_THREADS
374 self->peer_cert = SSL_get_peer_certificate(self->ssl);
375 PySSL_END_ALLOW_THREADS
376
377 Py_INCREF(Py_None);
378 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379}
380
Thomas Woutersed03b412007-08-28 21:37:11 +0000381static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 char namebuf[X509_NAME_MAXLEN];
385 int buflen;
386 PyObject *name_obj;
387 PyObject *value_obj;
388 PyObject *attr;
389 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
392 if (buflen < 0) {
393 _setSSLError(NULL, 0, __FILE__, __LINE__);
394 goto fail;
395 }
396 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
397 if (name_obj == NULL)
398 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000400 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
401 if (buflen < 0) {
402 _setSSLError(NULL, 0, __FILE__, __LINE__);
403 Py_DECREF(name_obj);
404 goto fail;
405 }
406 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000407 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 OPENSSL_free(valuebuf);
409 if (value_obj == NULL) {
410 Py_DECREF(name_obj);
411 goto fail;
412 }
413 attr = PyTuple_New(2);
414 if (attr == NULL) {
415 Py_DECREF(name_obj);
416 Py_DECREF(value_obj);
417 goto fail;
418 }
419 PyTuple_SET_ITEM(attr, 0, name_obj);
420 PyTuple_SET_ITEM(attr, 1, value_obj);
421 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000422
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000423 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000425}
426
427static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000429{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000430 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
431 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
432 PyObject *rdnt;
433 PyObject *attr = NULL; /* tuple to hold an attribute */
434 int entry_count = X509_NAME_entry_count(xname);
435 X509_NAME_ENTRY *entry;
436 ASN1_OBJECT *name;
437 ASN1_STRING *value;
438 int index_counter;
439 int rdn_level = -1;
440 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000441
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 dn = PyList_New(0);
443 if (dn == NULL)
444 return NULL;
445 /* now create another tuple to hold the top-level RDN */
446 rdn = PyList_New(0);
447 if (rdn == NULL)
448 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 for (index_counter = 0;
451 index_counter < entry_count;
452 index_counter++)
453 {
454 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 /* check to see if we've gotten to a new RDN */
457 if (rdn_level >= 0) {
458 if (rdn_level != entry->set) {
459 /* yes, new RDN */
460 /* add old RDN to DN */
461 rdnt = PyList_AsTuple(rdn);
462 Py_DECREF(rdn);
463 if (rdnt == NULL)
464 goto fail0;
465 retcode = PyList_Append(dn, rdnt);
466 Py_DECREF(rdnt);
467 if (retcode < 0)
468 goto fail0;
469 /* create new RDN */
470 rdn = PyList_New(0);
471 if (rdn == NULL)
472 goto fail0;
473 }
474 }
475 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000477 /* now add this attribute to the current RDN */
478 name = X509_NAME_ENTRY_get_object(entry);
479 value = X509_NAME_ENTRY_get_data(entry);
480 attr = _create_tuple_for_attribute(name, value);
481 /*
482 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
483 entry->set,
484 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
485 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
486 */
487 if (attr == NULL)
488 goto fail1;
489 retcode = PyList_Append(rdn, attr);
490 Py_DECREF(attr);
491 if (retcode < 0)
492 goto fail1;
493 }
494 /* now, there's typically a dangling RDN */
495 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
496 rdnt = PyList_AsTuple(rdn);
497 Py_DECREF(rdn);
498 if (rdnt == NULL)
499 goto fail0;
500 retcode = PyList_Append(dn, rdnt);
501 Py_DECREF(rdnt);
502 if (retcode < 0)
503 goto fail0;
504 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000506 /* convert list to tuple */
507 rdnt = PyList_AsTuple(dn);
508 Py_DECREF(dn);
509 if (rdnt == NULL)
510 return NULL;
511 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512
513 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
516 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 Py_XDECREF(dn);
518 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519}
520
521static PyObject *
522_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 /* this code follows the procedure outlined in
525 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
526 function to extract the STACK_OF(GENERAL_NAME),
527 then iterates through the stack to add the
528 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000530 int i, j;
531 PyObject *peer_alt_names = Py_None;
532 PyObject *v, *t;
533 X509_EXTENSION *ext = NULL;
534 GENERAL_NAMES *names = NULL;
535 GENERAL_NAME *name;
536 X509V3_EXT_METHOD *method;
537 BIO *biobuf = NULL;
538 char buf[2048];
539 char *vptr;
540 int len;
541 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000542#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000544#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000546#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 if (certificate == NULL)
549 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 /* get a memory buffer */
552 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 i = 0;
555 while ((i = X509_get_ext_by_NID(
556 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 if (peer_alt_names == Py_None) {
559 peer_alt_names = PyList_New(0);
560 if (peer_alt_names == NULL)
561 goto fail;
562 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 /* now decode the altName */
565 ext = X509_get_ext(certificate, i);
566 if(!(method = X509V3_EXT_get(ext))) {
567 PyErr_SetString
568 (PySSLErrorObject,
569 ERRSTR("No method for internalizing subjectAltName!"));
570 goto fail;
571 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 p = ext->value->data;
574 if (method->it)
575 names = (GENERAL_NAMES*)
576 (ASN1_item_d2i(NULL,
577 &p,
578 ext->value->length,
579 ASN1_ITEM_ptr(method->it)));
580 else
581 names = (GENERAL_NAMES*)
582 (method->d2i(NULL,
583 &p,
584 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 name = sk_GENERAL_NAME_value(names, j);
591 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 /* we special-case DirName as a tuple of
594 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 t = PyTuple_New(2);
597 if (t == NULL) {
598 goto fail;
599 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000601 v = PyUnicode_FromString("DirName");
602 if (v == NULL) {
603 Py_DECREF(t);
604 goto fail;
605 }
606 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 v = _create_tuple_for_X509_NAME (name->d.dirn);
609 if (v == NULL) {
610 Py_DECREF(t);
611 goto fail;
612 }
613 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 (void) BIO_reset(biobuf);
620 GENERAL_NAME_print(biobuf, name);
621 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
622 if (len < 0) {
623 _setSSLError(NULL, 0, __FILE__, __LINE__);
624 goto fail;
625 }
626 vptr = strchr(buf, ':');
627 if (vptr == NULL)
628 goto fail;
629 t = PyTuple_New(2);
630 if (t == NULL)
631 goto fail;
632 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
633 if (v == NULL) {
634 Py_DECREF(t);
635 goto fail;
636 }
637 PyTuple_SET_ITEM(t, 0, v);
638 v = PyUnicode_FromStringAndSize((vptr + 1),
639 (len - (vptr - buf + 1)));
640 if (v == NULL) {
641 Py_DECREF(t);
642 goto fail;
643 }
644 PyTuple_SET_ITEM(t, 1, v);
645 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 if (PyList_Append(peer_alt_names, t) < 0) {
650 Py_DECREF(t);
651 goto fail;
652 }
653 Py_DECREF(t);
654 }
655 }
656 BIO_free(biobuf);
657 if (peer_alt_names != Py_None) {
658 v = PyList_AsTuple(peer_alt_names);
659 Py_DECREF(peer_alt_names);
660 return v;
661 } else {
662 return peer_alt_names;
663 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000664
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
666 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 if (biobuf != NULL)
668 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 if (peer_alt_names != Py_None) {
671 Py_XDECREF(peer_alt_names);
672 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675}
676
677static PyObject *
678_decode_certificate (X509 *certificate, int verbose) {
679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 PyObject *retval = NULL;
681 BIO *biobuf = NULL;
682 PyObject *peer;
683 PyObject *peer_alt_names = NULL;
684 PyObject *issuer;
685 PyObject *version;
686 PyObject *sn_obj;
687 ASN1_INTEGER *serialNumber;
688 char buf[2048];
689 int len;
690 ASN1_TIME *notBefore, *notAfter;
691 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 retval = PyDict_New();
694 if (retval == NULL)
695 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000696
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 peer = _create_tuple_for_X509_NAME(
698 X509_get_subject_name(certificate));
699 if (peer == NULL)
700 goto fail0;
701 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
702 Py_DECREF(peer);
703 goto fail0;
704 }
705 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 if (verbose) {
708 issuer = _create_tuple_for_X509_NAME(
709 X509_get_issuer_name(certificate));
710 if (issuer == NULL)
711 goto fail0;
712 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
713 Py_DECREF(issuer);
714 goto fail0;
715 }
716 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 version = PyLong_FromLong(X509_get_version(certificate) + 1);
719 if (PyDict_SetItemString(retval, "version", version) < 0) {
720 Py_DECREF(version);
721 goto fail0;
722 }
723 Py_DECREF(version);
724 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 /* get a memory buffer */
727 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 (void) BIO_reset(biobuf);
732 serialNumber = X509_get_serialNumber(certificate);
733 /* should not exceed 20 octets, 160 bits, so buf is big enough */
734 i2a_ASN1_INTEGER(biobuf, serialNumber);
735 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
736 if (len < 0) {
737 _setSSLError(NULL, 0, __FILE__, __LINE__);
738 goto fail1;
739 }
740 sn_obj = PyUnicode_FromStringAndSize(buf, len);
741 if (sn_obj == NULL)
742 goto fail1;
743 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
744 Py_DECREF(sn_obj);
745 goto fail1;
746 }
747 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 (void) BIO_reset(biobuf);
750 notBefore = X509_get_notBefore(certificate);
751 ASN1_TIME_print(biobuf, notBefore);
752 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
753 if (len < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto fail1;
756 }
757 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
758 if (pnotBefore == NULL)
759 goto fail1;
760 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
761 Py_DECREF(pnotBefore);
762 goto fail1;
763 }
764 Py_DECREF(pnotBefore);
765 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 (void) BIO_reset(biobuf);
768 notAfter = X509_get_notAfter(certificate);
769 ASN1_TIME_print(biobuf, notAfter);
770 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
771 if (len < 0) {
772 _setSSLError(NULL, 0, __FILE__, __LINE__);
773 goto fail1;
774 }
775 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
776 if (pnotAfter == NULL)
777 goto fail1;
778 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
779 Py_DECREF(pnotAfter);
780 goto fail1;
781 }
782 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 peer_alt_names = _get_peer_alt_names(certificate);
787 if (peer_alt_names == NULL)
788 goto fail1;
789 else if (peer_alt_names != Py_None) {
790 if (PyDict_SetItemString(retval, "subjectAltName",
791 peer_alt_names) < 0) {
792 Py_DECREF(peer_alt_names);
793 goto fail1;
794 }
795 Py_DECREF(peer_alt_names);
796 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 BIO_free(biobuf);
799 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000800
801 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 if (biobuf != NULL)
803 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000804 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 Py_XDECREF(retval);
806 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000807}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000808
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809
810static PyObject *
811PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000814 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 X509 *x=NULL;
816 BIO *cert;
817 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818
Victor Stinner3800e1e2010-05-16 21:23:48 +0000819 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
820 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 if ((cert=BIO_new(BIO_s_file())) == NULL) {
824 PyErr_SetString(PySSLErrorObject,
825 "Can't malloc memory to read file");
826 goto fail0;
827 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Victor Stinner3800e1e2010-05-16 21:23:48 +0000829 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 PyErr_SetString(PySSLErrorObject,
831 "Can't open file");
832 goto fail0;
833 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
836 if (x == NULL) {
837 PyErr_SetString(PySSLErrorObject,
838 "Error decoding PEM-encoded file");
839 goto fail0;
840 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
844 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000845 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 if (cert != NULL) BIO_free(cert);
847 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848}
849
850
851static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000852PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 PyObject *retval = NULL;
855 int len;
856 int verification;
857 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000858
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000859 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
860 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 if (!self->peer_cert)
863 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 if (PyObject_IsTrue(binary_mode)) {
866 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 bytes_buf = NULL;
871 len = i2d_X509(self->peer_cert, &bytes_buf);
872 if (len < 0) {
873 PySSL_SetError(self, len, __FILE__, __LINE__);
874 return NULL;
875 }
876 /* this is actually an immutable bytes sequence */
877 retval = PyBytes_FromStringAndSize
878 ((const char *) bytes_buf, len);
879 OPENSSL_free(bytes_buf);
880 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 if ((verification & SSL_VERIFY_PEER) == 0)
885 return PyDict_New();
886 else
887 return _decode_certificate (self->peer_cert, 0);
888 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889}
890
891PyDoc_STRVAR(PySSL_peercert_doc,
892"peer_certificate([der=False]) -> certificate\n\
893\n\
894Returns the certificate for the peer. If no certificate was provided,\n\
895returns None. If a certificate was provided, but not validated, returns\n\
896an empty dictionary. Otherwise returns a dict containing information\n\
897about the peer certificate.\n\
898\n\
899If the optional argument is True, returns a DER-encoded copy of the\n\
900peer certificate, or None if no certificate was provided. This will\n\
901return the certificate even if it wasn't validated.");
902
Antoine Pitrou152efa22010-05-16 18:19:27 +0000903static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 PyObject *retval, *v;
906 SSL_CIPHER *current;
907 char *cipher_name;
908 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 if (self->ssl == NULL)
911 return Py_None;
912 current = SSL_get_current_cipher(self->ssl);
913 if (current == NULL)
914 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 retval = PyTuple_New(3);
917 if (retval == NULL)
918 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 cipher_name = (char *) SSL_CIPHER_get_name(current);
921 if (cipher_name == NULL) {
922 PyTuple_SET_ITEM(retval, 0, Py_None);
923 } else {
924 v = PyUnicode_FromString(cipher_name);
925 if (v == NULL)
926 goto fail0;
927 PyTuple_SET_ITEM(retval, 0, v);
928 }
929 cipher_protocol = SSL_CIPHER_get_version(current);
930 if (cipher_protocol == NULL) {
931 PyTuple_SET_ITEM(retval, 1, Py_None);
932 } else {
933 v = PyUnicode_FromString(cipher_protocol);
934 if (v == NULL)
935 goto fail0;
936 PyTuple_SET_ITEM(retval, 1, v);
937 }
938 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
939 if (v == NULL)
940 goto fail0;
941 PyTuple_SET_ITEM(retval, 2, v);
942 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000943
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 Py_DECREF(retval);
946 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947}
948
Antoine Pitrou152efa22010-05-16 18:19:27 +0000949static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000950{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 if (self->peer_cert) /* Possible not to have one? */
952 X509_free (self->peer_cert);
953 if (self->ssl)
954 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 Py_XDECREF(self->Socket);
956 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000957}
958
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000959/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000960 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000961 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000962 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000963
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000964static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000965check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000966{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 fd_set fds;
968 struct timeval tv;
969 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 /* Nothing to do unless we're in timeout mode (not non-blocking) */
972 if (s->sock_timeout < 0.0)
973 return SOCKET_IS_BLOCKING;
974 else if (s->sock_timeout == 0.0)
975 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 /* Guard against closed socket */
978 if (s->sock_fd < 0)
979 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 /* Prefer poll, if available, since you can poll() any fd
982 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000983#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 {
985 struct pollfd pollfd;
986 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 pollfd.fd = s->sock_fd;
989 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 /* s->sock_timeout is in seconds, timeout in ms */
992 timeout = (int)(s->sock_timeout * 1000 + 0.5);
993 PySSL_BEGIN_ALLOW_THREADS
994 rc = poll(&pollfd, 1, timeout);
995 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000996
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 goto normal_return;
998 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000999#endif
1000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001002#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 if (s->sock_fd >= FD_SETSIZE)
1004 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001005#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* Construct the arguments to select */
1008 tv.tv_sec = (int)s->sock_timeout;
1009 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1010 FD_ZERO(&fds);
1011 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 /* See if the socket is ready */
1014 PySSL_BEGIN_ALLOW_THREADS
1015 if (writing)
1016 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1017 else
1018 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1019 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001020
Bill Janssen6e027db2007-11-15 22:23:56 +00001021#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001023#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1025 (when we are able to write or when there's something to read) */
1026 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001027}
1028
Antoine Pitrou152efa22010-05-16 18:19:27 +00001029static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001030{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 Py_buffer buf;
1032 int len;
1033 int sockstate;
1034 int err;
1035 int nonblocking;
1036 PySocketSockObject *sock
1037 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001038
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 if (((PyObject*)sock) == Py_None) {
1040 _setSSLError("Underlying socket connection gone",
1041 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1042 return NULL;
1043 }
1044
1045 if (!PyArg_ParseTuple(args, "y*:write", &buf))
1046 return NULL;
1047
1048 /* just in case the blocking state of the socket has been changed */
1049 nonblocking = (sock->sock_timeout >= 0.0);
1050 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1051 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1052
1053 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1054 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1055 PyErr_SetString(PySSLErrorObject,
1056 "The write operation timed out");
1057 goto error;
1058 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1059 PyErr_SetString(PySSLErrorObject,
1060 "Underlying socket has been closed.");
1061 goto error;
1062 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1063 PyErr_SetString(PySSLErrorObject,
1064 "Underlying socket too large for select().");
1065 goto error;
1066 }
1067 do {
1068 err = 0;
1069 PySSL_BEGIN_ALLOW_THREADS
1070 len = SSL_write(self->ssl, buf.buf, buf.len);
1071 err = SSL_get_error(self->ssl, len);
1072 PySSL_END_ALLOW_THREADS
1073 if (PyErr_CheckSignals()) {
1074 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001075 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001077 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001079 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 } else {
1081 sockstate = SOCKET_OPERATION_OK;
1082 }
1083 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1084 PyErr_SetString(PySSLErrorObject,
1085 "The write operation timed out");
1086 goto error;
1087 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1088 PyErr_SetString(PySSLErrorObject,
1089 "Underlying socket has been closed.");
1090 goto error;
1091 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1092 break;
1093 }
1094 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001095
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 PyBuffer_Release(&buf);
1097 if (len > 0)
1098 return PyLong_FromLong(len);
1099 else
1100 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001101
1102error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 PyBuffer_Release(&buf);
1104 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001105}
1106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001107PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001108"write(s) -> len\n\
1109\n\
1110Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001111of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001112
Antoine Pitrou152efa22010-05-16 18:19:27 +00001113static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001114{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 PySSL_BEGIN_ALLOW_THREADS
1118 count = SSL_pending(self->ssl);
1119 PySSL_END_ALLOW_THREADS
1120 if (count < 0)
1121 return PySSL_SetError(self, count, __FILE__, __LINE__);
1122 else
1123 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001124}
1125
1126PyDoc_STRVAR(PySSL_SSLpending_doc,
1127"pending() -> count\n\
1128\n\
1129Returns the number of already decrypted bytes available for read,\n\
1130pending on the connection.\n");
1131
Antoine Pitrou152efa22010-05-16 18:19:27 +00001132static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001133{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 PyObject *dest = NULL;
1135 Py_buffer buf;
1136 int buf_passed = 0;
1137 int count = -1;
1138 char *mem;
1139 /* XXX this should use Py_ssize_t */
1140 int len = 1024;
1141 int sockstate;
1142 int err;
1143 int nonblocking;
1144 PySocketSockObject *sock
1145 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 if (((PyObject*)sock) == Py_None) {
1148 _setSSLError("Underlying socket connection gone",
1149 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1150 return NULL;
1151 }
1152
1153 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1154 return NULL;
1155 if ((dest == NULL) || (dest == Py_None)) {
1156 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1157 return NULL;
1158 mem = PyByteArray_AS_STRING(dest);
1159 } else if (PyLong_Check(dest)) {
1160 len = PyLong_AS_LONG(dest);
1161 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1162 return NULL;
1163 mem = PyByteArray_AS_STRING(dest);
1164 } else {
1165 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1166 return NULL;
1167 mem = buf.buf;
1168 len = buf.len;
1169 if ((count > 0) && (count <= len))
1170 len = count;
1171 buf_passed = 1;
1172 }
1173
1174 /* just in case the blocking state of the socket has been changed */
1175 nonblocking = (sock->sock_timeout >= 0.0);
1176 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1177 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1178
1179 /* first check if there are bytes ready to be read */
1180 PySSL_BEGIN_ALLOW_THREADS
1181 count = SSL_pending(self->ssl);
1182 PySSL_END_ALLOW_THREADS
1183
1184 if (!count) {
1185 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1186 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1187 PyErr_SetString(PySSLErrorObject,
1188 "The read operation timed out");
1189 goto error;
1190 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1191 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001192 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 goto error;
1194 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1195 count = 0;
1196 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001197 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 }
1199 do {
1200 err = 0;
1201 PySSL_BEGIN_ALLOW_THREADS
1202 count = SSL_read(self->ssl, mem, len);
1203 err = SSL_get_error(self->ssl, count);
1204 PySSL_END_ALLOW_THREADS
1205 if (PyErr_CheckSignals())
1206 goto error;
1207 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001208 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001210 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1212 (SSL_get_shutdown(self->ssl) ==
1213 SSL_RECEIVED_SHUTDOWN))
1214 {
1215 count = 0;
1216 goto done;
1217 } else {
1218 sockstate = SOCKET_OPERATION_OK;
1219 }
1220 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1221 PyErr_SetString(PySSLErrorObject,
1222 "The read operation timed out");
1223 goto error;
1224 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1225 break;
1226 }
1227 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1228 if (count <= 0) {
1229 PySSL_SetError(self, count, __FILE__, __LINE__);
1230 goto error;
1231 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001232 done:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 if (!buf_passed) {
1234 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1235 Py_DECREF(dest);
1236 return res;
1237 } else {
1238 PyBuffer_Release(&buf);
1239 return PyLong_FromLong(count);
1240 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001241 error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 if (!buf_passed) {
1243 Py_DECREF(dest);
1244 } else {
1245 PyBuffer_Release(&buf);
1246 }
1247 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001248}
1249
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001250PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001251"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001252\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001254
Antoine Pitrou152efa22010-05-16 18:19:27 +00001255static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001256{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 int err, ssl_err, sockstate, nonblocking;
1258 int zeros = 0;
1259 PySocketSockObject *sock
1260 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 /* Guard against closed socket */
1263 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1264 _setSSLError("Underlying socket connection gone",
1265 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1266 return NULL;
1267 }
1268
1269 /* Just in case the blocking state of the socket has been changed */
1270 nonblocking = (sock->sock_timeout >= 0.0);
1271 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1272 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1273
1274 while (1) {
1275 PySSL_BEGIN_ALLOW_THREADS
1276 /* Disable read-ahead so that unwrap can work correctly.
1277 * Otherwise OpenSSL might read in too much data,
1278 * eating clear text data that happens to be
1279 * transmitted after the SSL shutdown.
1280 * Should be safe to call repeatedly everytime this
1281 * function is used and the shutdown_seen_zero != 0
1282 * condition is met.
1283 */
1284 if (self->shutdown_seen_zero)
1285 SSL_set_read_ahead(self->ssl, 0);
1286 err = SSL_shutdown(self->ssl);
1287 PySSL_END_ALLOW_THREADS
1288 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1289 if (err > 0)
1290 break;
1291 if (err == 0) {
1292 /* Don't loop endlessly; instead preserve legacy
1293 behaviour of trying SSL_shutdown() only twice.
1294 This looks necessary for OpenSSL < 0.9.8m */
1295 if (++zeros > 1)
1296 break;
1297 /* Shutdown was sent, now try receiving */
1298 self->shutdown_seen_zero = 1;
1299 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001300 }
1301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 /* Possibly retry shutdown until timeout or failure */
1303 ssl_err = SSL_get_error(self->ssl, err);
1304 if (ssl_err == SSL_ERROR_WANT_READ)
1305 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1306 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1307 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1308 else
1309 break;
1310 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1311 if (ssl_err == SSL_ERROR_WANT_READ)
1312 PyErr_SetString(PySSLErrorObject,
1313 "The read operation timed out");
1314 else
1315 PyErr_SetString(PySSLErrorObject,
1316 "The write operation timed out");
1317 return NULL;
1318 }
1319 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1320 PyErr_SetString(PySSLErrorObject,
1321 "Underlying socket too large for select().");
1322 return NULL;
1323 }
1324 else if (sockstate != SOCKET_OPERATION_OK)
1325 /* Retain the SSL error code */
1326 break;
1327 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 if (err < 0)
1330 return PySSL_SetError(self, err, __FILE__, __LINE__);
1331 else {
1332 Py_INCREF(sock);
1333 return (PyObject *) sock;
1334 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001335}
1336
1337PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1338"shutdown(s) -> socket\n\
1339\n\
1340Does the SSL shutdown handshake with the remote end, and returns\n\
1341the underlying socket object.");
1342
1343
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001344static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1346 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1347 PySSL_SSLwrite_doc},
1348 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1349 PySSL_SSLread_doc},
1350 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1351 PySSL_SSLpending_doc},
1352 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1353 PySSL_peercert_doc},
1354 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1355 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1356 PySSL_SSLshutdown_doc},
1357 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001358};
1359
Antoine Pitrou152efa22010-05-16 18:19:27 +00001360static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001362 "_ssl._SSLSocket", /*tp_name*/
1363 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 0, /*tp_itemsize*/
1365 /* methods */
1366 (destructor)PySSL_dealloc, /*tp_dealloc*/
1367 0, /*tp_print*/
1368 0, /*tp_getattr*/
1369 0, /*tp_setattr*/
1370 0, /*tp_reserved*/
1371 0, /*tp_repr*/
1372 0, /*tp_as_number*/
1373 0, /*tp_as_sequence*/
1374 0, /*tp_as_mapping*/
1375 0, /*tp_hash*/
1376 0, /*tp_call*/
1377 0, /*tp_str*/
1378 0, /*tp_getattro*/
1379 0, /*tp_setattro*/
1380 0, /*tp_as_buffer*/
1381 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1382 0, /*tp_doc*/
1383 0, /*tp_traverse*/
1384 0, /*tp_clear*/
1385 0, /*tp_richcompare*/
1386 0, /*tp_weaklistoffset*/
1387 0, /*tp_iter*/
1388 0, /*tp_iternext*/
1389 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001390};
1391
Antoine Pitrou152efa22010-05-16 18:19:27 +00001392
1393/*
1394 * _SSLContext objects
1395 */
1396
1397static PyObject *
1398context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1399{
1400 char *kwlist[] = {"protocol", NULL};
1401 PySSLContext *self;
1402 int proto_version = PY_SSL_VERSION_SSL23;
1403 SSL_CTX *ctx = NULL;
1404
1405 if (!PyArg_ParseTupleAndKeywords(
1406 args, kwds, "i:_SSLContext", kwlist,
1407 &proto_version))
1408 return NULL;
1409
1410 PySSL_BEGIN_ALLOW_THREADS
1411 if (proto_version == PY_SSL_VERSION_TLS1)
1412 ctx = SSL_CTX_new(TLSv1_method());
1413 else if (proto_version == PY_SSL_VERSION_SSL3)
1414 ctx = SSL_CTX_new(SSLv3_method());
1415 else if (proto_version == PY_SSL_VERSION_SSL2)
1416 ctx = SSL_CTX_new(SSLv2_method());
1417 else if (proto_version == PY_SSL_VERSION_SSL23)
1418 ctx = SSL_CTX_new(SSLv23_method());
1419 else
1420 proto_version = -1;
1421 PySSL_END_ALLOW_THREADS
1422
1423 if (proto_version == -1) {
1424 PyErr_SetString(PyExc_ValueError,
1425 "invalid protocol version");
1426 return NULL;
1427 }
1428 if (ctx == NULL) {
1429 PyErr_SetString(PySSLErrorObject,
1430 "failed to allocate SSL context");
1431 return NULL;
1432 }
1433
1434 assert(type != NULL && type->tp_alloc != NULL);
1435 self = (PySSLContext *) type->tp_alloc(type, 0);
1436 if (self == NULL) {
1437 SSL_CTX_free(ctx);
1438 return NULL;
1439 }
1440 self->ctx = ctx;
1441 /* Defaults */
1442 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1443 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1444
1445 return (PyObject *)self;
1446}
1447
1448static void
1449context_dealloc(PySSLContext *self)
1450{
1451 SSL_CTX_free(self->ctx);
1452 Py_TYPE(self)->tp_free(self);
1453}
1454
1455static PyObject *
1456set_ciphers(PySSLContext *self, PyObject *args)
1457{
1458 int ret;
1459 const char *cipherlist;
1460
1461 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1462 return NULL;
1463 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1464 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001465 /* Clearing the error queue is necessary on some OpenSSL versions,
1466 otherwise the error will be reported again when another SSL call
1467 is done. */
1468 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001469 PyErr_SetString(PySSLErrorObject,
1470 "No cipher can be selected.");
1471 return NULL;
1472 }
1473 Py_RETURN_NONE;
1474}
1475
1476static PyObject *
1477get_verify_mode(PySSLContext *self, void *c)
1478{
1479 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1480 case SSL_VERIFY_NONE:
1481 return PyLong_FromLong(PY_SSL_CERT_NONE);
1482 case SSL_VERIFY_PEER:
1483 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1484 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1485 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1486 }
1487 PyErr_SetString(PySSLErrorObject,
1488 "invalid return value from SSL_CTX_get_verify_mode");
1489 return NULL;
1490}
1491
1492static int
1493set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1494{
1495 int n, mode;
1496 if (!PyArg_Parse(arg, "i", &n))
1497 return -1;
1498 if (n == PY_SSL_CERT_NONE)
1499 mode = SSL_VERIFY_NONE;
1500 else if (n == PY_SSL_CERT_OPTIONAL)
1501 mode = SSL_VERIFY_PEER;
1502 else if (n == PY_SSL_CERT_REQUIRED)
1503 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1504 else {
1505 PyErr_SetString(PyExc_ValueError,
1506 "invalid value for verify_mode");
1507 return -1;
1508 }
1509 SSL_CTX_set_verify(self->ctx, mode, NULL);
1510 return 0;
1511}
1512
1513static PyObject *
1514load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1515{
1516 char *kwlist[] = {"certfile", "keyfile", NULL};
1517 PyObject *certfile, *keyfile = NULL;
1518 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1519 int r;
1520
1521 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1522 "O|O:load_cert_chain", kwlist,
1523 &certfile, &keyfile))
1524 return NULL;
1525 if (keyfile == Py_None)
1526 keyfile = NULL;
1527 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1528 PyErr_SetString(PyExc_TypeError,
1529 "certfile should be a valid filesystem path");
1530 return NULL;
1531 }
1532 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1533 PyErr_SetString(PyExc_TypeError,
1534 "keyfile should be a valid filesystem path");
1535 goto error;
1536 }
1537 PySSL_BEGIN_ALLOW_THREADS
1538 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1539 PyBytes_AS_STRING(certfile_bytes));
1540 PySSL_END_ALLOW_THREADS
1541 if (r != 1) {
1542 _setSSLError(NULL, 0, __FILE__, __LINE__);
1543 goto error;
1544 }
1545 PySSL_BEGIN_ALLOW_THREADS
1546 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1547 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1548 SSL_FILETYPE_PEM);
1549 PySSL_END_ALLOW_THREADS
1550 Py_XDECREF(keyfile_bytes);
1551 Py_XDECREF(certfile_bytes);
1552 if (r != 1) {
1553 _setSSLError(NULL, 0, __FILE__, __LINE__);
1554 return NULL;
1555 }
1556 PySSL_BEGIN_ALLOW_THREADS
1557 r = SSL_CTX_check_private_key(self->ctx);
1558 PySSL_END_ALLOW_THREADS
1559 if (r != 1) {
1560 _setSSLError(NULL, 0, __FILE__, __LINE__);
1561 return NULL;
1562 }
1563 Py_RETURN_NONE;
1564
1565error:
1566 Py_XDECREF(keyfile_bytes);
1567 Py_XDECREF(certfile_bytes);
1568 return NULL;
1569}
1570
1571static PyObject *
1572load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1573{
1574 char *kwlist[] = {"cafile", "capath", NULL};
1575 PyObject *cafile = NULL, *capath = NULL;
1576 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1577 const char *cafile_buf = NULL, *capath_buf = NULL;
1578 int r;
1579
1580 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1581 "|OO:load_verify_locations", kwlist,
1582 &cafile, &capath))
1583 return NULL;
1584 if (cafile == Py_None)
1585 cafile = NULL;
1586 if (capath == Py_None)
1587 capath = NULL;
1588 if (cafile == NULL && capath == NULL) {
1589 PyErr_SetString(PyExc_TypeError,
1590 "cafile and capath cannot be both omitted");
1591 return NULL;
1592 }
1593 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1594 PyErr_SetString(PyExc_TypeError,
1595 "cafile should be a valid filesystem path");
1596 return NULL;
1597 }
1598 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1599 Py_DECREF(cafile_bytes);
1600 PyErr_SetString(PyExc_TypeError,
1601 "capath should be a valid filesystem path");
1602 return NULL;
1603 }
1604 if (cafile)
1605 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1606 if (capath)
1607 capath_buf = PyBytes_AS_STRING(capath_bytes);
1608 PySSL_BEGIN_ALLOW_THREADS
1609 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1610 PySSL_END_ALLOW_THREADS
1611 Py_XDECREF(cafile_bytes);
1612 Py_XDECREF(capath_bytes);
1613 if (r != 1) {
1614 _setSSLError(NULL, 0, __FILE__, __LINE__);
1615 return NULL;
1616 }
1617 Py_RETURN_NONE;
1618}
1619
1620static PyObject *
1621context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1622{
1623 char *kwlist[] = {"sock", "server_side", NULL};
1624 PySocketSockObject *sock;
1625 int server_side = 0;
1626
1627 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1628 PySocketModule.Sock_Type,
1629 &sock, &server_side))
1630 return NULL;
1631
1632 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1633}
1634
1635static PyGetSetDef context_getsetlist[] = {
1636 {"verify_mode", (getter) get_verify_mode,
1637 (setter) set_verify_mode, NULL},
1638 {NULL}, /* sentinel */
1639};
1640
1641static struct PyMethodDef context_methods[] = {
1642 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1643 METH_VARARGS | METH_KEYWORDS, NULL},
1644 {"set_ciphers", (PyCFunction) set_ciphers,
1645 METH_VARARGS, NULL},
1646 {"load_cert_chain", (PyCFunction) load_cert_chain,
1647 METH_VARARGS | METH_KEYWORDS, NULL},
1648 {"load_verify_locations", (PyCFunction) load_verify_locations,
1649 METH_VARARGS | METH_KEYWORDS, NULL},
1650 {NULL, NULL} /* sentinel */
1651};
1652
1653static PyTypeObject PySSLContext_Type = {
1654 PyVarObject_HEAD_INIT(NULL, 0)
1655 "_ssl._SSLContext", /*tp_name*/
1656 sizeof(PySSLContext), /*tp_basicsize*/
1657 0, /*tp_itemsize*/
1658 (destructor)context_dealloc, /*tp_dealloc*/
1659 0, /*tp_print*/
1660 0, /*tp_getattr*/
1661 0, /*tp_setattr*/
1662 0, /*tp_reserved*/
1663 0, /*tp_repr*/
1664 0, /*tp_as_number*/
1665 0, /*tp_as_sequence*/
1666 0, /*tp_as_mapping*/
1667 0, /*tp_hash*/
1668 0, /*tp_call*/
1669 0, /*tp_str*/
1670 0, /*tp_getattro*/
1671 0, /*tp_setattro*/
1672 0, /*tp_as_buffer*/
1673 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1674 0, /*tp_doc*/
1675 0, /*tp_traverse*/
1676 0, /*tp_clear*/
1677 0, /*tp_richcompare*/
1678 0, /*tp_weaklistoffset*/
1679 0, /*tp_iter*/
1680 0, /*tp_iternext*/
1681 context_methods, /*tp_methods*/
1682 0, /*tp_members*/
1683 context_getsetlist, /*tp_getset*/
1684 0, /*tp_base*/
1685 0, /*tp_dict*/
1686 0, /*tp_descr_get*/
1687 0, /*tp_descr_set*/
1688 0, /*tp_dictoffset*/
1689 0, /*tp_init*/
1690 0, /*tp_alloc*/
1691 context_new, /*tp_new*/
1692};
1693
1694
1695
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001696#ifdef HAVE_OPENSSL_RAND
1697
1698/* helper routines for seeding the SSL PRNG */
1699static PyObject *
1700PySSL_RAND_add(PyObject *self, PyObject *args)
1701{
1702 char *buf;
1703 int len;
1704 double entropy;
1705
1706 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001707 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001708 RAND_add(buf, len, entropy);
1709 Py_INCREF(Py_None);
1710 return Py_None;
1711}
1712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001713PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001714"RAND_add(string, entropy)\n\
1715\n\
1716Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001718
1719static PyObject *
1720PySSL_RAND_status(PyObject *self)
1721{
Christian Heimes217cfd12007-12-02 14:31:20 +00001722 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001723}
1724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001725PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001726"RAND_status() -> 0 or 1\n\
1727\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001728Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1729It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1730using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001731
1732static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001733PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001734{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001735 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001736 int bytes;
1737
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001738 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1739 PyUnicode_FSConverter, &path))
1740 return NULL;
1741
1742 bytes = RAND_egd(PyBytes_AsString(path));
1743 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001744 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001745 PyErr_SetString(PySSLErrorObject,
1746 "EGD connection failed or EGD did not return "
1747 "enough data to seed the PRNG");
1748 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001749 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001750 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001751}
1752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001753PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754"RAND_egd(path) -> bytes\n\
1755\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1757Returns number of bytes read. Raises SSLError if connection to EGD\n\
1758fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001759
1760#endif
1761
Bill Janssen40a0f662008-08-12 16:56:25 +00001762
1763
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001764/* List of functions exported by this module. */
1765
1766static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 {"_test_decode_cert", PySSL_test_decode_certificate,
1768 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001769#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1771 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001772 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001773 PySSL_RAND_egd_doc},
1774 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1775 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001776#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001777 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001778};
1779
1780
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781#ifdef WITH_THREAD
1782
1783/* an implementation of OpenSSL threading operations in terms
1784 of the Python C thread library */
1785
1786static PyThread_type_lock *_ssl_locks = NULL;
1787
1788static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790}
1791
Bill Janssen6e027db2007-11-15 22:23:56 +00001792static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 (int mode, int n, const char *file, int line) {
1794 /* this function is needed to perform locking on shared data
1795 structures. (Note that OpenSSL uses a number of global data
1796 structures that will be implicitly shared whenever multiple
1797 threads use OpenSSL.) Multi-threaded applications will
1798 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 locking_function() must be able to handle up to
1801 CRYPTO_num_locks() different mutex locks. It sets the n-th
1802 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 file and line are the file number of the function setting the
1805 lock. They can be useful for debugging.
1806 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 if ((_ssl_locks == NULL) ||
1809 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1810 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 if (mode & CRYPTO_LOCK) {
1813 PyThread_acquire_lock(_ssl_locks[n], 1);
1814 } else {
1815 PyThread_release_lock(_ssl_locks[n]);
1816 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001817}
1818
1819static int _setup_ssl_threads(void) {
1820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if (_ssl_locks == NULL) {
1824 _ssl_locks_count = CRYPTO_num_locks();
1825 _ssl_locks = (PyThread_type_lock *)
1826 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1827 if (_ssl_locks == NULL)
1828 return 0;
1829 memset(_ssl_locks, 0,
1830 sizeof(PyThread_type_lock) * _ssl_locks_count);
1831 for (i = 0; i < _ssl_locks_count; i++) {
1832 _ssl_locks[i] = PyThread_allocate_lock();
1833 if (_ssl_locks[i] == NULL) {
1834 unsigned int j;
1835 for (j = 0; j < i; j++) {
1836 PyThread_free_lock(_ssl_locks[j]);
1837 }
1838 free(_ssl_locks);
1839 return 0;
1840 }
1841 }
1842 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1843 CRYPTO_set_id_callback(_ssl_thread_id_function);
1844 }
1845 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001846}
1847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001849
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001850PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001851"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001852for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001853
Martin v. Löwis1a214512008-06-11 05:26:20 +00001854
1855static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 PyModuleDef_HEAD_INIT,
1857 "_ssl",
1858 module_doc,
1859 -1,
1860 PySSL_methods,
1861 NULL,
1862 NULL,
1863 NULL,
1864 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001865};
1866
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001867PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001868PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001869{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 PyObject *m, *d, *r;
1871 unsigned long libver;
1872 unsigned int major, minor, fix, patch, status;
1873 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001874
Antoine Pitrou152efa22010-05-16 18:19:27 +00001875 if (PyType_Ready(&PySSLContext_Type) < 0)
1876 return NULL;
1877 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 m = PyModule_Create(&_sslmodule);
1881 if (m == NULL)
1882 return NULL;
1883 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 /* Load _socket module and its C API */
1886 socket_api = PySocketModule_ImportModuleAndAPI();
1887 if (!socket_api)
1888 return NULL;
1889 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 /* Init OpenSSL */
1892 SSL_load_error_strings();
1893 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001894#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 /* note that this will start threading if not already started */
1896 if (!_setup_ssl_threads()) {
1897 return NULL;
1898 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001899#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 /* Add symbols to module dict */
1903 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1904 PySocketModule.error,
1905 NULL);
1906 if (PySSLErrorObject == NULL)
1907 return NULL;
1908 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1909 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001910 if (PyDict_SetItemString(d, "_SSLContext",
1911 (PyObject *)&PySSLContext_Type) != 0)
1912 return NULL;
1913 if (PyDict_SetItemString(d, "_SSLSocket",
1914 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001915 return NULL;
1916 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1917 PY_SSL_ERROR_ZERO_RETURN);
1918 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1919 PY_SSL_ERROR_WANT_READ);
1920 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1921 PY_SSL_ERROR_WANT_WRITE);
1922 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1923 PY_SSL_ERROR_WANT_X509_LOOKUP);
1924 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1925 PY_SSL_ERROR_SYSCALL);
1926 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1927 PY_SSL_ERROR_SSL);
1928 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1929 PY_SSL_ERROR_WANT_CONNECT);
1930 /* non ssl.h errorcodes */
1931 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1932 PY_SSL_ERROR_EOF);
1933 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1934 PY_SSL_ERROR_INVALID_ERROR_CODE);
1935 /* cert requirements */
1936 PyModule_AddIntConstant(m, "CERT_NONE",
1937 PY_SSL_CERT_NONE);
1938 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1939 PY_SSL_CERT_OPTIONAL);
1940 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1941 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 /* protocol versions */
1944 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1945 PY_SSL_VERSION_SSL2);
1946 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1947 PY_SSL_VERSION_SSL3);
1948 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1949 PY_SSL_VERSION_SSL23);
1950 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1951 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 /* OpenSSL version */
1954 /* SSLeay() gives us the version of the library linked against,
1955 which could be different from the headers version.
1956 */
1957 libver = SSLeay();
1958 r = PyLong_FromUnsignedLong(libver);
1959 if (r == NULL)
1960 return NULL;
1961 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1962 return NULL;
1963 status = libver & 0xF;
1964 libver >>= 4;
1965 patch = libver & 0xFF;
1966 libver >>= 8;
1967 fix = libver & 0xFF;
1968 libver >>= 8;
1969 minor = libver & 0xFF;
1970 libver >>= 8;
1971 major = libver & 0xFF;
1972 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1973 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1974 return NULL;
1975 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1976 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1977 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001980}