blob: 52fd3f96bbe7fb8e4df7bb9aaf7241758e0526fd [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 {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
116typedef struct {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000117 PyObject_HEAD
118 PyObject *Socket; /* weakref to socket on which we're layered */
119 SSL_CTX* ctx;
120 SSL* ssl;
121 X509* peer_cert;
122 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123
124} PySSLObject;
125
Jeremy Hylton938ace62002-07-17 16:30:39 +0000126static PyTypeObject PySSL_Type;
127static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000129static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000130 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
132static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000133
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000134#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000136typedef enum {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000137 SOCKET_IS_NONBLOCKING,
138 SOCKET_IS_BLOCKING,
139 SOCKET_HAS_TIMED_OUT,
140 SOCKET_HAS_BEEN_CLOSED,
141 SOCKET_TOO_LARGE_FOR_SELECT,
142 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000143} timeout_state;
144
Thomas Woutersed03b412007-08-28 21:37:11 +0000145/* Wrap error strings with filename and line # */
146#define STRINGIFY1(x) #x
147#define STRINGIFY2(x) STRINGIFY1(x)
148#define ERRSTR1(x,y,z) (x ":" y ": " z)
149#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
150
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000151/* XXX It might be helpful to augment the error message generated
152 below with the name of the SSL function that generated the error.
153 I expect it's obvious most of the time.
154*/
155
156static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000157PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000159 PyObject *v;
160 char buf[2048];
161 char *errstr;
162 int err;
163 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000165 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000166
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000167 if (obj->ssl != NULL) {
168 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000169
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000170 switch (err) {
171 case SSL_ERROR_ZERO_RETURN:
172 errstr = "TLS/SSL connection has been closed";
173 p = PY_SSL_ERROR_ZERO_RETURN;
174 break;
175 case SSL_ERROR_WANT_READ:
176 errstr = "The operation did not complete (read)";
177 p = PY_SSL_ERROR_WANT_READ;
178 break;
179 case SSL_ERROR_WANT_WRITE:
180 p = PY_SSL_ERROR_WANT_WRITE;
181 errstr = "The operation did not complete (write)";
182 break;
183 case SSL_ERROR_WANT_X509_LOOKUP:
184 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitroua29b1812010-05-12 14:08:45 +0000185 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000186 break;
187 case SSL_ERROR_WANT_CONNECT:
188 p = PY_SSL_ERROR_WANT_CONNECT;
189 errstr = "The operation did not complete (connect)";
190 break;
191 case SSL_ERROR_SYSCALL:
192 {
193 unsigned long e = ERR_get_error();
194 if (e == 0) {
195 PySocketSockObject *s
196 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
197 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitroua29b1812010-05-12 14:08:45 +0000198 p = PY_SSL_ERROR_EOF;
199 errstr = "EOF occurred in violation of protocol";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000200 } else if (ret == -1) {
Antoine Pitroua29b1812010-05-12 14:08:45 +0000201 /* underlying BIO reported an I/O error */
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000202 Py_INCREF(s);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000203 ERR_clear_error();
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000204 v = s->errorhandler();
205 Py_DECREF(s);
206 return v;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000207 } else { /* possible? */
Antoine Pitroua29b1812010-05-12 14:08:45 +0000208 p = PY_SSL_ERROR_SYSCALL;
209 errstr = "Some I/O error occurred";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000210 }
211 } else {
212 p = PY_SSL_ERROR_SYSCALL;
213 /* XXX Protected by global interpreter lock */
214 errstr = ERR_error_string(e, NULL);
215 }
216 break;
217 }
218 case SSL_ERROR_SSL:
219 {
220 unsigned long e = ERR_get_error();
221 p = PY_SSL_ERROR_SSL;
222 if (e != 0)
223 /* XXX Protected by global interpreter lock */
224 errstr = ERR_error_string(e, NULL);
225 else { /* possible? */
Antoine Pitroua29b1812010-05-12 14:08:45 +0000226 errstr = "A failure in the SSL library occurred";
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000227 }
228 break;
229 }
230 default:
231 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
232 errstr = "Invalid error code";
233 }
234 } else {
235 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
236 }
237 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000238 ERR_clear_error();
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000239 v = Py_BuildValue("(is)", p, buf);
240 if (v != NULL) {
241 PyErr_SetObject(PySSLErrorObject, v);
242 Py_DECREF(v);
243 }
244 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000245}
246
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247static PyObject *
248_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
249
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000250 char buf[2048];
251 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000253 if (errstr == NULL) {
254 errcode = ERR_peek_last_error();
255 errstr = ERR_error_string(errcode, NULL);
256 }
257 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou321257d2010-05-16 23:18:00 +0000258 ERR_clear_error();
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000259 v = Py_BuildValue("(is)", errcode, buf);
260 if (v != NULL) {
261 PyErr_SetObject(PySSLErrorObject, v);
262 Py_DECREF(v);
263 }
264 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000265}
266
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000267static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000268newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000269 enum py_ssl_server_or_client socket_type,
270 enum py_ssl_cert_requirements certreq,
271 enum py_ssl_version proto_version,
272 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000273{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000274 PySSLObject *self;
275 char *errstr = NULL;
276 int ret;
277 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000278
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000279 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
280 if (self == NULL)
281 return NULL;
282 self->peer_cert = NULL;
283 self->ssl = NULL;
284 self->ctx = NULL;
285 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000286
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000287 /* Make sure the SSL error state is initialized */
288 (void) ERR_get_state();
289 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000290
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000291 if ((key_file && !cert_file) || (!key_file && cert_file)) {
292 errstr = ERRSTR("Both the key & certificate files "
293 "must be specified");
294 goto fail;
295 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000296
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000297 if ((socket_type == PY_SSL_SERVER) &&
298 ((key_file == NULL) || (cert_file == NULL))) {
299 errstr = ERRSTR("Both the key & certificate files "
300 "must be specified for server-side operation");
301 goto fail;
302 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000303
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000304 PySSL_BEGIN_ALLOW_THREADS
305 if (proto_version == PY_SSL_VERSION_TLS1)
306 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
307 else if (proto_version == PY_SSL_VERSION_SSL3)
308 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
309 else if (proto_version == PY_SSL_VERSION_SSL2)
310 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
311 else if (proto_version == PY_SSL_VERSION_SSL23)
312 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
313 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000314
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000315 if (self->ctx == NULL) {
316 errstr = ERRSTR("Invalid SSL protocol variant specified.");
317 goto fail;
318 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000319
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000320 if (certreq != PY_SSL_CERT_NONE) {
321 if (cacerts_file == NULL) {
322 errstr = ERRSTR("No root certificates specified for "
Antoine Pitroua29b1812010-05-12 14:08:45 +0000323 "verification of other-side certificates.");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000324 goto fail;
325 } else {
326 PySSL_BEGIN_ALLOW_THREADS
327 ret = SSL_CTX_load_verify_locations(self->ctx,
328 cacerts_file,
329 NULL);
330 PySSL_END_ALLOW_THREADS
331 if (ret != 1) {
332 _setSSLError(NULL, 0, __FILE__, __LINE__);
333 goto fail;
334 }
335 }
336 }
337 if (key_file) {
338 PySSL_BEGIN_ALLOW_THREADS
339 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
340 SSL_FILETYPE_PEM);
341 PySSL_END_ALLOW_THREADS
342 if (ret != 1) {
343 _setSSLError(NULL, ret, __FILE__, __LINE__);
344 goto fail;
345 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000347 PySSL_BEGIN_ALLOW_THREADS
348 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
349 cert_file);
350 PySSL_END_ALLOW_THREADS
351 if (ret != 1) {
352 /*
353 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
354 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
355 */
356 if (ERR_peek_last_error() != 0) {
357 _setSSLError(NULL, ret, __FILE__, __LINE__);
358 goto fail;
359 }
360 }
361 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000363 /* ssl compatibility */
364 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000365
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000366 verification_mode = SSL_VERIFY_NONE;
367 if (certreq == PY_SSL_CERT_OPTIONAL)
368 verification_mode = SSL_VERIFY_PEER;
369 else if (certreq == PY_SSL_CERT_REQUIRED)
370 verification_mode = (SSL_VERIFY_PEER |
371 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
372 SSL_CTX_set_verify(self->ctx, verification_mode,
373 NULL); /* set verify lvl */
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000375 PySSL_BEGIN_ALLOW_THREADS
376 self->ssl = SSL_new(self->ctx); /* New ssl struct */
377 PySSL_END_ALLOW_THREADS
378 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000379#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000380 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitroud59ceb52010-04-09 20:47:00 +0000381#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000382
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000383 /* If the socket is in non-blocking mode or timeout mode, set the BIO
384 * to non-blocking mode (blocking is the default)
385 */
386 if (Sock->sock_timeout >= 0.0) {
387 /* Set both the read and write BIO's to non-blocking mode */
388 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
389 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
390 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000391
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000392 PySSL_BEGIN_ALLOW_THREADS
393 if (socket_type == PY_SSL_CLIENT)
394 SSL_set_connect_state(self->ssl);
395 else
396 SSL_set_accept_state(self->ssl);
397 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000398
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000399 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
400 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000401 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000402 if (errstr)
403 PyErr_SetString(PySSLErrorObject, errstr);
404 Py_DECREF(self);
405 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406}
407
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000409PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000411 PySocketSockObject *Sock;
412 int server_side = 0;
413 int verification_mode = PY_SSL_CERT_NONE;
414 int protocol = PY_SSL_VERSION_SSL23;
415 char *key_file = NULL;
416 char *cert_file = NULL;
417 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000418
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000419 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
420 PySocketModule.Sock_Type,
421 &Sock,
422 &server_side,
423 &key_file, &cert_file,
424 &verification_mode, &protocol,
425 &cacerts_file))
426 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000427
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000428 /*
429 fprintf(stderr,
430 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
431 "protocol %d, certs %p\n",
432 server_side, key_file, cert_file, verification_mode,
433 protocol, cacerts_file);
434 */
Thomas Woutersed03b412007-08-28 21:37:11 +0000435
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000436 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
437 server_side, verification_mode,
438 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000439}
440
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000441PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000442"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
443" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000444
445/* SSL object methods */
446
Bill Janssen6e027db2007-11-15 22:23:56 +0000447static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000449 int ret;
450 int err;
451 int sockstate, nonblocking;
452 PySocketSockObject *sock
453 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitrouec146182010-04-24 21:30:20 +0000454
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000455 if (((PyObject*)sock) == Py_None) {
456 _setSSLError("Underlying socket connection gone",
457 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
458 return NULL;
459 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000460 Py_INCREF(sock);
Antoine Pitrouec146182010-04-24 21:30:20 +0000461
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000462 /* just in case the blocking state of the socket has been changed */
463 nonblocking = (sock->sock_timeout >= 0.0);
464 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
465 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000466
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000467 /* Actually negotiate SSL connection */
468 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
469 sockstate = 0;
470 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000471 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000472 ret = SSL_do_handshake(self->ssl);
473 err = SSL_get_error(self->ssl, ret);
474 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000475 if (PyErr_CheckSignals())
476 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000477 if (err == SSL_ERROR_WANT_READ) {
478 sockstate = check_socket_and_wait_for_timeout(sock, 0);
479 } else if (err == SSL_ERROR_WANT_WRITE) {
480 sockstate = check_socket_and_wait_for_timeout(sock, 1);
481 } else {
482 sockstate = SOCKET_OPERATION_OK;
483 }
484 if (sockstate == SOCKET_HAS_TIMED_OUT) {
485 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000486 ERRSTR("The handshake operation timed out"));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000487 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000488 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
489 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000490 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000491 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000492 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
493 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000494 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000495 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000496 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
497 break;
498 }
499 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000500 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000501 if (ret < 1)
502 return PySSL_SetError(self, ret, __FILE__, __LINE__);
503 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000504
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000505 if (self->peer_cert)
506 X509_free (self->peer_cert);
507 PySSL_BEGIN_ALLOW_THREADS
508 self->peer_cert = SSL_get_peer_certificate(self->ssl);
509 PySSL_END_ALLOW_THREADS
510
511 Py_INCREF(Py_None);
512 return Py_None;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +0000513
514error:
515 Py_DECREF(sock);
516 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000517}
518
Thomas Woutersed03b412007-08-28 21:37:11 +0000519static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000521
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000522 char namebuf[X509_NAME_MAXLEN];
523 int buflen;
524 PyObject *name_obj;
525 PyObject *value_obj;
526 PyObject *attr;
527 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000528
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000529 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
530 if (buflen < 0) {
531 _setSSLError(NULL, 0, __FILE__, __LINE__);
532 goto fail;
533 }
534 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
535 if (name_obj == NULL)
536 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000537
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000538 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
539 if (buflen < 0) {
540 _setSSLError(NULL, 0, __FILE__, __LINE__);
541 Py_DECREF(name_obj);
542 goto fail;
543 }
544 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitroua29b1812010-05-12 14:08:45 +0000545 buflen, "strict");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000546 OPENSSL_free(valuebuf);
547 if (value_obj == NULL) {
548 Py_DECREF(name_obj);
549 goto fail;
550 }
551 attr = PyTuple_New(2);
552 if (attr == NULL) {
553 Py_DECREF(name_obj);
554 Py_DECREF(value_obj);
555 goto fail;
556 }
557 PyTuple_SET_ITEM(attr, 0, name_obj);
558 PyTuple_SET_ITEM(attr, 1, value_obj);
559 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000560
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000562 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000563}
564
565static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000567{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000568 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
569 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
570 PyObject *rdnt;
571 PyObject *attr = NULL; /* tuple to hold an attribute */
572 int entry_count = X509_NAME_entry_count(xname);
573 X509_NAME_ENTRY *entry;
574 ASN1_OBJECT *name;
575 ASN1_STRING *value;
576 int index_counter;
577 int rdn_level = -1;
578 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000580 dn = PyList_New(0);
581 if (dn == NULL)
582 return NULL;
583 /* now create another tuple to hold the top-level RDN */
584 rdn = PyList_New(0);
585 if (rdn == NULL)
586 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000588 for (index_counter = 0;
589 index_counter < entry_count;
590 index_counter++)
591 {
592 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000594 /* check to see if we've gotten to a new RDN */
595 if (rdn_level >= 0) {
596 if (rdn_level != entry->set) {
597 /* yes, new RDN */
598 /* add old RDN to DN */
599 rdnt = PyList_AsTuple(rdn);
600 Py_DECREF(rdn);
601 if (rdnt == NULL)
602 goto fail0;
603 retcode = PyList_Append(dn, rdnt);
604 Py_DECREF(rdnt);
605 if (retcode < 0)
606 goto fail0;
607 /* create new RDN */
608 rdn = PyList_New(0);
609 if (rdn == NULL)
610 goto fail0;
611 }
612 }
613 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000615 /* now add this attribute to the current RDN */
616 name = X509_NAME_ENTRY_get_object(entry);
617 value = X509_NAME_ENTRY_get_data(entry);
618 attr = _create_tuple_for_attribute(name, value);
619 /*
620 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
621 entry->set,
622 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
623 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
624 */
625 if (attr == NULL)
626 goto fail1;
627 retcode = PyList_Append(rdn, attr);
628 Py_DECREF(attr);
629 if (retcode < 0)
630 goto fail1;
631 }
632 /* now, there's typically a dangling RDN */
633 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
634 rdnt = PyList_AsTuple(rdn);
635 Py_DECREF(rdn);
636 if (rdnt == NULL)
637 goto fail0;
638 retcode = PyList_Append(dn, rdnt);
639 Py_DECREF(rdnt);
640 if (retcode < 0)
641 goto fail0;
642 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000644 /* convert list to tuple */
645 rdnt = PyList_AsTuple(dn);
646 Py_DECREF(dn);
647 if (rdnt == NULL)
648 return NULL;
649 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
651 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000652 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
654 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000655 Py_XDECREF(dn);
656 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657}
658
659static PyObject *
660_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000661
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000662 /* this code follows the procedure outlined in
663 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
664 function to extract the STACK_OF(GENERAL_NAME),
665 then iterates through the stack to add the
666 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000668 int i, j;
669 PyObject *peer_alt_names = Py_None;
670 PyObject *v, *t;
671 X509_EXTENSION *ext = NULL;
672 GENERAL_NAMES *names = NULL;
673 GENERAL_NAME *name;
674 X509V3_EXT_METHOD *method;
675 BIO *biobuf = NULL;
676 char buf[2048];
677 char *vptr;
678 int len;
679 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner117ff172010-03-02 22:49:30 +0000680#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000681 const unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000682#else
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000683 unsigned char *p;
Victor Stinner117ff172010-03-02 22:49:30 +0000684#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000686 if (certificate == NULL)
687 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000688
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000689 /* get a memory buffer */
690 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000692 i = 0;
693 while ((i = X509_get_ext_by_NID(
694 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000696 if (peer_alt_names == Py_None) {
697 peer_alt_names = PyList_New(0);
698 if (peer_alt_names == NULL)
699 goto fail;
700 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000701
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000702 /* now decode the altName */
703 ext = X509_get_ext(certificate, i);
704 if(!(method = X509V3_EXT_get(ext))) {
705 PyErr_SetString
706 (PySSLErrorObject,
707 ERRSTR("No method for internalizing subjectAltName!"));
708 goto fail;
709 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000711 p = ext->value->data;
712 if (method->it)
713 names = (GENERAL_NAMES*)
714 (ASN1_item_d2i(NULL,
715 &p,
716 ext->value->length,
717 ASN1_ITEM_ptr(method->it)));
718 else
719 names = (GENERAL_NAMES*)
720 (method->d2i(NULL,
721 &p,
722 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000724 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000726 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000727
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000728 name = sk_GENERAL_NAME_value(names, j);
729 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000731 /* we special-case DirName as a tuple of
732 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000734 t = PyTuple_New(2);
735 if (t == NULL) {
736 goto fail;
737 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000739 v = PyUnicode_FromString("DirName");
740 if (v == NULL) {
741 Py_DECREF(t);
742 goto fail;
743 }
744 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000746 v = _create_tuple_for_X509_NAME (name->d.dirn);
747 if (v == NULL) {
748 Py_DECREF(t);
749 goto fail;
750 }
751 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000752
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000753 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000755 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000757 (void) BIO_reset(biobuf);
758 GENERAL_NAME_print(biobuf, name);
759 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
760 if (len < 0) {
761 _setSSLError(NULL, 0, __FILE__, __LINE__);
762 goto fail;
763 }
764 vptr = strchr(buf, ':');
765 if (vptr == NULL)
766 goto fail;
767 t = PyTuple_New(2);
768 if (t == NULL)
769 goto fail;
770 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
771 if (v == NULL) {
772 Py_DECREF(t);
773 goto fail;
774 }
775 PyTuple_SET_ITEM(t, 0, v);
776 v = PyUnicode_FromStringAndSize((vptr + 1),
777 (len - (vptr - buf + 1)));
778 if (v == NULL) {
779 Py_DECREF(t);
780 goto fail;
781 }
782 PyTuple_SET_ITEM(t, 1, v);
783 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000785 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000787 if (PyList_Append(peer_alt_names, t) < 0) {
788 Py_DECREF(t);
789 goto fail;
790 }
791 Py_DECREF(t);
792 }
793 }
794 BIO_free(biobuf);
795 if (peer_alt_names != Py_None) {
796 v = PyList_AsTuple(peer_alt_names);
797 Py_DECREF(peer_alt_names);
798 return v;
799 } else {
800 return peer_alt_names;
801 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000802
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
804 fail:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000805 if (biobuf != NULL)
806 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000808 if (peer_alt_names != Py_None) {
809 Py_XDECREF(peer_alt_names);
810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000812 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813}
814
815static PyObject *
816_decode_certificate (X509 *certificate, int verbose) {
817
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000818 PyObject *retval = NULL;
819 BIO *biobuf = NULL;
820 PyObject *peer;
821 PyObject *peer_alt_names = NULL;
822 PyObject *issuer;
823 PyObject *version;
824 PyObject *sn_obj;
825 ASN1_INTEGER *serialNumber;
826 char buf[2048];
827 int len;
828 ASN1_TIME *notBefore, *notAfter;
829 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000830
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000831 retval = PyDict_New();
832 if (retval == NULL)
833 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000834
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000835 peer = _create_tuple_for_X509_NAME(
836 X509_get_subject_name(certificate));
837 if (peer == NULL)
838 goto fail0;
839 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
840 Py_DECREF(peer);
841 goto fail0;
842 }
843 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000844
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000845 if (verbose) {
846 issuer = _create_tuple_for_X509_NAME(
847 X509_get_issuer_name(certificate));
848 if (issuer == NULL)
849 goto fail0;
850 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
851 Py_DECREF(issuer);
852 goto fail0;
853 }
854 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000855
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000856 version = PyLong_FromLong(X509_get_version(certificate) + 1);
857 if (PyDict_SetItemString(retval, "version", version) < 0) {
858 Py_DECREF(version);
859 goto fail0;
860 }
861 Py_DECREF(version);
862 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000863
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000864 /* get a memory buffer */
865 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000866
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000867 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000868
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000869 (void) BIO_reset(biobuf);
870 serialNumber = X509_get_serialNumber(certificate);
871 /* should not exceed 20 octets, 160 bits, so buf is big enough */
872 i2a_ASN1_INTEGER(biobuf, serialNumber);
873 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
874 if (len < 0) {
875 _setSSLError(NULL, 0, __FILE__, __LINE__);
876 goto fail1;
877 }
878 sn_obj = PyUnicode_FromStringAndSize(buf, len);
879 if (sn_obj == NULL)
880 goto fail1;
881 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
882 Py_DECREF(sn_obj);
883 goto fail1;
884 }
885 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000887 (void) BIO_reset(biobuf);
888 notBefore = X509_get_notBefore(certificate);
889 ASN1_TIME_print(biobuf, notBefore);
890 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
891 if (len < 0) {
892 _setSSLError(NULL, 0, __FILE__, __LINE__);
893 goto fail1;
894 }
895 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
896 if (pnotBefore == NULL)
897 goto fail1;
898 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
899 Py_DECREF(pnotBefore);
900 goto fail1;
901 }
902 Py_DECREF(pnotBefore);
903 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000904
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000905 (void) BIO_reset(biobuf);
906 notAfter = X509_get_notAfter(certificate);
907 ASN1_TIME_print(biobuf, notAfter);
908 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
909 if (len < 0) {
910 _setSSLError(NULL, 0, __FILE__, __LINE__);
911 goto fail1;
912 }
913 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
914 if (pnotAfter == NULL)
915 goto fail1;
916 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
917 Py_DECREF(pnotAfter);
918 goto fail1;
919 }
920 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000921
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000922 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000924 peer_alt_names = _get_peer_alt_names(certificate);
925 if (peer_alt_names == NULL)
926 goto fail1;
927 else if (peer_alt_names != Py_None) {
928 if (PyDict_SetItemString(retval, "subjectAltName",
929 peer_alt_names) < 0) {
930 Py_DECREF(peer_alt_names);
931 goto fail1;
932 }
933 Py_DECREF(peer_alt_names);
934 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000935
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000936 BIO_free(biobuf);
937 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000938
939 fail1:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000940 if (biobuf != NULL)
941 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000942 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000943 Py_XDECREF(retval);
944 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000945}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000946
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947
948static PyObject *
949PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
950
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000951 PyObject *retval = NULL;
952 char *filename = NULL;
953 X509 *x=NULL;
954 BIO *cert;
955 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000957 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
958 &filename, &verbose))
959 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000961 if ((cert=BIO_new(BIO_s_file())) == NULL) {
962 PyErr_SetString(PySSLErrorObject,
963 "Can't malloc memory to read file");
964 goto fail0;
965 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000967 if (BIO_read_filename(cert,filename) <= 0) {
968 PyErr_SetString(PySSLErrorObject,
969 "Can't open file");
970 goto fail0;
971 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000973 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
974 if (x == NULL) {
975 PyErr_SetString(PySSLErrorObject,
976 "Error decoding PEM-encoded file");
977 goto fail0;
978 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000979
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000980 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
982 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000983
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000984 if (cert != NULL) BIO_free(cert);
985 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986}
987
988
989static PyObject *
990PySSL_peercert(PySSLObject *self, PyObject *args)
991{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000992 PyObject *retval = NULL;
993 int len;
994 int verification;
995 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000996
Antoine Pitrou30dc1a72010-05-05 16:01:14 +0000997 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
998 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001000 if (!self->peer_cert)
1001 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001003 if (PyObject_IsTrue(binary_mode)) {
1004 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001005
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001006 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001008 bytes_buf = NULL;
1009 len = i2d_X509(self->peer_cert, &bytes_buf);
1010 if (len < 0) {
1011 PySSL_SetError(self, len, __FILE__, __LINE__);
1012 return NULL;
1013 }
1014 /* this is actually an immutable bytes sequence */
1015 retval = PyBytes_FromStringAndSize
1016 ((const char *) bytes_buf, len);
1017 OPENSSL_free(bytes_buf);
1018 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001019
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001020 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001021
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001022 verification = SSL_CTX_get_verify_mode(self->ctx);
1023 if ((verification & SSL_VERIFY_PEER) == 0)
1024 return PyDict_New();
1025 else
1026 return _decode_certificate (self->peer_cert, 0);
1027 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001028}
1029
1030PyDoc_STRVAR(PySSL_peercert_doc,
1031"peer_certificate([der=False]) -> certificate\n\
1032\n\
1033Returns the certificate for the peer. If no certificate was provided,\n\
1034returns None. If a certificate was provided, but not validated, returns\n\
1035an empty dictionary. Otherwise returns a dict containing information\n\
1036about the peer certificate.\n\
1037\n\
1038If the optional argument is True, returns a DER-encoded copy of the\n\
1039peer certificate, or None if no certificate was provided. This will\n\
1040return the certificate even if it wasn't validated.");
1041
1042static PyObject *PySSL_cipher (PySSLObject *self) {
1043
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001044 PyObject *retval, *v;
1045 SSL_CIPHER *current;
1046 char *cipher_name;
1047 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001048
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001049 if (self->ssl == NULL)
1050 return Py_None;
1051 current = SSL_get_current_cipher(self->ssl);
1052 if (current == NULL)
1053 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001055 retval = PyTuple_New(3);
1056 if (retval == NULL)
1057 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001059 cipher_name = (char *) SSL_CIPHER_get_name(current);
1060 if (cipher_name == NULL) {
1061 PyTuple_SET_ITEM(retval, 0, Py_None);
1062 } else {
1063 v = PyUnicode_FromString(cipher_name);
1064 if (v == NULL)
1065 goto fail0;
1066 PyTuple_SET_ITEM(retval, 0, v);
1067 }
1068 cipher_protocol = SSL_CIPHER_get_version(current);
1069 if (cipher_protocol == NULL) {
1070 PyTuple_SET_ITEM(retval, 1, Py_None);
1071 } else {
1072 v = PyUnicode_FromString(cipher_protocol);
1073 if (v == NULL)
1074 goto fail0;
1075 PyTuple_SET_ITEM(retval, 1, v);
1076 }
1077 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1078 if (v == NULL)
1079 goto fail0;
1080 PyTuple_SET_ITEM(retval, 2, v);
1081 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001082
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083 fail0:
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001084 Py_DECREF(retval);
1085 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001086}
1087
Guido van Rossume6650f92007-12-06 19:05:55 +00001088static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001089{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001090 if (self->peer_cert) /* Possible not to have one? */
1091 X509_free (self->peer_cert);
1092 if (self->ssl)
1093 SSL_free(self->ssl);
1094 if (self->ctx)
1095 SSL_CTX_free(self->ctx);
1096 Py_XDECREF(self->Socket);
1097 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001098}
1099
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001100/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001101 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001102 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001103 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001104
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001105static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001106check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001107{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001108 fd_set fds;
1109 struct timeval tv;
1110 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001111
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001112 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1113 if (s->sock_timeout < 0.0)
1114 return SOCKET_IS_BLOCKING;
1115 else if (s->sock_timeout == 0.0)
1116 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001117
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001118 /* Guard against closed socket */
1119 if (s->sock_fd < 0)
1120 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001121
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001122 /* Prefer poll, if available, since you can poll() any fd
1123 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001124#ifdef HAVE_POLL
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001125 {
1126 struct pollfd pollfd;
1127 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001129 pollfd.fd = s->sock_fd;
1130 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001131
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001132 /* s->sock_timeout is in seconds, timeout in ms */
1133 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1134 PySSL_BEGIN_ALLOW_THREADS
1135 rc = poll(&pollfd, 1, timeout);
1136 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001137
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001138 goto normal_return;
1139 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001140#endif
1141
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001142 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001143#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001144 if (s->sock_fd >= FD_SETSIZE)
1145 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001146#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001147
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001148 /* Construct the arguments to select */
1149 tv.tv_sec = (int)s->sock_timeout;
1150 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1151 FD_ZERO(&fds);
1152 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001153
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001154 /* See if the socket is ready */
1155 PySSL_BEGIN_ALLOW_THREADS
1156 if (writing)
1157 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1158 else
1159 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1160 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001161
Bill Janssen6e027db2007-11-15 22:23:56 +00001162#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001163normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001164#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001165 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1166 (when we are able to write or when there's something to read) */
1167 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001168}
1169
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001170static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1171{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001172 char *data;
1173 int len;
1174 int count;
1175 int sockstate;
1176 int err;
1177 int nonblocking;
1178 PySocketSockObject *sock
1179 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001180
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001181 if (((PyObject*)sock) == Py_None) {
1182 _setSSLError("Underlying socket connection gone",
1183 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1184 return NULL;
1185 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001186 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001187
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001188 if (!PyArg_ParseTuple(args, "y#:write", &data, &count)) {
1189 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001190 return NULL;
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001191 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001192
1193 /* just in case the blocking state of the socket has been changed */
1194 nonblocking = (sock->sock_timeout >= 0.0);
1195 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1196 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1197
1198 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1199 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1200 PyErr_SetString(PySSLErrorObject,
1201 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001202 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001203 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1204 PyErr_SetString(PySSLErrorObject,
1205 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001206 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001207 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1208 PyErr_SetString(PySSLErrorObject,
1209 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001210 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001211 }
1212 do {
1213 err = 0;
1214 PySSL_BEGIN_ALLOW_THREADS
1215 len = SSL_write(self->ssl, data, count);
1216 err = SSL_get_error(self->ssl, len);
1217 PySSL_END_ALLOW_THREADS
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001218 if (PyErr_CheckSignals())
1219 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001220 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001221 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001222 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001223 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001224 } else {
1225 sockstate = SOCKET_OPERATION_OK;
1226 }
1227 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1228 PyErr_SetString(PySSLErrorObject,
1229 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001230 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001231 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1232 PyErr_SetString(PySSLErrorObject,
1233 "Underlying socket has been closed.");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001234 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001235 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1236 break;
1237 }
1238 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001239
1240 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001241 if (len > 0)
1242 return PyLong_FromLong(len);
1243 else
1244 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001245
1246error:
1247 Py_DECREF(sock);
1248 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001249}
1250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001252"write(s) -> len\n\
1253\n\
1254Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001255of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001256
Bill Janssen6e027db2007-11-15 22:23:56 +00001257static PyObject *PySSL_SSLpending(PySSLObject *self)
1258{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001259 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001260
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001261 PySSL_BEGIN_ALLOW_THREADS
1262 count = SSL_pending(self->ssl);
1263 PySSL_END_ALLOW_THREADS
1264 if (count < 0)
1265 return PySSL_SetError(self, count, __FILE__, __LINE__);
1266 else
1267 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001268}
1269
1270PyDoc_STRVAR(PySSL_SSLpending_doc,
1271"pending() -> count\n\
1272\n\
1273Returns the number of already decrypted bytes available for read,\n\
1274pending on the connection.\n");
1275
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001276static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1277{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001278 PyObject *dest = NULL;
1279 Py_buffer buf;
1280 int buf_passed = 0;
1281 int count = -1;
1282 char *mem;
1283 /* XXX this should use Py_ssize_t */
1284 int len = 1024;
1285 int sockstate;
1286 int err;
1287 int nonblocking;
1288 PySocketSockObject *sock
1289 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001290
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001291 if (((PyObject*)sock) == Py_None) {
1292 _setSSLError("Underlying socket connection gone",
1293 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1294 return NULL;
1295 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001296 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001297
1298 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001299 goto error;
1300
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001301 if ((dest == NULL) || (dest == Py_None)) {
1302 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001303 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001304 mem = PyByteArray_AS_STRING(dest);
1305 } else if (PyLong_Check(dest)) {
1306 len = PyLong_AS_LONG(dest);
1307 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001308 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001309 mem = PyByteArray_AS_STRING(dest);
1310 } else {
1311 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001312 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001313 mem = buf.buf;
1314 len = buf.len;
1315 if ((count > 0) && (count <= len))
1316 len = count;
1317 buf_passed = 1;
1318 }
1319
1320 /* just in case the blocking state of the socket has been changed */
1321 nonblocking = (sock->sock_timeout >= 0.0);
1322 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1323 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1324
1325 /* first check if there are bytes ready to be read */
1326 PySSL_BEGIN_ALLOW_THREADS
1327 count = SSL_pending(self->ssl);
1328 PySSL_END_ALLOW_THREADS
1329
1330 if (!count) {
1331 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1332 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1333 PyErr_SetString(PySSLErrorObject,
1334 "The read operation timed out");
1335 goto error;
1336 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1337 PyErr_SetString(PySSLErrorObject,
Antoine Pitroua29b1812010-05-12 14:08:45 +00001338 "Underlying socket too large for select().");
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001339 goto error;
1340 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1341 count = 0;
1342 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001343 }
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001344 }
1345 do {
1346 err = 0;
1347 PySSL_BEGIN_ALLOW_THREADS
1348 count = SSL_read(self->ssl, mem, len);
1349 err = SSL_get_error(self->ssl, count);
1350 PySSL_END_ALLOW_THREADS
1351 if (PyErr_CheckSignals())
1352 goto error;
1353 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001354 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001355 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001356 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001357 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1358 (SSL_get_shutdown(self->ssl) ==
1359 SSL_RECEIVED_SHUTDOWN))
1360 {
1361 count = 0;
1362 goto done;
1363 } else {
1364 sockstate = SOCKET_OPERATION_OK;
1365 }
1366 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1367 PyErr_SetString(PySSLErrorObject,
1368 "The read operation timed out");
1369 goto error;
1370 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1371 break;
1372 }
1373 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1374 if (count <= 0) {
1375 PySSL_SetError(self, count, __FILE__, __LINE__);
1376 goto error;
1377 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001378 done:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001379 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001380 if (!buf_passed) {
1381 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1382 Py_DECREF(dest);
1383 return res;
1384 } else {
1385 PyBuffer_Release(&buf);
1386 return PyLong_FromLong(count);
1387 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001388 error:
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001389 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001390 if (!buf_passed) {
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001391 Py_XDECREF(dest);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001392 } else {
1393 PyBuffer_Release(&buf);
1394 }
1395 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001396}
1397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001398PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001399"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001401Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001402
Bill Janssen40a0f662008-08-12 16:56:25 +00001403static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1404{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001405 int err, ssl_err, sockstate, nonblocking;
1406 int zeros = 0;
1407 PySocketSockObject *sock
1408 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001409
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001410 /* Guard against closed socket */
1411 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1412 _setSSLError("Underlying socket connection gone",
1413 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1414 return NULL;
1415 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001416 Py_INCREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001417
1418 /* Just in case the blocking state of the socket has been changed */
1419 nonblocking = (sock->sock_timeout >= 0.0);
1420 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1421 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1422
1423 while (1) {
1424 PySSL_BEGIN_ALLOW_THREADS
1425 /* Disable read-ahead so that unwrap can work correctly.
1426 * Otherwise OpenSSL might read in too much data,
1427 * eating clear text data that happens to be
1428 * transmitted after the SSL shutdown.
1429 * Should be safe to call repeatedly everytime this
1430 * function is used and the shutdown_seen_zero != 0
1431 * condition is met.
1432 */
1433 if (self->shutdown_seen_zero)
1434 SSL_set_read_ahead(self->ssl, 0);
1435 err = SSL_shutdown(self->ssl);
1436 PySSL_END_ALLOW_THREADS
1437 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1438 if (err > 0)
1439 break;
1440 if (err == 0) {
1441 /* Don't loop endlessly; instead preserve legacy
1442 behaviour of trying SSL_shutdown() only twice.
1443 This looks necessary for OpenSSL < 0.9.8m */
1444 if (++zeros > 1)
1445 break;
1446 /* Shutdown was sent, now try receiving */
1447 self->shutdown_seen_zero = 1;
1448 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001449 }
1450
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001451 /* Possibly retry shutdown until timeout or failure */
1452 ssl_err = SSL_get_error(self->ssl, err);
1453 if (ssl_err == SSL_ERROR_WANT_READ)
1454 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1455 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1456 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1457 else
1458 break;
1459 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1460 if (ssl_err == SSL_ERROR_WANT_READ)
1461 PyErr_SetString(PySSLErrorObject,
1462 "The read operation timed out");
1463 else
1464 PyErr_SetString(PySSLErrorObject,
1465 "The write operation timed out");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001466 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001467 }
1468 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1469 PyErr_SetString(PySSLErrorObject,
1470 "Underlying socket too large for select().");
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001471 goto error;
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001472 }
1473 else if (sockstate != SOCKET_OPERATION_OK)
1474 /* Retain the SSL error code */
1475 break;
1476 }
Antoine Pitrou5a1c4d12010-04-23 21:11:10 +00001477
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001478 if (err < 0) {
1479 Py_DECREF(sock);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001480 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001481 }
Antoine Pitrou94fbaac2010-06-24 22:49:57 +00001482 else
1483 /* It's already INCREF'ed */
1484 return (PyObject *) sock;
1485
1486error:
1487 Py_DECREF(sock);
1488 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001489}
1490
1491PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1492"shutdown(s) -> socket\n\
1493\n\
1494Does the SSL shutdown handshake with the remote end, and returns\n\
1495the underlying socket object.");
1496
1497
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001498static PyMethodDef PySSLMethods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001499 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1500 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1501 PySSL_SSLwrite_doc},
1502 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1503 PySSL_SSLread_doc},
1504 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1505 PySSL_SSLpending_doc},
1506 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1507 PySSL_peercert_doc},
1508 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1509 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1510 PySSL_SSLshutdown_doc},
1511 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001512};
1513
Jeremy Hylton938ace62002-07-17 16:30:39 +00001514static PyTypeObject PySSL_Type = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001515 PyVarObject_HEAD_INIT(NULL, 0)
1516 "ssl.SSLContext", /*tp_name*/
1517 sizeof(PySSLObject), /*tp_basicsize*/
1518 0, /*tp_itemsize*/
1519 /* methods */
1520 (destructor)PySSL_dealloc, /*tp_dealloc*/
1521 0, /*tp_print*/
1522 0, /*tp_getattr*/
1523 0, /*tp_setattr*/
1524 0, /*tp_reserved*/
1525 0, /*tp_repr*/
1526 0, /*tp_as_number*/
1527 0, /*tp_as_sequence*/
1528 0, /*tp_as_mapping*/
1529 0, /*tp_hash*/
1530 0, /*tp_call*/
1531 0, /*tp_str*/
1532 0, /*tp_getattro*/
1533 0, /*tp_setattro*/
1534 0, /*tp_as_buffer*/
1535 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1536 0, /*tp_doc*/
1537 0, /*tp_traverse*/
1538 0, /*tp_clear*/
1539 0, /*tp_richcompare*/
1540 0, /*tp_weaklistoffset*/
1541 0, /*tp_iter*/
1542 0, /*tp_iternext*/
1543 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001544};
1545
1546#ifdef HAVE_OPENSSL_RAND
1547
1548/* helper routines for seeding the SSL PRNG */
1549static PyObject *
1550PySSL_RAND_add(PyObject *self, PyObject *args)
1551{
1552 char *buf;
1553 int len;
1554 double entropy;
1555
1556 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001557 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001558 RAND_add(buf, len, entropy);
1559 Py_INCREF(Py_None);
1560 return Py_None;
1561}
1562
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001563PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001564"RAND_add(string, entropy)\n\
1565\n\
1566Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001568
1569static PyObject *
1570PySSL_RAND_status(PyObject *self)
1571{
Christian Heimes217cfd12007-12-02 14:31:20 +00001572 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001573}
1574
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001575PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001576"RAND_status() -> 0 or 1\n\
1577\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001578Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1579It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1580using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001581
1582static PyObject *
1583PySSL_RAND_egd(PyObject *self, PyObject *arg)
1584{
1585 int bytes;
1586
Bill Janssen6e027db2007-11-15 22:23:56 +00001587 if (!PyUnicode_Check(arg))
Antoine Pitroua29b1812010-05-12 14:08:45 +00001588 return PyErr_Format(PyExc_TypeError,
1589 "RAND_egd() expected string, found %s",
1590 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001591 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001592 if (bytes == -1) {
Antoine Pitroua29b1812010-05-12 14:08:45 +00001593 PyErr_SetString(PySSLErrorObject,
1594 "EGD connection failed or EGD did not return "
1595 "enough data to seed the PRNG");
1596 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001597 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001598 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001599}
1600
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001601PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001602"RAND_egd(path) -> bytes\n\
1603\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1605Returns number of bytes read. Raises SSLError if connection to EGD\n\
1606fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001607
1608#endif
1609
Bill Janssen40a0f662008-08-12 16:56:25 +00001610
1611
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612/* List of functions exported by this module. */
1613
1614static PyMethodDef PySSL_methods[] = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001615 {"sslwrap", PySSL_sslwrap,
1616 METH_VARARGS, ssl_doc},
1617 {"_test_decode_cert", PySSL_test_decode_certificate,
1618 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001619#ifdef HAVE_OPENSSL_RAND
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001620 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1621 PySSL_RAND_add_doc},
1622 {"RAND_egd", PySSL_RAND_egd, METH_O,
1623 PySSL_RAND_egd_doc},
1624 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1625 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001626#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001627 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001628};
1629
1630
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001631#ifdef WITH_THREAD
1632
1633/* an implementation of OpenSSL threading operations in terms
1634 of the Python C thread library */
1635
1636static PyThread_type_lock *_ssl_locks = NULL;
1637
1638static unsigned long _ssl_thread_id_function (void) {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001639 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640}
1641
Bill Janssen6e027db2007-11-15 22:23:56 +00001642static void _ssl_thread_locking_function
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001643 (int mode, int n, const char *file, int line) {
1644 /* this function is needed to perform locking on shared data
1645 structures. (Note that OpenSSL uses a number of global data
1646 structures that will be implicitly shared whenever multiple
1647 threads use OpenSSL.) Multi-threaded applications will
1648 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001650 locking_function() must be able to handle up to
1651 CRYPTO_num_locks() different mutex locks. It sets the n-th
1652 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001654 file and line are the file number of the function setting the
1655 lock. They can be useful for debugging.
1656 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001658 if ((_ssl_locks == NULL) ||
1659 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1660 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001662 if (mode & CRYPTO_LOCK) {
1663 PyThread_acquire_lock(_ssl_locks[n], 1);
1664 } else {
1665 PyThread_release_lock(_ssl_locks[n]);
1666 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667}
1668
1669static int _setup_ssl_threads(void) {
1670
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001671 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001673 if (_ssl_locks == NULL) {
1674 _ssl_locks_count = CRYPTO_num_locks();
1675 _ssl_locks = (PyThread_type_lock *)
1676 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1677 if (_ssl_locks == NULL)
1678 return 0;
1679 memset(_ssl_locks, 0,
1680 sizeof(PyThread_type_lock) * _ssl_locks_count);
1681 for (i = 0; i < _ssl_locks_count; i++) {
1682 _ssl_locks[i] = PyThread_allocate_lock();
1683 if (_ssl_locks[i] == NULL) {
1684 unsigned int j;
1685 for (j = 0; j < i; j++) {
1686 PyThread_free_lock(_ssl_locks[j]);
1687 }
1688 free(_ssl_locks);
1689 return 0;
1690 }
1691 }
1692 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1693 CRYPTO_set_id_callback(_ssl_thread_id_function);
1694 }
1695 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696}
1697
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001698#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001700PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001701"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001702for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001703
Martin v. Löwis1a214512008-06-11 05:26:20 +00001704
1705static struct PyModuleDef _sslmodule = {
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001706 PyModuleDef_HEAD_INIT,
1707 "_ssl",
1708 module_doc,
1709 -1,
1710 PySSL_methods,
1711 NULL,
1712 NULL,
1713 NULL,
1714 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001715};
1716
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001717PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001718PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001719{
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001720 PyObject *m, *d;
1721 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001722
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001723 if (PyType_Ready(&PySSL_Type) < 0)
1724 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001725
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001726 m = PyModule_Create(&_sslmodule);
1727 if (m == NULL)
1728 return NULL;
1729 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001730
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001731 /* Load _socket module and its C API */
1732 socket_api = PySocketModule_ImportModuleAndAPI();
1733 if (!socket_api)
1734 return NULL;
1735 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001736
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001737 /* Init OpenSSL */
1738 SSL_load_error_strings();
1739 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740#ifdef WITH_THREAD
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001741 /* note that this will start threading if not already started */
1742 if (!_setup_ssl_threads()) {
1743 return NULL;
1744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745#endif
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001746 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001747
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001748 /* Add symbols to module dict */
1749 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1750 PySocketModule.error,
1751 NULL);
1752 if (PySSLErrorObject == NULL)
1753 return NULL;
1754 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1755 return NULL;
1756 if (PyDict_SetItemString(d, "SSLType",
1757 (PyObject *)&PySSL_Type) != 0)
1758 return NULL;
1759 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1760 PY_SSL_ERROR_ZERO_RETURN);
1761 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1762 PY_SSL_ERROR_WANT_READ);
1763 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1764 PY_SSL_ERROR_WANT_WRITE);
1765 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1766 PY_SSL_ERROR_WANT_X509_LOOKUP);
1767 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1768 PY_SSL_ERROR_SYSCALL);
1769 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1770 PY_SSL_ERROR_SSL);
1771 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1772 PY_SSL_ERROR_WANT_CONNECT);
1773 /* non ssl.h errorcodes */
1774 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1775 PY_SSL_ERROR_EOF);
1776 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1777 PY_SSL_ERROR_INVALID_ERROR_CODE);
1778 /* cert requirements */
1779 PyModule_AddIntConstant(m, "CERT_NONE",
1780 PY_SSL_CERT_NONE);
1781 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1782 PY_SSL_CERT_OPTIONAL);
1783 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1784 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001785
Antoine Pitrou30dc1a72010-05-05 16:01:14 +00001786 /* protocol versions */
1787 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1788 PY_SSL_VERSION_SSL2);
1789 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1790 PY_SSL_VERSION_SSL3);
1791 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1792 PY_SSL_VERSION_SSL23);
1793 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1794 PY_SSL_VERSION_TLS1);
1795 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001796}