blob: 9abb736d8673562cef128e5408a02683ff7be9c6 [file] [log] [blame]
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001/*
2 * connection.c
3 *
4 * Copyright (C) AB Strakt 2001, All rights reserved
Jean-Paul Calderone8b63d452008-03-21 18:31:12 -04005 * Copyright (C) Jean-Paul Calderone 2008, All rights reserved
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05006 *
7 * SSL Connection objects and methods.
8 * See the file RATIONALE for a short explanation of why this module was written.
9 *
10 * Reviewed 2001-07-23
11 */
12#include <Python.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050013
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050014#ifndef MS_WINDOWS
15# include <sys/socket.h>
16# include <netinet/in.h>
17# if !(defined(__BEOS__) || defined(__CYGWIN__))
18# include <netinet/tcp.h>
19# endif
20#else
21# include <winsock.h>
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050022# include <wincrypt.h>
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050023#endif
24
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050025#define SSL_MODULE
26#include <openssl/err.h>
27
Jean-Paul Calderone12ea9a02008-02-22 12:24:39 -050028#include "ssl.h"
29
Jean-Paul Calderone897bc252008-02-18 20:50:23 -050030/**
31 * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
32 * apply some black winsock voodoo. This is basically just copied from Python's
33 * socketmodule.c
34 *
35 * Arguments: None
36 * Returns: None
37 */
38static void
39syscall_from_errno(void)
40{
41#ifdef MS_WINDOWS
42 int errnum = WSAGetLastError();
43 if (errnum)
44 {
45 static struct { int num; const char *msg; } *msgp, msgs[] = {
46 { WSAEINTR, "Interrupted system call" },
47 { WSAEBADF, "Bad file descriptor" },
48 { WSAEACCES, "Permission denied" },
49 { WSAEFAULT, "Bad address" },
50 { WSAEINVAL, "Invalid argument" },
51 { WSAEMFILE, "Too many open files" },
52 { WSAEWOULDBLOCK, "The socket operation could not complete "
53 "without blocking" },
54 { WSAEINPROGRESS, "Operation now in progress" },
55 { WSAEALREADY, "Operation already in progress" },
56 { WSAENOTSOCK, "Socket operation on non-socket" },
57 { WSAEDESTADDRREQ, "Destination address required" },
58 { WSAEMSGSIZE, "Message too long" },
59 { WSAEPROTOTYPE, "Protocol wrong type for socket" },
60 { WSAENOPROTOOPT, "Protocol not available" },
61 { WSAEPROTONOSUPPORT, "Protocol not supported" },
62 { WSAESOCKTNOSUPPORT, "Socket type not supported" },
63 { WSAEOPNOTSUPP, "Operation not supported" },
64 { WSAEPFNOSUPPORT, "Protocol family not supported" },
65 { WSAEAFNOSUPPORT, "Address family not supported" },
66 { WSAEADDRINUSE, "Address already in use" },
67 { WSAEADDRNOTAVAIL, "Can't assign requested address" },
68 { WSAENETDOWN, "Network is down" },
69 { WSAENETUNREACH, "Network is unreachable" },
70 { WSAENETRESET, "Network dropped connection on reset" },
71 { WSAECONNABORTED, "Software caused connection abort" },
72 { WSAECONNRESET, "Connection reset by peer" },
73 { WSAENOBUFS, "No buffer space available" },
74 { WSAEISCONN, "Socket is already connected" },
75 { WSAENOTCONN, "Socket is not connected" },
76 { WSAESHUTDOWN, "Can't send after socket shutdown" },
77 { WSAETOOMANYREFS, "Too many references: can't splice" },
78 { WSAETIMEDOUT, "Operation timed out" },
79 { WSAECONNREFUSED, "Connection refused" },
80 { WSAELOOP, "Too many levels of symbolic links" },
81 { WSAENAMETOOLONG, "File name too long" },
82 { WSAEHOSTDOWN, "Host is down" },
83 { WSAEHOSTUNREACH, "No route to host" },
84 { WSAENOTEMPTY, "Directory not empty" },
85 { WSAEPROCLIM, "Too many processes" },
86 { WSAEUSERS, "Too many users" },
87 { WSAEDQUOT, "Disc quota exceeded" },
88 { WSAESTALE, "Stale NFS file handle" },
89 { WSAEREMOTE, "Too many levels of remote in path" },
90 { WSASYSNOTREADY, "Network subsystem is unvailable" },
91 { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
92 { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
93 { WSAEDISCON, "Graceful shutdown in progress" },
94 /* Resolver errors */
95 { WSAHOST_NOT_FOUND, "No such host is known" },
96 { WSATRY_AGAIN, "Host not found, or server failed" },
97 { WSANO_RECOVERY, "Unexpected server error encountered" },
98 { WSANO_DATA, "Valid name without requested data" },
99 { WSANO_ADDRESS, "No address, look for MX record" },
100 { 0, NULL }
101 };
102 PyObject *v;
103 const char *msg = "winsock error";
104
105 for (msgp = msgs; msgp->msg; msgp++)
106 {
107 if (errnum == msgp->num)
108 {
109 msg = msgp->msg;
110 break;
111 }
112 }
113
114 v = Py_BuildValue("(is)", errnum, msg);
115 if (v != NULL)
116 {
117 PyErr_SetObject(ssl_SysCallError, v);
118 Py_DECREF(v);
119 }
120 return;
121 }
122#else
123 PyErr_SetFromErrno(ssl_SysCallError);
124#endif
125}
126
127/*
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400128 * Handle errors raised by BIO functions.
129 *
130 * Arguments: bio - The BIO object
131 * ret - The return value of the BIO_ function.
132 * Returns: None, the calling function should return NULL;
133 */
134static void
135handle_bio_errors(BIO* bio, int ret)
136{
137 if (BIO_should_retry(bio)) {
138 if (BIO_should_read(bio)) {
139 PyErr_SetNone(ssl_WantReadError);
140 } else if (BIO_should_write(bio)) {
141 PyErr_SetNone(ssl_WantWriteError);
142 } else if (BIO_should_io_special(bio)) {
143 /*
144 * It's somewhat unclear what this means. From the OpenSSL source,
145 * it seems like it should not be triggered by the memory BIO, so
146 * for the time being, this case shouldn't come up. The SSL BIO
147 * (which I think should be named the socket BIO) may trigger this
148 * case if its socket is not yet connected or it is busy doing
149 * something related to x509.
150 */
151 PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
152 } else {
153 /*
154 * I hope this is dead code. The BIO documentation suggests that
155 * one of the above three checks should always be true.
156 */
157 PyErr_SetString(PyExc_ValueError, "unknown bio failure");
158 }
159 } else {
160 /*
161 * If we aren't to retry, it's really an error, so fall back to the
162 * normal error reporting code. However, the BIO interface does not
163 * specify a uniform error reporting mechanism. We can only hope that
164 * the code which triggered the error also kindly pushed something onto
165 * the error stack.
166 */
167 exception_from_error_queue();
168 }
169}
170
171/*
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500172 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
173 *
174 * Arguments: ssl - The SSL object
175 * err - The return code from SSL_get_error
176 * ret - The return code from the SSL I/O function
177 * Returns: None, the calling function should return NULL
178 */
179static void
180handle_ssl_errors(SSL *ssl, int err, int ret)
181{
182 switch (err)
183 {
184 /*
185 * Strange as it may seem, ZeroReturn is not an error per se. It means
186 * that the SSL Connection has been closed correctly (note, not the
187 * transport layer!), i.e. closure alerts have been exchanged. This is
188 * an exception since
189 * + There's an SSL "error" code for it
190 * + You have to deal with it in any case, close the transport layer
191 * etc
192 */
193 case SSL_ERROR_ZERO_RETURN:
194 PyErr_SetNone(ssl_ZeroReturnError);
195 break;
196
197 /*
198 * The WantXYZ exceptions don't mean that there's an error, just that
199 * nothing could be read/written just now, maybe because the transport
200 * layer would block on the operation, or that there's not enough data
201 * available to fill an entire SSL record.
202 */
203 case SSL_ERROR_WANT_READ:
204 PyErr_SetNone(ssl_WantReadError);
205 break;
206
207 case SSL_ERROR_WANT_WRITE:
208 PyErr_SetNone(ssl_WantWriteError);
209 break;
210
211 case SSL_ERROR_WANT_X509_LOOKUP:
212 PyErr_SetNone(ssl_WantX509LookupError);
213 break;
214
215 case SSL_ERROR_SYSCALL:
216 if (ERR_peek_error() == 0)
217 {
218 if (ret < 0)
219 {
220 syscall_from_errno();
221 }
222 else
223 {
224 PyObject *v;
225
226 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
227 if (v != NULL)
228 {
229 PyErr_SetObject(ssl_SysCallError, v);
230 Py_DECREF(v);
231 }
232 }
233 break;
234 }
235
236 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
237
238 case SSL_ERROR_SSL:
239 ;
240 default:
241 exception_from_error_queue();
242 break;
243 }
244}
245
246/*
247 * Here be member methods of the Connection "class"
248 */
249
250static char ssl_Connection_get_context_doc[] = "\n\
251Get session context\n\
252\n\
253Arguments: self - The Connection object\n\
254 args - The Python argument tuple, should be empty\n\
255Returns: A Context object\n\
256";
257static PyObject *
258ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args)
259{
260 if (!PyArg_ParseTuple(args, ":get_context"))
261 return NULL;
262
263 Py_INCREF(self->context);
264 return (PyObject *)self->context;
265}
266
267static char ssl_Connection_pending_doc[] = "\n\
268Get the number of bytes that can be safely read from the connection\n\
269\n\
270Arguments: self - The Connection object\n\
271 args - The Python argument tuple, should be empty\n\
272Returns: \n\
273";
274static PyObject *
275ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args)
276{
277 int ret;
278
279 if (!PyArg_ParseTuple(args, ":pending"))
280 return NULL;
281
282 ret = SSL_pending(self->ssl);
283 return PyInt_FromLong((long)ret);
284}
285
Rick Deanb71c0d22009-04-01 14:09:23 -0500286static char ssl_Connection_bio_write_doc[] = "\n\
287When using non-socket connections this function sends\n\
288\"dirty\" data that would have traveled in on the network.\n\
289\n\
290Arguments: self - The Connection object\n\
291 args - The Python argument tuple, should be:\n\
292 buf - The string to bio_write\n\
293Returns: The number of bytes written\n\
294";
295static PyObject *
296ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
297{
298 char *buf;
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400299 int len, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500300
301 if(self->into_ssl == NULL)
302 {
303 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
304 return NULL;
305 }
306
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -0400307 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
Rick Deanb71c0d22009-04-01 14:09:23 -0500308 return NULL;
309
310 ret = BIO_write(self->into_ssl, buf, len);
311
312 if (PyErr_Occurred())
313 {
314 flush_error_queue();
315 return NULL;
316 }
317
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400318 if (ret <= 0) {
319 /*
320 * There was a problem with the BIO_write of some sort.
321 */
322 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500323 return NULL;
324 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400325
326 return PyInt_FromLong((long)ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500327}
328
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500329static char ssl_Connection_send_doc[] = "\n\
330Send data on the connection. NOTE: If you get one of the WantRead,\n\
331WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
332method again with the SAME buffer.\n\
333\n\
334Arguments: self - The Connection object\n\
335 args - The Python argument tuple, should be:\n\
336 buf - The string to send\n\
337 flags - (optional) Included for compatability with the socket\n\
338 API, the value is ignored\n\
339Returns: The number of bytes written\n\
340";
341static PyObject *
342ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args)
343{
344 char *buf;
345 int len, ret, err, flags;
346
347 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
348 return NULL;
349
350 MY_BEGIN_ALLOW_THREADS(self->tstate)
351 ret = SSL_write(self->ssl, buf, len);
352 MY_END_ALLOW_THREADS(self->tstate)
353
354 if (PyErr_Occurred())
355 {
356 flush_error_queue();
357 return NULL;
358 }
359
360 err = SSL_get_error(self->ssl, ret);
361 if (err == SSL_ERROR_NONE)
362 {
363 return PyInt_FromLong((long)ret);
364 }
365 else
366 {
367 handle_ssl_errors(self->ssl, err, ret);
368 return NULL;
369 }
370}
371
372static char ssl_Connection_sendall_doc[] = "\n\
373Send \"all\" data on the connection. This calls send() repeatedly until\n\
374all data is sent. If an error occurs, it's impossible to tell how much data\n\
375has been sent.\n\
376\n\
377Arguments: self - The Connection object\n\
378 args - The Python argument tuple, should be:\n\
379 buf - The string to send\n\
380 flags - (optional) Included for compatability with the socket\n\
381 API, the value is ignored\n\
382Returns: The number of bytes written\n\
383";
384static PyObject *
385ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
386{
387 char *buf;
388 int len, ret, err, flags;
389 PyObject *pyret = Py_None;
390
391 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
392 return NULL;
393
394 do {
395 MY_BEGIN_ALLOW_THREADS(self->tstate)
396 ret = SSL_write(self->ssl, buf, len);
397 MY_END_ALLOW_THREADS(self->tstate)
398 if (PyErr_Occurred())
399 {
400 flush_error_queue();
401 pyret = NULL;
402 break;
403 }
404 err = SSL_get_error(self->ssl, ret);
405 if (err == SSL_ERROR_NONE)
406 {
407 buf += ret;
408 len -= ret;
409 }
410 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
411 err == SSL_ERROR_ZERO_RETURN)
412 {
413 handle_ssl_errors(self->ssl, err, ret);
414 pyret = NULL;
415 break;
416 }
417 } while (len > 0);
418
419 Py_XINCREF(pyret);
420 return pyret;
421}
422
423static char ssl_Connection_recv_doc[] = "\n\
424Receive data on the connection. NOTE: If you get one of the WantRead,\n\
425WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
426method again with the SAME buffer.\n\
427\n\
428Arguments: self - The Connection object\n\
429 args - The Python argument tuple, should be:\n\
430 bufsiz - The maximum number of bytes to read\n\
431 flags - (optional) Included for compatability with the socket\n\
432 API, the value is ignored\n\
433Returns: The number of bytes read\n\
434";
435static PyObject *
436ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
437{
438 int bufsiz, ret, err, flags;
439 PyObject *buf;
440
441 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
442 return NULL;
443
444 buf = PyString_FromStringAndSize(NULL, bufsiz);
445 if (buf == NULL)
446 return NULL;
447
448 MY_BEGIN_ALLOW_THREADS(self->tstate)
449 ret = SSL_read(self->ssl, PyString_AsString(buf), bufsiz);
450 MY_END_ALLOW_THREADS(self->tstate)
451
452 if (PyErr_Occurred())
453 {
454 Py_DECREF(buf);
455 flush_error_queue();
456 return NULL;
457 }
458
459 err = SSL_get_error(self->ssl, ret);
460 if (err == SSL_ERROR_NONE)
461 {
462 if (ret != bufsiz && _PyString_Resize(&buf, ret) < 0)
463 return NULL;
464 return buf;
465 }
466 else
467 {
468 handle_ssl_errors(self->ssl, err, ret);
469 Py_DECREF(buf);
470 return NULL;
471 }
472}
473
Rick Deanb71c0d22009-04-01 14:09:23 -0500474static char ssl_Connection_bio_read_doc[] = "\n\
475When using non-socket connections this function reads\n\
476the \"dirty\" data that would have traveled away on the network.\n\
477\n\
478Arguments: self - The Connection object\n\
479 args - The Python argument tuple, should be:\n\
480 bufsiz - The maximum number of bytes to read\n\
481Returns: The string read.\n\
482";
483static PyObject *
484ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
485{
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400486 int bufsiz, ret;
Rick Deanb71c0d22009-04-01 14:09:23 -0500487 PyObject *buf;
488
489 if(self->from_ssl == NULL)
490 {
491 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
492 return NULL;
493 }
494
495 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
496 return NULL;
497
498 buf = PyString_FromStringAndSize(NULL, bufsiz);
499 if (buf == NULL)
500 return NULL;
501
502 ret = BIO_read(self->from_ssl, PyString_AsString(buf), bufsiz);
503
504 if (PyErr_Occurred())
505 {
506 Py_DECREF(buf);
507 flush_error_queue();
508 return NULL;
509 }
510
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400511 if (ret <= 0) {
512 /*
513 * There was a problem with the BIO_read of some sort.
514 */
515 handle_bio_errors(self->from_ssl, ret);
Rick Deanb71c0d22009-04-01 14:09:23 -0500516 Py_DECREF(buf);
517 return NULL;
518 }
Jean-Paul Calderoneaff0fc42009-04-27 17:13:34 -0400519
520 /*
521 * Shrink the string to match the number of bytes we actually read.
522 */
523 if (ret != bufsiz && _PyString_Resize(&buf, ret) < 0)
524 {
525 Py_DECREF(buf);
526 return NULL;
527 }
528 return buf;
Rick Deanb71c0d22009-04-01 14:09:23 -0500529}
530
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500531static char ssl_Connection_renegotiate_doc[] = "\n\
532Renegotiate the session\n\
533\n\
534Arguments: self - The Connection object\n\
535 args - The Python argument tuple, should be empty\n\
536Returns: True if the renegotiation can be started, false otherwise\n\
537";
538static PyObject *
539ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args)
540{
541 int ret;
542
543 if (!PyArg_ParseTuple(args, ":renegotiate"))
544 return NULL;
545
546 MY_BEGIN_ALLOW_THREADS(self->tstate);
547 ret = SSL_renegotiate(self->ssl);
548 MY_END_ALLOW_THREADS(self->tstate);
549
550 if (PyErr_Occurred())
551 {
552 flush_error_queue();
553 return NULL;
554 }
555
556 return PyInt_FromLong((long)ret);
557}
558
559static char ssl_Connection_do_handshake_doc[] = "\n\
560Perform an SSL handshake (usually called after renegotiate() or one of\n\
561set_*_state()). This can raise the same exceptions as send and recv.\n\
562\n\
563Arguments: self - The Connection object\n\
564 args - The Python argument tuple, should be empty\n\
565Returns: None.\n\
566";
567static PyObject *
568ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
569{
570 int ret, err;
571
572 if (!PyArg_ParseTuple(args, ":do_handshake"))
573 return NULL;
574
575 MY_BEGIN_ALLOW_THREADS(self->tstate);
576 ret = SSL_do_handshake(self->ssl);
577 MY_END_ALLOW_THREADS(self->tstate);
578
579 if (PyErr_Occurred())
580 {
581 flush_error_queue();
582 return NULL;
583 }
584
585 err = SSL_get_error(self->ssl, ret);
586 if (err == SSL_ERROR_NONE)
587 {
588 Py_INCREF(Py_None);
589 return Py_None;
590 }
591 else
592 {
593 handle_ssl_errors(self->ssl, err, ret);
594 return NULL;
595 }
596}
597
598#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
599static char ssl_Connection_renegotiate_pending_doc[] = "\n\
600Check if there's a renegotiation in progress, it will return false once\n\
601a renegotiation is finished.\n\
602\n\
603Arguments: self - The Connection object\n\
604 args - The Python argument tuple, should be empty\n\
605Returns: Whether there's a renegotiation in progress\n\
606";
607static PyObject *
608ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
609{
610 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
611 return NULL;
612
613 return PyInt_FromLong((long)SSL_renegotiate_pending(self->ssl));
614}
615#endif
616
617static char ssl_Connection_total_renegotiations_doc[] = "\n\
618Find out the total number of renegotiations.\n\
619\n\
620Arguments: self - The Connection object\n\
621 args - The Python argument tuple, should be empty\n\
622Returns: The number of renegotiations.\n\
623";
624static PyObject *
625ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
626{
627 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
628 return NULL;
629
630 return PyInt_FromLong(SSL_total_renegotiations(self->ssl));
631}
632
633static char ssl_Connection_set_accept_state_doc[] = "\n\
634Set the connection to work in server mode. The handshake will be handled\n\
635automatically by read/write.\n\
636\n\
637Arguments: self - The Connection object\n\
638 args - The Python argument tuple, should be empty\n\
639Returns: None\n\
640";
641static PyObject *
642ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
643{
644 if (!PyArg_ParseTuple(args, ":set_accept_state"))
645 return NULL;
646
647 SSL_set_accept_state(self->ssl);
648
649 Py_INCREF(Py_None);
650 return Py_None;
651}
652
653static char ssl_Connection_set_connect_state_doc[] = "\n\
654Set the connection to work in client mode. The handshake will be handled\n\
655automatically by read/write.\n\
656\n\
657Arguments: self - The Connection object\n\
658 args - The Python argument tuple, should be empty\n\
659Returns: None\n\
660";
661static PyObject *
662ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
663{
664 if (!PyArg_ParseTuple(args, ":set_connect_state"))
665 return NULL;
666
667 SSL_set_connect_state(self->ssl);
668
669 Py_INCREF(Py_None);
670 return Py_None;
671}
672
673static char ssl_Connection_connect_doc[] = "\n\
674Connect to remote host and set up client-side SSL\n\
675\n\
676Arguments: self - The Connection object\n\
677 args - The Python argument tuple, should be:\n\
678 addr - A remote address\n\
679Returns: What the socket's connect method returns\n\
680";
681static PyObject *
682ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
683{
684 PyObject *meth, *ret;
685
686 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
687 return NULL;
688
689 SSL_set_connect_state(self->ssl);
690
691 ret = PyEval_CallObject(meth, args);
692 Py_DECREF(meth);
693 if (ret == NULL)
694 return NULL;
695
696 return ret;
697}
698
699static char ssl_Connection_connect_ex_doc[] = "\n\
700Connect to remote host and set up client-side SSL. Note that if the socket's\n\
701connect_ex method doesn't return 0, SSL won't be initialized.\n\
702\n\
703Arguments: self - The Connection object\n\
704 args - The Python argument tuple, should be:\n\
705 addr - A remove address\n\
706Returns: What the socket's connect_ex method returns\n\
707";
708static PyObject *
709ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
710{
711 PyObject *meth, *ret;
712
713 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
714 return NULL;
715
716 SSL_set_connect_state(self->ssl);
717
718 ret = PyEval_CallObject(meth, args);
719 Py_DECREF(meth);
720 if (ret == NULL)
721 return NULL;
722 if (PyInt_Check(ret) && PyInt_AsLong(ret) != 0)
723 return ret;
724
725 return ret;
726}
727
728static char ssl_Connection_accept_doc[] = "\n\
729Accept incoming connection and set up SSL on it\n\
730\n\
731Arguments: self - The Connection object\n\
732 args - The Python argument tuple, should be empty\n\
733Returns: A (conn,addr) pair where conn is a Connection and addr is an\n\
734 address\n\
735";
736static PyObject *
737ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
738{
739 PyObject *tuple, *socket, *address, *meth;
740 ssl_ConnectionObj *conn;
741
742 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
743 return NULL;
744 tuple = PyEval_CallObject(meth, args);
745 Py_DECREF(meth);
746 if (tuple == NULL)
747 return NULL;
748
749 socket = PyTuple_GetItem(tuple, 0);
750 Py_INCREF(socket);
751 address = PyTuple_GetItem(tuple, 1);
752 Py_INCREF(address);
753 Py_DECREF(tuple);
754
755 conn = ssl_Connection_New(self->context, socket);
756 Py_DECREF(socket);
757 if (conn == NULL)
758 {
759 Py_DECREF(address);
760 return NULL;
761 }
762
763 SSL_set_accept_state(conn->ssl);
764
765 tuple = Py_BuildValue("(OO)", conn, address);
766
767 Py_DECREF(conn);
768 Py_DECREF(address);
769
770 return tuple;
771}
772
773static char ssl_Connection_shutdown_doc[] = "\n\
774Send closure alert\n\
775\n\
776Arguments: self - The Connection object\n\
777 args - The Python argument tuple, should be empty\n\
778Returns: True if the shutdown completed successfully (i.e. both sides\n\
779 have sent closure alerts), false otherwise (i.e. you have to\n\
780 wait for a ZeroReturnError on a recv() method call\n\
781";
782static PyObject *
783ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
784{
785 int ret;
786
787 if (!PyArg_ParseTuple(args, ":shutdown"))
788 return NULL;
789
790 MY_BEGIN_ALLOW_THREADS(self->tstate)
791 ret = SSL_shutdown(self->ssl);
792 MY_END_ALLOW_THREADS(self->tstate)
793
794 if (PyErr_Occurred())
795 {
796 flush_error_queue();
797 return NULL;
798 }
799
800 if (ret < 0)
801 {
802 exception_from_error_queue();
803 return NULL;
804 }
805 else if (ret > 0)
806 {
807 Py_INCREF(Py_True);
808 return Py_True;
809 }
810 else
811 {
812 Py_INCREF(Py_False);
813 return Py_False;
814 }
815}
816
817static char ssl_Connection_get_cipher_list_doc[] = "\n\
818Get the session cipher list\n\
819WARNING: API change! This used to take an optional argument, and return a\n\
820string.\n\
821\n\
822Arguments: self - The Connection object\n\
823 args - The Python argument tuple, should be empty\n\
824Returns: A list of cipher strings\n\
825";
826static PyObject *
827ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
828{
829 int idx = 0;
830 const char *ret;
831 PyObject *lst, *item;
832
833 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
834 return NULL;
835
836 lst = PyList_New(0);
837 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
838 {
839 item = PyString_FromString(ret);
840 PyList_Append(lst, item);
841 Py_DECREF(item);
842 idx++;
843 }
844 return lst;
845}
846
847static char ssl_Connection_makefile_doc[] = "\n\
848The makefile() method is not implemented, since there is no dup semantics\n\
849for SSL connections\n\
850XXX: Return self instead?\n\
851\n\
852Arguments: self - The Connection object\n\
853 args - The Python argument tuple, should be empty\n\
854Returns: NULL\n\
855";
856static PyObject *
857ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
858{
859 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
860 return NULL;
861}
862
863static char ssl_Connection_get_app_data_doc[] = "\n\
864Get application data\n\
865\n\
866Arguments: self - The Connection object\n\
867 args - The Python argument tuple, should be empty\n\
868Returns: The application data\n\
869";
870static PyObject *
871ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
872{
873 if (!PyArg_ParseTuple(args, ":get_app_data"))
874 return NULL;
875
876 Py_INCREF(self->app_data);
877 return self->app_data;
878}
879
880static char ssl_Connection_set_app_data_doc[] = "\n\
881Set application data\n\
882\n\
883Arguments: self - The Connection object\n\
884 args - The Python argument tuple, should be\n\
885 data - The application data\n\
886Returns: None\n\
887";
888static PyObject *
889ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
890{
891 PyObject *data;
892
893 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
894 return NULL;
895
896 Py_DECREF(self->app_data);
897 Py_INCREF(data);
898 self->app_data = data;
899
900 Py_INCREF(Py_None);
901 return Py_None;
902}
903
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -0500904static char ssl_Connection_get_shutdown_doc[] = "\n\
905Get shutdown state\n\
906\n\
907Arguments: self - The Connection object\n\
908 args - The Python argument tuple, should be empty\n\
909Returns: The shutdown state, a bitmask of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
910";
911static PyObject *
912ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
913{
914 if (!PyArg_ParseTuple(args, ":get_shutdown"))
915 return NULL;
916
917 return PyInt_FromLong((long)SSL_get_shutdown(self->ssl));
918}
919
920static char ssl_Connection_set_shutdown_doc[] = "\n\
921Set shutdown state\n\
922\n\
923Arguments: self - The Connection object\n\
924 args - The Python argument tuple, should be\n\
925 shutdown state - bitmask of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
926Returns: None\n\
927";
928static PyObject *
929ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
930{
931 int shutdown;
932
933 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
934 return NULL;
935
936 SSL_set_shutdown(self->ssl, shutdown);
937 Py_INCREF(Py_None);
938 return Py_None;
939}
940
Jean-Paul Calderone897bc252008-02-18 20:50:23 -0500941static char ssl_Connection_state_string_doc[] = "\n\
942Get a verbose state description\n\
943\n\
944Arguments: self - The Connection object\n\
945 args - The Python argument tuple, should be empty\n\
946Returns: A string representing the state\n\
947";
948static PyObject *
949ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
950{
951 if (!PyArg_ParseTuple(args, ":state_string"))
952 return NULL;
953
954 return PyString_FromString(SSL_state_string_long(self->ssl));
955}
956
Rick Deanb71c0d22009-04-01 14:09:23 -0500957static char ssl_Connection_client_random_doc[] = "\n\
958Get a copy of the client hello nonce.\n\
959\n\
960Arguments: self - The Connection object\n\
961 args - The Python argument tuple, should be empty\n\
962Returns: A string representing the state\n\
963";
964static PyObject *
965ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
966{
967 if (!PyArg_ParseTuple(args, ":client_random"))
968 return NULL;
969
970 if( self->ssl->session == NULL) {
971 Py_INCREF(Py_None);
972 return Py_None;
973 }
974 return PyString_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
975}
976
977static char ssl_Connection_server_random_doc[] = "\n\
978Get a copy of the server hello nonce.\n\
979\n\
980Arguments: self - The Connection object\n\
981 args - The Python argument tuple, should be empty\n\
982Returns: A string representing the state\n\
983";
984static PyObject *
985ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
986{
987 if (!PyArg_ParseTuple(args, ":server_random"))
988 return NULL;
989
990 if( self->ssl->session == NULL) {
991 Py_INCREF(Py_None);
992 return Py_None;
993 }
994 return PyString_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
995}
996
997static char ssl_Connection_master_key_doc[] = "\n\
998Get a copy of the master key.\n\
999\n\
1000Arguments: self - The Connection object\n\
1001 args - The Python argument tuple, should be empty\n\
1002Returns: A string representing the state\n\
1003";
1004static PyObject *
1005ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1006{
1007 if (!PyArg_ParseTuple(args, ":master_key"))
1008 return NULL;
1009
1010 if( self->ssl->session == NULL) {
1011 Py_INCREF(Py_None);
1012 return Py_None;
1013 }
1014 return PyString_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
1015}
1016
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001017static char ssl_Connection_sock_shutdown_doc[] = "\n\
1018See shutdown(2)\n\
1019\n\
1020Arguments: self - The Connection object\n\
1021 args - The Python argument tuple, should be whatever the\n\
1022 socket's shutdown() method expects\n\
1023Returns: What the socket's shutdown() method returns\n\
1024";
1025static PyObject *
1026ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1027{
1028 PyObject *meth, *ret;
1029
1030 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1031 return NULL;
1032 ret = PyEval_CallObject(meth, args);
1033 Py_DECREF(meth);
1034 return ret;
1035}
1036
1037static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1038Retrieve the other side's certificate (if any)\n\
1039\n\
1040Arguments: self - The Connection object\n\
1041 args - The Python argument tuple, should be empty\n\
1042Returns: The peer's certificate\n\
1043";
1044static PyObject *
1045ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1046{
1047 X509 *cert;
1048
1049 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1050 return NULL;
1051
1052 cert = SSL_get_peer_certificate(self->ssl);
1053 if (cert != NULL)
1054 {
1055 return (PyObject *)crypto_X509_New(cert, 1);
1056 }
1057 else
1058 {
1059 Py_INCREF(Py_None);
1060 return Py_None;
1061 }
1062}
1063
1064static char ssl_Connection_want_read_doc[] = "\n\
1065Checks if more data has to be read from the transport layer to complete an\n\
1066operation.\n\
1067\n\
1068Arguments: self - The Connection object\n\
1069 args - The Python argument tuple, should be empty\n\
1070Returns: True iff more data has to be read\n\
1071";
1072static PyObject *
1073ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1074{
1075 if (!PyArg_ParseTuple(args, ":want_read"))
1076 return NULL;
1077
1078 return PyInt_FromLong((long)SSL_want_read(self->ssl));
1079}
1080
1081static char ssl_Connection_want_write_doc[] = "\n\
1082Checks if there is data to write to the transport layer to complete an\n\
1083operation.\n\
1084\n\
1085Arguments: self - The Connection object\n\
1086 args - The Python argument tuple, should be empty\n\
1087Returns: True iff there is data to write\n\
1088";
1089static PyObject *
1090ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1091{
1092 if (!PyArg_ParseTuple(args, ":want_write"))
1093 return NULL;
1094
1095 return PyInt_FromLong((long)SSL_want_write(self->ssl));
1096}
1097
1098/*
1099 * Member methods in the Connection object
1100 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1101 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1102 * for convenience
1103 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1104 * function with the name 'name'
1105 */
1106#define ADD_METHOD(name) \
1107 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1108#define ADD_ALIAS(name,real) \
1109 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1110static PyMethodDef ssl_Connection_methods[] =
1111{
1112 ADD_METHOD(get_context),
1113 ADD_METHOD(pending),
1114 ADD_METHOD(send),
1115 ADD_ALIAS (write, send),
1116 ADD_METHOD(sendall),
1117 ADD_METHOD(recv),
1118 ADD_ALIAS (read, recv),
Rick Deanb71c0d22009-04-01 14:09:23 -05001119 ADD_METHOD(bio_read),
1120 ADD_METHOD(bio_write),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001121 ADD_METHOD(renegotiate),
1122 ADD_METHOD(do_handshake),
1123#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1124 ADD_METHOD(renegotiate_pending),
1125#endif
1126 ADD_METHOD(total_renegotiations),
1127 ADD_METHOD(connect),
1128 ADD_METHOD(connect_ex),
1129 ADD_METHOD(accept),
1130 ADD_METHOD(shutdown),
1131 ADD_METHOD(get_cipher_list),
1132 ADD_METHOD(makefile),
1133 ADD_METHOD(get_app_data),
1134 ADD_METHOD(set_app_data),
Jean-Paul Calderone72b8f0f2008-02-21 23:57:40 -05001135 ADD_METHOD(get_shutdown),
1136 ADD_METHOD(set_shutdown),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001137 ADD_METHOD(state_string),
Rick Deanb71c0d22009-04-01 14:09:23 -05001138 ADD_METHOD(server_random),
1139 ADD_METHOD(client_random),
1140 ADD_METHOD(master_key),
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001141 ADD_METHOD(sock_shutdown),
1142 ADD_METHOD(get_peer_certificate),
1143 ADD_METHOD(want_read),
1144 ADD_METHOD(want_write),
1145 ADD_METHOD(set_accept_state),
1146 ADD_METHOD(set_connect_state),
1147 { NULL, NULL }
1148};
1149#undef ADD_ALIAS
1150#undef ADD_METHOD
1151
1152
1153/*
1154 * Constructor for Connection objects
1155 *
1156 * Arguments: ctx - An SSL Context to use for this connection
1157 * sock - The socket to use for transport layer
1158 * Returns: The newly created Connection object
1159 */
1160ssl_ConnectionObj *
1161ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock)
1162{
1163 ssl_ConnectionObj *self;
1164 int fd;
1165
1166 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1167 if (self == NULL)
1168 return NULL;
1169
1170 Py_INCREF(ctx);
1171 self->context = ctx;
1172
1173 Py_INCREF(sock);
1174 self->socket = sock;
1175
1176 self->ssl = NULL;
Jean-Paul Calderonefc4ed0f2009-04-27 11:51:27 -04001177 self->from_ssl = NULL;
1178 self->into_ssl = NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001179
1180 Py_INCREF(Py_None);
1181 self->app_data = Py_None;
1182
1183 self->tstate = NULL;
1184
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001185 self->ssl = SSL_new(self->context->ctx);
1186 SSL_set_app_data(self->ssl, self);
Rick Deanb71c0d22009-04-01 14:09:23 -05001187
1188 if(self->socket == Py_None)
1189 {
1190 /* If it's not a socket or file, treat it like a memory buffer,
1191 * so crazy people can do things like EAP-TLS. */
1192 self->into_ssl = BIO_new(BIO_s_mem());
1193 self->from_ssl = BIO_new(BIO_s_mem());
1194 if(self->into_ssl == NULL || self->from_ssl == NULL)
1195 goto error;
1196 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1197 }
1198 else
1199 {
1200 fd = PyObject_AsFileDescriptor(self->socket);
1201 if (fd < 0)
1202 {
1203 Py_DECREF(self);
1204 return NULL;
1205 }
1206 else
1207 {
1208 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1209 }
1210 }
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001211
1212 PyObject_GC_Track(self);
1213
1214 return self;
Rick Deanb71c0d22009-04-01 14:09:23 -05001215
1216error:
1217 BIO_free(self->into_ssl); /* NULL safe */
1218 BIO_free(self->from_ssl); /* NULL safe */
1219 Py_DECREF(self);
1220 return NULL;
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001221}
1222
1223/*
1224 * Find attribute
1225 *
1226 * Arguments: self - The Connection object
1227 * name - The attribute name
1228 * Returns: A Python object for the attribute, or NULL if something went
1229 * wrong
1230 */
1231static PyObject *
1232ssl_Connection_getattr(ssl_ConnectionObj *self, char *name)
1233{
1234 PyObject *meth;
1235
1236 meth = Py_FindMethod(ssl_Connection_methods, (PyObject *)self, name);
1237
1238 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError))
1239 {
1240 PyErr_Clear();
1241 /* Try looking it up in the "socket" instead. */
1242 meth = PyObject_GetAttrString(self->socket, name);
1243 }
1244
1245 return meth;
1246}
1247
1248/*
1249 * Call the visitproc on all contained objects.
1250 *
1251 * Arguments: self - The Connection object
1252 * visit - Function to call
1253 * arg - Extra argument to visit
1254 * Returns: 0 if all goes well, otherwise the return code from the first
1255 * call that gave non-zero result.
1256 */
1257static int
1258ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1259{
1260 int ret = 0;
1261
1262 if (ret == 0 && self->context != NULL)
1263 ret = visit((PyObject *)self->context, arg);
1264 if (ret == 0 && self->socket != NULL)
1265 ret = visit(self->socket, arg);
1266 if (ret == 0 && self->app_data != NULL)
1267 ret = visit(self->app_data, arg);
1268 return ret;
1269}
1270
1271/*
1272 * Decref all contained objects and zero the pointers.
1273 *
1274 * Arguments: self - The Connection object
1275 * Returns: Always 0.
1276 */
1277static int
1278ssl_Connection_clear(ssl_ConnectionObj *self)
1279{
1280 Py_XDECREF(self->context);
1281 self->context = NULL;
1282 Py_XDECREF(self->socket);
1283 self->socket = NULL;
1284 Py_XDECREF(self->app_data);
1285 self->app_data = NULL;
Rick Deanb71c0d22009-04-01 14:09:23 -05001286 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1287 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
Jean-Paul Calderone897bc252008-02-18 20:50:23 -05001288 return 0;
1289}
1290
1291/*
1292 * Deallocate the memory used by the Connection object
1293 *
1294 * Arguments: self - The Connection object
1295 * Returns: None
1296 */
1297static void
1298ssl_Connection_dealloc(ssl_ConnectionObj *self)
1299{
1300 PyObject_GC_UnTrack(self);
1301 if (self->ssl != NULL)
1302 SSL_free(self->ssl);
1303 ssl_Connection_clear(self);
1304 PyObject_GC_Del(self);
1305}
1306
1307PyTypeObject ssl_Connection_Type = {
1308 PyObject_HEAD_INIT(NULL)
1309 0,
1310 "Connection",
1311 sizeof(ssl_ConnectionObj),
1312 0,
1313 (destructor)ssl_Connection_dealloc,
1314 NULL, /* print */
1315 (getattrfunc)ssl_Connection_getattr,
1316 NULL, /* setattr */
1317 NULL, /* compare */
1318 NULL, /* repr */
1319 NULL, /* as_number */
1320 NULL, /* as_sequence */
1321 NULL, /* as_mapping */
1322 NULL, /* hash */
1323 NULL, /* call */
1324 NULL, /* str */
1325 NULL, /* getattro */
1326 NULL, /* setattro */
1327 NULL, /* as_buffer */
1328 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1329 NULL, /* doc */
1330 (traverseproc)ssl_Connection_traverse,
1331 (inquiry)ssl_Connection_clear,
1332};
1333
1334
1335/*
1336 * Initiailze the Connection part of the SSL sub module
1337 *
1338 * Arguments: dict - Dictionary of the OpenSSL.SSL module
1339 * Returns: 1 for success, 0 otherwise
1340 */
1341int
1342init_ssl_connection(PyObject *dict)
1343{
1344 ssl_Connection_Type.ob_type = &PyType_Type;
1345 Py_INCREF(&ssl_Connection_Type);
1346 if (PyDict_SetItemString(dict, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0)
1347 return 0;
1348
1349 return 1;
1350}
1351