blob: 16fbb4db42ecaca7c0bc7a1ac74b9055ac580aad [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 Pitrou5a1c4d12010-04-23 21:11:10 +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 Pitrou30dc1a72010-05-05 16:01:14 +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 Pitrou30dc1a72010-05-05 16:01:14 +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 Pitrou30dc1a72010-05-05 16:01:14 +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 Pitrou30dc1a72010-05-05 16:01:14 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Victor Stinneree18b6f2011-05-10 00:38:00 +020066#ifndef OPENSSL_NO_SSL2
Antoine Pitrou30dc1a72010-05-05 16:01:14 +000067 PY_SSL_VERSION_SSL2,
Victor Stinneree18b6f2011-05-10 00:38:00 +020068#endif
69 PY_SSL_VERSION_SSL3=1,
Antoine Pitrou30dc1a72010-05-05 16:01:14 +000070 PY_SSL_VERSION_SSL23,
71 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000072};
73
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000074/* Include symbols from _socket module */
75#include "socketmodule.h"
76
Benjamin Petersonb173f782009-05-05 22:31:58 +000077static PySocketModule_APIObject PySocketModule;
78
Thomas Woutersed03b412007-08-28 21:37:11 +000079#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080#include <poll.h>
81#elif defined(HAVE_SYS_POLL_H)
82#include <sys/poll.h>
83#endif
84
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000085/* Include OpenSSL header files */
86#include "openssl/rsa.h"
87#include "openssl/crypto.h"
88#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000089#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090#include "openssl/pem.h"
91#include "openssl/ssl.h"
92#include "openssl/err.h"
93#include "openssl/rand.h"
94
95/* SSL error object */
96static PyObject *PySSLErrorObject;
97
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098#ifdef WITH_THREAD
99
100/* serves as a flag to see whether we've initialized the SSL thread support. */
101/* 0 means no, greater than 0 means yes */
102
103static unsigned int _ssl_locks_count = 0;
104
105#endif /* def WITH_THREAD */
106
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107/* SSL socket object */
108
109#define X509_NAME_MAXLEN 256
110
111/* RAND_* APIs got added to OpenSSL in 0.9.5 */
112#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
113# define HAVE_OPENSSL_RAND 1
114#else
115# undef HAVE_OPENSSL_RAND
116#endif
117
118typedef struct {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000119 PyObject_HEAD
120 PyObject *Socket; /* weakref to socket on which we're layered */
121 SSL_CTX* ctx;
122 SSL* ssl;
123 X509* peer_cert;
124 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000125
126} PySSLObject;
127
Jeremy Hylton938ace62002-07-17 16:30:39 +0000128static PyTypeObject PySSL_Type;
129static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
130static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000131static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000132 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000133static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
134static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000136#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000137
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000138typedef enum {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000139 SOCKET_IS_NONBLOCKING,
140 SOCKET_IS_BLOCKING,
141 SOCKET_HAS_TIMED_OUT,
142 SOCKET_HAS_BEEN_CLOSED,
143 SOCKET_TOO_LARGE_FOR_SELECT,
144 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000145} timeout_state;
146
Thomas Woutersed03b412007-08-28 21:37:11 +0000147/* Wrap error strings with filename and line # */
148#define STRINGIFY1(x) #x
149#define STRINGIFY2(x) STRINGIFY1(x)
150#define ERRSTR1(x,y,z) (x ":" y ": " z)
151#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
152
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000153/* XXX It might be helpful to augment the error message generated
154 below with the name of the SSL function that generated the error.
155 I expect it's obvious most of the time.
156*/
157
158static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000159PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000161 PyObject *v;
162 char buf[2048];
163 char *errstr;
164 int err;
165 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000167 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000168
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000169 if (obj->ssl != NULL) {
170 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000171
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000172 switch (err) {
173 case SSL_ERROR_ZERO_RETURN:
174 errstr = "TLS/SSL connection has been closed";
175 p = PY_SSL_ERROR_ZERO_RETURN;
176 break;
177 case SSL_ERROR_WANT_READ:
178 errstr = "The operation did not complete (read)";
179 p = PY_SSL_ERROR_WANT_READ;
180 break;
181 case SSL_ERROR_WANT_WRITE:
182 p = PY_SSL_ERROR_WANT_WRITE;
183 errstr = "The operation did not complete (write)";
184 break;
185 case SSL_ERROR_WANT_X509_LOOKUP:
186 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitroua29b1812010-05-12 14:08:45 +0000187 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000188 break;
189 case SSL_ERROR_WANT_CONNECT:
190 p = PY_SSL_ERROR_WANT_CONNECT;
191 errstr = "The operation did not complete (connect)";
192 break;
193 case SSL_ERROR_SYSCALL:
194 {
195 unsigned long e = ERR_get_error();
196 if (e == 0) {
197 PySocketSockObject *s
198 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
199 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitroua29b1812010-05-12 14:08:45 +0000200 p = PY_SSL_ERROR_EOF;
201 errstr = "EOF occurred in violation of protocol";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000202 } else if (ret == -1) {
Antoine Pitroua29b1812010-05-12 14:08:45 +0000203 /* underlying BIO reported an I/O error */
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000204 Py_INCREF(s);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000205 ERR_clear_error();
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000206 v = s->errorhandler();
207 Py_DECREF(s);
208 return v;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000209 } else { /* possible? */
Antoine Pitroua29b1812010-05-12 14:08:45 +0000210 p = PY_SSL_ERROR_SYSCALL;
211 errstr = "Some I/O error occurred";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +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 Pitroua29b1812010-05-12 14:08:45 +0000228 errstr = "A failure in the SSL library occurred";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +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);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000240 ERR_clear_error();
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000241 v = Py_BuildValue("(is)", p, buf);
242 if (v != NULL) {
243 PyErr_SetObject(PySSLErrorObject, v);
244 Py_DECREF(v);
245 }
246 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000247}
248
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000249static PyObject *
250_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
251
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000252 char buf[2048];
253 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000254
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000255 if (errstr == NULL) {
256 errcode = ERR_peek_last_error();
257 errstr = ERR_error_string(errcode, NULL);
258 }
259 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000260 ERR_clear_error();
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000261 v = Py_BuildValue("(is)", errcode, buf);
262 if (v != NULL) {
263 PyErr_SetObject(PySSLErrorObject, v);
264 Py_DECREF(v);
265 }
266 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267}
268
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000269static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000270newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000271 enum py_ssl_server_or_client socket_type,
272 enum py_ssl_cert_requirements certreq,
273 enum py_ssl_version proto_version,
274 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000275{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000276 PySSLObject *self;
277 char *errstr = NULL;
278 int ret;
279 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000281 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
282 if (self == NULL)
283 return NULL;
284 self->peer_cert = NULL;
285 self->ssl = NULL;
286 self->ctx = NULL;
287 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000288
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000289 /* Make sure the SSL error state is initialized */
290 (void) ERR_get_state();
291 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000292
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000293 if ((key_file && !cert_file) || (!key_file && cert_file)) {
294 errstr = ERRSTR("Both the key & certificate files "
295 "must be specified");
296 goto fail;
297 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000298
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000299 if ((socket_type == PY_SSL_SERVER) &&
300 ((key_file == NULL) || (cert_file == NULL))) {
301 errstr = ERRSTR("Both the key & certificate files "
302 "must be specified for server-side operation");
303 goto fail;
304 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000305
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000306 PySSL_BEGIN_ALLOW_THREADS
307 if (proto_version == PY_SSL_VERSION_TLS1)
308 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
309 else if (proto_version == PY_SSL_VERSION_SSL3)
310 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
Victor Stinneree18b6f2011-05-10 00:38:00 +0200311#ifndef OPENSSL_NO_SSL2
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000312 else if (proto_version == PY_SSL_VERSION_SSL2)
313 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Victor Stinneree18b6f2011-05-10 00:38:00 +0200314#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000315 else if (proto_version == PY_SSL_VERSION_SSL23)
316 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
317 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000318
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000319 if (self->ctx == NULL) {
320 errstr = ERRSTR("Invalid SSL protocol variant specified.");
321 goto fail;
322 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000323
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000324 if (certreq != PY_SSL_CERT_NONE) {
325 if (cacerts_file == NULL) {
326 errstr = ERRSTR("No root certificates specified for "
Antoine Pitroua29b1812010-05-12 14:08:45 +0000327 "verification of other-side certificates.");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000328 goto fail;
329 } else {
330 PySSL_BEGIN_ALLOW_THREADS
331 ret = SSL_CTX_load_verify_locations(self->ctx,
332 cacerts_file,
333 NULL);
334 PySSL_END_ALLOW_THREADS
335 if (ret != 1) {
336 _setSSLError(NULL, 0, __FILE__, __LINE__);
337 goto fail;
338 }
339 }
340 }
341 if (key_file) {
342 PySSL_BEGIN_ALLOW_THREADS
343 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
344 SSL_FILETYPE_PEM);
345 PySSL_END_ALLOW_THREADS
346 if (ret != 1) {
347 _setSSLError(NULL, ret, __FILE__, __LINE__);
348 goto fail;
349 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000350
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000351 PySSL_BEGIN_ALLOW_THREADS
352 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
353 cert_file);
354 PySSL_END_ALLOW_THREADS
355 if (ret != 1) {
356 /*
357 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
358 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
359 */
360 if (ERR_peek_last_error() != 0) {
361 _setSSLError(NULL, ret, __FILE__, __LINE__);
362 goto fail;
363 }
364 }
365 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000366
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000367 /* ssl compatibility */
Antoine Pitrouf2bf8a62012-01-27 09:48:47 +0100368 SSL_CTX_set_options(self->ctx,
369 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000371 verification_mode = SSL_VERIFY_NONE;
372 if (certreq == PY_SSL_CERT_OPTIONAL)
373 verification_mode = SSL_VERIFY_PEER;
374 else if (certreq == PY_SSL_CERT_REQUIRED)
375 verification_mode = (SSL_VERIFY_PEER |
376 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
377 SSL_CTX_set_verify(self->ctx, verification_mode,
378 NULL); /* set verify lvl */
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000380 PySSL_BEGIN_ALLOW_THREADS
381 self->ssl = SSL_new(self->ctx); /* New ssl struct */
382 PySSL_END_ALLOW_THREADS
383 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000384#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000385 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000386#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000387
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000388 /* If the socket is in non-blocking mode or timeout mode, set the BIO
389 * to non-blocking mode (blocking is the default)
390 */
391 if (Sock->sock_timeout >= 0.0) {
392 /* Set both the read and write BIO's to non-blocking mode */
393 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
394 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
395 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000396
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000397 PySSL_BEGIN_ALLOW_THREADS
398 if (socket_type == PY_SSL_CLIENT)
399 SSL_set_connect_state(self->ssl);
400 else
401 SSL_set_accept_state(self->ssl);
402 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000403
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000404 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
405 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000407 if (errstr)
408 PyErr_SetString(PySSLErrorObject, errstr);
409 Py_DECREF(self);
410 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000411}
412
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000413static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000414PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000416 PySocketSockObject *Sock;
417 int server_side = 0;
418 int verification_mode = PY_SSL_CERT_NONE;
419 int protocol = PY_SSL_VERSION_SSL23;
420 char *key_file = NULL;
421 char *cert_file = NULL;
422 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000424 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
425 PySocketModule.Sock_Type,
426 &Sock,
427 &server_side,
428 &key_file, &cert_file,
429 &verification_mode, &protocol,
430 &cacerts_file))
431 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000432
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000433 /*
434 fprintf(stderr,
435 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
436 "protocol %d, certs %p\n",
437 server_side, key_file, cert_file, verification_mode,
438 protocol, cacerts_file);
439 */
Thomas Woutersed03b412007-08-28 21:37:11 +0000440
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000441 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
442 server_side, verification_mode,
443 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000444}
445
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000446PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000447"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
448" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000449
450/* SSL object methods */
451
Bill Janssen6e027db2007-11-15 22:23:56 +0000452static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000453{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000454 int ret;
455 int err;
456 int sockstate, nonblocking;
457 PySocketSockObject *sock
458 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitrouec146182010-04-24 21:30:20 +0000459
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000460 if (((PyObject*)sock) == Py_None) {
461 _setSSLError("Underlying socket connection gone",
462 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
463 return NULL;
464 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000465 Py_INCREF(sock);
Antoine Pitrouec146182010-04-24 21:30:20 +0000466
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000467 /* just in case the blocking state of the socket has been changed */
468 nonblocking = (sock->sock_timeout >= 0.0);
469 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
470 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000471
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000472 /* Actually negotiate SSL connection */
473 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
474 sockstate = 0;
475 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000476 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000477 ret = SSL_do_handshake(self->ssl);
478 err = SSL_get_error(self->ssl, ret);
479 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000480 if (PyErr_CheckSignals())
481 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000482 if (err == SSL_ERROR_WANT_READ) {
483 sockstate = check_socket_and_wait_for_timeout(sock, 0);
484 } else if (err == SSL_ERROR_WANT_WRITE) {
485 sockstate = check_socket_and_wait_for_timeout(sock, 1);
486 } else {
487 sockstate = SOCKET_OPERATION_OK;
488 }
489 if (sockstate == SOCKET_HAS_TIMED_OUT) {
490 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000491 ERRSTR("The handshake operation timed out"));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000492 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000493 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
494 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000495 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000496 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000497 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
498 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000499 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000500 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000501 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
502 break;
503 }
504 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000505 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000506 if (ret < 1)
507 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000508
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000509 if (self->peer_cert)
510 X509_free (self->peer_cert);
511 PySSL_BEGIN_ALLOW_THREADS
512 self->peer_cert = SSL_get_peer_certificate(self->ssl);
513 PySSL_END_ALLOW_THREADS
514
515 Py_INCREF(Py_None);
516 return Py_None;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000517
518error:
519 Py_DECREF(sock);
520 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000521}
522
Thomas Woutersed03b412007-08-28 21:37:11 +0000523static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000525
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000526 char namebuf[X509_NAME_MAXLEN];
527 int buflen;
528 PyObject *name_obj;
529 PyObject *value_obj;
530 PyObject *attr;
531 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000532
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000533 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
534 if (buflen < 0) {
535 _setSSLError(NULL, 0, __FILE__, __LINE__);
536 goto fail;
537 }
538 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
539 if (name_obj == NULL)
540 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000541
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000542 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
543 if (buflen < 0) {
544 _setSSLError(NULL, 0, __FILE__, __LINE__);
545 Py_DECREF(name_obj);
546 goto fail;
547 }
548 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000549 buflen, "strict");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000550 OPENSSL_free(valuebuf);
551 if (value_obj == NULL) {
552 Py_DECREF(name_obj);
553 goto fail;
554 }
555 attr = PyTuple_New(2);
556 if (attr == NULL) {
557 Py_DECREF(name_obj);
558 Py_DECREF(value_obj);
559 goto fail;
560 }
561 PyTuple_SET_ITEM(attr, 0, name_obj);
562 PyTuple_SET_ITEM(attr, 1, value_obj);
563 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000564
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000566 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000567}
568
569static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000571{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000572 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
573 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
574 PyObject *rdnt;
575 PyObject *attr = NULL; /* tuple to hold an attribute */
576 int entry_count = X509_NAME_entry_count(xname);
577 X509_NAME_ENTRY *entry;
578 ASN1_OBJECT *name;
579 ASN1_STRING *value;
580 int index_counter;
581 int rdn_level = -1;
582 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000584 dn = PyList_New(0);
585 if (dn == NULL)
586 return NULL;
587 /* now create another tuple to hold the top-level RDN */
588 rdn = PyList_New(0);
589 if (rdn == NULL)
590 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000592 for (index_counter = 0;
593 index_counter < entry_count;
594 index_counter++)
595 {
596 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000598 /* check to see if we've gotten to a new RDN */
599 if (rdn_level >= 0) {
600 if (rdn_level != entry->set) {
601 /* yes, new RDN */
602 /* add old RDN to DN */
603 rdnt = PyList_AsTuple(rdn);
604 Py_DECREF(rdn);
605 if (rdnt == NULL)
606 goto fail0;
607 retcode = PyList_Append(dn, rdnt);
608 Py_DECREF(rdnt);
609 if (retcode < 0)
610 goto fail0;
611 /* create new RDN */
612 rdn = PyList_New(0);
613 if (rdn == NULL)
614 goto fail0;
615 }
616 }
617 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000619 /* now add this attribute to the current RDN */
620 name = X509_NAME_ENTRY_get_object(entry);
621 value = X509_NAME_ENTRY_get_data(entry);
622 attr = _create_tuple_for_attribute(name, value);
623 /*
624 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
625 entry->set,
626 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
627 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
628 */
629 if (attr == NULL)
630 goto fail1;
631 retcode = PyList_Append(rdn, attr);
632 Py_DECREF(attr);
633 if (retcode < 0)
634 goto fail1;
635 }
636 /* now, there's typically a dangling RDN */
637 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
638 rdnt = PyList_AsTuple(rdn);
639 Py_DECREF(rdn);
640 if (rdnt == NULL)
641 goto fail0;
642 retcode = PyList_Append(dn, rdnt);
643 Py_DECREF(rdnt);
644 if (retcode < 0)
645 goto fail0;
646 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000648 /* convert list to tuple */
649 rdnt = PyList_AsTuple(dn);
650 Py_DECREF(dn);
651 if (rdnt == NULL)
652 return NULL;
653 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
655 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000656 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657
658 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000659 Py_XDECREF(dn);
660 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661}
662
663static PyObject *
664_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000665
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000666 /* this code follows the procedure outlined in
667 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
668 function to extract the STACK_OF(GENERAL_NAME),
669 then iterates through the stack to add the
670 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000672 int i, j;
673 PyObject *peer_alt_names = Py_None;
674 PyObject *v, *t;
675 X509_EXTENSION *ext = NULL;
676 GENERAL_NAMES *names = NULL;
677 GENERAL_NAME *name;
Benjamin Peterson31370952010-10-13 22:20:48 +0000678 const X509V3_EXT_METHOD *method;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000679 BIO *biobuf = NULL;
680 char buf[2048];
681 char *vptr;
682 int len;
683 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner117ff172010-03-02 22:49:30 +0000684#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000685 const unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000686#else
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000687 unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000688#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000690 if (certificate == NULL)
691 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000693 /* get a memory buffer */
694 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000696 i = 0;
697 while ((i = X509_get_ext_by_NID(
698 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000700 if (peer_alt_names == Py_None) {
701 peer_alt_names = PyList_New(0);
702 if (peer_alt_names == NULL)
703 goto fail;
704 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000705
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000706 /* now decode the altName */
707 ext = X509_get_ext(certificate, i);
708 if(!(method = X509V3_EXT_get(ext))) {
709 PyErr_SetString
710 (PySSLErrorObject,
711 ERRSTR("No method for internalizing subjectAltName!"));
712 goto fail;
713 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000715 p = ext->value->data;
716 if (method->it)
717 names = (GENERAL_NAMES*)
718 (ASN1_item_d2i(NULL,
719 &p,
720 ext->value->length,
721 ASN1_ITEM_ptr(method->it)));
722 else
723 names = (GENERAL_NAMES*)
724 (method->d2i(NULL,
725 &p,
726 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000727
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000728 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000730 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000732 name = sk_GENERAL_NAME_value(names, j);
733 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000735 /* we special-case DirName as a tuple of
736 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000738 t = PyTuple_New(2);
739 if (t == NULL) {
740 goto fail;
741 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000743 v = PyUnicode_FromString("DirName");
744 if (v == NULL) {
745 Py_DECREF(t);
746 goto fail;
747 }
748 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000750 v = _create_tuple_for_X509_NAME (name->d.dirn);
751 if (v == NULL) {
752 Py_DECREF(t);
753 goto fail;
754 }
755 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000756
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000757 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000759 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000761 (void) BIO_reset(biobuf);
762 GENERAL_NAME_print(biobuf, name);
763 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
764 if (len < 0) {
765 _setSSLError(NULL, 0, __FILE__, __LINE__);
766 goto fail;
767 }
768 vptr = strchr(buf, ':');
769 if (vptr == NULL)
770 goto fail;
771 t = PyTuple_New(2);
772 if (t == NULL)
773 goto fail;
774 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
775 if (v == NULL) {
776 Py_DECREF(t);
777 goto fail;
778 }
779 PyTuple_SET_ITEM(t, 0, v);
780 v = PyUnicode_FromStringAndSize((vptr + 1),
781 (len - (vptr - buf + 1)));
782 if (v == NULL) {
783 Py_DECREF(t);
784 goto fail;
785 }
786 PyTuple_SET_ITEM(t, 1, v);
787 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000789 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000791 if (PyList_Append(peer_alt_names, t) < 0) {
792 Py_DECREF(t);
793 goto fail;
794 }
795 Py_DECREF(t);
796 }
797 }
798 BIO_free(biobuf);
799 if (peer_alt_names != Py_None) {
800 v = PyList_AsTuple(peer_alt_names);
801 Py_DECREF(peer_alt_names);
802 return v;
803 } else {
804 return peer_alt_names;
805 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000806
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
808 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000809 if (biobuf != NULL)
810 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000812 if (peer_alt_names != Py_None) {
813 Py_XDECREF(peer_alt_names);
814 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000816 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817}
818
819static PyObject *
820_decode_certificate (X509 *certificate, int verbose) {
821
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000822 PyObject *retval = NULL;
823 BIO *biobuf = NULL;
824 PyObject *peer;
825 PyObject *peer_alt_names = NULL;
826 PyObject *issuer;
827 PyObject *version;
828 PyObject *sn_obj;
829 ASN1_INTEGER *serialNumber;
830 char buf[2048];
831 int len;
832 ASN1_TIME *notBefore, *notAfter;
833 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000834
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000835 retval = PyDict_New();
836 if (retval == NULL)
837 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000838
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000839 peer = _create_tuple_for_X509_NAME(
840 X509_get_subject_name(certificate));
841 if (peer == NULL)
842 goto fail0;
843 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
844 Py_DECREF(peer);
845 goto fail0;
846 }
847 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000848
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000849 if (verbose) {
850 issuer = _create_tuple_for_X509_NAME(
851 X509_get_issuer_name(certificate));
852 if (issuer == NULL)
853 goto fail0;
854 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
855 Py_DECREF(issuer);
856 goto fail0;
857 }
858 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000859
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000860 version = PyLong_FromLong(X509_get_version(certificate) + 1);
861 if (PyDict_SetItemString(retval, "version", version) < 0) {
862 Py_DECREF(version);
863 goto fail0;
864 }
865 Py_DECREF(version);
866 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000867
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000868 /* get a memory buffer */
869 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000870
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000871 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000872
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000873 (void) BIO_reset(biobuf);
874 serialNumber = X509_get_serialNumber(certificate);
875 /* should not exceed 20 octets, 160 bits, so buf is big enough */
876 i2a_ASN1_INTEGER(biobuf, serialNumber);
877 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
878 if (len < 0) {
879 _setSSLError(NULL, 0, __FILE__, __LINE__);
880 goto fail1;
881 }
882 sn_obj = PyUnicode_FromStringAndSize(buf, len);
883 if (sn_obj == NULL)
884 goto fail1;
885 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
886 Py_DECREF(sn_obj);
887 goto fail1;
888 }
889 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000891 (void) BIO_reset(biobuf);
892 notBefore = X509_get_notBefore(certificate);
893 ASN1_TIME_print(biobuf, notBefore);
894 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
895 if (len < 0) {
896 _setSSLError(NULL, 0, __FILE__, __LINE__);
897 goto fail1;
898 }
899 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
900 if (pnotBefore == NULL)
901 goto fail1;
902 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
903 Py_DECREF(pnotBefore);
904 goto fail1;
905 }
906 Py_DECREF(pnotBefore);
907 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000908
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000909 (void) BIO_reset(biobuf);
910 notAfter = X509_get_notAfter(certificate);
911 ASN1_TIME_print(biobuf, notAfter);
912 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
913 if (len < 0) {
914 _setSSLError(NULL, 0, __FILE__, __LINE__);
915 goto fail1;
916 }
917 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
918 if (pnotAfter == NULL)
919 goto fail1;
920 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
921 Py_DECREF(pnotAfter);
922 goto fail1;
923 }
924 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000926 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000928 peer_alt_names = _get_peer_alt_names(certificate);
929 if (peer_alt_names == NULL)
930 goto fail1;
931 else if (peer_alt_names != Py_None) {
932 if (PyDict_SetItemString(retval, "subjectAltName",
933 peer_alt_names) < 0) {
934 Py_DECREF(peer_alt_names);
935 goto fail1;
936 }
937 Py_DECREF(peer_alt_names);
938 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000939
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000940 BIO_free(biobuf);
941 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000942
943 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000944 if (biobuf != NULL)
945 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000946 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000947 Py_XDECREF(retval);
948 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000949}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000950
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
952static PyObject *
953PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
954
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000955 PyObject *retval = NULL;
956 char *filename = NULL;
957 X509 *x=NULL;
958 BIO *cert;
959 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000961 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
962 &filename, &verbose))
963 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000965 if ((cert=BIO_new(BIO_s_file())) == NULL) {
966 PyErr_SetString(PySSLErrorObject,
967 "Can't malloc memory to read file");
968 goto fail0;
969 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000971 if (BIO_read_filename(cert,filename) <= 0) {
972 PyErr_SetString(PySSLErrorObject,
973 "Can't open file");
974 goto fail0;
975 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000977 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
978 if (x == NULL) {
979 PyErr_SetString(PySSLErrorObject,
980 "Error decoding PEM-encoded file");
981 goto fail0;
982 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000984 retval = _decode_certificate(x, verbose);
Mark Dickinson732cc9b2010-08-03 18:33:11 +0000985 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986
987 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000988
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000989 if (cert != NULL) BIO_free(cert);
990 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000991}
992
993
994static PyObject *
995PySSL_peercert(PySSLObject *self, PyObject *args)
996{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000997 PyObject *retval = NULL;
998 int len;
999 int verification;
1000 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001002 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1003 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001005 if (!self->peer_cert)
1006 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001008 if (PyObject_IsTrue(binary_mode)) {
1009 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001010
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001011 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001013 bytes_buf = NULL;
1014 len = i2d_X509(self->peer_cert, &bytes_buf);
1015 if (len < 0) {
1016 PySSL_SetError(self, len, __FILE__, __LINE__);
1017 return NULL;
1018 }
1019 /* this is actually an immutable bytes sequence */
1020 retval = PyBytes_FromStringAndSize
1021 ((const char *) bytes_buf, len);
1022 OPENSSL_free(bytes_buf);
1023 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001025 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001027 verification = SSL_CTX_get_verify_mode(self->ctx);
1028 if ((verification & SSL_VERIFY_PEER) == 0)
1029 return PyDict_New();
1030 else
1031 return _decode_certificate (self->peer_cert, 0);
1032 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001033}
1034
1035PyDoc_STRVAR(PySSL_peercert_doc,
1036"peer_certificate([der=False]) -> certificate\n\
1037\n\
1038Returns the certificate for the peer. If no certificate was provided,\n\
1039returns None. If a certificate was provided, but not validated, returns\n\
1040an empty dictionary. Otherwise returns a dict containing information\n\
1041about the peer certificate.\n\
1042\n\
1043If the optional argument is True, returns a DER-encoded copy of the\n\
1044peer certificate, or None if no certificate was provided. This will\n\
1045return the certificate even if it wasn't validated.");
1046
1047static PyObject *PySSL_cipher (PySSLObject *self) {
1048
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001049 PyObject *retval, *v;
Benjamin Peterson31370952010-10-13 22:20:48 +00001050 const SSL_CIPHER *current;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001051 char *cipher_name;
1052 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001054 if (self->ssl == NULL)
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001055 Py_RETURN_NONE;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001056 current = SSL_get_current_cipher(self->ssl);
1057 if (current == NULL)
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001058 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001060 retval = PyTuple_New(3);
1061 if (retval == NULL)
1062 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001064 cipher_name = (char *) SSL_CIPHER_get_name(current);
1065 if (cipher_name == NULL) {
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001066 Py_INCREF(Py_None);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001067 PyTuple_SET_ITEM(retval, 0, Py_None);
1068 } else {
1069 v = PyUnicode_FromString(cipher_name);
1070 if (v == NULL)
1071 goto fail0;
1072 PyTuple_SET_ITEM(retval, 0, v);
1073 }
1074 cipher_protocol = SSL_CIPHER_get_version(current);
1075 if (cipher_protocol == NULL) {
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001076 Py_INCREF(Py_None);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001077 PyTuple_SET_ITEM(retval, 1, Py_None);
1078 } else {
1079 v = PyUnicode_FromString(cipher_protocol);
1080 if (v == NULL)
1081 goto fail0;
1082 PyTuple_SET_ITEM(retval, 1, v);
1083 }
1084 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1085 if (v == NULL)
1086 goto fail0;
1087 PyTuple_SET_ITEM(retval, 2, v);
1088 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001089
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001091 Py_DECREF(retval);
1092 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093}
1094
Guido van Rossume6650f92007-12-06 19:05:55 +00001095static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001096{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001097 if (self->peer_cert) /* Possible not to have one? */
1098 X509_free (self->peer_cert);
1099 if (self->ssl)
1100 SSL_free(self->ssl);
1101 if (self->ctx)
1102 SSL_CTX_free(self->ctx);
1103 Py_XDECREF(self->Socket);
1104 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001105}
1106
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001107/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001108 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001109 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001110 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001111
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001112static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001113check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001114{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001115 fd_set fds;
1116 struct timeval tv;
1117 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001118
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001119 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1120 if (s->sock_timeout < 0.0)
1121 return SOCKET_IS_BLOCKING;
1122 else if (s->sock_timeout == 0.0)
1123 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001124
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001125 /* Guard against closed socket */
1126 if (s->sock_fd < 0)
1127 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001128
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001129 /* Prefer poll, if available, since you can poll() any fd
1130 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001131#ifdef HAVE_POLL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001132 {
1133 struct pollfd pollfd;
1134 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001135
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001136 pollfd.fd = s->sock_fd;
1137 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001139 /* s->sock_timeout is in seconds, timeout in ms */
1140 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1141 PySSL_BEGIN_ALLOW_THREADS
1142 rc = poll(&pollfd, 1, timeout);
1143 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001144
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001145 goto normal_return;
1146 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001147#endif
1148
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001149 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001150#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001151 if (s->sock_fd >= FD_SETSIZE)
1152 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001153#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001154
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001155 /* Construct the arguments to select */
1156 tv.tv_sec = (int)s->sock_timeout;
1157 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1158 FD_ZERO(&fds);
1159 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001160
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001161 /* See if the socket is ready */
1162 PySSL_BEGIN_ALLOW_THREADS
1163 if (writing)
1164 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1165 else
1166 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1167 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001168
Bill Janssen6e027db2007-11-15 22:23:56 +00001169#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001170normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001171#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001172 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1173 (when we are able to write or when there's something to read) */
1174 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001175}
1176
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001177static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1178{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001179 char *data;
1180 int len;
1181 int count;
1182 int sockstate;
1183 int err;
1184 int nonblocking;
1185 PySocketSockObject *sock
1186 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001187
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001188 if (((PyObject*)sock) == Py_None) {
1189 _setSSLError("Underlying socket connection gone",
1190 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1191 return NULL;
1192 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001193 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001194
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001195 if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) {
1196 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001197 return NULL;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001198 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001199
1200 /* just in case the blocking state of the socket has been changed */
1201 nonblocking = (sock->sock_timeout >= 0.0);
1202 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1203 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1204
1205 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1206 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1207 PyErr_SetString(PySSLErrorObject,
1208 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001209 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001210 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1211 PyErr_SetString(PySSLErrorObject,
1212 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001213 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001214 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1215 PyErr_SetString(PySSLErrorObject,
1216 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001217 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001218 }
1219 do {
1220 err = 0;
1221 PySSL_BEGIN_ALLOW_THREADS
1222 len = SSL_write(self->ssl, data, count);
1223 err = SSL_get_error(self->ssl, len);
1224 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001225 if (PyErr_CheckSignals())
1226 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001227 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001228 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001229 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001230 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001231 } else {
1232 sockstate = SOCKET_OPERATION_OK;
1233 }
1234 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1235 PyErr_SetString(PySSLErrorObject,
1236 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001237 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001238 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1239 PyErr_SetString(PySSLErrorObject,
1240 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001241 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001242 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1243 break;
1244 }
1245 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001246
1247 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001248 if (len > 0)
1249 return PyLong_FromLong(len);
1250 else
1251 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001252
1253error:
1254 Py_DECREF(sock);
1255 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001256}
1257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001258PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001259"write(s) -> len\n\
1260\n\
1261Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001262of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001263
Bill Janssen6e027db2007-11-15 22:23:56 +00001264static PyObject *PySSL_SSLpending(PySSLObject *self)
1265{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001266 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001267
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001268 PySSL_BEGIN_ALLOW_THREADS
1269 count = SSL_pending(self->ssl);
1270 PySSL_END_ALLOW_THREADS
1271 if (count < 0)
1272 return PySSL_SetError(self, count, __FILE__, __LINE__);
1273 else
1274 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001275}
1276
1277PyDoc_STRVAR(PySSL_SSLpending_doc,
1278"pending() -> count\n\
1279\n\
1280Returns the number of already decrypted bytes available for read,\n\
1281pending on the connection.\n");
1282
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001283static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1284{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001285 PyObject *dest = NULL;
1286 Py_buffer buf;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001287 char *mem;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001288 int len, count;
1289 int buf_passed = 0;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001290 int sockstate;
1291 int err;
1292 int nonblocking;
1293 PySocketSockObject *sock
1294 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001295
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001296 if (((PyObject*)sock) == Py_None) {
1297 _setSSLError("Underlying socket connection gone",
1298 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1299 return NULL;
1300 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001301 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001302
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001303 buf.obj = NULL;
1304 buf.buf = NULL;
1305 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001306 goto error;
1307
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001308 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1309 dest = PyBytes_FromStringAndSize(NULL, len);
1310 if (dest == NULL)
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001311 goto error;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001312 mem = PyBytes_AS_STRING(dest);
1313 }
1314 else {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001315 buf_passed = 1;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001316 mem = buf.buf;
1317 if (len <= 0 || len > buf.len) {
1318 len = (int) buf.len;
1319 if (buf.len != len) {
1320 PyErr_SetString(PyExc_OverflowError,
1321 "maximum length can't fit in a C 'int'");
1322 goto error;
1323 }
1324 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001325 }
1326
1327 /* just in case the blocking state of the socket has been changed */
1328 nonblocking = (sock->sock_timeout >= 0.0);
1329 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1330 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1331
1332 /* first check if there are bytes ready to be read */
1333 PySSL_BEGIN_ALLOW_THREADS
1334 count = SSL_pending(self->ssl);
1335 PySSL_END_ALLOW_THREADS
1336
1337 if (!count) {
1338 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1339 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1340 PyErr_SetString(PySSLErrorObject,
1341 "The read operation timed out");
1342 goto error;
1343 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1344 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +00001345 "Underlying socket too large for select().");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001346 goto error;
1347 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1348 count = 0;
1349 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001350 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001351 }
1352 do {
1353 err = 0;
1354 PySSL_BEGIN_ALLOW_THREADS
1355 count = SSL_read(self->ssl, mem, len);
1356 err = SSL_get_error(self->ssl, count);
1357 PySSL_END_ALLOW_THREADS
1358 if (PyErr_CheckSignals())
1359 goto error;
1360 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001361 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001362 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001363 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001364 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1365 (SSL_get_shutdown(self->ssl) ==
1366 SSL_RECEIVED_SHUTDOWN))
1367 {
1368 count = 0;
1369 goto done;
1370 } else {
1371 sockstate = SOCKET_OPERATION_OK;
1372 }
1373 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1374 PyErr_SetString(PySSLErrorObject,
1375 "The read operation timed out");
1376 goto error;
1377 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1378 break;
1379 }
1380 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1381 if (count <= 0) {
1382 PySSL_SetError(self, count, __FILE__, __LINE__);
1383 goto error;
1384 }
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001385
1386done:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001387 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001388 if (!buf_passed) {
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001389 _PyBytes_Resize(&dest, count);
1390 return dest;
1391 }
1392 else {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001393 PyBuffer_Release(&buf);
1394 return PyLong_FromLong(count);
1395 }
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001396
1397error:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001398 Py_DECREF(sock);
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001399 if (!buf_passed)
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001400 Py_XDECREF(dest);
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001401 else
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001402 PyBuffer_Release(&buf);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001403 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001404}
1405
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001406PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001407"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001408\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001409Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001410
Bill Janssen40a0f662008-08-12 16:56:25 +00001411static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1412{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001413 int err, ssl_err, sockstate, nonblocking;
1414 int zeros = 0;
1415 PySocketSockObject *sock
1416 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001417
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001418 /* Guard against closed socket */
1419 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1420 _setSSLError("Underlying socket connection gone",
1421 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1422 return NULL;
1423 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001424 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001425
1426 /* Just in case the blocking state of the socket has been changed */
1427 nonblocking = (sock->sock_timeout >= 0.0);
1428 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1429 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1430
1431 while (1) {
1432 PySSL_BEGIN_ALLOW_THREADS
1433 /* Disable read-ahead so that unwrap can work correctly.
1434 * Otherwise OpenSSL might read in too much data,
1435 * eating clear text data that happens to be
1436 * transmitted after the SSL shutdown.
1437 * Should be safe to call repeatedly everytime this
1438 * function is used and the shutdown_seen_zero != 0
1439 * condition is met.
1440 */
1441 if (self->shutdown_seen_zero)
1442 SSL_set_read_ahead(self->ssl, 0);
1443 err = SSL_shutdown(self->ssl);
1444 PySSL_END_ALLOW_THREADS
1445 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1446 if (err > 0)
1447 break;
1448 if (err == 0) {
1449 /* Don't loop endlessly; instead preserve legacy
1450 behaviour of trying SSL_shutdown() only twice.
1451 This looks necessary for OpenSSL < 0.9.8m */
1452 if (++zeros > 1)
1453 break;
1454 /* Shutdown was sent, now try receiving */
1455 self->shutdown_seen_zero = 1;
1456 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001457 }
1458
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001459 /* Possibly retry shutdown until timeout or failure */
1460 ssl_err = SSL_get_error(self->ssl, err);
1461 if (ssl_err == SSL_ERROR_WANT_READ)
1462 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1463 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1464 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1465 else
1466 break;
1467 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1468 if (ssl_err == SSL_ERROR_WANT_READ)
1469 PyErr_SetString(PySSLErrorObject,
1470 "The read operation timed out");
1471 else
1472 PyErr_SetString(PySSLErrorObject,
1473 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001474 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001475 }
1476 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1477 PyErr_SetString(PySSLErrorObject,
1478 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001479 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001480 }
1481 else if (sockstate != SOCKET_OPERATION_OK)
1482 /* Retain the SSL error code */
1483 break;
1484 }
Antoine Pitrou5a1c4d12010-04-23 21:11:10 +00001485
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001486 if (err < 0) {
1487 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001488 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001489 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001490 else
1491 /* It's already INCREF'ed */
1492 return (PyObject *) sock;
1493
1494error:
1495 Py_DECREF(sock);
1496 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001497}
1498
1499PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1500"shutdown(s) -> socket\n\
1501\n\
1502Does the SSL shutdown handshake with the remote end, and returns\n\
1503the underlying socket object.");
1504
1505
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001506static PyMethodDef PySSLMethods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001507 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1508 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1509 PySSL_SSLwrite_doc},
1510 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1511 PySSL_SSLread_doc},
1512 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1513 PySSL_SSLpending_doc},
1514 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1515 PySSL_peercert_doc},
1516 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1517 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1518 PySSL_SSLshutdown_doc},
1519 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001520};
1521
Jeremy Hylton938ace62002-07-17 16:30:39 +00001522static PyTypeObject PySSL_Type = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001523 PyVarObject_HEAD_INIT(NULL, 0)
1524 "ssl.SSLContext", /*tp_name*/
1525 sizeof(PySSLObject), /*tp_basicsize*/
1526 0, /*tp_itemsize*/
1527 /* methods */
1528 (destructor)PySSL_dealloc, /*tp_dealloc*/
1529 0, /*tp_print*/
1530 0, /*tp_getattr*/
1531 0, /*tp_setattr*/
1532 0, /*tp_reserved*/
1533 0, /*tp_repr*/
1534 0, /*tp_as_number*/
1535 0, /*tp_as_sequence*/
1536 0, /*tp_as_mapping*/
1537 0, /*tp_hash*/
1538 0, /*tp_call*/
1539 0, /*tp_str*/
1540 0, /*tp_getattro*/
1541 0, /*tp_setattro*/
1542 0, /*tp_as_buffer*/
1543 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1544 0, /*tp_doc*/
1545 0, /*tp_traverse*/
1546 0, /*tp_clear*/
1547 0, /*tp_richcompare*/
1548 0, /*tp_weaklistoffset*/
1549 0, /*tp_iter*/
1550 0, /*tp_iternext*/
1551 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001552};
1553
1554#ifdef HAVE_OPENSSL_RAND
1555
1556/* helper routines for seeding the SSL PRNG */
1557static PyObject *
1558PySSL_RAND_add(PyObject *self, PyObject *args)
1559{
1560 char *buf;
1561 int len;
1562 double entropy;
1563
1564 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001565 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001566 RAND_add(buf, len, entropy);
1567 Py_INCREF(Py_None);
1568 return Py_None;
1569}
1570
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001571PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001572"RAND_add(string, entropy)\n\
1573\n\
1574Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001576
1577static PyObject *
1578PySSL_RAND_status(PyObject *self)
1579{
Christian Heimes217cfd12007-12-02 14:31:20 +00001580 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001581}
1582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001583PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001584"RAND_status() -> 0 or 1\n\
1585\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001586Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1587It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1588using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001589
1590static PyObject *
1591PySSL_RAND_egd(PyObject *self, PyObject *arg)
1592{
1593 int bytes;
1594
Bill Janssen6e027db2007-11-15 22:23:56 +00001595 if (!PyUnicode_Check(arg))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001596 return PyErr_Format(PyExc_TypeError,
1597 "RAND_egd() expected string, found %s",
1598 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001599 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001600 if (bytes == -1) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001601 PyErr_SetString(PySSLErrorObject,
1602 "EGD connection failed or EGD did not return "
1603 "enough data to seed the PRNG");
1604 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001605 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001606 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001607}
1608
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001609PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001610"RAND_egd(path) -> bytes\n\
1611\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001612Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1613Returns number of bytes read. Raises SSLError if connection to EGD\n\
1614fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001615
1616#endif
1617
Bill Janssen40a0f662008-08-12 16:56:25 +00001618
1619
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620/* List of functions exported by this module. */
1621
1622static PyMethodDef PySSL_methods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001623 {"sslwrap", PySSL_sslwrap,
1624 METH_VARARGS, ssl_doc},
1625 {"_test_decode_cert", PySSL_test_decode_certificate,
1626 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001627#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001628 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1629 PySSL_RAND_add_doc},
1630 {"RAND_egd", PySSL_RAND_egd, METH_O,
1631 PySSL_RAND_egd_doc},
1632 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1633 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001634#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001635 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001636};
1637
1638
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639#ifdef WITH_THREAD
1640
1641/* an implementation of OpenSSL threading operations in terms
1642 of the Python C thread library */
1643
1644static PyThread_type_lock *_ssl_locks = NULL;
1645
1646static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001647 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648}
1649
Bill Janssen6e027db2007-11-15 22:23:56 +00001650static void _ssl_thread_locking_function
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001651 (int mode, int n, const char *file, int line) {
1652 /* this function is needed to perform locking on shared data
1653 structures. (Note that OpenSSL uses a number of global data
1654 structures that will be implicitly shared whenever multiple
1655 threads use OpenSSL.) Multi-threaded applications will
1656 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001658 locking_function() must be able to handle up to
1659 CRYPTO_num_locks() different mutex locks. It sets the n-th
1660 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001662 file and line are the file number of the function setting the
1663 lock. They can be useful for debugging.
1664 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001666 if ((_ssl_locks == NULL) ||
1667 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1668 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001670 if (mode & CRYPTO_LOCK) {
1671 PyThread_acquire_lock(_ssl_locks[n], 1);
1672 } else {
1673 PyThread_release_lock(_ssl_locks[n]);
1674 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001675}
1676
1677static int _setup_ssl_threads(void) {
1678
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001679 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001680
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001681 if (_ssl_locks == NULL) {
1682 _ssl_locks_count = CRYPTO_num_locks();
1683 _ssl_locks = (PyThread_type_lock *)
1684 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1685 if (_ssl_locks == NULL)
1686 return 0;
1687 memset(_ssl_locks, 0,
1688 sizeof(PyThread_type_lock) * _ssl_locks_count);
1689 for (i = 0; i < _ssl_locks_count; i++) {
1690 _ssl_locks[i] = PyThread_allocate_lock();
1691 if (_ssl_locks[i] == NULL) {
1692 unsigned int j;
1693 for (j = 0; j < i; j++) {
1694 PyThread_free_lock(_ssl_locks[j]);
1695 }
1696 free(_ssl_locks);
1697 return 0;
1698 }
1699 }
1700 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1701 CRYPTO_set_id_callback(_ssl_thread_id_function);
1702 }
1703 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001704}
1705
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001706#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001708PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001709"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001710for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001711
Martin v. Löwis1a214512008-06-11 05:26:20 +00001712
1713static struct PyModuleDef _sslmodule = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001714 PyModuleDef_HEAD_INIT,
1715 "_ssl",
1716 module_doc,
1717 -1,
1718 PySSL_methods,
1719 NULL,
1720 NULL,
1721 NULL,
1722 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001723};
1724
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001725PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001726PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001727{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001728 PyObject *m, *d;
1729 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001730
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001731 if (PyType_Ready(&PySSL_Type) < 0)
1732 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001733
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001734 m = PyModule_Create(&_sslmodule);
1735 if (m == NULL)
1736 return NULL;
1737 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001738
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001739 /* Load _socket module and its C API */
1740 socket_api = PySocketModule_ImportModuleAndAPI();
1741 if (!socket_api)
1742 return NULL;
1743 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001744
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001745 /* Init OpenSSL */
1746 SSL_load_error_strings();
1747 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748#ifdef WITH_THREAD
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001749 /* note that this will start threading if not already started */
1750 if (!_setup_ssl_threads()) {
1751 return NULL;
1752 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001753#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001754 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001755
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001756 /* Add symbols to module dict */
1757 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1758 PySocketModule.error,
1759 NULL);
1760 if (PySSLErrorObject == NULL)
1761 return NULL;
1762 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1763 return NULL;
1764 if (PyDict_SetItemString(d, "SSLType",
1765 (PyObject *)&PySSL_Type) != 0)
1766 return NULL;
1767 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1768 PY_SSL_ERROR_ZERO_RETURN);
1769 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1770 PY_SSL_ERROR_WANT_READ);
1771 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1772 PY_SSL_ERROR_WANT_WRITE);
1773 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1774 PY_SSL_ERROR_WANT_X509_LOOKUP);
1775 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1776 PY_SSL_ERROR_SYSCALL);
1777 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1778 PY_SSL_ERROR_SSL);
1779 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1780 PY_SSL_ERROR_WANT_CONNECT);
1781 /* non ssl.h errorcodes */
1782 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1783 PY_SSL_ERROR_EOF);
1784 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1785 PY_SSL_ERROR_INVALID_ERROR_CODE);
1786 /* cert requirements */
1787 PyModule_AddIntConstant(m, "CERT_NONE",
1788 PY_SSL_CERT_NONE);
1789 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1790 PY_SSL_CERT_OPTIONAL);
1791 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1792 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001793
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001794 /* protocol versions */
Victor Stinneree18b6f2011-05-10 00:38:00 +02001795#ifndef OPENSSL_NO_SSL2
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001796 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1797 PY_SSL_VERSION_SSL2);
Victor Stinneree18b6f2011-05-10 00:38:00 +02001798#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001799 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1800 PY_SSL_VERSION_SSL3);
1801 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1802 PY_SSL_VERSION_SSL23);
1803 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1804 PY_SSL_VERSION_TLS1);
1805 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001806}