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 */
59 char server
[X509_NAME_MAXLEN
];
60 char issuer
[X509_NAME_MAXLEN
];
64 static PyTypeObject PySSL_Type
;
65 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
66 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
68 #define PySSLObject_Check(v) ((v)->ob_type == &PySSL_Type)
70 /* XXX It might be helpful to augment the error message generated
71 below with the name of the SSL function that generated the error.
72 I expect it's obvious most of the time.
76 PySSL_SetError(PySSLObject
*obj
, int ret
)
85 err
= SSL_get_error(obj
->ssl
, ret
);
88 case SSL_ERROR_ZERO_RETURN
:
89 errstr
= "TLS/SSL connection has been closed";
90 p
= PY_SSL_ERROR_ZERO_RETURN
;
92 case SSL_ERROR_WANT_READ
:
93 errstr
= "The operation did not complete (read)";
94 p
= PY_SSL_ERROR_WANT_READ
;
96 case SSL_ERROR_WANT_WRITE
:
97 p
= PY_SSL_ERROR_WANT_WRITE
;
98 errstr
= "The operation did not complete (write)";
100 case SSL_ERROR_WANT_X509_LOOKUP
:
101 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
102 errstr
= "The operation did not complete (X509 lookup)";
104 case SSL_ERROR_WANT_CONNECT
:
105 p
= PY_SSL_ERROR_WANT_CONNECT
;
106 errstr
= "The operation did not complete (connect)";
108 case SSL_ERROR_SYSCALL
:
110 unsigned long e
= ERR_get_error();
113 p
= PY_SSL_ERROR_EOF
;
114 errstr
= "EOF occurred in violation of protocol";
115 } else if (ret
== -1) {
116 /* the underlying BIO reported an I/O error */
117 return obj
->Socket
->errorhandler();
118 } else { /* possible? */
119 p
= PY_SSL_ERROR_SYSCALL
;
120 errstr
= "Some I/O error occurred";
123 p
= PY_SSL_ERROR_SYSCALL
;
124 /* XXX Protected by global interpreter lock */
125 errstr
= ERR_error_string(e
, NULL
);
131 unsigned long e
= ERR_get_error();
132 p
= PY_SSL_ERROR_SSL
;
134 /* XXX Protected by global interpreter lock */
135 errstr
= ERR_error_string(e
, NULL
);
136 else { /* possible? */
137 errstr
= "A failure in the SSL library occurred";
142 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
143 errstr
= "Invalid error code";
145 n
= PyInt_FromLong((long) p
);
154 s
= PyString_FromString(errstr
);
159 PyTuple_SET_ITEM(v
, 0, n
);
160 PyTuple_SET_ITEM(v
, 1, s
);
161 PyErr_SetObject(PySSLErrorObject
, v
);
166 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
)
172 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
174 errstr
= "newPySSLObject error";
177 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
178 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
179 self
->server_cert
= NULL
;
184 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
185 errstr
= "Both the key & certificate files must be specified";
189 Py_BEGIN_ALLOW_THREADS
190 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
192 if (self
->ctx
== NULL
) {
193 errstr
= "SSL_CTX_new error";
198 Py_BEGIN_ALLOW_THREADS
199 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
203 errstr
= "SSL_CTX_use_PrivateKey_file error";
207 Py_BEGIN_ALLOW_THREADS
208 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
212 errstr
= "SSL_CTX_use_certificate_chain_file error";
217 Py_BEGIN_ALLOW_THREADS
218 SSL_CTX_set_verify(self
->ctx
,
219 SSL_VERIFY_NONE
, NULL
); /* set verify lvl */
220 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
222 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
223 Py_BEGIN_ALLOW_THREADS
224 SSL_set_connect_state(self
->ssl
);
227 /* Actually negotiate SSL connection */
228 /* XXX If SSL_connect() returns 0, it's also a failure. */
229 ret
= SSL_connect(self
->ssl
);
232 PySSL_SetError(self
, ret
);
235 self
->ssl
->debug
= 1;
237 Py_BEGIN_ALLOW_THREADS
238 if ((self
->server_cert
= SSL_get_peer_certificate(self
->ssl
))) {
239 X509_NAME_oneline(X509_get_subject_name(self
->server_cert
),
240 self
->server
, X509_NAME_MAXLEN
);
241 X509_NAME_oneline(X509_get_issuer_name(self
->server_cert
),
242 self
->issuer
, X509_NAME_MAXLEN
);
246 Py_INCREF(self
->Socket
);
250 PyErr_SetString(PySSLErrorObject
, errstr
);
256 PySocket_ssl(PyObject
*self
, PyObject
*args
)
259 PySocketSockObject
*Sock
;
260 char *key_file
= NULL
;
261 char *cert_file
= NULL
;
263 if (!PyArg_ParseTuple(args
, "O!|zz:ssl",
264 PySocketModule
.Sock_Type
,
266 &key_file
, &cert_file
))
269 rv
= newPySSLObject(Sock
, key_file
, cert_file
);
272 return (PyObject
*)rv
;
275 PyDoc_STRVAR(ssl_doc
,
276 "ssl(socket, [keyfile, certfile]) -> sslobject");
278 /* SSL object methods */
281 PySSL_server(PySSLObject
*self
)
283 return PyString_FromString(self
->server
);
287 PySSL_issuer(PySSLObject
*self
)
289 return PyString_FromString(self
->issuer
);
293 static void PySSL_dealloc(PySSLObject
*self
)
295 if (self
->server_cert
) /* Possible not to have one? */
296 X509_free (self
->server_cert
);
300 SSL_CTX_free(self
->ctx
);
301 Py_XDECREF(self
->Socket
);
305 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
310 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &len
))
313 Py_BEGIN_ALLOW_THREADS
314 len
= SSL_write(self
->ssl
, data
, len
);
317 return PyInt_FromLong(len
);
319 return PySSL_SetError(self
, len
);
322 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
325 Writes the string s into the SSL object. Returns the number\n\
328 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
334 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
337 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
340 Py_BEGIN_ALLOW_THREADS
341 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
345 return PySSL_SetError(self
, count
);
348 _PyString_Resize(&buf
, count
);
352 PyDoc_STRVAR(PySSL_SSLread_doc
,
353 "read([len]) -> string\n\
355 Read up to len bytes from the SSL socket.");
357 static PyMethodDef PySSLMethods
[] = {
358 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
360 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
362 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
363 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
367 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
369 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
372 static PyTypeObject PySSL_Type
= {
373 PyObject_HEAD_INIT(NULL
)
375 "socket.SSL", /*tp_name*/
376 sizeof(PySSLObject
), /*tp_basicsize*/
379 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
381 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
386 0, /*tp_as_sequence*/
391 #ifdef HAVE_OPENSSL_RAND
393 /* helper routines for seeding the SSL PRNG */
395 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
401 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
403 RAND_add(buf
, len
, entropy
);
408 PyDoc_STRVAR(PySSL_RAND_add_doc
,
409 "RAND_add(string, entropy)\n\
411 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
412 bound on the entropy contained in string.");
415 PySSL_RAND_status(PyObject
*self
)
417 return PyInt_FromLong(RAND_status());
420 PyDoc_STRVAR(PySSL_RAND_status_doc
,
421 "RAND_status() -> 0 or 1\n\
423 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
424 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
425 using the ssl() function.");
428 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
432 if (!PyString_Check(arg
))
433 return PyErr_Format(PyExc_TypeError
,
434 "RAND_egd() expected string, found %s",
435 arg
->ob_type
->tp_name
);
436 bytes
= RAND_egd(PyString_AS_STRING(arg
));
438 PyErr_SetString(PySSLErrorObject
,
439 "EGD connection failed or EGD did not return "
440 "enough data to seed the PRNG");
443 return PyInt_FromLong(bytes
);
446 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
447 "RAND_egd(path) -> bytes\n\
449 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
450 of bytes read. Raises socket.sslerror if connection to EGD fails or\n\
451 if it does provide enough data to seed PRNG.");
455 /* List of functions exported by this module. */
457 static PyMethodDef PySSL_methods
[] = {
458 {"ssl", PySocket_ssl
,
459 METH_VARARGS
, ssl_doc
},
460 #ifdef HAVE_OPENSSL_RAND
461 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
463 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
465 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
466 PySSL_RAND_status_doc
},
468 {NULL
, NULL
} /* Sentinel */
472 PyDoc_STRVAR(module_doc
,
473 "Implementation module for SSL socket operations. See the socket module\n\
474 for documentation.");
481 PySSL_Type
.ob_type
= &PyType_Type
;
483 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
484 d
= PyModule_GetDict(m
);
486 /* Load _socket module and its C API */
487 if (PySocketModule_ImportModuleAndAPI())
491 SSL_load_error_strings();
492 SSLeay_add_ssl_algorithms();
494 /* Add symbols to module dict */
495 PySSLErrorObject
= PyErr_NewException("socket.sslerror", NULL
, NULL
);
496 if (PySSLErrorObject
== NULL
)
498 PyDict_SetItemString(d
, "sslerror", PySSLErrorObject
);
499 if (PyDict_SetItemString(d
, "SSLType",
500 (PyObject
*)&PySSL_Type
) != 0)
502 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
503 PY_SSL_ERROR_ZERO_RETURN
);
504 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
505 PY_SSL_ERROR_WANT_READ
);
506 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
507 PY_SSL_ERROR_WANT_WRITE
);
508 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
509 PY_SSL_ERROR_WANT_X509_LOOKUP
);
510 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
511 PY_SSL_ERROR_SYSCALL
);
512 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
514 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
515 PY_SSL_ERROR_WANT_CONNECT
);
516 /* non ssl.h errorcodes */
517 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
519 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
520 PY_SSL_ERROR_INVALID_ERROR_CODE
);