4 * Copyright (C) AB Strakt
5 * Copyright (C) Jean-Paul Calderone
6 * See LICENSE for details.
8 * SSL Connection objects and methods.
9 * See the file RATIONALE for a short explanation of why this module was written.
16 # include <sys/socket.h>
17 # include <netinet/in.h>
18 # if !(defined(__BEOS__) || defined(__CYGWIN__))
19 # include <netinet/tcp.h>
23 # include <wincrypt.h>
27 #include <openssl/bio.h>
28 #include <openssl/err.h>
32 * If we are on UNIX, fine, just use PyErr_SetFromErrno. If we are on Windows,
33 * apply some black winsock voodoo. This is basically just copied from Python's
40 syscall_from_errno(void)
43 int errnum = WSAGetLastError();
46 static struct { int num; const char *msg; } *msgp, msgs[] = {
47 { WSAEINTR, "Interrupted system call" },
48 { WSAEBADF, "Bad file descriptor" },
49 { WSAEACCES, "Permission denied" },
50 { WSAEFAULT, "Bad address" },
51 { WSAEINVAL, "Invalid argument" },
52 { WSAEMFILE, "Too many open files" },
53 { WSAEWOULDBLOCK, "The socket operation could not complete "
55 { WSAEINPROGRESS, "Operation now in progress" },
56 { WSAEALREADY, "Operation already in progress" },
57 { WSAENOTSOCK, "Socket operation on non-socket" },
58 { WSAEDESTADDRREQ, "Destination address required" },
59 { WSAEMSGSIZE, "Message too long" },
60 { WSAEPROTOTYPE, "Protocol wrong type for socket" },
61 { WSAENOPROTOOPT, "Protocol not available" },
62 { WSAEPROTONOSUPPORT, "Protocol not supported" },
63 { WSAESOCKTNOSUPPORT, "Socket type not supported" },
64 { WSAEOPNOTSUPP, "Operation not supported" },
65 { WSAEPFNOSUPPORT, "Protocol family not supported" },
66 { WSAEAFNOSUPPORT, "Address family not supported" },
67 { WSAEADDRINUSE, "Address already in use" },
68 { WSAEADDRNOTAVAIL, "Can't assign requested address" },
69 { WSAENETDOWN, "Network is down" },
70 { WSAENETUNREACH, "Network is unreachable" },
71 { WSAENETRESET, "Network dropped connection on reset" },
72 { WSAECONNABORTED, "Software caused connection abort" },
73 { WSAECONNRESET, "Connection reset by peer" },
74 { WSAENOBUFS, "No buffer space available" },
75 { WSAEISCONN, "Socket is already connected" },
76 { WSAENOTCONN, "Socket is not connected" },
77 { WSAESHUTDOWN, "Can't send after socket shutdown" },
78 { WSAETOOMANYREFS, "Too many references: can't splice" },
79 { WSAETIMEDOUT, "Operation timed out" },
80 { WSAECONNREFUSED, "Connection refused" },
81 { WSAELOOP, "Too many levels of symbolic links" },
82 { WSAENAMETOOLONG, "File name too long" },
83 { WSAEHOSTDOWN, "Host is down" },
84 { WSAEHOSTUNREACH, "No route to host" },
85 { WSAENOTEMPTY, "Directory not empty" },
86 { WSAEPROCLIM, "Too many processes" },
87 { WSAEUSERS, "Too many users" },
88 { WSAEDQUOT, "Disc quota exceeded" },
89 { WSAESTALE, "Stale NFS file handle" },
90 { WSAEREMOTE, "Too many levels of remote in path" },
91 { WSASYSNOTREADY, "Network subsystem is unvailable" },
92 { WSAVERNOTSUPPORTED, "WinSock version is not supported" },
93 { WSANOTINITIALISED, "Successful WSAStartup() not yet performed" },
94 { WSAEDISCON, "Graceful shutdown in progress" },
96 { WSAHOST_NOT_FOUND, "No such host is known" },
97 { WSATRY_AGAIN, "Host not found, or server failed" },
98 { WSANO_RECOVERY, "Unexpected server error encountered" },
99 { WSANO_DATA, "Valid name without requested data" },
100 { WSANO_ADDRESS, "No address, look for MX record" },
104 const char *msg = "winsock error";
106 for (msgp = msgs; msgp->msg; msgp++)
108 if (errnum == msgp->num)
115 v = Py_BuildValue("(is)", errnum, msg);
118 PyErr_SetObject(ssl_SysCallError, v);
124 PyErr_SetFromErrno(ssl_SysCallError);
129 * Handle errors raised by BIO functions.
131 * Arguments: bio - The BIO object
132 * ret - The return value of the BIO_ function.
133 * Returns: None, the calling function should return NULL;
136 handle_bio_errors(BIO* bio, int ret)
138 if (BIO_should_retry(bio)) {
139 if (BIO_should_read(bio)) {
140 PyErr_SetNone(ssl_WantReadError);
141 } else if (BIO_should_write(bio)) {
142 PyErr_SetNone(ssl_WantWriteError);
143 } else if (BIO_should_io_special(bio)) {
145 * It's somewhat unclear what this means. From the OpenSSL source,
146 * it seems like it should not be triggered by the memory BIO, so
147 * for the time being, this case shouldn't come up. The SSL BIO
148 * (which I think should be named the socket BIO) may trigger this
149 * case if its socket is not yet connected or it is busy doing
150 * something related to x509.
152 PyErr_SetString(PyExc_ValueError, "BIO_should_io_special");
155 * I hope this is dead code. The BIO documentation suggests that
156 * one of the above three checks should always be true.
158 PyErr_SetString(PyExc_ValueError, "unknown bio failure");
162 * If we aren't to retry, it's really an error, so fall back to the
163 * normal error reporting code. However, the BIO interface does not
164 * specify a uniform error reporting mechanism. We can only hope that
165 * the code which triggered the error also kindly pushed something onto
168 exception_from_error_queue(ssl_Error);
173 * Handle errors raised by SSL I/O functions. NOTE: Not SSL_shutdown ;)
175 * Arguments: ssl - The SSL object
176 * err - The return code from SSL_get_error
177 * ret - The return code from the SSL I/O function
178 * Returns: None, the calling function should return NULL
181 handle_ssl_errors(SSL *ssl, int err, int ret)
186 * Strange as it may seem, ZeroReturn is not an error per se. It means
187 * that the SSL Connection has been closed correctly (note, not the
188 * transport layer!), i.e. closure alerts have been exchanged. This is
190 * + There's an SSL "error" code for it
191 * + You have to deal with it in any case, close the transport layer
194 case SSL_ERROR_ZERO_RETURN:
195 PyErr_SetNone(ssl_ZeroReturnError);
199 * The WantXYZ exceptions don't mean that there's an error, just that
200 * nothing could be read/written just now, maybe because the transport
201 * layer would block on the operation, or that there's not enough data
202 * available to fill an entire SSL record.
204 case SSL_ERROR_WANT_READ:
205 PyErr_SetNone(ssl_WantReadError);
208 case SSL_ERROR_WANT_WRITE:
209 PyErr_SetNone(ssl_WantWriteError);
212 case SSL_ERROR_WANT_X509_LOOKUP:
213 PyErr_SetNone(ssl_WantX509LookupError);
216 case SSL_ERROR_SYSCALL:
217 if (ERR_peek_error() == 0)
221 syscall_from_errno();
227 v = Py_BuildValue("(is)", -1, "Unexpected EOF");
230 PyErr_SetObject(ssl_SysCallError, v);
237 /* NOTE: Fall-through here, we don't want to duplicate code, right? */
242 exception_from_error_queue(ssl_Error);
248 * Here be member methods of the Connection "class"
251 static char ssl_Connection_get_context_doc[] = "\n\
252 Get session context\n\
254 @return: A Context object\n\
257 ssl_Connection_get_context(ssl_ConnectionObj *self, PyObject *args) {
258 if (!PyArg_ParseTuple(args, ":get_context")) {
262 Py_INCREF(self->context);
263 return (PyObject *)self->context;
266 static char ssl_Connection_pending_doc[] = "\n\
267 Get the number of bytes that can be safely read from the connection\n\
269 @return: The number of bytes available in the receive buffer.\n\
272 ssl_Connection_pending(ssl_ConnectionObj *self, PyObject *args) {
275 if (!PyArg_ParseTuple(args, ":pending")) {
279 ret = SSL_pending(self->ssl);
280 return PyLong_FromLong((long)ret);
283 static char ssl_Connection_bio_write_doc[] = "\n\
284 When using non-socket connections this function sends\n\
285 \"dirty\" data that would have traveled in on the network.\n\
287 @param buf: The string to put into the memory BIO.\n\
288 @return: The number of bytes written\n\
291 ssl_Connection_bio_write(ssl_ConnectionObj *self, PyObject *args)
296 if (self->into_ssl == NULL)
298 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
302 if (!PyArg_ParseTuple(args, "s#|i:bio_write", &buf, &len))
305 ret = BIO_write(self->into_ssl, buf, len);
307 if (PyErr_Occurred())
315 * There was a problem with the BIO_write of some sort.
317 handle_bio_errors(self->into_ssl, ret);
321 return PyLong_FromLong((long)ret);
324 static char ssl_Connection_send_doc[] = "\n\
325 Send data on the connection. NOTE: If you get one of the WantRead,\n\
326 WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
327 method again with the SAME buffer.\n\
329 @param buf: The string to send\n\
330 @param flags: (optional) Included for compatibility with the socket\n\
331 API, the value is ignored\n\
332 @return: The number of bytes written\n\
335 ssl_Connection_send(ssl_ConnectionObj *self, PyObject *args) {
336 int len, ret, err, flags;
339 #if PY_VERSION_HEX >= 0x02060000
342 if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
349 if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags))
353 MY_BEGIN_ALLOW_THREADS(self->tstate)
354 ret = SSL_write(self->ssl, buf, len);
355 MY_END_ALLOW_THREADS(self->tstate)
357 #if PY_VERSION_HEX >= 0x02060000
358 PyBuffer_Release(&pbuf);
361 if (PyErr_Occurred())
367 err = SSL_get_error(self->ssl, ret);
368 if (err == SSL_ERROR_NONE)
370 return PyLong_FromLong((long)ret);
374 handle_ssl_errors(self->ssl, err, ret);
379 static char ssl_Connection_sendall_doc[] = "\n\
380 Send \"all\" data on the connection. This calls send() repeatedly until\n\
381 all data is sent. If an error occurs, it's impossible to tell how much data\n\
384 @param buf: The string to send\n\
385 @param flags: (optional) Included for compatibility with the socket\n\
386 API, the value is ignored\n\
387 @return: The number of bytes written\n\
390 ssl_Connection_sendall(ssl_ConnectionObj *self, PyObject *args)
393 int len, ret, err, flags;
394 PyObject *pyret = Py_None;
396 #if PY_VERSION_HEX >= 0x02060000
399 if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
405 if (!PyArg_ParseTuple(args, "s#|i:sendall", &buf, &len, &flags))
410 MY_BEGIN_ALLOW_THREADS(self->tstate)
411 ret = SSL_write(self->ssl, buf, len);
412 MY_END_ALLOW_THREADS(self->tstate)
413 if (PyErr_Occurred())
419 err = SSL_get_error(self->ssl, ret);
420 if (err == SSL_ERROR_NONE)
425 else if (err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL ||
426 err == SSL_ERROR_ZERO_RETURN)
428 handle_ssl_errors(self->ssl, err, ret);
434 #if PY_VERSION_HEX >= 0x02060000
435 PyBuffer_Release(&pbuf);
442 static char ssl_Connection_recv_doc[] = "\n\
443 Receive data on the connection. NOTE: If you get one of the WantRead,\n\
444 WantWrite or WantX509Lookup exceptions on this, you have to call the\n\
445 method again with the SAME buffer.\n\
447 @param bufsiz: The maximum number of bytes to read\n\
448 @param flags: (optional) Included for compatibility with the socket\n\
449 API, the value is ignored\n\
450 @return: The string read from the Connection\n\
453 ssl_Connection_recv(ssl_ConnectionObj *self, PyObject *args)
455 int bufsiz, ret, err, flags;
458 if (!PyArg_ParseTuple(args, "i|i:recv", &bufsiz, &flags))
461 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
465 MY_BEGIN_ALLOW_THREADS(self->tstate)
466 ret = SSL_read(self->ssl, PyBytes_AsString(buf), bufsiz);
467 MY_END_ALLOW_THREADS(self->tstate)
469 if (PyErr_Occurred())
476 err = SSL_get_error(self->ssl, ret);
477 if (err == SSL_ERROR_NONE)
479 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
485 handle_ssl_errors(self->ssl, err, ret);
491 static char ssl_Connection_bio_read_doc[] = "\n\
492 When using non-socket connections this function reads\n\
493 the \"dirty\" data that would have traveled away on the network.\n\
495 @param bufsiz: The maximum number of bytes to read\n\
496 @return: The string read.\n\
499 ssl_Connection_bio_read(ssl_ConnectionObj *self, PyObject *args)
504 if (self->from_ssl == NULL)
506 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
510 if (!PyArg_ParseTuple(args, "i:bio_read", &bufsiz))
513 buf = PyBytes_FromStringAndSize(NULL, bufsiz);
517 ret = BIO_read(self->from_ssl, PyBytes_AsString(buf), bufsiz);
519 if (PyErr_Occurred())
528 * There was a problem with the BIO_read of some sort.
530 handle_bio_errors(self->from_ssl, ret);
536 * Shrink the string to match the number of bytes we actually read.
538 if (ret != bufsiz && _PyBytes_Resize(&buf, ret) < 0)
546 static char ssl_Connection_renegotiate_doc[] = "\n\
547 Renegotiate the session\n\
549 @return: True if the renegotiation can be started, false otherwise\n\
552 ssl_Connection_renegotiate(ssl_ConnectionObj *self, PyObject *args) {
555 if (!PyArg_ParseTuple(args, ":renegotiate")) {
559 MY_BEGIN_ALLOW_THREADS(self->tstate);
560 ret = SSL_renegotiate(self->ssl);
561 MY_END_ALLOW_THREADS(self->tstate);
563 if (PyErr_Occurred()) {
568 return PyLong_FromLong((long)ret);
571 static char ssl_Connection_do_handshake_doc[] = "\n\
572 Perform an SSL handshake (usually called after renegotiate() or one of\n\
573 set_*_state()). This can raise the same exceptions as send and recv.\n\
578 ssl_Connection_do_handshake(ssl_ConnectionObj *self, PyObject *args)
582 if (!PyArg_ParseTuple(args, ":do_handshake"))
585 MY_BEGIN_ALLOW_THREADS(self->tstate);
586 ret = SSL_do_handshake(self->ssl);
587 MY_END_ALLOW_THREADS(self->tstate);
589 if (PyErr_Occurred())
595 err = SSL_get_error(self->ssl, ret);
596 if (err == SSL_ERROR_NONE)
603 handle_ssl_errors(self->ssl, err, ret);
608 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
609 static char ssl_Connection_renegotiate_pending_doc[] = "\n\
610 Check if there's a renegotiation in progress, it will return false once\n\
611 a renegotiation is finished.\n\
613 @return: Whether there's a renegotiation in progress\n\
616 ssl_Connection_renegotiate_pending(ssl_ConnectionObj *self, PyObject *args)
618 if (!PyArg_ParseTuple(args, ":renegotiate_pending"))
621 return PyLong_FromLong((long)SSL_renegotiate_pending(self->ssl));
625 static char ssl_Connection_total_renegotiations_doc[] = "\n\
626 Find out the total number of renegotiations.\n\
628 @return: The number of renegotiations.\n\
631 ssl_Connection_total_renegotiations(ssl_ConnectionObj *self, PyObject *args)
633 if (!PyArg_ParseTuple(args, ":total_renegotiations"))
636 return PyLong_FromLong(SSL_total_renegotiations(self->ssl));
639 static char ssl_Connection_set_accept_state_doc[] = "\n\
640 Set the connection to work in server mode. The handshake will be handled\n\
641 automatically by read/write.\n\
646 ssl_Connection_set_accept_state(ssl_ConnectionObj *self, PyObject *args)
648 if (!PyArg_ParseTuple(args, ":set_accept_state"))
651 SSL_set_accept_state(self->ssl);
657 static char ssl_Connection_set_connect_state_doc[] = "\n\
658 Set the connection to work in client mode. The handshake will be handled\n\
659 automatically by read/write.\n\
664 ssl_Connection_set_connect_state(ssl_ConnectionObj *self, PyObject *args)
666 if (!PyArg_ParseTuple(args, ":set_connect_state"))
669 SSL_set_connect_state(self->ssl);
675 static char ssl_Connection_connect_doc[] = "\n\
676 Connect to remote host and set up client-side SSL\n\
678 @param addr: A remote address\n\
679 @return: What the socket's connect method returns\n\
682 ssl_Connection_connect(ssl_ConnectionObj *self, PyObject *args)
684 PyObject *meth, *ret;
686 if ((meth = PyObject_GetAttrString(self->socket, "connect")) == NULL)
689 SSL_set_connect_state(self->ssl);
691 ret = PyEval_CallObject(meth, args);
699 static char ssl_Connection_connect_ex_doc[] = "\n\
700 Connect to remote host and set up client-side SSL. Note that if the socket's\n\
701 connect_ex method doesn't return 0, SSL won't be initialized.\n\
703 @param addr: A remove address\n\
704 @return: What the socket's connect_ex method returns\n\
707 ssl_Connection_connect_ex(ssl_ConnectionObj *self, PyObject *args)
709 PyObject *meth, *ret;
711 if ((meth = PyObject_GetAttrString(self->socket, "connect_ex")) == NULL)
714 SSL_set_connect_state(self->ssl);
716 ret = PyEval_CallObject(meth, args);
721 static char ssl_Connection_accept_doc[] = "\n\
722 Accept incoming connection and set up SSL on it\n\
724 @return: A (conn,addr) pair where conn is a Connection and addr is an\n\
728 ssl_Connection_accept(ssl_ConnectionObj *self, PyObject *args)
730 PyObject *tuple, *socket, *address, *meth;
731 ssl_ConnectionObj *conn;
733 if ((meth = PyObject_GetAttrString(self->socket, "accept")) == NULL)
735 tuple = PyEval_CallObject(meth, args);
740 socket = PyTuple_GetItem(tuple, 0);
742 address = PyTuple_GetItem(tuple, 1);
746 conn = ssl_Connection_New(self->context, socket);
754 SSL_set_accept_state(conn->ssl);
756 tuple = Py_BuildValue("(OO)", conn, address);
764 static char ssl_Connection_bio_shutdown_doc[] = "\n\
765 When using non-socket connections this function signals end of\n\
766 data on the input for this connection.\n\
772 ssl_Connection_bio_shutdown(ssl_ConnectionObj *self, PyObject *args)
774 if (self->from_ssl == NULL)
776 PyErr_SetString(PyExc_TypeError, "Connection sock was not None");
780 BIO_set_mem_eof_return(self->into_ssl, 0);
787 static char ssl_Connection_shutdown_doc[] = "\n\
788 Send closure alert\n\
790 @return: True if the shutdown completed successfully (i.e. both sides\n\
791 have sent closure alerts), false otherwise (i.e. you have to\n\
792 wait for a ZeroReturnError on a recv() method call\n\
795 ssl_Connection_shutdown(ssl_ConnectionObj *self, PyObject *args)
799 if (!PyArg_ParseTuple(args, ":shutdown"))
802 MY_BEGIN_ALLOW_THREADS(self->tstate)
803 ret = SSL_shutdown(self->ssl);
804 MY_END_ALLOW_THREADS(self->tstate)
806 if (PyErr_Occurred())
814 exception_from_error_queue(ssl_Error);
829 static char ssl_Connection_get_cipher_list_doc[] = "\n\
830 Get the session cipher list\n\
832 @return: A list of cipher strings\n\
835 ssl_Connection_get_cipher_list(ssl_ConnectionObj *self, PyObject *args)
839 PyObject *lst, *item;
841 if (!PyArg_ParseTuple(args, ":get_cipher_list"))
845 while ((ret = SSL_get_cipher_list(self->ssl, idx)) != NULL)
847 item = PyText_FromString(ret);
848 PyList_Append(lst, item);
855 static char ssl_Connection_get_client_ca_list_doc[] = "\n\
856 Get CAs whose certificates are suggested for client authentication.\n\
858 @return: If this is a server connection, a list of X509Names representing\n\
859 the acceptable CAs as set by L{OpenSSL.SSL.Context.set_client_ca_list} or\n\
860 L{OpenSSL.SSL.Context.add_client_ca}. If this is a client connection,\n\
861 the list of such X509Names sent by the server, or an empty list if that\n\
862 has not yet happened.\n\
866 ssl_Connection_get_client_ca_list(ssl_ConnectionObj *self, PyObject *args) {
867 STACK_OF(X509_NAME) *CANames;
871 if (!PyArg_ParseTuple(args, ":get_client_ca_list")) {
874 CANames = SSL_get_client_CA_list(self->ssl);
875 if (CANames == NULL) {
876 return PyList_New(0);
878 n = sk_X509_NAME_num(CANames);
879 CAList = PyList_New(n);
880 if (CAList == NULL) {
883 for (i = 0; i < n; i++) {
887 CAName = X509_NAME_dup(sk_X509_NAME_value(CANames, i));
888 if (CAName == NULL) {
890 exception_from_error_queue(ssl_Error);
893 CA = (PyObject *)new_x509name(CAName, 1);
895 X509_NAME_free(CAName);
899 if (PyList_SetItem(CAList, i, CA)) {
908 static char ssl_Connection_makefile_doc[] = "\n\
909 The makefile() method is not implemented, since there is no dup semantics\n\
910 for SSL connections\n\
912 @raise NotImplementedError\n\
915 ssl_Connection_makefile(ssl_ConnectionObj *self, PyObject *args)
917 PyErr_SetString(PyExc_NotImplementedError, "Cannot make file object of SSL.Connection");
921 static char ssl_Connection_get_app_data_doc[] = "\n\
922 Get application data\n\
924 @return: The application data\n\
927 ssl_Connection_get_app_data(ssl_ConnectionObj *self, PyObject *args)
929 if (!PyArg_ParseTuple(args, ":get_app_data"))
932 Py_INCREF(self->app_data);
933 return self->app_data;
936 static char ssl_Connection_set_app_data_doc[] = "\n\
937 Set application data\n\
939 @param data - The application data\n\
943 ssl_Connection_set_app_data(ssl_ConnectionObj *self, PyObject *args)
947 if (!PyArg_ParseTuple(args, "O:set_app_data", &data))
950 Py_DECREF(self->app_data);
952 self->app_data = data;
958 static char ssl_Connection_get_shutdown_doc[] = "\n\
959 Get shutdown state\n\
961 @return: The shutdown state, a bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
964 ssl_Connection_get_shutdown(ssl_ConnectionObj *self, PyObject *args)
966 if (!PyArg_ParseTuple(args, ":get_shutdown"))
969 return PyLong_FromLong((long)SSL_get_shutdown(self->ssl));
972 static char ssl_Connection_set_shutdown_doc[] = "\n\
973 Set shutdown state\n\
975 @param state - bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.\n\
979 ssl_Connection_set_shutdown(ssl_ConnectionObj *self, PyObject *args)
983 if (!PyArg_ParseTuple(args, "i:set_shutdown", &shutdown))
986 SSL_set_shutdown(self->ssl, shutdown);
991 static char ssl_Connection_state_string_doc[] = "\n\
992 Get a verbose state description\n\
994 @return: A string representing the state\n\
997 ssl_Connection_state_string(ssl_ConnectionObj *self, PyObject *args)
999 if (!PyArg_ParseTuple(args, ":state_string"))
1002 return PyText_FromString(SSL_state_string_long(self->ssl));
1005 static char ssl_Connection_client_random_doc[] = "\n\
1006 Get a copy of the client hello nonce.\n\
1008 @return: A string representing the state\n\
1011 ssl_Connection_client_random(ssl_ConnectionObj *self, PyObject *args)
1013 if (!PyArg_ParseTuple(args, ":client_random"))
1016 if (self->ssl->session == NULL) {
1020 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->client_random, SSL3_RANDOM_SIZE);
1023 static char ssl_Connection_server_random_doc[] = "\n\
1024 Get a copy of the server hello nonce.\n\
1026 @return: A string representing the state\n\
1029 ssl_Connection_server_random(ssl_ConnectionObj *self, PyObject *args)
1031 if (!PyArg_ParseTuple(args, ":server_random"))
1034 if (self->ssl->session == NULL) {
1038 return PyBytes_FromStringAndSize( (const char *) self->ssl->s3->server_random, SSL3_RANDOM_SIZE);
1041 static char ssl_Connection_master_key_doc[] = "\n\
1042 Get a copy of the master key.\n\
1044 @return: A string representing the state\n\
1047 ssl_Connection_master_key(ssl_ConnectionObj *self, PyObject *args)
1049 if (!PyArg_ParseTuple(args, ":master_key"))
1052 if (self->ssl->session == NULL) {
1056 return PyBytes_FromStringAndSize( (const char *) self->ssl->session->master_key, self->ssl->session->master_key_length);
1059 static char ssl_Connection_sock_shutdown_doc[] = "\n\
1062 @return: What the socket's shutdown() method returns\n\
1065 ssl_Connection_sock_shutdown(ssl_ConnectionObj *self, PyObject *args)
1067 PyObject *meth, *ret;
1069 if ((meth = PyObject_GetAttrString(self->socket, "shutdown")) == NULL)
1071 ret = PyEval_CallObject(meth, args);
1076 static char ssl_Connection_get_peer_certificate_doc[] = "\n\
1077 Retrieve the other side's certificate (if any)\n\
1079 @return: The peer's certificate\n\
1082 ssl_Connection_get_peer_certificate(ssl_ConnectionObj *self, PyObject *args)
1086 if (!PyArg_ParseTuple(args, ":get_peer_certificate"))
1089 cert = SSL_get_peer_certificate(self->ssl);
1092 return (PyObject *)new_x509(cert, 1);
1101 static char ssl_Connection_want_read_doc[] = "\n\
1102 Checks if more data has to be read from the transport layer to complete an\n\
1105 @return: True iff more data has to be read\n\
1108 ssl_Connection_want_read(ssl_ConnectionObj *self, PyObject *args)
1110 if (!PyArg_ParseTuple(args, ":want_read"))
1113 return PyLong_FromLong((long)SSL_want_read(self->ssl));
1116 static char ssl_Connection_want_write_doc[] = "\n\
1117 Checks if there is data to write to the transport layer to complete an\n\
1120 @return: True iff there is data to write\n\
1123 ssl_Connection_want_write(ssl_ConnectionObj *self, PyObject *args)
1125 if (!PyArg_ParseTuple(args, ":want_write"))
1128 return PyLong_FromLong((long)SSL_want_write(self->ssl));
1132 * Member methods in the Connection object
1133 * ADD_METHOD(name) expands to a correct PyMethodDef declaration
1134 * { 'name', (PyCFunction)ssl_Connection_name, METH_VARARGS }
1136 * ADD_ALIAS(name,real) creates an "alias" of the ssl_Connection_real
1137 * function with the name 'name'
1139 #define ADD_METHOD(name) \
1140 { #name, (PyCFunction)ssl_Connection_##name, METH_VARARGS, ssl_Connection_##name##_doc }
1141 #define ADD_ALIAS(name,real) \
1142 { #name, (PyCFunction)ssl_Connection_##real, METH_VARARGS, ssl_Connection_##real##_doc }
1143 static PyMethodDef ssl_Connection_methods[] =
1145 ADD_METHOD(get_context),
1146 ADD_METHOD(pending),
1148 ADD_ALIAS (write, send),
1149 ADD_METHOD(sendall),
1151 ADD_ALIAS (read, recv),
1152 ADD_METHOD(bio_read),
1153 ADD_METHOD(bio_write),
1154 ADD_METHOD(renegotiate),
1155 ADD_METHOD(do_handshake),
1156 #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x00907000L
1157 ADD_METHOD(renegotiate_pending),
1159 ADD_METHOD(total_renegotiations),
1160 ADD_METHOD(connect),
1161 ADD_METHOD(connect_ex),
1163 ADD_METHOD(bio_shutdown),
1164 ADD_METHOD(shutdown),
1165 ADD_METHOD(get_cipher_list),
1166 ADD_METHOD(get_client_ca_list),
1167 ADD_METHOD(makefile),
1168 ADD_METHOD(get_app_data),
1169 ADD_METHOD(set_app_data),
1170 ADD_METHOD(get_shutdown),
1171 ADD_METHOD(set_shutdown),
1172 ADD_METHOD(state_string),
1173 ADD_METHOD(server_random),
1174 ADD_METHOD(client_random),
1175 ADD_METHOD(master_key),
1176 ADD_METHOD(sock_shutdown),
1177 ADD_METHOD(get_peer_certificate),
1178 ADD_METHOD(want_read),
1179 ADD_METHOD(want_write),
1180 ADD_METHOD(set_accept_state),
1181 ADD_METHOD(set_connect_state),
1187 static char ssl_Connection_doc[] = "\n\
1188 Connection(context, socket) -> Connection instance\n\
1190 Create a new Connection object, using the given OpenSSL.SSL.Context instance\n\
1193 @param context: An SSL Context to use for this connection\n\
1194 @param socket: The socket to use for transport layer\n\
1198 * Initializer used by ssl_Connection_new and ssl_Connection_New. *Not*
1199 * tp_init. This takes an already allocated ssl_ConnectionObj, a context, and
1200 * a optionally a socket, and glues them all together.
1202 static ssl_ConnectionObj*
1203 ssl_Connection_init(ssl_ConnectionObj *self, ssl_ContextObj *ctx, PyObject *sock) {
1207 self->context = ctx;
1210 self->socket = sock;
1213 self->from_ssl = NULL;
1214 self->into_ssl = NULL;
1217 self->app_data = Py_None;
1219 self->tstate = NULL;
1221 self->ssl = SSL_new(self->context->ctx);
1222 SSL_set_app_data(self->ssl, self);
1224 if (self->socket == Py_None)
1226 /* If it's not a socket or file, treat it like a memory buffer,
1227 * so crazy people can do things like EAP-TLS. */
1228 self->into_ssl = BIO_new(BIO_s_mem());
1229 self->from_ssl = BIO_new(BIO_s_mem());
1230 if (self->into_ssl == NULL || self->from_ssl == NULL)
1232 SSL_set_bio(self->ssl, self->into_ssl, self->from_ssl);
1236 fd = PyObject_AsFileDescriptor(self->socket);
1244 SSL_set_fd(self->ssl, (SOCKET_T)fd);
1250 BIO_free(self->into_ssl); /* NULL safe */
1251 BIO_free(self->from_ssl); /* NULL safe */
1257 * Constructor for Connection objects
1259 * Arguments: ctx - An SSL Context to use for this connection
1260 * sock - The socket to use for transport layer
1261 * Returns: The newly created Connection object
1264 ssl_Connection_New(ssl_ContextObj *ctx, PyObject *sock) {
1265 ssl_ConnectionObj *self;
1267 self = PyObject_GC_New(ssl_ConnectionObj, &ssl_Connection_Type);
1271 self = ssl_Connection_init(self, ctx, sock);
1275 PyObject_GC_Track((PyObject *)self);
1280 ssl_Connection_new(PyTypeObject *subtype, PyObject *args, PyObject *kwargs) {
1281 ssl_ConnectionObj *self;
1282 ssl_ContextObj *ctx;
1284 static char *kwlist[] = {"context", "socket", NULL};
1286 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!O:Connection", kwlist,
1287 &ssl_Context_Type, &ctx, &sock)) {
1291 self = (ssl_ConnectionObj *)subtype->tp_alloc(subtype, 1);
1296 return (PyObject *)ssl_Connection_init(self, ctx, sock);
1302 * Arguments: self - The Connection object
1303 * name - The attribute name
1304 * Returns: A Python object for the attribute, or NULL if something went
1308 ssl_Connection_getattro(ssl_ConnectionObj *self, PyObject *nameobj) {
1311 meth = PyObject_GenericGetAttr((PyObject*)self, nameobj);
1312 if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1314 /* Try looking it up in the "socket" instead. */
1315 meth = PyObject_GenericGetAttr(self->socket, nameobj);
1322 * Call the visitproc on all contained objects.
1324 * Arguments: self - The Connection object
1325 * visit - Function to call
1326 * arg - Extra argument to visit
1327 * Returns: 0 if all goes well, otherwise the return code from the first
1328 * call that gave non-zero result.
1331 ssl_Connection_traverse(ssl_ConnectionObj *self, visitproc visit, void *arg)
1335 if (ret == 0 && self->context != NULL)
1336 ret = visit((PyObject *)self->context, arg);
1337 if (ret == 0 && self->socket != NULL)
1338 ret = visit(self->socket, arg);
1339 if (ret == 0 && self->app_data != NULL)
1340 ret = visit(self->app_data, arg);
1345 * Decref all contained objects and zero the pointers.
1347 * Arguments: self - The Connection object
1348 * Returns: Always 0.
1351 ssl_Connection_clear(ssl_ConnectionObj *self)
1353 Py_XDECREF(self->context);
1354 self->context = NULL;
1355 Py_XDECREF(self->socket);
1356 self->socket = NULL;
1357 Py_XDECREF(self->app_data);
1358 self->app_data = NULL;
1359 self->into_ssl = NULL; /* was cleaned up by SSL_free() */
1360 self->from_ssl = NULL; /* was cleaned up by SSL_free() */
1365 * Deallocate the memory used by the Connection object
1367 * Arguments: self - The Connection object
1371 ssl_Connection_dealloc(ssl_ConnectionObj *self)
1373 PyObject_GC_UnTrack(self);
1374 if (self->ssl != NULL)
1375 SSL_free(self->ssl);
1376 ssl_Connection_clear(self);
1377 PyObject_GC_Del(self);
1380 PyTypeObject ssl_Connection_Type = {
1381 PyOpenSSL_HEAD_INIT(&PyType_Type, 0)
1382 "OpenSSL.SSL.Connection",
1383 sizeof(ssl_ConnectionObj),
1385 (destructor)ssl_Connection_dealloc,
1387 NULL, /* tp_getattr */
1391 NULL, /* as_number */
1392 NULL, /* as_sequence */
1393 NULL, /* as_mapping */
1397 (getattrofunc)ssl_Connection_getattro, /* getattro */
1398 NULL, /* setattro */
1399 NULL, /* as_buffer */
1400 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1401 ssl_Connection_doc, /* doc */
1402 (traverseproc)ssl_Connection_traverse,
1403 (inquiry)ssl_Connection_clear,
1404 NULL, /* tp_richcompare */
1405 0, /* tp_weaklistoffset */
1407 NULL, /* tp_iternext */
1408 ssl_Connection_methods, /* tp_methods */
1409 NULL, /* tp_members */
1410 NULL, /* tp_getset */
1413 NULL, /* tp_descr_get */
1414 NULL, /* tp_descr_set */
1415 0, /* tp_dictoffset */
1417 NULL, /* tp_alloc */
1418 ssl_Connection_new, /* tp_new */
1423 * Initiailze the Connection part of the SSL sub module
1425 * Arguments: dict - The OpenSSL.SSL module
1426 * Returns: 1 for success, 0 otherwise
1429 init_ssl_connection(PyObject *module) {
1431 if (PyType_Ready(&ssl_Connection_Type) < 0) {
1435 if (PyModule_AddObject(module, "Connection", (PyObject *)&ssl_Connection_Type) != 0) {
1439 if (PyModule_AddObject(module, "ConnectionType", (PyObject *)&ssl_Connection_Type) != 0) {