blob: 8ebdc9b99db2f98a1a6ea346b47a5001ca3c5307 [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 */
368 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000369
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000370 verification_mode = SSL_VERIFY_NONE;
371 if (certreq == PY_SSL_CERT_OPTIONAL)
372 verification_mode = SSL_VERIFY_PEER;
373 else if (certreq == PY_SSL_CERT_REQUIRED)
374 verification_mode = (SSL_VERIFY_PEER |
375 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
376 SSL_CTX_set_verify(self->ctx, verification_mode,
377 NULL); /* set verify lvl */
Thomas Woutersed03b412007-08-28 21:37:11 +0000378
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000379 PySSL_BEGIN_ALLOW_THREADS
380 self->ssl = SSL_new(self->ctx); /* New ssl struct */
381 PySSL_END_ALLOW_THREADS
382 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000383#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000384 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000385#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000386
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000387 /* If the socket is in non-blocking mode or timeout mode, set the BIO
388 * to non-blocking mode (blocking is the default)
389 */
390 if (Sock->sock_timeout >= 0.0) {
391 /* Set both the read and write BIO's to non-blocking mode */
392 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
393 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
394 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000395
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000396 PySSL_BEGIN_ALLOW_THREADS
397 if (socket_type == PY_SSL_CLIENT)
398 SSL_set_connect_state(self->ssl);
399 else
400 SSL_set_accept_state(self->ssl);
401 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000402
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000403 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
404 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000406 if (errstr)
407 PyErr_SetString(PySSLErrorObject, errstr);
408 Py_DECREF(self);
409 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410}
411
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000412static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000413PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000414{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000415 PySocketSockObject *Sock;
416 int server_side = 0;
417 int verification_mode = PY_SSL_CERT_NONE;
418 int protocol = PY_SSL_VERSION_SSL23;
419 char *key_file = NULL;
420 char *cert_file = NULL;
421 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000422
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000423 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
424 PySocketModule.Sock_Type,
425 &Sock,
426 &server_side,
427 &key_file, &cert_file,
428 &verification_mode, &protocol,
429 &cacerts_file))
430 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000431
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000432 /*
433 fprintf(stderr,
434 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
435 "protocol %d, certs %p\n",
436 server_side, key_file, cert_file, verification_mode,
437 protocol, cacerts_file);
438 */
Thomas Woutersed03b412007-08-28 21:37:11 +0000439
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000440 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
441 server_side, verification_mode,
442 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443}
444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000445PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000446"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
447" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448
449/* SSL object methods */
450
Bill Janssen6e027db2007-11-15 22:23:56 +0000451static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000453 int ret;
454 int err;
455 int sockstate, nonblocking;
456 PySocketSockObject *sock
457 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitrouec146182010-04-24 21:30:20 +0000458
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000459 if (((PyObject*)sock) == Py_None) {
460 _setSSLError("Underlying socket connection gone",
461 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
462 return NULL;
463 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000464 Py_INCREF(sock);
Antoine Pitrouec146182010-04-24 21:30:20 +0000465
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000466 /* just in case the blocking state of the socket has been changed */
467 nonblocking = (sock->sock_timeout >= 0.0);
468 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
469 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000470
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000471 /* Actually negotiate SSL connection */
472 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
473 sockstate = 0;
474 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000475 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000476 ret = SSL_do_handshake(self->ssl);
477 err = SSL_get_error(self->ssl, ret);
478 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000479 if (PyErr_CheckSignals())
480 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000481 if (err == SSL_ERROR_WANT_READ) {
482 sockstate = check_socket_and_wait_for_timeout(sock, 0);
483 } else if (err == SSL_ERROR_WANT_WRITE) {
484 sockstate = check_socket_and_wait_for_timeout(sock, 1);
485 } else {
486 sockstate = SOCKET_OPERATION_OK;
487 }
488 if (sockstate == SOCKET_HAS_TIMED_OUT) {
489 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000490 ERRSTR("The handshake operation timed out"));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000491 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000492 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
493 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000494 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000495 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000496 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
497 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000498 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000499 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000500 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
501 break;
502 }
503 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000504 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000505 if (ret < 1)
506 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000507
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000508 if (self->peer_cert)
509 X509_free (self->peer_cert);
510 PySSL_BEGIN_ALLOW_THREADS
511 self->peer_cert = SSL_get_peer_certificate(self->ssl);
512 PySSL_END_ALLOW_THREADS
513
514 Py_INCREF(Py_None);
515 return Py_None;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000516
517error:
518 Py_DECREF(sock);
519 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000520}
521
Thomas Woutersed03b412007-08-28 21:37:11 +0000522static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000524
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000525 char namebuf[X509_NAME_MAXLEN];
526 int buflen;
527 PyObject *name_obj;
528 PyObject *value_obj;
529 PyObject *attr;
530 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000532 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
533 if (buflen < 0) {
534 _setSSLError(NULL, 0, __FILE__, __LINE__);
535 goto fail;
536 }
537 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
538 if (name_obj == NULL)
539 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000540
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000541 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
542 if (buflen < 0) {
543 _setSSLError(NULL, 0, __FILE__, __LINE__);
544 Py_DECREF(name_obj);
545 goto fail;
546 }
547 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000548 buflen, "strict");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000549 OPENSSL_free(valuebuf);
550 if (value_obj == NULL) {
551 Py_DECREF(name_obj);
552 goto fail;
553 }
554 attr = PyTuple_New(2);
555 if (attr == NULL) {
556 Py_DECREF(name_obj);
557 Py_DECREF(value_obj);
558 goto fail;
559 }
560 PyTuple_SET_ITEM(attr, 0, name_obj);
561 PyTuple_SET_ITEM(attr, 1, value_obj);
562 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000563
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000565 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000566}
567
568static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000570{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000571 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
572 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
573 PyObject *rdnt;
574 PyObject *attr = NULL; /* tuple to hold an attribute */
575 int entry_count = X509_NAME_entry_count(xname);
576 X509_NAME_ENTRY *entry;
577 ASN1_OBJECT *name;
578 ASN1_STRING *value;
579 int index_counter;
580 int rdn_level = -1;
581 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000583 dn = PyList_New(0);
584 if (dn == NULL)
585 return NULL;
586 /* now create another tuple to hold the top-level RDN */
587 rdn = PyList_New(0);
588 if (rdn == NULL)
589 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000591 for (index_counter = 0;
592 index_counter < entry_count;
593 index_counter++)
594 {
595 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000597 /* check to see if we've gotten to a new RDN */
598 if (rdn_level >= 0) {
599 if (rdn_level != entry->set) {
600 /* yes, new RDN */
601 /* add old RDN to DN */
602 rdnt = PyList_AsTuple(rdn);
603 Py_DECREF(rdn);
604 if (rdnt == NULL)
605 goto fail0;
606 retcode = PyList_Append(dn, rdnt);
607 Py_DECREF(rdnt);
608 if (retcode < 0)
609 goto fail0;
610 /* create new RDN */
611 rdn = PyList_New(0);
612 if (rdn == NULL)
613 goto fail0;
614 }
615 }
616 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000618 /* now add this attribute to the current RDN */
619 name = X509_NAME_ENTRY_get_object(entry);
620 value = X509_NAME_ENTRY_get_data(entry);
621 attr = _create_tuple_for_attribute(name, value);
622 /*
623 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
624 entry->set,
625 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
626 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
627 */
628 if (attr == NULL)
629 goto fail1;
630 retcode = PyList_Append(rdn, attr);
631 Py_DECREF(attr);
632 if (retcode < 0)
633 goto fail1;
634 }
635 /* now, there's typically a dangling RDN */
636 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
637 rdnt = PyList_AsTuple(rdn);
638 Py_DECREF(rdn);
639 if (rdnt == NULL)
640 goto fail0;
641 retcode = PyList_Append(dn, rdnt);
642 Py_DECREF(rdnt);
643 if (retcode < 0)
644 goto fail0;
645 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000647 /* convert list to tuple */
648 rdnt = PyList_AsTuple(dn);
649 Py_DECREF(dn);
650 if (rdnt == NULL)
651 return NULL;
652 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
654 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000655 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
657 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000658 Py_XDECREF(dn);
659 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660}
661
662static PyObject *
663_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000664
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000665 /* this code follows the procedure outlined in
666 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
667 function to extract the STACK_OF(GENERAL_NAME),
668 then iterates through the stack to add the
669 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000671 int i, j;
672 PyObject *peer_alt_names = Py_None;
673 PyObject *v, *t;
674 X509_EXTENSION *ext = NULL;
675 GENERAL_NAMES *names = NULL;
676 GENERAL_NAME *name;
Benjamin Peterson31370952010-10-13 22:20:48 +0000677 const X509V3_EXT_METHOD *method;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000678 BIO *biobuf = NULL;
679 char buf[2048];
680 char *vptr;
681 int len;
682 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner117ff172010-03-02 22:49:30 +0000683#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000684 const unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000685#else
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000686 unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000687#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000688
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000689 if (certificate == NULL)
690 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000692 /* get a memory buffer */
693 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000695 i = 0;
696 while ((i = X509_get_ext_by_NID(
697 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000699 if (peer_alt_names == Py_None) {
700 peer_alt_names = PyList_New(0);
701 if (peer_alt_names == NULL)
702 goto fail;
703 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000704
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000705 /* now decode the altName */
706 ext = X509_get_ext(certificate, i);
707 if(!(method = X509V3_EXT_get(ext))) {
708 PyErr_SetString
709 (PySSLErrorObject,
710 ERRSTR("No method for internalizing subjectAltName!"));
711 goto fail;
712 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000714 p = ext->value->data;
715 if (method->it)
716 names = (GENERAL_NAMES*)
717 (ASN1_item_d2i(NULL,
718 &p,
719 ext->value->length,
720 ASN1_ITEM_ptr(method->it)));
721 else
722 names = (GENERAL_NAMES*)
723 (method->d2i(NULL,
724 &p,
725 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000727 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000729 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000731 name = sk_GENERAL_NAME_value(names, j);
732 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000734 /* we special-case DirName as a tuple of
735 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000737 t = PyTuple_New(2);
738 if (t == NULL) {
739 goto fail;
740 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000742 v = PyUnicode_FromString("DirName");
743 if (v == NULL) {
744 Py_DECREF(t);
745 goto fail;
746 }
747 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000749 v = _create_tuple_for_X509_NAME (name->d.dirn);
750 if (v == NULL) {
751 Py_DECREF(t);
752 goto fail;
753 }
754 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000755
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000756 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000758 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000760 (void) BIO_reset(biobuf);
761 GENERAL_NAME_print(biobuf, name);
762 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
763 if (len < 0) {
764 _setSSLError(NULL, 0, __FILE__, __LINE__);
765 goto fail;
766 }
767 vptr = strchr(buf, ':');
768 if (vptr == NULL)
769 goto fail;
770 t = PyTuple_New(2);
771 if (t == NULL)
772 goto fail;
773 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
774 if (v == NULL) {
775 Py_DECREF(t);
776 goto fail;
777 }
778 PyTuple_SET_ITEM(t, 0, v);
779 v = PyUnicode_FromStringAndSize((vptr + 1),
780 (len - (vptr - buf + 1)));
781 if (v == NULL) {
782 Py_DECREF(t);
783 goto fail;
784 }
785 PyTuple_SET_ITEM(t, 1, v);
786 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000788 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000790 if (PyList_Append(peer_alt_names, t) < 0) {
791 Py_DECREF(t);
792 goto fail;
793 }
794 Py_DECREF(t);
795 }
796 }
797 BIO_free(biobuf);
798 if (peer_alt_names != Py_None) {
799 v = PyList_AsTuple(peer_alt_names);
800 Py_DECREF(peer_alt_names);
801 return v;
802 } else {
803 return peer_alt_names;
804 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000805
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
807 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000808 if (biobuf != NULL)
809 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000811 if (peer_alt_names != Py_None) {
812 Py_XDECREF(peer_alt_names);
813 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000815 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816}
817
818static PyObject *
819_decode_certificate (X509 *certificate, int verbose) {
820
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000821 PyObject *retval = NULL;
822 BIO *biobuf = NULL;
823 PyObject *peer;
824 PyObject *peer_alt_names = NULL;
825 PyObject *issuer;
826 PyObject *version;
827 PyObject *sn_obj;
828 ASN1_INTEGER *serialNumber;
829 char buf[2048];
830 int len;
831 ASN1_TIME *notBefore, *notAfter;
832 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000833
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000834 retval = PyDict_New();
835 if (retval == NULL)
836 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000837
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000838 peer = _create_tuple_for_X509_NAME(
839 X509_get_subject_name(certificate));
840 if (peer == NULL)
841 goto fail0;
842 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
843 Py_DECREF(peer);
844 goto fail0;
845 }
846 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000847
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000848 if (verbose) {
849 issuer = _create_tuple_for_X509_NAME(
850 X509_get_issuer_name(certificate));
851 if (issuer == NULL)
852 goto fail0;
853 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
854 Py_DECREF(issuer);
855 goto fail0;
856 }
857 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000858
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000859 version = PyLong_FromLong(X509_get_version(certificate) + 1);
860 if (PyDict_SetItemString(retval, "version", version) < 0) {
861 Py_DECREF(version);
862 goto fail0;
863 }
864 Py_DECREF(version);
865 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000866
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000867 /* get a memory buffer */
868 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000869
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000870 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000871
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000872 (void) BIO_reset(biobuf);
873 serialNumber = X509_get_serialNumber(certificate);
874 /* should not exceed 20 octets, 160 bits, so buf is big enough */
875 i2a_ASN1_INTEGER(biobuf, serialNumber);
876 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
877 if (len < 0) {
878 _setSSLError(NULL, 0, __FILE__, __LINE__);
879 goto fail1;
880 }
881 sn_obj = PyUnicode_FromStringAndSize(buf, len);
882 if (sn_obj == NULL)
883 goto fail1;
884 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
885 Py_DECREF(sn_obj);
886 goto fail1;
887 }
888 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000890 (void) BIO_reset(biobuf);
891 notBefore = X509_get_notBefore(certificate);
892 ASN1_TIME_print(biobuf, notBefore);
893 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
894 if (len < 0) {
895 _setSSLError(NULL, 0, __FILE__, __LINE__);
896 goto fail1;
897 }
898 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
899 if (pnotBefore == NULL)
900 goto fail1;
901 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
902 Py_DECREF(pnotBefore);
903 goto fail1;
904 }
905 Py_DECREF(pnotBefore);
906 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000907
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000908 (void) BIO_reset(biobuf);
909 notAfter = X509_get_notAfter(certificate);
910 ASN1_TIME_print(biobuf, notAfter);
911 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
912 if (len < 0) {
913 _setSSLError(NULL, 0, __FILE__, __LINE__);
914 goto fail1;
915 }
916 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
917 if (pnotAfter == NULL)
918 goto fail1;
919 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
920 Py_DECREF(pnotAfter);
921 goto fail1;
922 }
923 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000925 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000927 peer_alt_names = _get_peer_alt_names(certificate);
928 if (peer_alt_names == NULL)
929 goto fail1;
930 else if (peer_alt_names != Py_None) {
931 if (PyDict_SetItemString(retval, "subjectAltName",
932 peer_alt_names) < 0) {
933 Py_DECREF(peer_alt_names);
934 goto fail1;
935 }
936 Py_DECREF(peer_alt_names);
937 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000938
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000939 BIO_free(biobuf);
940 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000941
942 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000943 if (biobuf != NULL)
944 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000945 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000946 Py_XDECREF(retval);
947 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000948}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000949
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950
951static PyObject *
952PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
953
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000954 PyObject *retval = NULL;
955 char *filename = NULL;
956 X509 *x=NULL;
957 BIO *cert;
958 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000960 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
961 &filename, &verbose))
962 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000964 if ((cert=BIO_new(BIO_s_file())) == NULL) {
965 PyErr_SetString(PySSLErrorObject,
966 "Can't malloc memory to read file");
967 goto fail0;
968 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000970 if (BIO_read_filename(cert,filename) <= 0) {
971 PyErr_SetString(PySSLErrorObject,
972 "Can't open file");
973 goto fail0;
974 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000976 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
977 if (x == NULL) {
978 PyErr_SetString(PySSLErrorObject,
979 "Error decoding PEM-encoded file");
980 goto fail0;
981 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000983 retval = _decode_certificate(x, verbose);
Mark Dickinson732cc9b2010-08-03 18:33:11 +0000984 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
986 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000987
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000988 if (cert != NULL) BIO_free(cert);
989 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990}
991
992
993static PyObject *
994PySSL_peercert(PySSLObject *self, PyObject *args)
995{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000996 PyObject *retval = NULL;
997 int len;
998 int verification;
999 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001001 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1002 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001004 if (!self->peer_cert)
1005 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001006
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001007 if (PyObject_IsTrue(binary_mode)) {
1008 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001010 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001012 bytes_buf = NULL;
1013 len = i2d_X509(self->peer_cert, &bytes_buf);
1014 if (len < 0) {
1015 PySSL_SetError(self, len, __FILE__, __LINE__);
1016 return NULL;
1017 }
1018 /* this is actually an immutable bytes sequence */
1019 retval = PyBytes_FromStringAndSize
1020 ((const char *) bytes_buf, len);
1021 OPENSSL_free(bytes_buf);
1022 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001024 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001025
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001026 verification = SSL_CTX_get_verify_mode(self->ctx);
1027 if ((verification & SSL_VERIFY_PEER) == 0)
1028 return PyDict_New();
1029 else
1030 return _decode_certificate (self->peer_cert, 0);
1031 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032}
1033
1034PyDoc_STRVAR(PySSL_peercert_doc,
1035"peer_certificate([der=False]) -> certificate\n\
1036\n\
1037Returns the certificate for the peer. If no certificate was provided,\n\
1038returns None. If a certificate was provided, but not validated, returns\n\
1039an empty dictionary. Otherwise returns a dict containing information\n\
1040about the peer certificate.\n\
1041\n\
1042If the optional argument is True, returns a DER-encoded copy of the\n\
1043peer certificate, or None if no certificate was provided. This will\n\
1044return the certificate even if it wasn't validated.");
1045
1046static PyObject *PySSL_cipher (PySSLObject *self) {
1047
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001048 PyObject *retval, *v;
Benjamin Peterson31370952010-10-13 22:20:48 +00001049 const SSL_CIPHER *current;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001050 char *cipher_name;
1051 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001053 if (self->ssl == NULL)
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001054 Py_RETURN_NONE;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001055 current = SSL_get_current_cipher(self->ssl);
1056 if (current == NULL)
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001057 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001059 retval = PyTuple_New(3);
1060 if (retval == NULL)
1061 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001063 cipher_name = (char *) SSL_CIPHER_get_name(current);
1064 if (cipher_name == NULL) {
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001065 Py_INCREF(Py_None);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001066 PyTuple_SET_ITEM(retval, 0, Py_None);
1067 } else {
1068 v = PyUnicode_FromString(cipher_name);
1069 if (v == NULL)
1070 goto fail0;
1071 PyTuple_SET_ITEM(retval, 0, v);
1072 }
1073 cipher_protocol = SSL_CIPHER_get_version(current);
1074 if (cipher_protocol == NULL) {
Hirokazu Yamamoto8e63c682010-12-09 12:30:05 +00001075 Py_INCREF(Py_None);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001076 PyTuple_SET_ITEM(retval, 1, Py_None);
1077 } else {
1078 v = PyUnicode_FromString(cipher_protocol);
1079 if (v == NULL)
1080 goto fail0;
1081 PyTuple_SET_ITEM(retval, 1, v);
1082 }
1083 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1084 if (v == NULL)
1085 goto fail0;
1086 PyTuple_SET_ITEM(retval, 2, v);
1087 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001088
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001090 Py_DECREF(retval);
1091 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092}
1093
Guido van Rossume6650f92007-12-06 19:05:55 +00001094static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001095{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001096 if (self->peer_cert) /* Possible not to have one? */
1097 X509_free (self->peer_cert);
1098 if (self->ssl)
1099 SSL_free(self->ssl);
1100 if (self->ctx)
1101 SSL_CTX_free(self->ctx);
1102 Py_XDECREF(self->Socket);
1103 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001104}
1105
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001106/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001107 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001108 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001109 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001110
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001111static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001112check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001113{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001114 fd_set fds;
1115 struct timeval tv;
1116 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001117
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001118 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1119 if (s->sock_timeout < 0.0)
1120 return SOCKET_IS_BLOCKING;
1121 else if (s->sock_timeout == 0.0)
1122 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001123
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001124 /* Guard against closed socket */
1125 if (s->sock_fd < 0)
1126 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001127
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001128 /* Prefer poll, if available, since you can poll() any fd
1129 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130#ifdef HAVE_POLL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001131 {
1132 struct pollfd pollfd;
1133 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001134
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001135 pollfd.fd = s->sock_fd;
1136 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001137
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001138 /* s->sock_timeout is in seconds, timeout in ms */
1139 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1140 PySSL_BEGIN_ALLOW_THREADS
1141 rc = poll(&pollfd, 1, timeout);
1142 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001143
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001144 goto normal_return;
1145 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001146#endif
1147
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001148 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001149#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001150 if (s->sock_fd >= FD_SETSIZE)
1151 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001152#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001153
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001154 /* Construct the arguments to select */
1155 tv.tv_sec = (int)s->sock_timeout;
1156 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1157 FD_ZERO(&fds);
1158 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001159
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001160 /* See if the socket is ready */
1161 PySSL_BEGIN_ALLOW_THREADS
1162 if (writing)
1163 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1164 else
1165 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1166 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001167
Bill Janssen6e027db2007-11-15 22:23:56 +00001168#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001169normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001170#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001171 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1172 (when we are able to write or when there's something to read) */
1173 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001174}
1175
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001176static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1177{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001178 char *data;
1179 int len;
1180 int count;
1181 int sockstate;
1182 int err;
1183 int nonblocking;
1184 PySocketSockObject *sock
1185 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001186
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001187 if (((PyObject*)sock) == Py_None) {
1188 _setSSLError("Underlying socket connection gone",
1189 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1190 return NULL;
1191 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001192 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001193
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001194 if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) {
1195 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001196 return NULL;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001197 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001198
1199 /* just in case the blocking state of the socket has been changed */
1200 nonblocking = (sock->sock_timeout >= 0.0);
1201 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1202 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1203
1204 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1205 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1206 PyErr_SetString(PySSLErrorObject,
1207 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001208 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001209 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1210 PyErr_SetString(PySSLErrorObject,
1211 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001212 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001213 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1214 PyErr_SetString(PySSLErrorObject,
1215 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001216 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001217 }
1218 do {
1219 err = 0;
1220 PySSL_BEGIN_ALLOW_THREADS
1221 len = SSL_write(self->ssl, data, count);
1222 err = SSL_get_error(self->ssl, len);
1223 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001224 if (PyErr_CheckSignals())
1225 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001226 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001227 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001228 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001229 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001230 } else {
1231 sockstate = SOCKET_OPERATION_OK;
1232 }
1233 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1234 PyErr_SetString(PySSLErrorObject,
1235 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001236 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001237 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1238 PyErr_SetString(PySSLErrorObject,
1239 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001240 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001241 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1242 break;
1243 }
1244 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001245
1246 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001247 if (len > 0)
1248 return PyLong_FromLong(len);
1249 else
1250 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001251
1252error:
1253 Py_DECREF(sock);
1254 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001255}
1256
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001257PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001258"write(s) -> len\n\
1259\n\
1260Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001262
Bill Janssen6e027db2007-11-15 22:23:56 +00001263static PyObject *PySSL_SSLpending(PySSLObject *self)
1264{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001265 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001266
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001267 PySSL_BEGIN_ALLOW_THREADS
1268 count = SSL_pending(self->ssl);
1269 PySSL_END_ALLOW_THREADS
1270 if (count < 0)
1271 return PySSL_SetError(self, count, __FILE__, __LINE__);
1272 else
1273 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001274}
1275
1276PyDoc_STRVAR(PySSL_SSLpending_doc,
1277"pending() -> count\n\
1278\n\
1279Returns the number of already decrypted bytes available for read,\n\
1280pending on the connection.\n");
1281
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001282static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1283{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001284 PyObject *dest = NULL;
1285 Py_buffer buf;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001286 char *mem;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001287 int len, count;
1288 int buf_passed = 0;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001289 int sockstate;
1290 int err;
1291 int nonblocking;
1292 PySocketSockObject *sock
1293 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001294
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001295 if (((PyObject*)sock) == Py_None) {
1296 _setSSLError("Underlying socket connection gone",
1297 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1298 return NULL;
1299 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001300 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001301
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001302 buf.obj = NULL;
1303 buf.buf = NULL;
1304 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001305 goto error;
1306
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001307 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1308 dest = PyBytes_FromStringAndSize(NULL, len);
1309 if (dest == NULL)
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001310 goto error;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001311 mem = PyBytes_AS_STRING(dest);
1312 }
1313 else {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001314 buf_passed = 1;
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001315 mem = buf.buf;
1316 if (len <= 0 || len > buf.len) {
1317 len = (int) buf.len;
1318 if (buf.len != len) {
1319 PyErr_SetString(PyExc_OverflowError,
1320 "maximum length can't fit in a C 'int'");
1321 goto error;
1322 }
1323 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001324 }
1325
1326 /* just in case the blocking state of the socket has been changed */
1327 nonblocking = (sock->sock_timeout >= 0.0);
1328 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1329 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1330
1331 /* first check if there are bytes ready to be read */
1332 PySSL_BEGIN_ALLOW_THREADS
1333 count = SSL_pending(self->ssl);
1334 PySSL_END_ALLOW_THREADS
1335
1336 if (!count) {
1337 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1338 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1339 PyErr_SetString(PySSLErrorObject,
1340 "The read operation timed out");
1341 goto error;
1342 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1343 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +00001344 "Underlying socket too large for select().");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001345 goto error;
1346 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1347 count = 0;
1348 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001349 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001350 }
1351 do {
1352 err = 0;
1353 PySSL_BEGIN_ALLOW_THREADS
1354 count = SSL_read(self->ssl, mem, len);
1355 err = SSL_get_error(self->ssl, count);
1356 PySSL_END_ALLOW_THREADS
1357 if (PyErr_CheckSignals())
1358 goto error;
1359 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001360 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001361 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001362 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001363 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1364 (SSL_get_shutdown(self->ssl) ==
1365 SSL_RECEIVED_SHUTDOWN))
1366 {
1367 count = 0;
1368 goto done;
1369 } else {
1370 sockstate = SOCKET_OPERATION_OK;
1371 }
1372 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1373 PyErr_SetString(PySSLErrorObject,
1374 "The read operation timed out");
1375 goto error;
1376 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1377 break;
1378 }
1379 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1380 if (count <= 0) {
1381 PySSL_SetError(self, count, __FILE__, __LINE__);
1382 goto error;
1383 }
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001384
1385done:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001386 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001387 if (!buf_passed) {
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001388 _PyBytes_Resize(&dest, count);
1389 return dest;
1390 }
1391 else {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001392 PyBuffer_Release(&buf);
1393 return PyLong_FromLong(count);
1394 }
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001395
1396error:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001397 Py_DECREF(sock);
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001398 if (!buf_passed)
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001399 Py_XDECREF(dest);
Antoine Pitrou10c4c232010-09-03 18:39:47 +00001400 else
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001401 PyBuffer_Release(&buf);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001402 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001403}
1404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001405PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001406"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001407\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001408Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001409
Bill Janssen40a0f662008-08-12 16:56:25 +00001410static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1411{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001412 int err, ssl_err, sockstate, nonblocking;
1413 int zeros = 0;
1414 PySocketSockObject *sock
1415 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001416
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001417 /* Guard against closed socket */
1418 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1419 _setSSLError("Underlying socket connection gone",
1420 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1421 return NULL;
1422 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001423 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001424
1425 /* Just in case the blocking state of the socket has been changed */
1426 nonblocking = (sock->sock_timeout >= 0.0);
1427 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1428 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1429
1430 while (1) {
1431 PySSL_BEGIN_ALLOW_THREADS
1432 /* Disable read-ahead so that unwrap can work correctly.
1433 * Otherwise OpenSSL might read in too much data,
1434 * eating clear text data that happens to be
1435 * transmitted after the SSL shutdown.
1436 * Should be safe to call repeatedly everytime this
1437 * function is used and the shutdown_seen_zero != 0
1438 * condition is met.
1439 */
1440 if (self->shutdown_seen_zero)
1441 SSL_set_read_ahead(self->ssl, 0);
1442 err = SSL_shutdown(self->ssl);
1443 PySSL_END_ALLOW_THREADS
1444 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1445 if (err > 0)
1446 break;
1447 if (err == 0) {
1448 /* Don't loop endlessly; instead preserve legacy
1449 behaviour of trying SSL_shutdown() only twice.
1450 This looks necessary for OpenSSL < 0.9.8m */
1451 if (++zeros > 1)
1452 break;
1453 /* Shutdown was sent, now try receiving */
1454 self->shutdown_seen_zero = 1;
1455 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001456 }
1457
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001458 /* Possibly retry shutdown until timeout or failure */
1459 ssl_err = SSL_get_error(self->ssl, err);
1460 if (ssl_err == SSL_ERROR_WANT_READ)
1461 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1462 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1463 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1464 else
1465 break;
1466 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1467 if (ssl_err == SSL_ERROR_WANT_READ)
1468 PyErr_SetString(PySSLErrorObject,
1469 "The read operation timed out");
1470 else
1471 PyErr_SetString(PySSLErrorObject,
1472 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001473 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001474 }
1475 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1476 PyErr_SetString(PySSLErrorObject,
1477 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001478 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001479 }
1480 else if (sockstate != SOCKET_OPERATION_OK)
1481 /* Retain the SSL error code */
1482 break;
1483 }
Antoine Pitrou5a1c4d12010-04-23 21:11:10 +00001484
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001485 if (err < 0) {
1486 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001487 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001488 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001489 else
1490 /* It's already INCREF'ed */
1491 return (PyObject *) sock;
1492
1493error:
1494 Py_DECREF(sock);
1495 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001496}
1497
1498PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1499"shutdown(s) -> socket\n\
1500\n\
1501Does the SSL shutdown handshake with the remote end, and returns\n\
1502the underlying socket object.");
1503
1504
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001505static PyMethodDef PySSLMethods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001506 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1507 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1508 PySSL_SSLwrite_doc},
1509 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1510 PySSL_SSLread_doc},
1511 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1512 PySSL_SSLpending_doc},
1513 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1514 PySSL_peercert_doc},
1515 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1516 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1517 PySSL_SSLshutdown_doc},
1518 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001519};
1520
Jeremy Hylton938ace62002-07-17 16:30:39 +00001521static PyTypeObject PySSL_Type = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001522 PyVarObject_HEAD_INIT(NULL, 0)
1523 "ssl.SSLContext", /*tp_name*/
1524 sizeof(PySSLObject), /*tp_basicsize*/
1525 0, /*tp_itemsize*/
1526 /* methods */
1527 (destructor)PySSL_dealloc, /*tp_dealloc*/
1528 0, /*tp_print*/
1529 0, /*tp_getattr*/
1530 0, /*tp_setattr*/
1531 0, /*tp_reserved*/
1532 0, /*tp_repr*/
1533 0, /*tp_as_number*/
1534 0, /*tp_as_sequence*/
1535 0, /*tp_as_mapping*/
1536 0, /*tp_hash*/
1537 0, /*tp_call*/
1538 0, /*tp_str*/
1539 0, /*tp_getattro*/
1540 0, /*tp_setattro*/
1541 0, /*tp_as_buffer*/
1542 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1543 0, /*tp_doc*/
1544 0, /*tp_traverse*/
1545 0, /*tp_clear*/
1546 0, /*tp_richcompare*/
1547 0, /*tp_weaklistoffset*/
1548 0, /*tp_iter*/
1549 0, /*tp_iternext*/
1550 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001551};
1552
1553#ifdef HAVE_OPENSSL_RAND
1554
1555/* helper routines for seeding the SSL PRNG */
1556static PyObject *
1557PySSL_RAND_add(PyObject *self, PyObject *args)
1558{
1559 char *buf;
1560 int len;
1561 double entropy;
1562
1563 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001564 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001565 RAND_add(buf, len, entropy);
1566 Py_INCREF(Py_None);
1567 return Py_None;
1568}
1569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001570PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001571"RAND_add(string, entropy)\n\
1572\n\
1573Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001575
1576static PyObject *
1577PySSL_RAND_status(PyObject *self)
1578{
Christian Heimes217cfd12007-12-02 14:31:20 +00001579 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001580}
1581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001582PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001583"RAND_status() -> 0 or 1\n\
1584\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001585Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1586It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1587using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588
1589static PyObject *
1590PySSL_RAND_egd(PyObject *self, PyObject *arg)
1591{
1592 int bytes;
1593
Bill Janssen6e027db2007-11-15 22:23:56 +00001594 if (!PyUnicode_Check(arg))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001595 return PyErr_Format(PyExc_TypeError,
1596 "RAND_egd() expected string, found %s",
1597 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001598 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001599 if (bytes == -1) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001600 PyErr_SetString(PySSLErrorObject,
1601 "EGD connection failed or EGD did not return "
1602 "enough data to seed the PRNG");
1603 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001604 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001605 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001606}
1607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001608PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001609"RAND_egd(path) -> bytes\n\
1610\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001611Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1612Returns number of bytes read. Raises SSLError if connection to EGD\n\
1613fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001614
1615#endif
1616
Bill Janssen40a0f662008-08-12 16:56:25 +00001617
1618
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001619/* List of functions exported by this module. */
1620
1621static PyMethodDef PySSL_methods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001622 {"sslwrap", PySSL_sslwrap,
1623 METH_VARARGS, ssl_doc},
1624 {"_test_decode_cert", PySSL_test_decode_certificate,
1625 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001626#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001627 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1628 PySSL_RAND_add_doc},
1629 {"RAND_egd", PySSL_RAND_egd, METH_O,
1630 PySSL_RAND_egd_doc},
1631 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1632 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001633#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001634 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001635};
1636
1637
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001638#ifdef WITH_THREAD
1639
1640/* an implementation of OpenSSL threading operations in terms
1641 of the Python C thread library */
1642
1643static PyThread_type_lock *_ssl_locks = NULL;
1644
1645static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001646 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647}
1648
Bill Janssen6e027db2007-11-15 22:23:56 +00001649static void _ssl_thread_locking_function
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001650 (int mode, int n, const char *file, int line) {
1651 /* this function is needed to perform locking on shared data
1652 structures. (Note that OpenSSL uses a number of global data
1653 structures that will be implicitly shared whenever multiple
1654 threads use OpenSSL.) Multi-threaded applications will
1655 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001656
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001657 locking_function() must be able to handle up to
1658 CRYPTO_num_locks() different mutex locks. It sets the n-th
1659 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001661 file and line are the file number of the function setting the
1662 lock. They can be useful for debugging.
1663 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001665 if ((_ssl_locks == NULL) ||
1666 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1667 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001669 if (mode & CRYPTO_LOCK) {
1670 PyThread_acquire_lock(_ssl_locks[n], 1);
1671 } else {
1672 PyThread_release_lock(_ssl_locks[n]);
1673 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674}
1675
1676static int _setup_ssl_threads(void) {
1677
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001678 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001679
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001680 if (_ssl_locks == NULL) {
1681 _ssl_locks_count = CRYPTO_num_locks();
1682 _ssl_locks = (PyThread_type_lock *)
1683 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1684 if (_ssl_locks == NULL)
1685 return 0;
1686 memset(_ssl_locks, 0,
1687 sizeof(PyThread_type_lock) * _ssl_locks_count);
1688 for (i = 0; i < _ssl_locks_count; i++) {
1689 _ssl_locks[i] = PyThread_allocate_lock();
1690 if (_ssl_locks[i] == NULL) {
1691 unsigned int j;
1692 for (j = 0; j < i; j++) {
1693 PyThread_free_lock(_ssl_locks[j]);
1694 }
1695 free(_ssl_locks);
1696 return 0;
1697 }
1698 }
1699 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1700 CRYPTO_set_id_callback(_ssl_thread_id_function);
1701 }
1702 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001703}
1704
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001705#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001707PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001708"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001709for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001710
Martin v. Löwis1a214512008-06-11 05:26:20 +00001711
1712static struct PyModuleDef _sslmodule = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001713 PyModuleDef_HEAD_INIT,
1714 "_ssl",
1715 module_doc,
1716 -1,
1717 PySSL_methods,
1718 NULL,
1719 NULL,
1720 NULL,
1721 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001722};
1723
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001724PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001725PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001726{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001727 PyObject *m, *d;
1728 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001729
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001730 if (PyType_Ready(&PySSL_Type) < 0)
1731 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001732
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001733 m = PyModule_Create(&_sslmodule);
1734 if (m == NULL)
1735 return NULL;
1736 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001737
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001738 /* Load _socket module and its C API */
1739 socket_api = PySocketModule_ImportModuleAndAPI();
1740 if (!socket_api)
1741 return NULL;
1742 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001743
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001744 /* Init OpenSSL */
1745 SSL_load_error_strings();
1746 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747#ifdef WITH_THREAD
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001748 /* note that this will start threading if not already started */
1749 if (!_setup_ssl_threads()) {
1750 return NULL;
1751 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001753 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001755 /* Add symbols to module dict */
1756 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1757 PySocketModule.error,
1758 NULL);
1759 if (PySSLErrorObject == NULL)
1760 return NULL;
1761 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1762 return NULL;
1763 if (PyDict_SetItemString(d, "SSLType",
1764 (PyObject *)&PySSL_Type) != 0)
1765 return NULL;
1766 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1767 PY_SSL_ERROR_ZERO_RETURN);
1768 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1769 PY_SSL_ERROR_WANT_READ);
1770 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1771 PY_SSL_ERROR_WANT_WRITE);
1772 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1773 PY_SSL_ERROR_WANT_X509_LOOKUP);
1774 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1775 PY_SSL_ERROR_SYSCALL);
1776 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1777 PY_SSL_ERROR_SSL);
1778 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1779 PY_SSL_ERROR_WANT_CONNECT);
1780 /* non ssl.h errorcodes */
1781 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1782 PY_SSL_ERROR_EOF);
1783 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1784 PY_SSL_ERROR_INVALID_ERROR_CODE);
1785 /* cert requirements */
1786 PyModule_AddIntConstant(m, "CERT_NONE",
1787 PY_SSL_CERT_NONE);
1788 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1789 PY_SSL_CERT_OPTIONAL);
1790 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1791 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001792
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001793 /* protocol versions */
Victor Stinneree18b6f2011-05-10 00:38:00 +02001794#ifndef OPENSSL_NO_SSL2
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001795 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1796 PY_SSL_VERSION_SSL2);
Victor Stinneree18b6f2011-05-10 00:38:00 +02001797#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001798 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1799 PY_SSL_VERSION_SSL3);
1800 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1801 PY_SSL_VERSION_SSL23);
1802 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1803 PY_SSL_VERSION_TLS1);
1804 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001805}