3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
5 This module is imported by socket.py. It should *not* be used
12 /* these mirror ssl.h */
15 PY_SSL_ERROR_WANT_READ
,
16 PY_SSL_ERROR_WANT_WRITE
,
17 PY_SSL_ERROR_WANT_X509_LOOKUP
,
18 PY_SSL_ERROR_SYSCALL
, /* look at error stack/return value/errno */
19 PY_SSL_ERROR_ZERO_RETURN
,
20 PY_SSL_ERROR_WANT_CONNECT
,
21 /* start of non ssl.h errorcodes */
22 PY_SSL_ERROR_EOF
, /* special case of SSL_ERROR_SYSCALL */
23 PY_SSL_ERROR_INVALID_ERROR_CODE
26 /* Include symbols from _socket module */
27 #include "socketmodule.h"
29 #if defined(HAVE_POLL_H)
31 #elif defined(HAVE_SYS_POLL_H)
35 /* Include OpenSSL header files */
36 #include "openssl/rsa.h"
37 #include "openssl/crypto.h"
38 #include "openssl/x509.h"
39 #include "openssl/pem.h"
40 #include "openssl/ssl.h"
41 #include "openssl/err.h"
42 #include "openssl/rand.h"
44 /* SSL error object */
45 static PyObject
*PySSLErrorObject
;
47 /* SSL socket object */
49 #define X509_NAME_MAXLEN 256
51 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
52 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
53 # define HAVE_OPENSSL_RAND 1
55 # undef HAVE_OPENSSL_RAND
60 PySocketSockObject
*Socket
; /* Socket on which we're layered */
64 char server
[X509_NAME_MAXLEN
];
65 char issuer
[X509_NAME_MAXLEN
];
69 static PyTypeObject PySSL_Type
;
70 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
71 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
72 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
75 #define PySSLObject_Check(v) ((v)->ob_type == &PySSL_Type)
78 SOCKET_IS_NONBLOCKING
,
81 SOCKET_HAS_BEEN_CLOSED
,
82 SOCKET_TOO_LARGE_FOR_SELECT
,
86 /* XXX It might be helpful to augment the error message generated
87 below with the name of the SSL function that generated the error.
88 I expect it's obvious most of the time.
92 PySSL_SetError(PySSLObject
*obj
, int ret
)
101 err
= SSL_get_error(obj
->ssl
, ret
);
104 case SSL_ERROR_ZERO_RETURN
:
105 errstr
= "TLS/SSL connection has been closed";
106 p
= PY_SSL_ERROR_ZERO_RETURN
;
108 case SSL_ERROR_WANT_READ
:
109 errstr
= "The operation did not complete (read)";
110 p
= PY_SSL_ERROR_WANT_READ
;
112 case SSL_ERROR_WANT_WRITE
:
113 p
= PY_SSL_ERROR_WANT_WRITE
;
114 errstr
= "The operation did not complete (write)";
116 case SSL_ERROR_WANT_X509_LOOKUP
:
117 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
118 errstr
= "The operation did not complete (X509 lookup)";
120 case SSL_ERROR_WANT_CONNECT
:
121 p
= PY_SSL_ERROR_WANT_CONNECT
;
122 errstr
= "The operation did not complete (connect)";
124 case SSL_ERROR_SYSCALL
:
126 unsigned long e
= ERR_get_error();
128 if (ret
== 0 || !obj
->Socket
) {
129 p
= PY_SSL_ERROR_EOF
;
130 errstr
= "EOF occurred in violation of protocol";
131 } else if (ret
== -1) {
132 /* the underlying BIO reported an I/O error */
133 return obj
->Socket
->errorhandler();
134 } else { /* possible? */
135 p
= PY_SSL_ERROR_SYSCALL
;
136 errstr
= "Some I/O error occurred";
139 p
= PY_SSL_ERROR_SYSCALL
;
140 /* XXX Protected by global interpreter lock */
141 errstr
= ERR_error_string(e
, NULL
);
147 unsigned long e
= ERR_get_error();
148 p
= PY_SSL_ERROR_SSL
;
150 /* XXX Protected by global interpreter lock */
151 errstr
= ERR_error_string(e
, NULL
);
152 else { /* possible? */
153 errstr
= "A failure in the SSL library occurred";
158 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
159 errstr
= "Invalid error code";
161 n
= PyInt_FromLong((long) p
);
170 s
= PyString_FromString(errstr
);
175 PyTuple_SET_ITEM(v
, 0, n
);
176 PyTuple_SET_ITEM(v
, 1, s
);
177 PyErr_SetObject(PySSLErrorObject
, v
);
183 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
)
191 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
194 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
195 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
196 self
->server_cert
= NULL
;
201 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
202 errstr
= "Both the key & certificate files must be specified";
206 Py_BEGIN_ALLOW_THREADS
207 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
209 if (self
->ctx
== NULL
) {
210 errstr
= "SSL_CTX_new error";
215 Py_BEGIN_ALLOW_THREADS
216 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
220 errstr
= "SSL_CTX_use_PrivateKey_file error";
224 Py_BEGIN_ALLOW_THREADS
225 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
228 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
); /* ssl compatibility */
230 errstr
= "SSL_CTX_use_certificate_chain_file error";
235 Py_BEGIN_ALLOW_THREADS
236 SSL_CTX_set_verify(self
->ctx
,
237 SSL_VERIFY_NONE
, NULL
); /* set verify lvl */
238 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
240 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
242 /* If the socket is in non-blocking mode or timeout mode, set the BIO
243 * to non-blocking mode (blocking is the default)
245 if (Sock
->sock_timeout
>= 0.0) {
246 /* Set both the read and write BIO's to non-blocking mode */
247 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
248 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
251 Py_BEGIN_ALLOW_THREADS
252 SSL_set_connect_state(self
->ssl
);
255 /* Actually negotiate SSL connection */
256 /* XXX If SSL_connect() returns 0, it's also a failure. */
259 Py_BEGIN_ALLOW_THREADS
260 ret
= SSL_connect(self
->ssl
);
261 err
= SSL_get_error(self
->ssl
, ret
);
263 if(PyErr_CheckSignals()) {
266 if (err
== SSL_ERROR_WANT_READ
) {
267 sockstate
= check_socket_and_wait_for_timeout(Sock
, 0);
268 } else if (err
== SSL_ERROR_WANT_WRITE
) {
269 sockstate
= check_socket_and_wait_for_timeout(Sock
, 1);
271 sockstate
= SOCKET_OPERATION_OK
;
273 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
274 PyErr_SetString(PySSLErrorObject
, "The connect operation timed out");
276 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
277 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
279 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
280 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
282 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
285 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
287 PySSL_SetError(self
, ret
);
290 self
->ssl
->debug
= 1;
292 Py_BEGIN_ALLOW_THREADS
293 if ((self
->server_cert
= SSL_get_peer_certificate(self
->ssl
))) {
294 X509_NAME_oneline(X509_get_subject_name(self
->server_cert
),
295 self
->server
, X509_NAME_MAXLEN
);
296 X509_NAME_oneline(X509_get_issuer_name(self
->server_cert
),
297 self
->issuer
, X509_NAME_MAXLEN
);
301 Py_INCREF(self
->Socket
);
305 PyErr_SetString(PySSLErrorObject
, errstr
);
311 PySocket_ssl(PyObject
*self
, PyObject
*args
)
314 PySocketSockObject
*Sock
;
315 char *key_file
= NULL
;
316 char *cert_file
= NULL
;
318 if (!PyArg_ParseTuple(args
, "O!|zz:ssl",
319 PySocketModule
.Sock_Type
,
321 &key_file
, &cert_file
))
324 rv
= newPySSLObject(Sock
, key_file
, cert_file
);
327 return (PyObject
*)rv
;
330 PyDoc_STRVAR(ssl_doc
,
331 "ssl(socket, [keyfile, certfile]) -> sslobject");
333 /* SSL object methods */
336 PySSL_server(PySSLObject
*self
)
338 return PyString_FromString(self
->server
);
342 PySSL_issuer(PySSLObject
*self
)
344 return PyString_FromString(self
->issuer
);
348 static void PySSL_dealloc(PySSLObject
*self
)
350 if (self
->server_cert
) /* Possible not to have one? */
351 X509_free (self
->server_cert
);
355 SSL_CTX_free(self
->ctx
);
356 Py_XDECREF(self
->Socket
);
360 /* If the socket has a timeout, do a select()/poll() on the socket.
361 The argument writing indicates the direction.
362 Returns one of the possibilities in the timeout_state enum (above).
366 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
372 /* Nothing to do unless we're in timeout mode (not non-blocking) */
373 if (s
->sock_timeout
< 0.0)
374 return SOCKET_IS_BLOCKING
;
375 else if (s
->sock_timeout
== 0.0)
376 return SOCKET_IS_NONBLOCKING
;
378 /* Guard against closed socket */
380 return SOCKET_HAS_BEEN_CLOSED
;
382 /* Prefer poll, if available, since you can poll() any fd
383 * which can't be done with select(). */
386 struct pollfd pollfd
;
389 pollfd
.fd
= s
->sock_fd
;
390 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
392 /* s->sock_timeout is in seconds, timeout in ms */
393 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
394 Py_BEGIN_ALLOW_THREADS
395 rc
= poll(&pollfd
, 1, timeout
);
402 /* Guard against socket too large for select*/
403 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
404 if (s
->sock_fd
>= FD_SETSIZE
)
405 return SOCKET_TOO_LARGE_FOR_SELECT
;
408 /* Construct the arguments to select */
409 tv
.tv_sec
= (int)s
->sock_timeout
;
410 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
412 FD_SET(s
->sock_fd
, &fds
);
414 /* See if the socket is ready */
415 Py_BEGIN_ALLOW_THREADS
417 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
419 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
423 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
424 (when we are able to write or when there's something to read) */
425 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
428 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
436 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &count
))
439 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
440 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
441 PyErr_SetString(PySSLErrorObject
, "The write operation timed out");
443 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
444 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
446 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
447 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
452 Py_BEGIN_ALLOW_THREADS
453 len
= SSL_write(self
->ssl
, data
, count
);
454 err
= SSL_get_error(self
->ssl
, len
);
456 if(PyErr_CheckSignals()) {
459 if (err
== SSL_ERROR_WANT_READ
) {
460 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
461 } else if (err
== SSL_ERROR_WANT_WRITE
) {
462 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
464 sockstate
= SOCKET_OPERATION_OK
;
466 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
467 PyErr_SetString(PySSLErrorObject
, "The write operation timed out");
469 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
470 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
472 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
475 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
477 return PyInt_FromLong(len
);
479 return PySSL_SetError(self
, len
);
482 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
485 Writes the string s into the SSL object. Returns the number\n\
488 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
496 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
499 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
502 /* first check if there are bytes ready to be read */
503 Py_BEGIN_ALLOW_THREADS
504 count
= SSL_pending(self
->ssl
);
508 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
509 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
510 PyErr_SetString(PySSLErrorObject
, "The read operation timed out");
513 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
514 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
520 Py_BEGIN_ALLOW_THREADS
521 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
522 err
= SSL_get_error(self
->ssl
, count
);
524 if(PyErr_CheckSignals()) {
528 if (err
== SSL_ERROR_WANT_READ
) {
529 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
530 } else if (err
== SSL_ERROR_WANT_WRITE
) {
531 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
533 sockstate
= SOCKET_OPERATION_OK
;
535 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
536 PyErr_SetString(PySSLErrorObject
, "The read operation timed out");
539 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
542 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
545 return PySSL_SetError(self
, count
);
548 _PyString_Resize(&buf
, count
);
552 PyDoc_STRVAR(PySSL_SSLread_doc
,
553 "read([len]) -> string\n\
555 Read up to len bytes from the SSL socket.");
557 static PyMethodDef PySSLMethods
[] = {
558 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
560 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
562 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
563 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
567 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
569 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
572 static PyTypeObject PySSL_Type
= {
573 PyObject_HEAD_INIT(NULL
)
575 "socket.SSL", /*tp_name*/
576 sizeof(PySSLObject
), /*tp_basicsize*/
579 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
581 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
586 0, /*tp_as_sequence*/
591 #ifdef HAVE_OPENSSL_RAND
593 /* helper routines for seeding the SSL PRNG */
595 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
601 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
603 RAND_add(buf
, len
, entropy
);
608 PyDoc_STRVAR(PySSL_RAND_add_doc
,
609 "RAND_add(string, entropy)\n\
611 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
612 bound on the entropy contained in string.");
615 PySSL_RAND_status(PyObject
*self
)
617 return PyInt_FromLong(RAND_status());
620 PyDoc_STRVAR(PySSL_RAND_status_doc
,
621 "RAND_status() -> 0 or 1\n\
623 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
624 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
625 using the ssl() function.");
628 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
632 if (!PyString_Check(arg
))
633 return PyErr_Format(PyExc_TypeError
,
634 "RAND_egd() expected string, found %s",
635 arg
->ob_type
->tp_name
);
636 bytes
= RAND_egd(PyString_AS_STRING(arg
));
638 PyErr_SetString(PySSLErrorObject
,
639 "EGD connection failed or EGD did not return "
640 "enough data to seed the PRNG");
643 return PyInt_FromLong(bytes
);
646 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
647 "RAND_egd(path) -> bytes\n\
649 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
650 of bytes read. Raises socket.sslerror if connection to EGD fails or\n\
651 if it does provide enough data to seed PRNG.");
655 /* List of functions exported by this module. */
657 static PyMethodDef PySSL_methods
[] = {
658 {"ssl", PySocket_ssl
,
659 METH_VARARGS
, ssl_doc
},
660 #ifdef HAVE_OPENSSL_RAND
661 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
663 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
665 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
666 PySSL_RAND_status_doc
},
668 {NULL
, NULL
} /* Sentinel */
672 PyDoc_STRVAR(module_doc
,
673 "Implementation module for SSL socket operations. See the socket module\n\
674 for documentation.");
681 PySSL_Type
.ob_type
= &PyType_Type
;
683 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
686 d
= PyModule_GetDict(m
);
688 /* Load _socket module and its C API */
689 if (PySocketModule_ImportModuleAndAPI())
693 SSL_load_error_strings();
694 SSLeay_add_ssl_algorithms();
696 /* Add symbols to module dict */
697 PySSLErrorObject
= PyErr_NewException("socket.sslerror",
698 PySocketModule
.error
,
700 if (PySSLErrorObject
== NULL
)
702 PyDict_SetItemString(d
, "sslerror", PySSLErrorObject
);
703 if (PyDict_SetItemString(d
, "SSLType",
704 (PyObject
*)&PySSL_Type
) != 0)
706 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
707 PY_SSL_ERROR_ZERO_RETURN
);
708 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
709 PY_SSL_ERROR_WANT_READ
);
710 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
711 PY_SSL_ERROR_WANT_WRITE
);
712 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
713 PY_SSL_ERROR_WANT_X509_LOOKUP
);
714 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
715 PY_SSL_ERROR_SYSCALL
);
716 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
718 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
719 PY_SSL_ERROR_WANT_CONNECT
);
720 /* non ssl.h errorcodes */
721 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
723 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
724 PY_SSL_ERROR_INVALID_ERROR_CODE
);