blob: 5ddbb1dc222ccf48f651395438510e3c4db7cd6f [file] [log] [blame]
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +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.
Bill Janssen98d19da2007-09-10 21:51:02 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen934b16d2008-06-28 22:19:33 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Bill Janssen98d19da2007-09-10 21:51:02 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Bill Janssen98d19da2007-09-10 21:51:02 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitroua5c4b552010-04-22 23:33:02 +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"
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000018
Bill Janssen98d19da2007-09-10 21:51:02 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Christian Heimes0d604cf2013-08-21 13:26:05 +020021
22#ifdef HAVE_PTHREAD_ATFORK
23# include <pthread.h>
24#endif
25
Bill Janssen98d19da2007-09-10 21:51:02 +000026#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000027 PyThreadState *_save = NULL; \
28 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
29#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
30#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
31#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
32 }
Bill Janssen98d19da2007-09-10 21:51:02 +000033
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000034#else /* no WITH_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +000035
36#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000056};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000057
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000058enum py_ssl_server_or_client {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000059 PY_SSL_CLIENT,
60 PY_SSL_SERVER
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000061};
62
63enum py_ssl_cert_requirements {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000064 PY_SSL_CERT_NONE,
65 PY_SSL_CERT_OPTIONAL,
66 PY_SSL_CERT_REQUIRED
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000067};
68
69enum py_ssl_version {
Victor Stinnerb1241f92011-05-10 01:52:03 +020070#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000071 PY_SSL_VERSION_SSL2,
Victor Stinnerb1241f92011-05-10 01:52:03 +020072#endif
73 PY_SSL_VERSION_SSL3=1,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +000074 PY_SSL_VERSION_SSL23,
75 PY_SSL_VERSION_TLS1
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000076};
77
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000078/* Include symbols from _socket module */
79#include "socketmodule.h"
80
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +000081#if defined(HAVE_POLL_H)
Anthony Baxter93ab5fa2006-07-11 02:04:09 +000082#include <poll.h>
83#elif defined(HAVE_SYS_POLL_H)
84#include <sys/poll.h>
85#endif
86
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000087/* Include OpenSSL header files */
88#include "openssl/rsa.h"
89#include "openssl/crypto.h"
90#include "openssl/x509.h"
Bill Janssen98d19da2007-09-10 21:51:02 +000091#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000092#include "openssl/pem.h"
93#include "openssl/ssl.h"
94#include "openssl/err.h"
95#include "openssl/rand.h"
96
97/* SSL error object */
98static PyObject *PySSLErrorObject;
99
Bill Janssen98d19da2007-09-10 21:51:02 +0000100#ifdef WITH_THREAD
101
102/* serves as a flag to see whether we've initialized the SSL thread support. */
103/* 0 means no, greater than 0 means yes */
104
105static unsigned int _ssl_locks_count = 0;
106
107#endif /* def WITH_THREAD */
108
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000109/* SSL socket object */
110
111#define X509_NAME_MAXLEN 256
112
113/* RAND_* APIs got added to OpenSSL in 0.9.5 */
114#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
115# define HAVE_OPENSSL_RAND 1
116#else
117# undef HAVE_OPENSSL_RAND
118#endif
119
120typedef struct {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000121 PyObject_HEAD
122 PySocketSockObject *Socket; /* Socket on which we're layered */
123 SSL_CTX* ctx;
124 SSL* ssl;
125 X509* peer_cert;
126 char server[X509_NAME_MAXLEN];
127 char issuer[X509_NAME_MAXLEN];
128 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
130} PySSLObject;
131
Jeremy Hylton938ace62002-07-17 16:30:39 +0000132static PyTypeObject PySSL_Type;
133static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
134static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000135static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000136 int writing);
Bill Janssen98d19da2007-09-10 21:51:02 +0000137static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
138static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000139
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000140#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000141
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000142typedef enum {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000143 SOCKET_IS_NONBLOCKING,
144 SOCKET_IS_BLOCKING,
145 SOCKET_HAS_TIMED_OUT,
146 SOCKET_HAS_BEEN_CLOSED,
147 SOCKET_TOO_LARGE_FOR_SELECT,
148 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000149} timeout_state;
150
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000151/* Wrap error strings with filename and line # */
152#define STRINGIFY1(x) #x
153#define STRINGIFY2(x) STRINGIFY1(x)
154#define ERRSTR1(x,y,z) (x ":" y ": " z)
155#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
156
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157/* XXX It might be helpful to augment the error message generated
158 below with the name of the SSL function that generated the error.
159 I expect it's obvious most of the time.
160*/
161
162static PyObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000163PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000165 PyObject *v;
166 char buf[2048];
167 char *errstr;
168 int err;
169 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000170
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000171 assert(ret <= 0);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000172
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000173 if (obj->ssl != NULL) {
174 err = SSL_get_error(obj->ssl, ret);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000175
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000176 switch (err) {
177 case SSL_ERROR_ZERO_RETURN:
178 errstr = "TLS/SSL connection has been closed";
179 p = PY_SSL_ERROR_ZERO_RETURN;
180 break;
181 case SSL_ERROR_WANT_READ:
182 errstr = "The operation did not complete (read)";
183 p = PY_SSL_ERROR_WANT_READ;
184 break;
185 case SSL_ERROR_WANT_WRITE:
186 p = PY_SSL_ERROR_WANT_WRITE;
187 errstr = "The operation did not complete (write)";
188 break;
189 case SSL_ERROR_WANT_X509_LOOKUP:
190 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000191 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000192 break;
193 case SSL_ERROR_WANT_CONNECT:
194 p = PY_SSL_ERROR_WANT_CONNECT;
195 errstr = "The operation did not complete (connect)";
196 break;
197 case SSL_ERROR_SYSCALL:
198 {
199 unsigned long e = ERR_get_error();
200 if (e == 0) {
201 if (ret == 0 || !obj->Socket) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000202 p = PY_SSL_ERROR_EOF;
203 errstr = "EOF occurred in violation of protocol";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000204 } else if (ret == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000205 /* underlying BIO reported an I/O error */
Antoine Pitrou508a2372010-05-16 23:11:46 +0000206 ERR_clear_error();
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000207 return obj->Socket->errorhandler();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000208 } else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000209 p = PY_SSL_ERROR_SYSCALL;
210 errstr = "Some I/O error occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000211 }
212 } else {
213 p = PY_SSL_ERROR_SYSCALL;
214 /* XXX Protected by global interpreter lock */
215 errstr = ERR_error_string(e, NULL);
216 }
217 break;
218 }
219 case SSL_ERROR_SSL:
220 {
221 unsigned long e = ERR_get_error();
222 p = PY_SSL_ERROR_SSL;
223 if (e != 0)
224 /* XXX Protected by global interpreter lock */
225 errstr = ERR_error_string(e, NULL);
226 else { /* possible? */
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000227 errstr = "A failure in the SSL library occurred";
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000228 }
229 break;
230 }
231 default:
232 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
233 errstr = "Invalid error code";
234 }
235 } else {
236 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
237 }
238 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000239 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000240 v = Py_BuildValue("(is)", p, buf);
241 if (v != NULL) {
242 PyErr_SetObject(PySSLErrorObject, v);
243 Py_DECREF(v);
244 }
245 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000246}
247
Bill Janssen98d19da2007-09-10 21:51:02 +0000248static PyObject *
249_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
250
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000251 char buf[2048];
252 PyObject *v;
Bill Janssen98d19da2007-09-10 21:51:02 +0000253
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000254 if (errstr == NULL) {
255 errcode = ERR_peek_last_error();
256 errstr = ERR_error_string(errcode, NULL);
257 }
258 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou508a2372010-05-16 23:11:46 +0000259 ERR_clear_error();
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000260 v = Py_BuildValue("(is)", errcode, buf);
261 if (v != NULL) {
262 PyErr_SetObject(PySSLErrorObject, v);
263 Py_DECREF(v);
264 }
265 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000266}
267
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000268static PySSLObject *
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000269newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000270 enum py_ssl_server_or_client socket_type,
271 enum py_ssl_cert_requirements certreq,
272 enum py_ssl_version proto_version,
273 char *cacerts_file, char *ciphers)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000274{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000275 PySSLObject *self;
276 char *errstr = NULL;
277 int ret;
278 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000280 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
281 if (self == NULL)
282 return NULL;
283 memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
284 memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);
285 self->peer_cert = NULL;
286 self->ssl = NULL;
287 self->ctx = NULL;
288 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000289
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000290 /* Make sure the SSL error state is initialized */
291 (void) ERR_get_state();
292 ERR_clear_error();
Bill Janssen98d19da2007-09-10 21:51:02 +0000293
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000294 if ((key_file && !cert_file) || (!key_file && cert_file)) {
295 errstr = ERRSTR("Both the key & certificate files "
296 "must be specified");
297 goto fail;
298 }
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000299
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000300 if ((socket_type == PY_SSL_SERVER) &&
301 ((key_file == NULL) || (cert_file == NULL))) {
302 errstr = ERRSTR("Both the key & certificate files "
303 "must be specified for server-side operation");
304 goto fail;
305 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000307 PySSL_BEGIN_ALLOW_THREADS
308 if (proto_version == PY_SSL_VERSION_TLS1)
309 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
310 else if (proto_version == PY_SSL_VERSION_SSL3)
311 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
Victor Stinnerb1241f92011-05-10 01:52:03 +0200312#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000313 else if (proto_version == PY_SSL_VERSION_SSL2)
314 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Victor Stinnerb1241f92011-05-10 01:52:03 +0200315#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000316 else if (proto_version == PY_SSL_VERSION_SSL23)
317 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
318 PySSL_END_ALLOW_THREADS
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000319
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000320 if (self->ctx == NULL) {
321 errstr = ERRSTR("Invalid SSL protocol variant specified.");
322 goto fail;
323 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000324
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000325 if (ciphers != NULL) {
326 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
327 if (ret == 0) {
328 errstr = ERRSTR("No cipher can be selected.");
329 goto fail;
330 }
331 }
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000332
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000333 if (certreq != PY_SSL_CERT_NONE) {
334 if (cacerts_file == NULL) {
335 errstr = ERRSTR("No root certificates specified for "
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000336 "verification of other-side certificates.");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000337 goto fail;
338 } else {
339 PySSL_BEGIN_ALLOW_THREADS
340 ret = SSL_CTX_load_verify_locations(self->ctx,
341 cacerts_file,
342 NULL);
343 PySSL_END_ALLOW_THREADS
344 if (ret != 1) {
345 _setSSLError(NULL, 0, __FILE__, __LINE__);
346 goto fail;
347 }
348 }
349 }
350 if (key_file) {
351 PySSL_BEGIN_ALLOW_THREADS
352 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
353 SSL_FILETYPE_PEM);
354 PySSL_END_ALLOW_THREADS
355 if (ret != 1) {
356 _setSSLError(NULL, ret, __FILE__, __LINE__);
357 goto fail;
358 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000359
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000360 PySSL_BEGIN_ALLOW_THREADS
361 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
362 cert_file);
363 PySSL_END_ALLOW_THREADS
364 if (ret != 1) {
365 /*
366 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
367 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
368 */
369 if (ERR_peek_last_error() != 0) {
370 _setSSLError(NULL, ret, __FILE__, __LINE__);
371 goto fail;
372 }
373 }
374 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000376 /* ssl compatibility */
Antoine Pitroud358e052012-01-27 09:42:45 +0100377 SSL_CTX_set_options(self->ctx,
378 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Bill Janssen98d19da2007-09-10 21:51:02 +0000379
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000380 verification_mode = SSL_VERIFY_NONE;
381 if (certreq == PY_SSL_CERT_OPTIONAL)
382 verification_mode = SSL_VERIFY_PEER;
383 else if (certreq == PY_SSL_CERT_REQUIRED)
384 verification_mode = (SSL_VERIFY_PEER |
385 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
386 SSL_CTX_set_verify(self->ctx, verification_mode,
387 NULL); /* set verify lvl */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000388
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000389 PySSL_BEGIN_ALLOW_THREADS
390 self->ssl = SSL_new(self->ctx); /* New ssl struct */
391 PySSL_END_ALLOW_THREADS
392 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou92719c52010-04-09 20:38:39 +0000393#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000394 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou92719c52010-04-09 20:38:39 +0000395#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000396
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000397 /* If the socket is in non-blocking mode or timeout mode, set the BIO
398 * to non-blocking mode (blocking is the default)
399 */
400 if (Sock->sock_timeout >= 0.0) {
401 /* Set both the read and write BIO's to non-blocking mode */
402 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
403 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
404 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000405
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000406 PySSL_BEGIN_ALLOW_THREADS
407 if (socket_type == PY_SSL_CLIENT)
408 SSL_set_connect_state(self->ssl);
409 else
410 SSL_set_accept_state(self->ssl);
411 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000412
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000413 self->Socket = Sock;
414 Py_INCREF(self->Socket);
415 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000417 if (errstr)
418 PyErr_SetString(PySSLErrorObject, errstr);
419 Py_DECREF(self);
420 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000421}
422
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423static PyObject *
Guido van Rossum780b80d2007-08-27 18:42:23 +0000424PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000425{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000426 PySocketSockObject *Sock;
427 int server_side = 0;
428 int verification_mode = PY_SSL_CERT_NONE;
429 int protocol = PY_SSL_VERSION_SSL23;
430 char *key_file = NULL;
431 char *cert_file = NULL;
432 char *cacerts_file = NULL;
433 char *ciphers = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000434
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000435 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
436 PySocketModule.Sock_Type,
437 &Sock,
438 &server_side,
439 &key_file, &cert_file,
440 &verification_mode, &protocol,
441 &cacerts_file, &ciphers))
442 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000444 /*
445 fprintf(stderr,
446 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
447 "protocol %d, certs %p\n",
448 server_side, key_file, cert_file, verification_mode,
449 protocol, cacerts_file);
450 */
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000452 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
453 server_side, verification_mode,
454 protocol, cacerts_file,
455 ciphers);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000456}
457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000458PyDoc_STRVAR(ssl_doc,
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000459"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
Antoine Pitrou0a6373c2010-04-17 17:10:38 +0000460" cacertsfile, ciphers]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000461
462/* SSL object methods */
463
Bill Janssen934b16d2008-06-28 22:19:33 +0000464static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
465{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000466 int ret;
467 int err;
468 int sockstate, nonblocking;
Antoine Pitrou4d3e3722010-04-24 19:57:01 +0000469
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000470 /* just in case the blocking state of the socket has been changed */
471 nonblocking = (self->Socket->sock_timeout >= 0.0);
472 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
473 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +0000474
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000475 /* Actually negotiate SSL connection */
476 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
477 do {
478 PySSL_BEGIN_ALLOW_THREADS
479 ret = SSL_do_handshake(self->ssl);
480 err = SSL_get_error(self->ssl, ret);
481 PySSL_END_ALLOW_THREADS
482 if(PyErr_CheckSignals()) {
483 return NULL;
484 }
485 if (err == SSL_ERROR_WANT_READ) {
486 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
487 } else if (err == SSL_ERROR_WANT_WRITE) {
488 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
489 } else {
490 sockstate = SOCKET_OPERATION_OK;
491 }
492 if (sockstate == SOCKET_HAS_TIMED_OUT) {
493 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000494 ERRSTR("The handshake operation timed out"));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000495 return NULL;
496 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
497 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000498 ERRSTR("Underlying socket has been closed."));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000499 return NULL;
500 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
501 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000502 ERRSTR("Underlying socket too large for select()."));
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000503 return NULL;
504 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
505 break;
506 }
507 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
508 if (ret < 1)
509 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen934b16d2008-06-28 22:19:33 +0000510
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000511 if (self->peer_cert)
512 X509_free (self->peer_cert);
513 PySSL_BEGIN_ALLOW_THREADS
514 if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {
515 X509_NAME_oneline(X509_get_subject_name(self->peer_cert),
516 self->server, X509_NAME_MAXLEN);
517 X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),
518 self->issuer, X509_NAME_MAXLEN);
519 }
520 PySSL_END_ALLOW_THREADS
Bill Janssen934b16d2008-06-28 22:19:33 +0000521
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000522 Py_INCREF(Py_None);
523 return Py_None;
Bill Janssen934b16d2008-06-28 22:19:33 +0000524}
525
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000526static PyObject *
527PySSL_server(PySSLObject *self)
528{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000529 return PyString_FromString(self->server);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000530}
531
532static PyObject *
533PySSL_issuer(PySSLObject *self)
534{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000535 return PyString_FromString(self->issuer);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000536}
537
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000538static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000539_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000540
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000541 char namebuf[X509_NAME_MAXLEN];
542 int buflen;
543 PyObject *name_obj;
544 PyObject *value_obj;
545 PyObject *attr;
546 unsigned char *valuebuf = NULL;
Guido van Rossum780b80d2007-08-27 18:42:23 +0000547
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000548 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
549 if (buflen < 0) {
550 _setSSLError(NULL, 0, __FILE__, __LINE__);
551 goto fail;
552 }
553 name_obj = PyString_FromStringAndSize(namebuf, buflen);
554 if (name_obj == NULL)
555 goto fail;
556
557 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
558 if (buflen < 0) {
559 _setSSLError(NULL, 0, __FILE__, __LINE__);
560 Py_DECREF(name_obj);
561 goto fail;
562 }
563 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +0000564 buflen, "strict");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000565 OPENSSL_free(valuebuf);
566 if (value_obj == NULL) {
567 Py_DECREF(name_obj);
568 goto fail;
569 }
570 attr = PyTuple_New(2);
571 if (attr == NULL) {
572 Py_DECREF(name_obj);
573 Py_DECREF(value_obj);
574 goto fail;
575 }
576 PyTuple_SET_ITEM(attr, 0, name_obj);
577 PyTuple_SET_ITEM(attr, 1, value_obj);
578 return attr;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000579
Bill Janssen98d19da2007-09-10 21:51:02 +0000580 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000581 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000582}
583
584static PyObject *
Bill Janssen98d19da2007-09-10 21:51:02 +0000585_create_tuple_for_X509_NAME (X509_NAME *xname)
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000586{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000587 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
588 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
589 PyObject *rdnt;
590 PyObject *attr = NULL; /* tuple to hold an attribute */
591 int entry_count = X509_NAME_entry_count(xname);
592 X509_NAME_ENTRY *entry;
593 ASN1_OBJECT *name;
594 ASN1_STRING *value;
595 int index_counter;
596 int rdn_level = -1;
597 int retcode;
Bill Janssen98d19da2007-09-10 21:51:02 +0000598
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000599 dn = PyList_New(0);
600 if (dn == NULL)
601 return NULL;
602 /* now create another tuple to hold the top-level RDN */
603 rdn = PyList_New(0);
604 if (rdn == NULL)
605 goto fail0;
Bill Janssen98d19da2007-09-10 21:51:02 +0000606
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000607 for (index_counter = 0;
608 index_counter < entry_count;
609 index_counter++)
610 {
611 entry = X509_NAME_get_entry(xname, index_counter);
Bill Janssen98d19da2007-09-10 21:51:02 +0000612
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000613 /* check to see if we've gotten to a new RDN */
614 if (rdn_level >= 0) {
615 if (rdn_level != entry->set) {
616 /* yes, new RDN */
617 /* add old RDN to DN */
618 rdnt = PyList_AsTuple(rdn);
619 Py_DECREF(rdn);
620 if (rdnt == NULL)
621 goto fail0;
622 retcode = PyList_Append(dn, rdnt);
623 Py_DECREF(rdnt);
624 if (retcode < 0)
625 goto fail0;
626 /* create new RDN */
627 rdn = PyList_New(0);
628 if (rdn == NULL)
629 goto fail0;
630 }
631 }
632 rdn_level = entry->set;
Bill Janssen98d19da2007-09-10 21:51:02 +0000633
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000634 /* now add this attribute to the current RDN */
635 name = X509_NAME_ENTRY_get_object(entry);
636 value = X509_NAME_ENTRY_get_data(entry);
637 attr = _create_tuple_for_attribute(name, value);
638 /*
639 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
640 entry->set,
641 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
642 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
643 */
644 if (attr == NULL)
645 goto fail1;
646 retcode = PyList_Append(rdn, attr);
647 Py_DECREF(attr);
648 if (retcode < 0)
649 goto fail1;
650 }
651 /* now, there's typically a dangling RDN */
Antoine Pitroudd7e0712012-02-15 22:25:27 +0100652 if (rdn != NULL) {
653 if (PyList_GET_SIZE(rdn) > 0) {
654 rdnt = PyList_AsTuple(rdn);
655 Py_DECREF(rdn);
656 if (rdnt == NULL)
657 goto fail0;
658 retcode = PyList_Append(dn, rdnt);
659 Py_DECREF(rdnt);
660 if (retcode < 0)
661 goto fail0;
662 }
663 else {
664 Py_DECREF(rdn);
665 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000666 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000667
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000668 /* convert list to tuple */
669 rdnt = PyList_AsTuple(dn);
670 Py_DECREF(dn);
671 if (rdnt == NULL)
672 return NULL;
673 return rdnt;
Bill Janssen98d19da2007-09-10 21:51:02 +0000674
675 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000676 Py_XDECREF(rdn);
Bill Janssen98d19da2007-09-10 21:51:02 +0000677
678 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000679 Py_XDECREF(dn);
680 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000681}
682
683static PyObject *
684_get_peer_alt_names (X509 *certificate) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000685
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000686 /* this code follows the procedure outlined in
687 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
688 function to extract the STACK_OF(GENERAL_NAME),
689 then iterates through the stack to add the
690 names. */
691
692 int i, j;
693 PyObject *peer_alt_names = Py_None;
694 PyObject *v, *t;
695 X509_EXTENSION *ext = NULL;
696 GENERAL_NAMES *names = NULL;
697 GENERAL_NAME *name;
Benjamin Peterson8e734032010-10-13 22:10:31 +0000698 const X509V3_EXT_METHOD *method;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000699 BIO *biobuf = NULL;
700 char buf[2048];
701 char *vptr;
702 int len;
703 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner3f75cc52010-03-02 22:44:42 +0000704#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000705 const unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000706#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000707 unsigned char *p;
Victor Stinner3f75cc52010-03-02 22:44:42 +0000708#endif
Bill Janssen98d19da2007-09-10 21:51:02 +0000709
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000710 if (certificate == NULL)
711 return peer_alt_names;
Bill Janssen98d19da2007-09-10 21:51:02 +0000712
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000713 /* get a memory buffer */
714 biobuf = BIO_new(BIO_s_mem());
Bill Janssen98d19da2007-09-10 21:51:02 +0000715
Antoine Pitrouf06eb462011-10-01 19:30:58 +0200716 i = -1;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000717 while ((i = X509_get_ext_by_NID(
718 certificate, NID_subject_alt_name, i)) >= 0) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000719
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000720 if (peer_alt_names == Py_None) {
721 peer_alt_names = PyList_New(0);
722 if (peer_alt_names == NULL)
723 goto fail;
724 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000725
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000726 /* now decode the altName */
727 ext = X509_get_ext(certificate, i);
728 if(!(method = X509V3_EXT_get(ext))) {
729 PyErr_SetString(PySSLErrorObject,
730 ERRSTR("No method for internalizing subjectAltName!"));
731 goto fail;
732 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000733
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000734 p = ext->value->data;
735 if (method->it)
736 names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,
737 &p,
738 ext->value->length,
739 ASN1_ITEM_ptr(method->it)));
740 else
741 names = (GENERAL_NAMES*) (method->d2i(NULL,
742 &p,
743 ext->value->length));
Bill Janssen98d19da2007-09-10 21:51:02 +0000744
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000745 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000746 /* get a rendering of each name in the set of names */
Christian Heimes88b174c2013-08-17 00:54:47 +0200747 int gntype;
748 ASN1_STRING *as = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000749
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000750 name = sk_GENERAL_NAME_value(names, j);
Christian Heimesf1bd47a2013-08-17 17:18:56 +0200751 gntype = name->type;
Christian Heimes88b174c2013-08-17 00:54:47 +0200752 switch (gntype) {
753 case GEN_DIRNAME:
754 /* we special-case DirName as a tuple of
755 tuples of attributes */
Bill Janssen98d19da2007-09-10 21:51:02 +0000756
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000757 t = PyTuple_New(2);
758 if (t == NULL) {
759 goto fail;
760 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000761
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000762 v = PyString_FromString("DirName");
763 if (v == NULL) {
764 Py_DECREF(t);
765 goto fail;
766 }
767 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen98d19da2007-09-10 21:51:02 +0000768
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000769 v = _create_tuple_for_X509_NAME (name->d.dirn);
770 if (v == NULL) {
771 Py_DECREF(t);
772 goto fail;
773 }
774 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200775 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000776
Christian Heimes88b174c2013-08-17 00:54:47 +0200777 case GEN_EMAIL:
778 case GEN_DNS:
779 case GEN_URI:
780 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
781 correctly, CVE-2013-4238 */
782 t = PyTuple_New(2);
783 if (t == NULL)
784 goto fail;
785 switch (gntype) {
786 case GEN_EMAIL:
787 v = PyString_FromString("email");
788 as = name->d.rfc822Name;
789 break;
790 case GEN_DNS:
791 v = PyString_FromString("DNS");
792 as = name->d.dNSName;
793 break;
794 case GEN_URI:
795 v = PyString_FromString("URI");
796 as = name->d.uniformResourceIdentifier;
797 break;
798 }
799 if (v == NULL) {
800 Py_DECREF(t);
801 goto fail;
802 }
803 PyTuple_SET_ITEM(t, 0, v);
804 v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
805 ASN1_STRING_length(as));
806 if (v == NULL) {
807 Py_DECREF(t);
808 goto fail;
809 }
810 PyTuple_SET_ITEM(t, 1, v);
811 break;
Bill Janssen98d19da2007-09-10 21:51:02 +0000812
Christian Heimes88b174c2013-08-17 00:54:47 +0200813 default:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000814 /* for everything else, we use the OpenSSL print form */
Christian Heimes88b174c2013-08-17 00:54:47 +0200815 switch (gntype) {
816 /* check for new general name type */
817 case GEN_OTHERNAME:
818 case GEN_X400:
819 case GEN_EDIPARTY:
820 case GEN_IPADD:
821 case GEN_RID:
822 break;
823 default:
824 if (PyErr_Warn(PyExc_RuntimeWarning,
825 "Unknown general name type") == -1) {
826 goto fail;
827 }
828 break;
829 }
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000830 (void) BIO_reset(biobuf);
831 GENERAL_NAME_print(biobuf, name);
832 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
833 if (len < 0) {
834 _setSSLError(NULL, 0, __FILE__, __LINE__);
835 goto fail;
836 }
837 vptr = strchr(buf, ':');
838 if (vptr == NULL)
839 goto fail;
840 t = PyTuple_New(2);
841 if (t == NULL)
842 goto fail;
843 v = PyString_FromStringAndSize(buf, (vptr - buf));
844 if (v == NULL) {
845 Py_DECREF(t);
846 goto fail;
847 }
848 PyTuple_SET_ITEM(t, 0, v);
849 v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));
850 if (v == NULL) {
851 Py_DECREF(t);
852 goto fail;
853 }
854 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes88b174c2013-08-17 00:54:47 +0200855 break;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000856 }
857
858 /* and add that rendering to the list */
859
860 if (PyList_Append(peer_alt_names, t) < 0) {
861 Py_DECREF(t);
862 goto fail;
863 }
864 Py_DECREF(t);
865 }
Antoine Pitrouaa1c9672011-11-23 01:39:19 +0100866 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000867 }
868 BIO_free(biobuf);
869 if (peer_alt_names != Py_None) {
870 v = PyList_AsTuple(peer_alt_names);
871 Py_DECREF(peer_alt_names);
872 return v;
873 } else {
874 return peer_alt_names;
875 }
876
Bill Janssen98d19da2007-09-10 21:51:02 +0000877
878 fail:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000879 if (biobuf != NULL)
880 BIO_free(biobuf);
Bill Janssen98d19da2007-09-10 21:51:02 +0000881
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000882 if (peer_alt_names != Py_None) {
883 Py_XDECREF(peer_alt_names);
884 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000885
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000886 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +0000887}
888
889static PyObject *
890_decode_certificate (X509 *certificate, int verbose) {
891
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000892 PyObject *retval = NULL;
893 BIO *biobuf = NULL;
894 PyObject *peer;
895 PyObject *peer_alt_names = NULL;
896 PyObject *issuer;
897 PyObject *version;
898 PyObject *sn_obj;
899 ASN1_INTEGER *serialNumber;
900 char buf[2048];
901 int len;
902 ASN1_TIME *notBefore, *notAfter;
903 PyObject *pnotBefore, *pnotAfter;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000904
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000905 retval = PyDict_New();
906 if (retval == NULL)
907 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000908
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000909 peer = _create_tuple_for_X509_NAME(
910 X509_get_subject_name(certificate));
911 if (peer == NULL)
912 goto fail0;
913 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
914 Py_DECREF(peer);
915 goto fail0;
916 }
917 Py_DECREF(peer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000918
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000919 if (verbose) {
920 issuer = _create_tuple_for_X509_NAME(
921 X509_get_issuer_name(certificate));
922 if (issuer == NULL)
923 goto fail0;
924 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
925 Py_DECREF(issuer);
926 goto fail0;
927 }
928 Py_DECREF(issuer);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000929
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000930 version = PyInt_FromLong(X509_get_version(certificate) + 1);
931 if (PyDict_SetItemString(retval, "version", version) < 0) {
932 Py_DECREF(version);
933 goto fail0;
934 }
935 Py_DECREF(version);
936 }
Bill Janssen98d19da2007-09-10 21:51:02 +0000937
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000938 /* get a memory buffer */
939 biobuf = BIO_new(BIO_s_mem());
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +0000940
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000941 if (verbose) {
Bill Janssen98d19da2007-09-10 21:51:02 +0000942
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000943 (void) BIO_reset(biobuf);
944 serialNumber = X509_get_serialNumber(certificate);
945 /* should not exceed 20 octets, 160 bits, so buf is big enough */
946 i2a_ASN1_INTEGER(biobuf, serialNumber);
947 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
948 if (len < 0) {
949 _setSSLError(NULL, 0, __FILE__, __LINE__);
950 goto fail1;
951 }
952 sn_obj = PyString_FromStringAndSize(buf, len);
953 if (sn_obj == NULL)
954 goto fail1;
955 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
956 Py_DECREF(sn_obj);
957 goto fail1;
958 }
959 Py_DECREF(sn_obj);
Bill Janssen98d19da2007-09-10 21:51:02 +0000960
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +0000961 (void) BIO_reset(biobuf);
962 notBefore = X509_get_notBefore(certificate);
963 ASN1_TIME_print(biobuf, notBefore);
964 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
965 if (len < 0) {
966 _setSSLError(NULL, 0, __FILE__, __LINE__);
967 goto fail1;
968 }
969 pnotBefore = PyString_FromStringAndSize(buf, len);
970 if (pnotBefore == NULL)
971 goto fail1;
972 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
973 Py_DECREF(pnotBefore);
974 goto fail1;
975 }
976 Py_DECREF(pnotBefore);
977 }
978
979 (void) BIO_reset(biobuf);
980 notAfter = X509_get_notAfter(certificate);
981 ASN1_TIME_print(biobuf, notAfter);
982 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
983 if (len < 0) {
984 _setSSLError(NULL, 0, __FILE__, __LINE__);
985 goto fail1;
986 }
987 pnotAfter = PyString_FromStringAndSize(buf, len);
988 if (pnotAfter == NULL)
989 goto fail1;
990 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
991 Py_DECREF(pnotAfter);
992 goto fail1;
993 }
994 Py_DECREF(pnotAfter);
995
996 /* Now look for subjectAltName */
997
998 peer_alt_names = _get_peer_alt_names(certificate);
999 if (peer_alt_names == NULL)
1000 goto fail1;
1001 else if (peer_alt_names != Py_None) {
1002 if (PyDict_SetItemString(retval, "subjectAltName",
1003 peer_alt_names) < 0) {
1004 Py_DECREF(peer_alt_names);
1005 goto fail1;
1006 }
1007 Py_DECREF(peer_alt_names);
1008 }
1009
1010 BIO_free(biobuf);
1011 return retval;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001012
1013 fail1:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001014 if (biobuf != NULL)
1015 BIO_free(biobuf);
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001016 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001017 Py_XDECREF(retval);
1018 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001019}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001020
Bill Janssen98d19da2007-09-10 21:51:02 +00001021
1022static PyObject *
1023PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1024
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001025 PyObject *retval = NULL;
1026 char *filename = NULL;
1027 X509 *x=NULL;
1028 BIO *cert;
1029 int verbose = 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00001030
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001031 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))
1032 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001033
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001034 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1035 PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");
1036 goto fail0;
1037 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001038
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001039 if (BIO_read_filename(cert,filename) <= 0) {
1040 PyErr_SetString(PySSLErrorObject, "Can't open file");
1041 goto fail0;
1042 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001043
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001044 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1045 if (x == NULL) {
1046 PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");
1047 goto fail0;
1048 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001049
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001050 retval = _decode_certificate(x, verbose);
Mark Dickinson793c71c2010-08-03 18:34:53 +00001051 X509_free(x);
Bill Janssen98d19da2007-09-10 21:51:02 +00001052
1053 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001054
1055 if (cert != NULL) BIO_free(cert);
1056 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001057}
1058
1059
1060static PyObject *
1061PySSL_peercert(PySSLObject *self, PyObject *args)
1062{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001063 PyObject *retval = NULL;
1064 int len;
1065 int verification;
1066 PyObject *binary_mode = Py_None;
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001067 int b;
Bill Janssen98d19da2007-09-10 21:51:02 +00001068
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001069 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1070 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001071
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001072 if (!self->peer_cert)
1073 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001074
Antoine Pitrouc5bef752012-08-15 23:16:51 +02001075 b = PyObject_IsTrue(binary_mode);
1076 if (b < 0)
1077 return NULL;
1078 if (b) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001079 /* return cert in DER-encoded format */
Bill Janssen98d19da2007-09-10 21:51:02 +00001080
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001081 unsigned char *bytes_buf = NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001082
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001083 bytes_buf = NULL;
1084 len = i2d_X509(self->peer_cert, &bytes_buf);
1085 if (len < 0) {
1086 PySSL_SetError(self, len, __FILE__, __LINE__);
1087 return NULL;
1088 }
1089 retval = PyString_FromStringAndSize((const char *) bytes_buf, len);
1090 OPENSSL_free(bytes_buf);
1091 return retval;
Bill Janssen98d19da2007-09-10 21:51:02 +00001092
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001093 } else {
Bill Janssen98d19da2007-09-10 21:51:02 +00001094
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001095 verification = SSL_CTX_get_verify_mode(self->ctx);
1096 if ((verification & SSL_VERIFY_PEER) == 0)
1097 return PyDict_New();
1098 else
1099 return _decode_certificate (self->peer_cert, 0);
1100 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001101}
1102
1103PyDoc_STRVAR(PySSL_peercert_doc,
1104"peer_certificate([der=False]) -> certificate\n\
1105\n\
1106Returns the certificate for the peer. If no certificate was provided,\n\
1107returns None. If a certificate was provided, but not validated, returns\n\
1108an empty dictionary. Otherwise returns a dict containing information\n\
1109about the peer certificate.\n\
1110\n\
1111If the optional argument is True, returns a DER-encoded copy of the\n\
1112peer certificate, or None if no certificate was provided. This will\n\
1113return the certificate even if it wasn't validated.");
1114
1115static PyObject *PySSL_cipher (PySSLObject *self) {
1116
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001117 PyObject *retval, *v;
Benjamin Peterson8e734032010-10-13 22:10:31 +00001118 const SSL_CIPHER *current;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001119 char *cipher_name;
1120 char *cipher_protocol;
Bill Janssen98d19da2007-09-10 21:51:02 +00001121
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001122 if (self->ssl == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001123 Py_RETURN_NONE;
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001124 current = SSL_get_current_cipher(self->ssl);
1125 if (current == NULL)
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001126 Py_RETURN_NONE;
Bill Janssen98d19da2007-09-10 21:51:02 +00001127
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001128 retval = PyTuple_New(3);
1129 if (retval == NULL)
1130 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001131
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001132 cipher_name = (char *) SSL_CIPHER_get_name(current);
1133 if (cipher_name == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001134 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001135 PyTuple_SET_ITEM(retval, 0, Py_None);
1136 } else {
1137 v = PyString_FromString(cipher_name);
1138 if (v == NULL)
1139 goto fail0;
1140 PyTuple_SET_ITEM(retval, 0, v);
1141 }
1142 cipher_protocol = SSL_CIPHER_get_version(current);
1143 if (cipher_protocol == NULL) {
Hirokazu Yamamotoa9b16892010-12-09 12:12:42 +00001144 Py_INCREF(Py_None);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001145 PyTuple_SET_ITEM(retval, 1, Py_None);
1146 } else {
1147 v = PyString_FromString(cipher_protocol);
1148 if (v == NULL)
1149 goto fail0;
1150 PyTuple_SET_ITEM(retval, 1, v);
1151 }
1152 v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));
1153 if (v == NULL)
1154 goto fail0;
1155 PyTuple_SET_ITEM(retval, 2, v);
1156 return retval;
1157
Bill Janssen98d19da2007-09-10 21:51:02 +00001158 fail0:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001159 Py_DECREF(retval);
1160 return NULL;
Bill Janssen98d19da2007-09-10 21:51:02 +00001161}
1162
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001163static void PySSL_dealloc(PySSLObject *self)
1164{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001165 if (self->peer_cert) /* Possible not to have one? */
1166 X509_free (self->peer_cert);
1167 if (self->ssl)
1168 SSL_free(self->ssl);
1169 if (self->ctx)
1170 SSL_CTX_free(self->ctx);
1171 Py_XDECREF(self->Socket);
1172 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001173}
1174
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001175/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001176 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001177 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001178 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001179
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001180static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001181check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001182{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001183 fd_set fds;
1184 struct timeval tv;
1185 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001186
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001187 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1188 if (s->sock_timeout < 0.0)
1189 return SOCKET_IS_BLOCKING;
1190 else if (s->sock_timeout == 0.0)
1191 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001192
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001193 /* Guard against closed socket */
1194 if (s->sock_fd < 0)
1195 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001196
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001197 /* Prefer poll, if available, since you can poll() any fd
1198 * which can't be done with select(). */
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001199#ifdef HAVE_POLL
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001200 {
1201 struct pollfd pollfd;
1202 int timeout;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001203
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001204 pollfd.fd = s->sock_fd;
1205 pollfd.events = writing ? POLLOUT : POLLIN;
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001206
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001207 /* s->sock_timeout is in seconds, timeout in ms */
1208 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1209 PySSL_BEGIN_ALLOW_THREADS
1210 rc = poll(&pollfd, 1, timeout);
1211 PySSL_END_ALLOW_THREADS
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001212
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001213 goto normal_return;
1214 }
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001215#endif
1216
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001217 /* Guard against socket too large for select*/
Charles-François Natalifda7b372011-08-28 16:22:33 +02001218 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001219 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001220
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001221 /* Construct the arguments to select */
1222 tv.tv_sec = (int)s->sock_timeout;
1223 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1224 FD_ZERO(&fds);
1225 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001226
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001227 /* See if the socket is ready */
1228 PySSL_BEGIN_ALLOW_THREADS
1229 if (writing)
1230 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1231 else
1232 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1233 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001234
Bill Janssen934b16d2008-06-28 22:19:33 +00001235#ifdef HAVE_POLL
Anthony Baxter93ab5fa2006-07-11 02:04:09 +00001236normal_return:
Bill Janssen934b16d2008-06-28 22:19:33 +00001237#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001238 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1239 (when we are able to write or when there's something to read) */
1240 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001241}
1242
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001243static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1244{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001245 Py_buffer buf;
1246 int len;
1247 int sockstate;
1248 int err;
1249 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001250
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001251 if (!PyArg_ParseTuple(args, "s*:write", &buf))
1252 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253
Victor Stinnerc1a44262013-06-25 00:48:02 +02001254 if (buf.len > INT_MAX) {
1255 PyErr_Format(PyExc_OverflowError,
1256 "string longer than %d bytes", INT_MAX);
1257 goto error;
1258 }
1259
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001260 /* just in case the blocking state of the socket has been changed */
1261 nonblocking = (self->Socket->sock_timeout >= 0.0);
1262 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1263 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001264
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001265 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1266 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1267 PyErr_SetString(PySSLErrorObject,
1268 "The write operation timed out");
1269 goto error;
1270 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1271 PyErr_SetString(PySSLErrorObject,
1272 "Underlying socket has been closed.");
1273 goto error;
1274 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1275 PyErr_SetString(PySSLErrorObject,
1276 "Underlying socket too large for select().");
1277 goto error;
1278 }
1279 do {
1280 PySSL_BEGIN_ALLOW_THREADS
Victor Stinnerc1a44262013-06-25 00:48:02 +02001281 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001282 err = SSL_get_error(self->ssl, len);
1283 PySSL_END_ALLOW_THREADS
1284 if (PyErr_CheckSignals()) {
1285 goto error;
1286 }
1287 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001288 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001289 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001290 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001291 } else {
1292 sockstate = SOCKET_OPERATION_OK;
1293 }
1294 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1295 PyErr_SetString(PySSLErrorObject,
1296 "The write operation timed out");
1297 goto error;
1298 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1299 PyErr_SetString(PySSLErrorObject,
1300 "Underlying socket has been closed.");
1301 goto error;
1302 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1303 break;
1304 }
1305 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001306
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001307 PyBuffer_Release(&buf);
1308 if (len > 0)
1309 return PyInt_FromLong(len);
1310 else
1311 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou5ba84912009-10-19 17:59:07 +00001312
1313error:
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001314 PyBuffer_Release(&buf);
1315 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001316}
1317
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001318PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001319"write(s) -> len\n\
1320\n\
1321Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001322of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001323
Bill Janssen934b16d2008-06-28 22:19:33 +00001324static PyObject *PySSL_SSLpending(PySSLObject *self)
1325{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001326 int count = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001327
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001328 PySSL_BEGIN_ALLOW_THREADS
1329 count = SSL_pending(self->ssl);
1330 PySSL_END_ALLOW_THREADS
1331 if (count < 0)
1332 return PySSL_SetError(self, count, __FILE__, __LINE__);
1333 else
1334 return PyInt_FromLong(count);
Bill Janssen934b16d2008-06-28 22:19:33 +00001335}
1336
1337PyDoc_STRVAR(PySSL_SSLpending_doc,
1338"pending() -> count\n\
1339\n\
1340Returns the number of already decrypted bytes available for read,\n\
1341pending on the connection.\n");
1342
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001343static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1344{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001345 PyObject *buf;
1346 int count = 0;
1347 int len = 1024;
1348 int sockstate;
1349 int err;
1350 int nonblocking;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001351
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001352 if (!PyArg_ParseTuple(args, "|i:read", &len))
1353 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001355 if (!(buf = PyString_FromStringAndSize((char *) 0, len)))
1356 return NULL;
Guido van Rossum4f2c3dd2007-08-25 15:08:43 +00001357
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001358 /* just in case the blocking state of the socket has been changed */
1359 nonblocking = (self->Socket->sock_timeout >= 0.0);
1360 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1361 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Bill Janssen934b16d2008-06-28 22:19:33 +00001362
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001363 /* first check if there are bytes ready to be read */
1364 PySSL_BEGIN_ALLOW_THREADS
1365 count = SSL_pending(self->ssl);
1366 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001367
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001368 if (!count) {
1369 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1370 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1371 PyErr_SetString(PySSLErrorObject,
1372 "The read operation timed out");
1373 Py_DECREF(buf);
1374 return NULL;
1375 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1376 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001377 "Underlying socket too large for select().");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001378 Py_DECREF(buf);
1379 return NULL;
1380 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1381 if (SSL_get_shutdown(self->ssl) !=
1382 SSL_RECEIVED_SHUTDOWN)
1383 {
1384 Py_DECREF(buf);
1385 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001386 "Socket closed without SSL shutdown handshake");
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001387 return NULL;
1388 } else {
1389 /* should contain a zero-length string */
1390 _PyString_Resize(&buf, 0);
1391 return buf;
1392 }
1393 }
1394 }
1395 do {
1396 PySSL_BEGIN_ALLOW_THREADS
1397 count = SSL_read(self->ssl, PyString_AsString(buf), len);
1398 err = SSL_get_error(self->ssl, count);
1399 PySSL_END_ALLOW_THREADS
1400 if(PyErr_CheckSignals()) {
1401 Py_DECREF(buf);
1402 return NULL;
1403 }
1404 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001405 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001406 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001407 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001408 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1409 (SSL_get_shutdown(self->ssl) ==
1410 SSL_RECEIVED_SHUTDOWN))
1411 {
1412 _PyString_Resize(&buf, 0);
1413 return buf;
1414 } else {
1415 sockstate = SOCKET_OPERATION_OK;
1416 }
1417 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1418 PyErr_SetString(PySSLErrorObject,
1419 "The read operation timed out");
1420 Py_DECREF(buf);
1421 return NULL;
1422 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1423 break;
1424 }
1425 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1426 if (count <= 0) {
1427 Py_DECREF(buf);
1428 return PySSL_SetError(self, count, __FILE__, __LINE__);
1429 }
1430 if (count != len)
1431 _PyString_Resize(&buf, count);
1432 return buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001433}
1434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001435PyDoc_STRVAR(PySSL_SSLread_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001436"read([len]) -> string\n\
1437\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001438Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001439
Bill Janssen934b16d2008-06-28 22:19:33 +00001440static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1441{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001442 int err, ssl_err, sockstate, nonblocking;
1443 int zeros = 0;
Bill Janssen934b16d2008-06-28 22:19:33 +00001444
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001445 /* Guard against closed socket */
1446 if (self->Socket->sock_fd < 0) {
1447 PyErr_SetString(PySSLErrorObject,
1448 "Underlying socket has been closed.");
1449 return NULL;
1450 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001451
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001452 /* Just in case the blocking state of the socket has been changed */
1453 nonblocking = (self->Socket->sock_timeout >= 0.0);
1454 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1455 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001456
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001457 while (1) {
1458 PySSL_BEGIN_ALLOW_THREADS
1459 /* Disable read-ahead so that unwrap can work correctly.
1460 * Otherwise OpenSSL might read in too much data,
1461 * eating clear text data that happens to be
1462 * transmitted after the SSL shutdown.
Ezio Melotti419e23c2013-08-17 16:56:09 +03001463 * Should be safe to call repeatedly every time this
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001464 * function is used and the shutdown_seen_zero != 0
1465 * condition is met.
1466 */
1467 if (self->shutdown_seen_zero)
1468 SSL_set_read_ahead(self->ssl, 0);
1469 err = SSL_shutdown(self->ssl);
1470 PySSL_END_ALLOW_THREADS
1471 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1472 if (err > 0)
1473 break;
1474 if (err == 0) {
1475 /* Don't loop endlessly; instead preserve legacy
1476 behaviour of trying SSL_shutdown() only twice.
1477 This looks necessary for OpenSSL < 0.9.8m */
1478 if (++zeros > 1)
1479 break;
1480 /* Shutdown was sent, now try receiving */
1481 self->shutdown_seen_zero = 1;
1482 continue;
1483 }
Antoine Pitroua5c4b552010-04-22 23:33:02 +00001484
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001485 /* Possibly retry shutdown until timeout or failure */
1486 ssl_err = SSL_get_error(self->ssl, err);
1487 if (ssl_err == SSL_ERROR_WANT_READ)
1488 sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);
1489 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1490 sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);
1491 else
1492 break;
1493 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1494 if (ssl_err == SSL_ERROR_WANT_READ)
1495 PyErr_SetString(PySSLErrorObject,
1496 "The read operation timed out");
1497 else
1498 PyErr_SetString(PySSLErrorObject,
1499 "The write operation timed out");
1500 return NULL;
1501 }
1502 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1503 PyErr_SetString(PySSLErrorObject,
1504 "Underlying socket too large for select().");
1505 return NULL;
1506 }
1507 else if (sockstate != SOCKET_OPERATION_OK)
1508 /* Retain the SSL error code */
1509 break;
1510 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001511
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001512 if (err < 0)
1513 return PySSL_SetError(self, err, __FILE__, __LINE__);
1514 else {
1515 Py_INCREF(self->Socket);
1516 return (PyObject *) (self->Socket);
1517 }
Bill Janssen934b16d2008-06-28 22:19:33 +00001518}
1519
1520PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1521"shutdown(s) -> socket\n\
1522\n\
1523Does the SSL shutdown handshake with the remote end, and returns\n\
1524the underlying socket object.");
1525
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001526static PyMethodDef PySSLMethods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001527 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1528 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1529 PySSL_SSLwrite_doc},
1530 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1531 PySSL_SSLread_doc},
1532 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1533 PySSL_SSLpending_doc},
1534 {"server", (PyCFunction)PySSL_server, METH_NOARGS},
1535 {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},
1536 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1537 PySSL_peercert_doc},
1538 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1539 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1540 PySSL_SSLshutdown_doc},
1541 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001542};
1543
1544static PyObject *PySSL_getattr(PySSLObject *self, char *name)
1545{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001546 return Py_FindMethod(PySSLMethods, (PyObject *)self, name);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547}
1548
Jeremy Hylton938ace62002-07-17 16:30:39 +00001549static PyTypeObject PySSL_Type = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001550 PyVarObject_HEAD_INIT(NULL, 0)
1551 "ssl.SSLContext", /*tp_name*/
1552 sizeof(PySSLObject), /*tp_basicsize*/
1553 0, /*tp_itemsize*/
1554 /* methods */
1555 (destructor)PySSL_dealloc, /*tp_dealloc*/
1556 0, /*tp_print*/
1557 (getattrfunc)PySSL_getattr, /*tp_getattr*/
1558 0, /*tp_setattr*/
1559 0, /*tp_compare*/
1560 0, /*tp_repr*/
1561 0, /*tp_as_number*/
1562 0, /*tp_as_sequence*/
1563 0, /*tp_as_mapping*/
1564 0, /*tp_hash*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001565};
1566
1567#ifdef HAVE_OPENSSL_RAND
1568
1569/* helper routines for seeding the SSL PRNG */
1570static PyObject *
1571PySSL_RAND_add(PyObject *self, PyObject *args)
1572{
1573 char *buf;
1574 int len;
1575 double entropy;
1576
1577 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001578 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001579 RAND_add(buf, len, entropy);
1580 Py_INCREF(Py_None);
1581 return Py_None;
1582}
1583
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001584PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001585"RAND_add(string, entropy)\n\
1586\n\
1587Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001588bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001589
1590static PyObject *
1591PySSL_RAND_status(PyObject *self)
1592{
1593 return PyInt_FromLong(RAND_status());
1594}
1595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001596PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001597"RAND_status() -> 0 or 1\n\
1598\n\
1599Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1600It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001602
1603static PyObject *
1604PySSL_RAND_egd(PyObject *self, PyObject *arg)
1605{
1606 int bytes;
1607
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001608 if (!PyString_Check(arg))
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001609 return PyErr_Format(PyExc_TypeError,
1610 "RAND_egd() expected string, found %s",
1611 Py_TYPE(arg)->tp_name);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001612 bytes = RAND_egd(PyString_AS_STRING(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001613 if (bytes == -1) {
Antoine Pitrou2e136ab2010-05-12 14:02:34 +00001614 PyErr_SetString(PySSLErrorObject,
1615 "EGD connection failed or EGD did not return "
1616 "enough data to seed the PRNG");
1617 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001618 }
1619 return PyInt_FromLong(bytes);
1620}
1621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001622PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001623"RAND_egd(path) -> bytes\n\
1624\n\
Bill Janssen98d19da2007-09-10 21:51:02 +00001625Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1626Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimesb4ec8422013-08-17 17:25:18 +02001627fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001628
Christian Heimes0d604cf2013-08-21 13:26:05 +02001629/* Seed OpenSSL's PRNG at fork(), http://bugs.python.org/issue18747
1630 *
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001631 * The parent handler seeds the PRNG from pseudo-random data like pid, the
Christian Heimes8ee5ffd2013-08-25 14:19:16 +02001632 * current time (miliseconds or seconds) and an uninitialized array.
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001633 * The array contains stack variables that are impossible to predict
Christian Heimes0d604cf2013-08-21 13:26:05 +02001634 * on most systems, e.g. function return address (subject to ASLR), the
1635 * stack protection canary and automatic variables.
1636 * The code is inspired by Apache's ssl_rand_seed() function.
1637 *
1638 * Note:
1639 * The code uses pthread_atfork() until Python has a proper atfork API. The
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001640 * handlers are not removed from the child process. A parent handler is used
Christian Heimes8ee5ffd2013-08-25 14:19:16 +02001641 * instead of a child handler because fork() is supposed to be async-signal
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001642 * safe but the handler calls unsafe functions.
Christian Heimes0d604cf2013-08-21 13:26:05 +02001643 */
1644
1645#if defined(HAVE_PTHREAD_ATFORK) && defined(WITH_THREAD)
1646#define PYSSL_RAND_ATFORK 1
1647
1648static void
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001649PySSL_RAND_atfork_parent(void)
Christian Heimes0d604cf2013-08-21 13:26:05 +02001650{
1651 struct {
1652 char stack[128]; /* uninitialized (!) stack data, 128 is an
1653 arbitrary number. */
1654 pid_t pid; /* current pid */
1655 time_t time; /* current time */
1656 } seed;
1657
1658#ifdef WITH_VALGRIND
1659 VALGRIND_MAKE_MEM_DEFINED(seed.stack, sizeof(seed.stack));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001660#endif
Christian Heimes0d604cf2013-08-21 13:26:05 +02001661 seed.pid = getpid();
1662 seed.time = time(NULL);
Christian Heimes0d604cf2013-08-21 13:26:05 +02001663 RAND_add((unsigned char *)&seed, sizeof(seed), 0.0);
1664}
1665
1666static int
1667PySSL_RAND_atfork(void)
1668{
1669 static int registered = 0;
1670 int retval;
1671
1672 if (registered)
1673 return 0;
1674
1675 retval = pthread_atfork(NULL, /* prepare */
Christian Heimes1d0f73d2013-08-22 13:19:48 +02001676 PySSL_RAND_atfork_parent, /* parent */
1677 NULL); /* child */
Christian Heimes0d604cf2013-08-21 13:26:05 +02001678 if (retval != 0) {
1679 PyErr_SetFromErrno(PyExc_OSError);
1680 return -1;
1681 }
1682 registered = 1;
1683 return 0;
1684}
1685#endif /* HAVE_PTHREAD_ATFORK */
1686
1687#endif /* HAVE_OPENSSL_RAND */
1688
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689
1690/* List of functions exported by this module. */
1691
1692static PyMethodDef PySSL_methods[] = {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001693 {"sslwrap", PySSL_sslwrap,
1694 METH_VARARGS, ssl_doc},
1695 {"_test_decode_cert", PySSL_test_decode_certificate,
1696 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001697#ifdef HAVE_OPENSSL_RAND
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001698 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1699 PySSL_RAND_add_doc},
1700 {"RAND_egd", PySSL_RAND_egd, METH_O,
1701 PySSL_RAND_egd_doc},
1702 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1703 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001704#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001705 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001706};
1707
1708
Bill Janssen98d19da2007-09-10 21:51:02 +00001709#ifdef WITH_THREAD
1710
1711/* an implementation of OpenSSL threading operations in terms
1712 of the Python C thread library */
1713
1714static PyThread_type_lock *_ssl_locks = NULL;
1715
Christian Heimes10107812013-08-19 17:36:29 +02001716#if OPENSSL_VERSION_NUMBER >= 0x10000000
1717/* use new CRYPTO_THREADID API. */
1718static void
1719_ssl_threadid_callback(CRYPTO_THREADID *id)
1720{
1721 CRYPTO_THREADID_set_numeric(id,
1722 (unsigned long)PyThread_get_thread_ident());
1723}
1724#else
1725/* deprecated CRYPTO_set_id_callback() API. */
1726static unsigned long
1727_ssl_thread_id_function (void) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001728 return PyThread_get_thread_ident();
Bill Janssen98d19da2007-09-10 21:51:02 +00001729}
Christian Heimes10107812013-08-19 17:36:29 +02001730#endif
Bill Janssen98d19da2007-09-10 21:51:02 +00001731
1732static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001733 /* this function is needed to perform locking on shared data
1734 structures. (Note that OpenSSL uses a number of global data
1735 structures that will be implicitly shared whenever multiple threads
1736 use OpenSSL.) Multi-threaded applications will crash at random if
1737 it is not set.
Bill Janssen98d19da2007-09-10 21:51:02 +00001738
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001739 locking_function() must be able to handle up to CRYPTO_num_locks()
1740 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1741 releases it otherwise.
Bill Janssen98d19da2007-09-10 21:51:02 +00001742
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001743 file and line are the file number of the function setting the
1744 lock. They can be useful for debugging.
1745 */
Bill Janssen98d19da2007-09-10 21:51:02 +00001746
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001747 if ((_ssl_locks == NULL) ||
1748 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1749 return;
Bill Janssen98d19da2007-09-10 21:51:02 +00001750
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001751 if (mode & CRYPTO_LOCK) {
1752 PyThread_acquire_lock(_ssl_locks[n], 1);
1753 } else {
1754 PyThread_release_lock(_ssl_locks[n]);
1755 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001756}
1757
1758static int _setup_ssl_threads(void) {
1759
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001760 unsigned int i;
Bill Janssen98d19da2007-09-10 21:51:02 +00001761
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001762 if (_ssl_locks == NULL) {
1763 _ssl_locks_count = CRYPTO_num_locks();
1764 _ssl_locks = (PyThread_type_lock *)
1765 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1766 if (_ssl_locks == NULL)
1767 return 0;
1768 memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);
1769 for (i = 0; i < _ssl_locks_count; i++) {
1770 _ssl_locks[i] = PyThread_allocate_lock();
1771 if (_ssl_locks[i] == NULL) {
1772 unsigned int j;
1773 for (j = 0; j < i; j++) {
1774 PyThread_free_lock(_ssl_locks[j]);
1775 }
1776 free(_ssl_locks);
1777 return 0;
1778 }
1779 }
1780 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes10107812013-08-19 17:36:29 +02001781#if OPENSSL_VERSION_NUMBER >= 0x10000000
1782 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
1783#else
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001784 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes10107812013-08-19 17:36:29 +02001785#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001786 }
1787 return 1;
Bill Janssen98d19da2007-09-10 21:51:02 +00001788}
1789
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001790#endif /* def HAVE_THREAD */
Bill Janssen98d19da2007-09-10 21:51:02 +00001791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001792PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001794for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001795
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001796PyMODINIT_FUNC
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001797init_ssl(void)
1798{
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001799 PyObject *m, *d, *r;
1800 unsigned long libver;
1801 unsigned int major, minor, fix, patch, status;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001802
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001803 Py_TYPE(&PySSL_Type) = &PyType_Type;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001804
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001805 m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
1806 if (m == NULL)
1807 return;
1808 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001809
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001810 /* Load _socket module and its C API */
1811 if (PySocketModule_ImportModuleAndAPI())
1812 return;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001813
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001814 /* Init OpenSSL */
1815 SSL_load_error_strings();
1816 SSL_library_init();
Bill Janssen98d19da2007-09-10 21:51:02 +00001817#ifdef WITH_THREAD
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001818 /* note that this will start threading if not already started */
1819 if (!_setup_ssl_threads()) {
1820 return;
1821 }
Bill Janssen98d19da2007-09-10 21:51:02 +00001822#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001823 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001824
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001825 /* Add symbols to module dict */
1826 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1827 PySocketModule.error,
1828 NULL);
1829 if (PySSLErrorObject == NULL)
1830 return;
1831 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1832 return;
1833 if (PyDict_SetItemString(d, "SSLType",
1834 (PyObject *)&PySSL_Type) != 0)
1835 return;
1836 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1837 PY_SSL_ERROR_ZERO_RETURN);
1838 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1839 PY_SSL_ERROR_WANT_READ);
1840 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1841 PY_SSL_ERROR_WANT_WRITE);
1842 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1843 PY_SSL_ERROR_WANT_X509_LOOKUP);
1844 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1845 PY_SSL_ERROR_SYSCALL);
1846 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1847 PY_SSL_ERROR_SSL);
1848 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1849 PY_SSL_ERROR_WANT_CONNECT);
1850 /* non ssl.h errorcodes */
1851 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1852 PY_SSL_ERROR_EOF);
1853 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1854 PY_SSL_ERROR_INVALID_ERROR_CODE);
1855 /* cert requirements */
1856 PyModule_AddIntConstant(m, "CERT_NONE",
1857 PY_SSL_CERT_NONE);
1858 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1859 PY_SSL_CERT_OPTIONAL);
1860 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1861 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001862
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001863 /* protocol versions */
Victor Stinnerb1241f92011-05-10 01:52:03 +02001864#ifndef OPENSSL_NO_SSL2
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001865 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1866 PY_SSL_VERSION_SSL2);
Victor Stinnerb1241f92011-05-10 01:52:03 +02001867#endif
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001868 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1869 PY_SSL_VERSION_SSL3);
1870 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1871 PY_SSL_VERSION_SSL23);
1872 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1873 PY_SSL_VERSION_TLS1);
Antoine Pitrouf9de5342010-04-05 21:35:07 +00001874
Antoine Pitroua4c2a5c2010-05-05 15:53:45 +00001875 /* OpenSSL version */
1876 /* SSLeay() gives us the version of the library linked against,
1877 which could be different from the headers version.
1878 */
1879 libver = SSLeay();
1880 r = PyLong_FromUnsignedLong(libver);
1881 if (r == NULL)
1882 return;
1883 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1884 return;
1885 status = libver & 0xF;
1886 libver >>= 4;
1887 patch = libver & 0xFF;
1888 libver >>= 8;
1889 fix = libver & 0xFF;
1890 libver >>= 8;
1891 minor = libver & 0xFF;
1892 libver >>= 8;
1893 major = libver & 0xFF;
1894 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1895 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1896 return;
1897 r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));
1898 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1899 return;
Christian Heimes0d604cf2013-08-21 13:26:05 +02001900
1901#ifdef PYSSL_RAND_ATFORK
1902 if (PySSL_RAND_atfork() == -1)
1903 return;
1904#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001905}