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 /* Include OpenSSL header files */
30 #include "openssl/rsa.h"
31 #include "openssl/crypto.h"
32 #include "openssl/x509.h"
33 #include "openssl/pem.h"
34 #include "openssl/ssl.h"
35 #include "openssl/err.h"
36 #include "openssl/rand.h"
38 /* SSL error object */
39 static PyObject
*PySSLErrorObject
;
41 /* SSL socket object */
43 #define X509_NAME_MAXLEN 256
45 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
46 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
47 # define HAVE_OPENSSL_RAND 1
49 # undef HAVE_OPENSSL_RAND
54 PySocketSockObject
*Socket
; /* Socket on which we're layered */
58 char server
[X509_NAME_MAXLEN
];
59 char issuer
[X509_NAME_MAXLEN
];
63 static PyTypeObject PySSL_Type
;
64 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
65 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
66 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
69 #define PySSLObject_Check(v) ((v)->ob_type == &PySSL_Type)
72 SOCKET_IS_NONBLOCKING
,
75 SOCKET_HAS_BEEN_CLOSED
,
76 SOCKET_TOO_LARGE_FOR_SELECT
,
80 /* XXX It might be helpful to augment the error message generated
81 below with the name of the SSL function that generated the error.
82 I expect it's obvious most of the time.
86 PySSL_SetError(PySSLObject
*obj
, int ret
)
95 err
= SSL_get_error(obj
->ssl
, ret
);
98 case SSL_ERROR_ZERO_RETURN
:
99 errstr
= "TLS/SSL connection has been closed";
100 p
= PY_SSL_ERROR_ZERO_RETURN
;
102 case SSL_ERROR_WANT_READ
:
103 errstr
= "The operation did not complete (read)";
104 p
= PY_SSL_ERROR_WANT_READ
;
106 case SSL_ERROR_WANT_WRITE
:
107 p
= PY_SSL_ERROR_WANT_WRITE
;
108 errstr
= "The operation did not complete (write)";
110 case SSL_ERROR_WANT_X509_LOOKUP
:
111 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
112 errstr
= "The operation did not complete (X509 lookup)";
114 case SSL_ERROR_WANT_CONNECT
:
115 p
= PY_SSL_ERROR_WANT_CONNECT
;
116 errstr
= "The operation did not complete (connect)";
118 case SSL_ERROR_SYSCALL
:
120 unsigned long e
= ERR_get_error();
122 if (ret
== 0 || !obj
->Socket
) {
123 p
= PY_SSL_ERROR_EOF
;
124 errstr
= "EOF occurred in violation of protocol";
125 } else if (ret
== -1) {
126 /* the underlying BIO reported an I/O error */
127 return obj
->Socket
->errorhandler();
128 } else { /* possible? */
129 p
= PY_SSL_ERROR_SYSCALL
;
130 errstr
= "Some I/O error occurred";
133 p
= PY_SSL_ERROR_SYSCALL
;
134 /* XXX Protected by global interpreter lock */
135 errstr
= ERR_error_string(e
, NULL
);
141 unsigned long e
= ERR_get_error();
142 p
= PY_SSL_ERROR_SSL
;
144 /* XXX Protected by global interpreter lock */
145 errstr
= ERR_error_string(e
, NULL
);
146 else { /* possible? */
147 errstr
= "A failure in the SSL library occurred";
152 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
153 errstr
= "Invalid error code";
155 n
= PyInt_FromLong((long) p
);
164 s
= PyString_FromString(errstr
);
169 PyTuple_SET_ITEM(v
, 0, n
);
170 PyTuple_SET_ITEM(v
, 1, s
);
171 PyErr_SetObject(PySSLErrorObject
, v
);
177 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
)
185 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
188 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
189 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
190 self
->server_cert
= NULL
;
195 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
196 errstr
= "Both the key & certificate files must be specified";
200 Py_BEGIN_ALLOW_THREADS
201 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
203 if (self
->ctx
== NULL
) {
204 errstr
= "SSL_CTX_new error";
209 Py_BEGIN_ALLOW_THREADS
210 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
214 errstr
= "SSL_CTX_use_PrivateKey_file error";
218 Py_BEGIN_ALLOW_THREADS
219 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
222 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
); /* ssl compatibility */
224 errstr
= "SSL_CTX_use_certificate_chain_file error";
229 Py_BEGIN_ALLOW_THREADS
230 SSL_CTX_set_verify(self
->ctx
,
231 SSL_VERIFY_NONE
, NULL
); /* set verify lvl */
232 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
234 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
236 /* If the socket is in non-blocking mode or timeout mode, set the BIO
237 * to non-blocking mode (blocking is the default)
239 if (Sock
->sock_timeout
>= 0.0) {
240 /* Set both the read and write BIO's to non-blocking mode */
241 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
242 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
245 Py_BEGIN_ALLOW_THREADS
246 SSL_set_connect_state(self
->ssl
);
249 /* Actually negotiate SSL connection */
250 /* XXX If SSL_connect() returns 0, it's also a failure. */
253 Py_BEGIN_ALLOW_THREADS
254 ret
= SSL_connect(self
->ssl
);
255 err
= SSL_get_error(self
->ssl
, ret
);
257 if(PyErr_CheckSignals()) {
260 if (err
== SSL_ERROR_WANT_READ
) {
261 sockstate
= check_socket_and_wait_for_timeout(Sock
, 0);
262 } else if (err
== SSL_ERROR_WANT_WRITE
) {
263 sockstate
= check_socket_and_wait_for_timeout(Sock
, 1);
265 sockstate
= SOCKET_OPERATION_OK
;
267 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
268 PyErr_SetString(PySSLErrorObject
, "The connect operation timed out");
270 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
271 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
273 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
274 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
276 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
279 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
281 PySSL_SetError(self
, ret
);
284 self
->ssl
->debug
= 1;
286 Py_BEGIN_ALLOW_THREADS
287 if ((self
->server_cert
= SSL_get_peer_certificate(self
->ssl
))) {
288 X509_NAME_oneline(X509_get_subject_name(self
->server_cert
),
289 self
->server
, X509_NAME_MAXLEN
);
290 X509_NAME_oneline(X509_get_issuer_name(self
->server_cert
),
291 self
->issuer
, X509_NAME_MAXLEN
);
295 Py_INCREF(self
->Socket
);
299 PyErr_SetString(PySSLErrorObject
, errstr
);
305 PySocket_ssl(PyObject
*self
, PyObject
*args
)
308 PySocketSockObject
*Sock
;
309 char *key_file
= NULL
;
310 char *cert_file
= NULL
;
312 if (!PyArg_ParseTuple(args
, "O!|zz:ssl",
313 PySocketModule
.Sock_Type
,
315 &key_file
, &cert_file
))
318 rv
= newPySSLObject(Sock
, key_file
, cert_file
);
321 return (PyObject
*)rv
;
324 PyDoc_STRVAR(ssl_doc
,
325 "ssl(socket, [keyfile, certfile]) -> sslobject");
327 /* SSL object methods */
330 PySSL_server(PySSLObject
*self
)
332 return PyString_FromString(self
->server
);
336 PySSL_issuer(PySSLObject
*self
)
338 return PyString_FromString(self
->issuer
);
342 static void PySSL_dealloc(PySSLObject
*self
)
344 if (self
->server_cert
) /* Possible not to have one? */
345 X509_free (self
->server_cert
);
349 SSL_CTX_free(self
->ctx
);
350 Py_XDECREF(self
->Socket
);
354 /* If the socket has a timeout, do a select() on the socket.
355 The argument writing indicates the direction.
356 Returns one of the possibilities in the timeout_state enum (above).
360 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
366 /* Nothing to do unless we're in timeout mode (not non-blocking) */
367 if (s
->sock_timeout
< 0.0)
368 return SOCKET_IS_BLOCKING
;
369 else if (s
->sock_timeout
== 0.0)
370 return SOCKET_IS_NONBLOCKING
;
372 /* Guard against closed socket */
374 return SOCKET_HAS_BEEN_CLOSED
;
376 /* Guard against socket too large for select*/
377 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
378 if (s
->sock_fd
>= FD_SETSIZE
)
379 return SOCKET_TOO_LARGE_FOR_SELECT
;
382 /* Construct the arguments to select */
383 tv
.tv_sec
= (int)s
->sock_timeout
;
384 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
386 FD_SET(s
->sock_fd
, &fds
);
388 /* See if the socket is ready */
389 Py_BEGIN_ALLOW_THREADS
391 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
393 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
396 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
397 (when we are able to write or when there's something to read) */
398 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
401 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
409 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &count
))
412 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
413 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
414 PyErr_SetString(PySSLErrorObject
, "The write operation timed out");
416 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
417 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
419 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
420 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
425 Py_BEGIN_ALLOW_THREADS
426 len
= SSL_write(self
->ssl
, data
, count
);
427 err
= SSL_get_error(self
->ssl
, len
);
429 if(PyErr_CheckSignals()) {
432 if (err
== SSL_ERROR_WANT_READ
) {
433 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
434 } else if (err
== SSL_ERROR_WANT_WRITE
) {
435 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
437 sockstate
= SOCKET_OPERATION_OK
;
439 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
440 PyErr_SetString(PySSLErrorObject
, "The write operation timed out");
442 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
443 PyErr_SetString(PySSLErrorObject
, "Underlying socket has been closed.");
445 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
448 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
450 return PyInt_FromLong(len
);
452 return PySSL_SetError(self
, len
);
455 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
458 Writes the string s into the SSL object. Returns the number\n\
461 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
469 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
472 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
475 /* first check if there are bytes ready to be read */
476 Py_BEGIN_ALLOW_THREADS
477 count
= SSL_pending(self
->ssl
);
481 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
482 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
483 PyErr_SetString(PySSLErrorObject
, "The read operation timed out");
486 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
487 PyErr_SetString(PySSLErrorObject
, "Underlying socket too large for select().");
493 Py_BEGIN_ALLOW_THREADS
494 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
495 err
= SSL_get_error(self
->ssl
, count
);
497 if(PyErr_CheckSignals()) {
501 if (err
== SSL_ERROR_WANT_READ
) {
502 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
503 } else if (err
== SSL_ERROR_WANT_WRITE
) {
504 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
506 sockstate
= SOCKET_OPERATION_OK
;
508 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
509 PyErr_SetString(PySSLErrorObject
, "The read operation timed out");
512 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
515 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
518 return PySSL_SetError(self
, count
);
521 _PyString_Resize(&buf
, count
);
525 PyDoc_STRVAR(PySSL_SSLread_doc
,
526 "read([len]) -> string\n\
528 Read up to len bytes from the SSL socket.");
530 static PyMethodDef PySSLMethods
[] = {
531 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
533 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
535 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
536 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
540 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
542 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
545 static PyTypeObject PySSL_Type
= {
546 PyObject_HEAD_INIT(NULL
)
548 "socket.SSL", /*tp_name*/
549 sizeof(PySSLObject
), /*tp_basicsize*/
552 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
554 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
559 0, /*tp_as_sequence*/
564 #ifdef HAVE_OPENSSL_RAND
566 /* helper routines for seeding the SSL PRNG */
568 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
574 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
576 RAND_add(buf
, len
, entropy
);
581 PyDoc_STRVAR(PySSL_RAND_add_doc
,
582 "RAND_add(string, entropy)\n\
584 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
585 bound on the entropy contained in string.");
588 PySSL_RAND_status(PyObject
*self
)
590 return PyInt_FromLong(RAND_status());
593 PyDoc_STRVAR(PySSL_RAND_status_doc
,
594 "RAND_status() -> 0 or 1\n\
596 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
597 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
598 using the ssl() function.");
601 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
605 if (!PyString_Check(arg
))
606 return PyErr_Format(PyExc_TypeError
,
607 "RAND_egd() expected string, found %s",
608 arg
->ob_type
->tp_name
);
609 bytes
= RAND_egd(PyString_AS_STRING(arg
));
611 PyErr_SetString(PySSLErrorObject
,
612 "EGD connection failed or EGD did not return "
613 "enough data to seed the PRNG");
616 return PyInt_FromLong(bytes
);
619 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
620 "RAND_egd(path) -> bytes\n\
622 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
623 of bytes read. Raises socket.sslerror if connection to EGD fails or\n\
624 if it does provide enough data to seed PRNG.");
628 /* List of functions exported by this module. */
630 static PyMethodDef PySSL_methods
[] = {
631 {"ssl", PySocket_ssl
,
632 METH_VARARGS
, ssl_doc
},
633 #ifdef HAVE_OPENSSL_RAND
634 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
636 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
638 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
639 PySSL_RAND_status_doc
},
641 {NULL
, NULL
} /* Sentinel */
645 PyDoc_STRVAR(module_doc
,
646 "Implementation module for SSL socket operations. See the socket module\n\
647 for documentation.");
654 PySSL_Type
.ob_type
= &PyType_Type
;
656 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
659 d
= PyModule_GetDict(m
);
661 /* Load _socket module and its C API */
662 if (PySocketModule_ImportModuleAndAPI())
666 SSL_load_error_strings();
667 SSLeay_add_ssl_algorithms();
669 /* Add symbols to module dict */
670 PySSLErrorObject
= PyErr_NewException("socket.sslerror",
671 PySocketModule
.error
,
673 if (PySSLErrorObject
== NULL
)
675 PyDict_SetItemString(d
, "sslerror", PySSLErrorObject
);
676 if (PyDict_SetItemString(d
, "SSLType",
677 (PyObject
*)&PySSL_Type
) != 0)
679 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
680 PY_SSL_ERROR_ZERO_RETURN
);
681 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
682 PY_SSL_ERROR_WANT_READ
);
683 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
684 PY_SSL_ERROR_WANT_WRITE
);
685 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
686 PY_SSL_ERROR_WANT_X509_LOOKUP
);
687 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
688 PY_SSL_ERROR_SYSCALL
);
689 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
691 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
692 PY_SSL_ERROR_WANT_CONNECT
);
693 /* non ssl.h errorcodes */
694 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
696 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
697 PY_SSL_ERROR_INVALID_ERROR_CODE
);