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
13 /* these mirror ssl.h */
16 PY_SSL_ERROR_WANT_READ
,
17 PY_SSL_ERROR_WANT_WRITE
,
18 PY_SSL_ERROR_WANT_X509_LOOKUP
,
19 PY_SSL_ERROR_SYSCALL
, /* look at error stack/return value/errno */
20 PY_SSL_ERROR_ZERO_RETURN
,
21 PY_SSL_ERROR_WANT_CONNECT
,
22 /* start of non ssl.h errorcodes */
23 PY_SSL_ERROR_EOF
, /* special case of SSL_ERROR_SYSCALL */
24 PY_SSL_ERROR_INVALID_ERROR_CODE
27 enum py_ssl_server_or_client
{
32 enum py_ssl_cert_requirements
{
45 /* Include symbols from _socket module */
46 #include "socketmodule.h"
48 #if defined(HAVE_POLL_H)
50 #elif defined(HAVE_SYS_POLL_H)
54 /* Include OpenSSL header files */
55 #include "openssl/rsa.h"
56 #include "openssl/crypto.h"
57 #include "openssl/x509.h"
58 #include "openssl/pem.h"
59 #include "openssl/ssl.h"
60 #include "openssl/err.h"
61 #include "openssl/rand.h"
63 /* SSL error object */
64 static PyObject
*PySSLErrorObject
;
66 /* SSL socket object */
68 #define X509_NAME_MAXLEN 256
70 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
71 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
72 # define HAVE_OPENSSL_RAND 1
74 # undef HAVE_OPENSSL_RAND
79 PySocketSockObject
*Socket
; /* Socket on which we're layered */
83 char server
[X509_NAME_MAXLEN
];
84 char issuer
[X509_NAME_MAXLEN
];
88 static PyTypeObject PySSL_Type
;
89 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
90 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
91 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
93 static PyObject
*PySSL_peercert(PySSLObject
*self
);
96 #define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type)
99 SOCKET_IS_NONBLOCKING
,
101 SOCKET_HAS_TIMED_OUT
,
102 SOCKET_HAS_BEEN_CLOSED
,
103 SOCKET_TOO_LARGE_FOR_SELECT
,
107 /* Wrap error strings with filename and line # */
108 #define STRINGIFY1(x) #x
109 #define STRINGIFY2(x) STRINGIFY1(x)
110 #define ERRSTR1(x,y,z) (x ":" y ": " z)
111 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
113 /* XXX It might be helpful to augment the error message generated
114 below with the name of the SSL function that generated the error.
115 I expect it's obvious most of the time.
119 PySSL_SetError(PySSLObject
*obj
, int ret
, char *filename
, int lineno
)
125 enum py_ssl_error p
= PY_SSL_ERROR_NONE
;
129 if ((obj
!= NULL
) && (obj
->ssl
!= NULL
)) {
130 err
= SSL_get_error(obj
->ssl
, ret
);
133 case SSL_ERROR_ZERO_RETURN
:
134 errstr
= "TLS/SSL connection has been closed";
135 p
= PY_SSL_ERROR_ZERO_RETURN
;
137 case SSL_ERROR_WANT_READ
:
138 errstr
= "The operation did not complete (read)";
139 p
= PY_SSL_ERROR_WANT_READ
;
141 case SSL_ERROR_WANT_WRITE
:
142 p
= PY_SSL_ERROR_WANT_WRITE
;
143 errstr
= "The operation did not complete (write)";
145 case SSL_ERROR_WANT_X509_LOOKUP
:
146 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
148 "The operation did not complete (X509 lookup)";
150 case SSL_ERROR_WANT_CONNECT
:
151 p
= PY_SSL_ERROR_WANT_CONNECT
;
152 errstr
= "The operation did not complete (connect)";
154 case SSL_ERROR_SYSCALL
:
156 unsigned long e
= ERR_get_error();
158 if (ret
== 0 || !obj
->Socket
) {
159 p
= PY_SSL_ERROR_EOF
;
161 "EOF occurred in violation of protocol";
162 } else if (ret
== -1) {
163 /* underlying BIO reported an I/O error */
164 return obj
->Socket
->errorhandler();
165 } else { /* possible? */
166 p
= PY_SSL_ERROR_SYSCALL
;
167 errstr
= "Some I/O error occurred";
170 p
= PY_SSL_ERROR_SYSCALL
;
171 /* XXX Protected by global interpreter lock */
172 errstr
= ERR_error_string(e
, NULL
);
178 unsigned long e
= ERR_get_error();
179 p
= PY_SSL_ERROR_SSL
;
181 /* XXX Protected by global interpreter lock */
182 errstr
= ERR_error_string(e
, NULL
);
183 else { /* possible? */
185 "A failure in the SSL library occurred";
190 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
191 errstr
= "Invalid error code";
194 errstr
= ERR_error_string(ERR_peek_last_error(), NULL
);
196 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
197 v
= Py_BuildValue("(is)", p
, buf
);
199 PyErr_SetObject(PySSLErrorObject
, v
);
206 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
,
207 enum py_ssl_server_or_client socket_type
,
208 enum py_ssl_cert_requirements certreq
,
209 enum py_ssl_version proto_version
,
217 int verification_mode
;
219 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
222 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
223 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
224 self
->peer_cert
= NULL
;
229 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
230 errstr
= ERRSTR("Both the key & certificate files "
231 "must be specified");
235 if ((socket_type
== PY_SSL_SERVER
) &&
236 ((key_file
== NULL
) || (cert_file
== NULL
))) {
237 errstr
= ERRSTR("Both the key & certificate files "
238 "must be specified for server-side operation");
242 Py_BEGIN_ALLOW_THREADS
243 if (proto_version
== PY_SSL_VERSION_TLS1
)
244 self
->ctx
= SSL_CTX_new(TLSv1_method()); /* Set up context */
245 else if (proto_version
== PY_SSL_VERSION_SSL3
)
246 self
->ctx
= SSL_CTX_new(SSLv3_method()); /* Set up context */
247 else if (proto_version
== PY_SSL_VERSION_SSL2
)
248 self
->ctx
= SSL_CTX_new(SSLv2_method()); /* Set up context */
250 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
253 if (self
->ctx
== NULL
) {
254 errstr
= ERRSTR("Invalid SSL protocol variant specified.");
258 if (certreq
!= PY_SSL_CERT_NONE
) {
259 if (cacerts_file
== NULL
) {
260 errstr
= ERRSTR("No root certificates specified for "
261 "verification of other-side certificates.");
264 Py_BEGIN_ALLOW_THREADS
265 ret
= SSL_CTX_load_verify_locations(self
->ctx
,
270 PySSL_SetError(NULL
, 0, __FILE__
, __LINE__
);
276 Py_BEGIN_ALLOW_THREADS
277 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
281 PySSL_SetError(NULL
, 0, __FILE__
, __LINE__
);
285 Py_BEGIN_ALLOW_THREADS
286 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
290 PySSL_SetError(NULL
, 0, __FILE__
, __LINE__
);
293 /* ssl compatibility */
294 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
);
297 verification_mode
= SSL_VERIFY_NONE
;
298 if (certreq
== PY_SSL_CERT_OPTIONAL
)
299 verification_mode
= SSL_VERIFY_PEER
;
300 else if (certreq
== PY_SSL_CERT_REQUIRED
)
301 verification_mode
= (SSL_VERIFY_PEER
|
302 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
);
303 SSL_CTX_set_verify(self
->ctx
, verification_mode
,
304 NULL
); /* set verify lvl */
306 Py_BEGIN_ALLOW_THREADS
307 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
309 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
311 /* If the socket is in non-blocking mode or timeout mode, set the BIO
312 * to non-blocking mode (blocking is the default)
314 if (Sock
->sock_timeout
>= 0.0) {
315 /* Set both the read and write BIO's to non-blocking mode */
316 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
317 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
320 Py_BEGIN_ALLOW_THREADS
321 if (socket_type
== PY_SSL_CLIENT
)
322 SSL_set_connect_state(self
->ssl
);
324 SSL_set_accept_state(self
->ssl
);
327 /* Actually negotiate SSL connection */
328 /* XXX If SSL_connect() returns 0, it's also a failure. */
331 Py_BEGIN_ALLOW_THREADS
332 if (socket_type
== PY_SSL_CLIENT
)
333 ret
= SSL_connect(self
->ssl
);
335 ret
= SSL_accept(self
->ssl
);
336 err
= SSL_get_error(self
->ssl
, ret
);
338 if(PyErr_CheckSignals()) {
341 if (err
== SSL_ERROR_WANT_READ
) {
342 sockstate
= check_socket_and_wait_for_timeout(Sock
, 0);
343 } else if (err
== SSL_ERROR_WANT_WRITE
) {
344 sockstate
= check_socket_and_wait_for_timeout(Sock
, 1);
346 sockstate
= SOCKET_OPERATION_OK
;
348 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
349 PyErr_SetString(PySSLErrorObject
,
350 ERRSTR("The connect operation timed out"));
352 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
353 PyErr_SetString(PySSLErrorObject
,
354 ERRSTR("Underlying socket has been closed."));
356 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
357 PyErr_SetString(PySSLErrorObject
,
358 ERRSTR("Underlying socket too large for select()."));
360 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
363 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
365 PySSL_SetError(self
, ret
, __FILE__
, __LINE__
);
368 self
->ssl
->debug
= 1;
370 Py_BEGIN_ALLOW_THREADS
371 if ((self
->peer_cert
= SSL_get_peer_certificate(self
->ssl
))) {
372 X509_NAME_oneline(X509_get_subject_name(self
->peer_cert
),
373 self
->server
, X509_NAME_MAXLEN
);
374 X509_NAME_oneline(X509_get_issuer_name(self
->peer_cert
),
375 self
->issuer
, X509_NAME_MAXLEN
);
379 Py_INCREF(self
->Socket
);
383 PyErr_SetString(PySSLErrorObject
, errstr
);
389 PySSL_sslwrap(PyObject
*self
, PyObject
*args
)
391 PySocketSockObject
*Sock
;
393 int verification_mode
= PY_SSL_CERT_NONE
;
394 int protocol
= PY_SSL_VERSION_SSL23
;
395 char *key_file
= NULL
;
396 char *cert_file
= NULL
;
397 char *cacerts_file
= NULL
;
399 if (!PyArg_ParseTuple(args
, "O!i|zziiz:sslwrap",
400 PySocketModule
.Sock_Type
,
403 &key_file
, &cert_file
,
404 &verification_mode
, &protocol
,
410 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
411 "protocol %d, certs %p\n",
412 server_side, key_file, cert_file, verification_mode,
413 protocol, cacerts_file);
416 return (PyObject
*) newPySSLObject(Sock
, key_file
, cert_file
,
417 server_side
, verification_mode
,
418 protocol
, cacerts_file
);
421 PyDoc_STRVAR(ssl_doc
,
422 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
423 " cacertsfile]) -> sslobject");
425 /* SSL object methods */
428 PySSL_server(PySSLObject
*self
)
430 return PyString_FromString(self
->server
);
434 PySSL_issuer(PySSLObject
*self
)
436 return PyString_FromString(self
->issuer
);
440 _create_dict_for_X509_NAME (X509_NAME
*xname
)
442 PyObject
*pd
= PyDict_New();
448 for (index_counter
= 0;
449 index_counter
< X509_NAME_entry_count(xname
);
452 char namebuf
[X509_NAME_MAXLEN
];
457 unsigned char *valuebuf
= NULL
;
459 X509_NAME_ENTRY
*entry
= X509_NAME_get_entry(xname
,
462 ASN1_OBJECT
*name
= X509_NAME_ENTRY_get_object(entry
);
463 buflen
= OBJ_obj2txt(namebuf
, sizeof(namebuf
), name
, 0);
466 name_obj
= PyString_FromStringAndSize(namebuf
, buflen
);
467 if (name_obj
== NULL
)
470 value
= X509_NAME_ENTRY_get_data(entry
);
471 buflen
= ASN1_STRING_to_UTF8(&valuebuf
, value
);
476 value_obj
= PyUnicode_DecodeUTF8((char *) valuebuf
,
478 OPENSSL_free(valuebuf
);
479 if (value_obj
== NULL
) {
483 if (PyDict_SetItem(pd
, name_obj
, value_obj
) < 0) {
485 Py_DECREF(value_obj
);
489 Py_DECREF(value_obj
);
499 PySSL_peercert(PySSLObject
*self
)
501 PyObject
*retval
= NULL
;
508 ASN1_TIME
*notBefore
, *notAfter
;
509 PyObject
*pnotBefore
, *pnotAfter
;
512 if (!self
->peer_cert
)
515 retval
= PyDict_New();
519 verification
= SSL_CTX_get_verify_mode(self
->ctx
);
520 if ((verification
& SSL_VERIFY_PEER
) == 0)
523 peer
= _create_dict_for_X509_NAME(
524 X509_get_subject_name(self
->peer_cert
));
527 if (PyDict_SetItemString(retval
, (const char *) "subject", peer
) < 0) {
533 issuer
= _create_dict_for_X509_NAME(
534 X509_get_issuer_name(self
->peer_cert
));
537 if (PyDict_SetItemString(retval
, (const char *)"issuer", issuer
) < 0) {
543 version
= PyInt_FromLong(X509_get_version(self
->peer_cert
));
544 if (PyDict_SetItemString(retval
, "version", version
) < 0) {
550 /* get a memory buffer */
551 biobuf
= BIO_new(BIO_s_mem());
553 notBefore
= X509_get_notBefore(self
->peer_cert
);
554 ASN1_TIME_print(biobuf
, notBefore
);
555 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
556 pnotBefore
= PyString_FromStringAndSize(buf
, len
);
557 if (pnotBefore
== NULL
)
559 if (PyDict_SetItemString(retval
, "notBefore", pnotBefore
) < 0) {
560 Py_DECREF(pnotBefore
);
563 Py_DECREF(pnotBefore
);
565 (void) BIO_reset(biobuf
);
566 notAfter
= X509_get_notAfter(self
->peer_cert
);
567 ASN1_TIME_print(biobuf
, notAfter
);
568 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
570 pnotAfter
= PyString_FromStringAndSize(buf
, len
);
571 if (pnotAfter
== NULL
)
573 if (PyDict_SetItemString(retval
, "notAfter", pnotAfter
) < 0) {
574 Py_DECREF(pnotAfter
);
577 Py_DECREF(pnotAfter
);
588 static void PySSL_dealloc(PySSLObject
*self
)
590 if (self
->peer_cert
) /* Possible not to have one? */
591 X509_free (self
->peer_cert
);
595 SSL_CTX_free(self
->ctx
);
596 Py_XDECREF(self
->Socket
);
600 /* If the socket has a timeout, do a select()/poll() on the socket.
601 The argument writing indicates the direction.
602 Returns one of the possibilities in the timeout_state enum (above).
606 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
612 /* Nothing to do unless we're in timeout mode (not non-blocking) */
613 if (s
->sock_timeout
< 0.0)
614 return SOCKET_IS_BLOCKING
;
615 else if (s
->sock_timeout
== 0.0)
616 return SOCKET_IS_NONBLOCKING
;
618 /* Guard against closed socket */
620 return SOCKET_HAS_BEEN_CLOSED
;
622 /* Prefer poll, if available, since you can poll() any fd
623 * which can't be done with select(). */
626 struct pollfd pollfd
;
629 pollfd
.fd
= s
->sock_fd
;
630 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
632 /* s->sock_timeout is in seconds, timeout in ms */
633 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
634 Py_BEGIN_ALLOW_THREADS
635 rc
= poll(&pollfd
, 1, timeout
);
642 /* Guard against socket too large for select*/
643 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
644 if (s
->sock_fd
>= FD_SETSIZE
)
645 return SOCKET_TOO_LARGE_FOR_SELECT
;
648 /* Construct the arguments to select */
649 tv
.tv_sec
= (int)s
->sock_timeout
;
650 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
652 FD_SET(s
->sock_fd
, &fds
);
654 /* See if the socket is ready */
655 Py_BEGIN_ALLOW_THREADS
657 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
659 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
663 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
664 (when we are able to write or when there's something to read) */
665 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
668 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
676 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &count
))
679 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
680 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
681 PyErr_SetString(PySSLErrorObject
,
682 "The write operation timed out");
684 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
685 PyErr_SetString(PySSLErrorObject
,
686 "Underlying socket has been closed.");
688 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
689 PyErr_SetString(PySSLErrorObject
,
690 "Underlying socket too large for select().");
695 Py_BEGIN_ALLOW_THREADS
696 len
= SSL_write(self
->ssl
, data
, count
);
697 err
= SSL_get_error(self
->ssl
, len
);
699 if(PyErr_CheckSignals()) {
702 if (err
== SSL_ERROR_WANT_READ
) {
704 check_socket_and_wait_for_timeout(self
->Socket
, 0);
705 } else if (err
== SSL_ERROR_WANT_WRITE
) {
707 check_socket_and_wait_for_timeout(self
->Socket
, 1);
709 sockstate
= SOCKET_OPERATION_OK
;
711 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
712 PyErr_SetString(PySSLErrorObject
,
713 "The write operation timed out");
715 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
716 PyErr_SetString(PySSLErrorObject
,
717 "Underlying socket has been closed.");
719 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
722 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
724 return PyInt_FromLong(len
);
726 return PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
729 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
732 Writes the string s into the SSL object. Returns the number\n\
735 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
743 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
746 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
749 /* first check if there are bytes ready to be read */
750 Py_BEGIN_ALLOW_THREADS
751 count
= SSL_pending(self
->ssl
);
755 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
756 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
757 PyErr_SetString(PySSLErrorObject
,
758 "The read operation timed out");
761 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
762 PyErr_SetString(PySSLErrorObject
,
763 "Underlying socket too large for select().");
766 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
767 if (SSL_get_shutdown(self
->ssl
) !=
768 SSL_RECEIVED_SHUTDOWN
)
771 PyErr_SetString(PySSLErrorObject
,
772 "Socket closed without SSL shutdown handshake");
775 /* should contain a zero-length string */
776 _PyString_Resize(&buf
, 0);
783 Py_BEGIN_ALLOW_THREADS
784 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
785 err
= SSL_get_error(self
->ssl
, count
);
787 if(PyErr_CheckSignals()) {
791 if (err
== SSL_ERROR_WANT_READ
) {
793 check_socket_and_wait_for_timeout(self
->Socket
, 0);
794 } else if (err
== SSL_ERROR_WANT_WRITE
) {
796 check_socket_and_wait_for_timeout(self
->Socket
, 1);
797 } else if ((err
== SSL_ERROR_ZERO_RETURN
) &&
798 (SSL_get_shutdown(self
->ssl
) ==
799 SSL_RECEIVED_SHUTDOWN
))
801 _PyString_Resize(&buf
, 0);
804 sockstate
= SOCKET_OPERATION_OK
;
806 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
807 PyErr_SetString(PySSLErrorObject
,
808 "The read operation timed out");
811 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
814 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
817 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
820 _PyString_Resize(&buf
, count
);
824 PyDoc_STRVAR(PySSL_SSLread_doc
,
825 "read([len]) -> string\n\
827 Read up to len bytes from the SSL socket.");
829 static PyObject
*PySSL_SSLshutdown(PySSLObject
*self
, PyObject
*args
)
833 /* Guard against closed socket */
834 if (self
->Socket
->sock_fd
< 0) {
835 PyErr_SetString(PySSLErrorObject
,
836 "Underlying socket has been closed.");
840 Py_BEGIN_ALLOW_THREADS
841 err
= SSL_shutdown(self
->ssl
);
843 /* we need to call it again to finish the shutdown */
844 err
= SSL_shutdown(self
->ssl
);
849 return PySSL_SetError(self
, err
, __FILE__
, __LINE__
);
851 Py_INCREF(self
->Socket
);
852 return (PyObject
*) (self
->Socket
);
856 PyDoc_STRVAR(PySSL_SSLshutdown_doc
,
857 "shutdown(s) -> socket\n\
859 Does the SSL shutdown handshake with the remote end, and returns\n\
860 the underlying socket object.");
862 static PyMethodDef PySSLMethods
[] = {
863 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
865 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
867 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
868 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
869 {"peer_certificate", (PyCFunction
)PySSL_peercert
, METH_NOARGS
},
870 {"shutdown", (PyCFunction
)PySSL_SSLshutdown
, METH_NOARGS
,
871 PySSL_SSLshutdown_doc
},
875 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
877 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
880 static PyTypeObject PySSL_Type
= {
881 PyVarObject_HEAD_INIT(NULL
, 0)
882 "ssl.SSLContext", /*tp_name*/
883 sizeof(PySSLObject
), /*tp_basicsize*/
886 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
888 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
893 0, /*tp_as_sequence*/
898 #ifdef HAVE_OPENSSL_RAND
900 /* helper routines for seeding the SSL PRNG */
902 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
908 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
910 RAND_add(buf
, len
, entropy
);
915 PyDoc_STRVAR(PySSL_RAND_add_doc
,
916 "RAND_add(string, entropy)\n\
918 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
919 bound on the entropy contained in string.");
922 PySSL_RAND_status(PyObject
*self
)
924 return PyInt_FromLong(RAND_status());
927 PyDoc_STRVAR(PySSL_RAND_status_doc
,
928 "RAND_status() -> 0 or 1\n\
930 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
931 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
932 using the ssl() function.");
935 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
939 if (!PyString_Check(arg
))
940 return PyErr_Format(PyExc_TypeError
,
941 "RAND_egd() expected string, found %s",
942 Py_Type(arg
)->tp_name
);
943 bytes
= RAND_egd(PyString_AS_STRING(arg
));
945 PyErr_SetString(PySSLErrorObject
,
946 "EGD connection failed or EGD did not return "
947 "enough data to seed the PRNG");
950 return PyInt_FromLong(bytes
);
953 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
954 "RAND_egd(path) -> bytes\n\
956 Queries the entropy gather daemon (EGD) on socket path. Returns number\n\
957 of bytes read. Raises ssl.sslerror if connection to EGD fails or\n\
958 if it does provide enough data to seed PRNG.");
962 /* List of functions exported by this module. */
964 static PyMethodDef PySSL_methods
[] = {
965 {"sslwrap", PySSL_sslwrap
,
966 METH_VARARGS
, ssl_doc
},
967 #ifdef HAVE_OPENSSL_RAND
968 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
970 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
972 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
973 PySSL_RAND_status_doc
},
975 {NULL
, NULL
} /* Sentinel */
979 PyDoc_STRVAR(module_doc
,
980 "Implementation module for SSL socket operations. See the socket module\n\
981 for documentation.");
988 Py_Type(&PySSL_Type
) = &PyType_Type
;
990 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
993 d
= PyModule_GetDict(m
);
995 /* Load _socket module and its C API */
996 if (PySocketModule_ImportModuleAndAPI())
1000 SSL_load_error_strings();
1001 SSLeay_add_ssl_algorithms();
1003 /* Add symbols to module dict */
1004 PySSLErrorObject
= PyErr_NewException("ssl.sslerror",
1005 PySocketModule
.error
,
1007 if (PySSLErrorObject
== NULL
)
1009 if (PyDict_SetItemString(d
, "sslerror", PySSLErrorObject
) != 0)
1011 if (PyDict_SetItemString(d
, "SSLType",
1012 (PyObject
*)&PySSL_Type
) != 0)
1014 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
1015 PY_SSL_ERROR_ZERO_RETURN
);
1016 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
1017 PY_SSL_ERROR_WANT_READ
);
1018 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
1019 PY_SSL_ERROR_WANT_WRITE
);
1020 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
1021 PY_SSL_ERROR_WANT_X509_LOOKUP
);
1022 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
1023 PY_SSL_ERROR_SYSCALL
);
1024 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
1026 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
1027 PY_SSL_ERROR_WANT_CONNECT
);
1028 /* non ssl.h errorcodes */
1029 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
1031 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
1032 PY_SSL_ERROR_INVALID_ERROR_CODE
);
1033 /* cert requirements */
1034 PyModule_AddIntConstant(m
, "CERT_NONE",
1036 PyModule_AddIntConstant(m
, "CERT_OPTIONAL",
1037 PY_SSL_CERT_OPTIONAL
);
1038 PyModule_AddIntConstant(m
, "CERT_REQUIRED",
1039 PY_SSL_CERT_REQUIRED
);
1041 /* protocol versions */
1042 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv2",
1043 PY_SSL_VERSION_SSL2
);
1044 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv3",
1045 PY_SSL_VERSION_SSL3
);
1046 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv23",
1047 PY_SSL_VERSION_SSL23
);
1048 PyModule_AddIntConstant(m
, "PROTOCOL_TLSv1",
1049 PY_SSL_VERSION_TLS1
);