3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
4 Re-worked a bit by Bill Janssen to add server-side support and
7 This module is imported by ssl.py. It should *not* be used
10 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12 XXX what about SSL_MODE_AUTO_RETRY
19 #define PySSL_BEGIN_ALLOW_THREADS { \
20 PyThreadState *_save = NULL; \
21 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
22 #define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
23 #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
24 #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 #else /* no WITH_THREAD */
29 #define PySSL_BEGIN_ALLOW_THREADS
30 #define PySSL_BLOCK_THREADS
31 #define PySSL_UNBLOCK_THREADS
32 #define PySSL_END_ALLOW_THREADS
37 /* these mirror ssl.h */
40 PY_SSL_ERROR_WANT_READ
,
41 PY_SSL_ERROR_WANT_WRITE
,
42 PY_SSL_ERROR_WANT_X509_LOOKUP
,
43 PY_SSL_ERROR_SYSCALL
, /* look at error stack/return value/errno */
44 PY_SSL_ERROR_ZERO_RETURN
,
45 PY_SSL_ERROR_WANT_CONNECT
,
46 /* start of non ssl.h errorcodes */
47 PY_SSL_ERROR_EOF
, /* special case of SSL_ERROR_SYSCALL */
48 PY_SSL_ERROR_INVALID_ERROR_CODE
51 enum py_ssl_server_or_client
{
56 enum py_ssl_cert_requirements
{
69 /* Include symbols from _socket module */
70 #include "socketmodule.h"
72 #if defined(HAVE_POLL_H)
74 #elif defined(HAVE_SYS_POLL_H)
78 /* Include OpenSSL header files */
79 #include "openssl/rsa.h"
80 #include "openssl/crypto.h"
81 #include "openssl/x509.h"
82 #include "openssl/x509v3.h"
83 #include "openssl/pem.h"
84 #include "openssl/ssl.h"
85 #include "openssl/err.h"
86 #include "openssl/rand.h"
88 /* SSL error object */
89 static PyObject
*PySSLErrorObject
;
93 /* serves as a flag to see whether we've initialized the SSL thread support. */
94 /* 0 means no, greater than 0 means yes */
96 static unsigned int _ssl_locks_count
= 0;
98 #endif /* def WITH_THREAD */
100 /* SSL socket object */
102 #define X509_NAME_MAXLEN 256
104 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
105 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
106 # define HAVE_OPENSSL_RAND 1
108 # undef HAVE_OPENSSL_RAND
113 PySocketSockObject
*Socket
; /* Socket on which we're layered */
117 char server
[X509_NAME_MAXLEN
];
118 char issuer
[X509_NAME_MAXLEN
];
122 static PyTypeObject PySSL_Type
;
123 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
124 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
125 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
127 static PyObject
*PySSL_peercert(PySSLObject
*self
, PyObject
*args
);
128 static PyObject
*PySSL_cipher(PySSLObject
*self
);
130 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
133 SOCKET_IS_NONBLOCKING
,
135 SOCKET_HAS_TIMED_OUT
,
136 SOCKET_HAS_BEEN_CLOSED
,
137 SOCKET_TOO_LARGE_FOR_SELECT
,
141 /* Wrap error strings with filename and line # */
142 #define STRINGIFY1(x) #x
143 #define STRINGIFY2(x) STRINGIFY1(x)
144 #define ERRSTR1(x,y,z) (x ":" y ": " z)
145 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
147 /* XXX It might be helpful to augment the error message generated
148 below with the name of the SSL function that generated the error.
149 I expect it's obvious most of the time.
153 PySSL_SetError(PySSLObject
*obj
, int ret
, char *filename
, int lineno
)
159 enum py_ssl_error p
= PY_SSL_ERROR_NONE
;
163 if (obj
->ssl
!= NULL
) {
164 err
= SSL_get_error(obj
->ssl
, ret
);
167 case SSL_ERROR_ZERO_RETURN
:
168 errstr
= "TLS/SSL connection has been closed";
169 p
= PY_SSL_ERROR_ZERO_RETURN
;
171 case SSL_ERROR_WANT_READ
:
172 errstr
= "The operation did not complete (read)";
173 p
= PY_SSL_ERROR_WANT_READ
;
175 case SSL_ERROR_WANT_WRITE
:
176 p
= PY_SSL_ERROR_WANT_WRITE
;
177 errstr
= "The operation did not complete (write)";
179 case SSL_ERROR_WANT_X509_LOOKUP
:
180 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
182 "The operation did not complete (X509 lookup)";
184 case SSL_ERROR_WANT_CONNECT
:
185 p
= PY_SSL_ERROR_WANT_CONNECT
;
186 errstr
= "The operation did not complete (connect)";
188 case SSL_ERROR_SYSCALL
:
190 unsigned long e
= ERR_get_error();
192 if (ret
== 0 || !obj
->Socket
) {
193 p
= PY_SSL_ERROR_EOF
;
195 "EOF occurred in violation of protocol";
196 } else if (ret
== -1) {
197 /* underlying BIO reported an I/O error */
198 return obj
->Socket
->errorhandler();
199 } else { /* possible? */
200 p
= PY_SSL_ERROR_SYSCALL
;
201 errstr
= "Some I/O error occurred";
204 p
= PY_SSL_ERROR_SYSCALL
;
205 /* XXX Protected by global interpreter lock */
206 errstr
= ERR_error_string(e
, NULL
);
212 unsigned long e
= ERR_get_error();
213 p
= PY_SSL_ERROR_SSL
;
215 /* XXX Protected by global interpreter lock */
216 errstr
= ERR_error_string(e
, NULL
);
217 else { /* possible? */
219 "A failure in the SSL library occurred";
224 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
225 errstr
= "Invalid error code";
228 errstr
= ERR_error_string(ERR_peek_last_error(), NULL
);
230 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
231 v
= Py_BuildValue("(is)", p
, buf
);
233 PyErr_SetObject(PySSLErrorObject
, v
);
240 _setSSLError (char *errstr
, int errcode
, char *filename
, int lineno
) {
245 if (errstr
== NULL
) {
246 errcode
= ERR_peek_last_error();
247 errstr
= ERR_error_string(errcode
, NULL
);
249 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
250 v
= Py_BuildValue("(is)", errcode
, buf
);
252 PyErr_SetObject(PySSLErrorObject
, v
);
259 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
,
260 enum py_ssl_server_or_client socket_type
,
261 enum py_ssl_cert_requirements certreq
,
262 enum py_ssl_version proto_version
,
270 int verification_mode
;
272 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
275 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
276 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
277 self
->peer_cert
= NULL
;
282 /* Make sure the SSL error state is initialized */
283 (void) ERR_get_state();
286 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
287 errstr
= ERRSTR("Both the key & certificate files "
288 "must be specified");
292 if ((socket_type
== PY_SSL_SERVER
) &&
293 ((key_file
== NULL
) || (cert_file
== NULL
))) {
294 errstr
= ERRSTR("Both the key & certificate files "
295 "must be specified for server-side operation");
299 PySSL_BEGIN_ALLOW_THREADS
300 if (proto_version
== PY_SSL_VERSION_TLS1
)
301 self
->ctx
= SSL_CTX_new(TLSv1_method()); /* Set up context */
302 else if (proto_version
== PY_SSL_VERSION_SSL3
)
303 self
->ctx
= SSL_CTX_new(SSLv3_method()); /* Set up context */
304 else if (proto_version
== PY_SSL_VERSION_SSL2
)
305 self
->ctx
= SSL_CTX_new(SSLv2_method()); /* Set up context */
306 else if (proto_version
== PY_SSL_VERSION_SSL23
)
307 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
308 PySSL_END_ALLOW_THREADS
310 if (self
->ctx
== NULL
) {
311 errstr
= ERRSTR("Invalid SSL protocol variant specified.");
315 if (certreq
!= PY_SSL_CERT_NONE
) {
316 if (cacerts_file
== NULL
) {
317 errstr
= ERRSTR("No root certificates specified for "
318 "verification of other-side certificates.");
321 PySSL_BEGIN_ALLOW_THREADS
322 ret
= SSL_CTX_load_verify_locations(self
->ctx
,
325 PySSL_END_ALLOW_THREADS
327 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
333 PySSL_BEGIN_ALLOW_THREADS
334 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
336 PySSL_END_ALLOW_THREADS
338 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
342 PySSL_BEGIN_ALLOW_THREADS
343 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
345 PySSL_END_ALLOW_THREADS
348 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
349 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
351 if (ERR_peek_last_error() != 0) {
352 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
358 /* ssl compatibility */
359 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
);
361 verification_mode
= SSL_VERIFY_NONE
;
362 if (certreq
== PY_SSL_CERT_OPTIONAL
)
363 verification_mode
= SSL_VERIFY_PEER
;
364 else if (certreq
== PY_SSL_CERT_REQUIRED
)
365 verification_mode
= (SSL_VERIFY_PEER
|
366 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
);
367 SSL_CTX_set_verify(self
->ctx
, verification_mode
,
368 NULL
); /* set verify lvl */
370 PySSL_BEGIN_ALLOW_THREADS
371 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
372 PySSL_END_ALLOW_THREADS
373 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
375 /* If the socket is in non-blocking mode or timeout mode, set the BIO
376 * to non-blocking mode (blocking is the default)
378 if (Sock
->sock_timeout
>= 0.0) {
379 /* Set both the read and write BIO's to non-blocking mode */
380 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
381 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
384 PySSL_BEGIN_ALLOW_THREADS
385 if (socket_type
== PY_SSL_CLIENT
)
386 SSL_set_connect_state(self
->ssl
);
388 SSL_set_accept_state(self
->ssl
);
389 PySSL_END_ALLOW_THREADS
391 /* Actually negotiate SSL connection */
392 /* XXX If SSL_connect() returns 0, it's also a failure. */
395 PySSL_BEGIN_ALLOW_THREADS
396 if (socket_type
== PY_SSL_CLIENT
)
397 ret
= SSL_connect(self
->ssl
);
399 ret
= SSL_accept(self
->ssl
);
400 err
= SSL_get_error(self
->ssl
, ret
);
401 PySSL_END_ALLOW_THREADS
402 if(PyErr_CheckSignals()) {
405 if (err
== SSL_ERROR_WANT_READ
) {
406 sockstate
= check_socket_and_wait_for_timeout(Sock
, 0);
407 } else if (err
== SSL_ERROR_WANT_WRITE
) {
408 sockstate
= check_socket_and_wait_for_timeout(Sock
, 1);
410 sockstate
= SOCKET_OPERATION_OK
;
412 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
413 PyErr_SetString(PySSLErrorObject
,
414 ERRSTR("The connect operation timed out"));
416 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
417 PyErr_SetString(PySSLErrorObject
,
418 ERRSTR("Underlying socket has been closed."));
420 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
421 PyErr_SetString(PySSLErrorObject
,
422 ERRSTR("Underlying socket too large for select()."));
424 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
427 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
429 PySSL_SetError(self
, ret
, __FILE__
, __LINE__
);
432 self
->ssl
->debug
= 1;
434 PySSL_BEGIN_ALLOW_THREADS
435 if ((self
->peer_cert
= SSL_get_peer_certificate(self
->ssl
))) {
436 X509_NAME_oneline(X509_get_subject_name(self
->peer_cert
),
437 self
->server
, X509_NAME_MAXLEN
);
438 X509_NAME_oneline(X509_get_issuer_name(self
->peer_cert
),
439 self
->issuer
, X509_NAME_MAXLEN
);
441 PySSL_END_ALLOW_THREADS
443 Py_INCREF(self
->Socket
);
447 PyErr_SetString(PySSLErrorObject
, errstr
);
453 PySSL_sslwrap(PyObject
*self
, PyObject
*args
)
455 PySocketSockObject
*Sock
;
457 int verification_mode
= PY_SSL_CERT_NONE
;
458 int protocol
= PY_SSL_VERSION_SSL23
;
459 char *key_file
= NULL
;
460 char *cert_file
= NULL
;
461 char *cacerts_file
= NULL
;
463 if (!PyArg_ParseTuple(args
, "O!i|zziiz:sslwrap",
464 PySocketModule
.Sock_Type
,
467 &key_file
, &cert_file
,
468 &verification_mode
, &protocol
,
474 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
475 "protocol %d, certs %p\n",
476 server_side, key_file, cert_file, verification_mode,
477 protocol, cacerts_file);
480 return (PyObject
*) newPySSLObject(Sock
, key_file
, cert_file
,
481 server_side
, verification_mode
,
482 protocol
, cacerts_file
);
485 PyDoc_STRVAR(ssl_doc
,
486 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
487 " cacertsfile]) -> sslobject");
489 /* SSL object methods */
492 PySSL_server(PySSLObject
*self
)
494 return PyString_FromString(self
->server
);
498 PySSL_issuer(PySSLObject
*self
)
500 return PyString_FromString(self
->issuer
);
504 _create_tuple_for_attribute (ASN1_OBJECT
*name
, ASN1_STRING
*value
) {
506 char namebuf
[X509_NAME_MAXLEN
];
511 unsigned char *valuebuf
= NULL
;
513 buflen
= OBJ_obj2txt(namebuf
, sizeof(namebuf
), name
, 0);
515 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
518 name_obj
= PyString_FromStringAndSize(namebuf
, buflen
);
519 if (name_obj
== NULL
)
522 buflen
= ASN1_STRING_to_UTF8(&valuebuf
, value
);
524 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
528 value_obj
= PyUnicode_DecodeUTF8((char *) valuebuf
,
530 OPENSSL_free(valuebuf
);
531 if (value_obj
== NULL
) {
535 attr
= PyTuple_New(2);
538 Py_DECREF(value_obj
);
541 PyTuple_SET_ITEM(attr
, 0, name_obj
);
542 PyTuple_SET_ITEM(attr
, 1, value_obj
);
550 _create_tuple_for_X509_NAME (X509_NAME
*xname
)
552 PyObject
*dn
= NULL
; /* tuple which represents the "distinguished name" */
553 PyObject
*rdn
= NULL
; /* tuple to hold a "relative distinguished name" */
555 PyObject
*attr
= NULL
; /* tuple to hold an attribute */
556 int entry_count
= X509_NAME_entry_count(xname
);
557 X509_NAME_ENTRY
*entry
;
567 /* now create another tuple to hold the top-level RDN */
572 for (index_counter
= 0;
573 index_counter
< entry_count
;
576 entry
= X509_NAME_get_entry(xname
, index_counter
);
578 /* check to see if we've gotten to a new RDN */
579 if (rdn_level
>= 0) {
580 if (rdn_level
!= entry
->set
) {
582 /* add old RDN to DN */
583 rdnt
= PyList_AsTuple(rdn
);
587 retcode
= PyList_Append(dn
, rdnt
);
597 rdn_level
= entry
->set
;
599 /* now add this attribute to the current RDN */
600 name
= X509_NAME_ENTRY_get_object(entry
);
601 value
= X509_NAME_ENTRY_get_data(entry
);
602 attr
= _create_tuple_for_attribute(name
, value
);
604 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
606 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
607 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
611 retcode
= PyList_Append(rdn
, attr
);
616 /* now, there's typically a dangling RDN */
617 if ((rdn
!= NULL
) && (PyList_Size(rdn
) > 0)) {
618 rdnt
= PyList_AsTuple(rdn
);
622 retcode
= PyList_Append(dn
, rdnt
);
628 /* convert list to tuple */
629 rdnt
= PyList_AsTuple(dn
);
644 _get_peer_alt_names (X509
*certificate
) {
646 /* this code follows the procedure outlined in
647 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
648 function to extract the STACK_OF(GENERAL_NAME),
649 then iterates through the stack to add the
653 PyObject
*peer_alt_names
= Py_None
;
655 X509_EXTENSION
*ext
= NULL
;
656 GENERAL_NAMES
*names
= NULL
;
658 X509V3_EXT_METHOD
*method
;
663 const unsigned char *p
;
665 if (certificate
== NULL
)
666 return peer_alt_names
;
668 /* get a memory buffer */
669 biobuf
= BIO_new(BIO_s_mem());
672 while ((i
= X509_get_ext_by_NID(
673 certificate
, NID_subject_alt_name
, i
)) >= 0) {
675 if (peer_alt_names
== Py_None
) {
676 peer_alt_names
= PyList_New(0);
677 if (peer_alt_names
== NULL
)
681 /* now decode the altName */
682 ext
= X509_get_ext(certificate
, i
);
683 if(!(method
= X509V3_EXT_get(ext
))) {
684 PyErr_SetString(PySSLErrorObject
,
685 ERRSTR("No method for internalizing subjectAltName!"));
689 p
= ext
->value
->data
;
691 names
= (GENERAL_NAMES
*) (ASN1_item_d2i(NULL
,
694 ASN1_ITEM_ptr(method
->it
)));
696 names
= (GENERAL_NAMES
*) (method
->d2i(NULL
,
698 ext
->value
->length
));
700 for(j
= 0; j
< sk_GENERAL_NAME_num(names
); j
++) {
702 /* get a rendering of each name in the set of names */
704 name
= sk_GENERAL_NAME_value(names
, j
);
705 if (name
->type
== GEN_DIRNAME
) {
707 /* we special-case DirName as a tuple of tuples of attributes */
714 v
= PyString_FromString("DirName");
719 PyTuple_SET_ITEM(t
, 0, v
);
721 v
= _create_tuple_for_X509_NAME (name
->d
.dirn
);
726 PyTuple_SET_ITEM(t
, 1, v
);
730 /* for everything else, we use the OpenSSL print form */
732 (void) BIO_reset(biobuf
);
733 GENERAL_NAME_print(biobuf
, name
);
734 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
736 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
739 vptr
= strchr(buf
, ':');
745 v
= PyString_FromStringAndSize(buf
, (vptr
- buf
));
750 PyTuple_SET_ITEM(t
, 0, v
);
751 v
= PyString_FromStringAndSize((vptr
+ 1), (len
- (vptr
- buf
+ 1)));
756 PyTuple_SET_ITEM(t
, 1, v
);
759 /* and add that rendering to the list */
761 if (PyList_Append(peer_alt_names
, t
) < 0) {
769 if (peer_alt_names
!= Py_None
) {
770 v
= PyList_AsTuple(peer_alt_names
);
771 Py_DECREF(peer_alt_names
);
774 return peer_alt_names
;
782 if (peer_alt_names
!= Py_None
) {
783 Py_XDECREF(peer_alt_names
);
790 _decode_certificate (X509
*certificate
, int verbose
) {
792 PyObject
*retval
= NULL
;
795 PyObject
*peer_alt_names
= NULL
;
799 ASN1_INTEGER
*serialNumber
;
802 ASN1_TIME
*notBefore
, *notAfter
;
803 PyObject
*pnotBefore
, *pnotAfter
;
805 retval
= PyDict_New();
809 peer
= _create_tuple_for_X509_NAME(
810 X509_get_subject_name(certificate
));
813 if (PyDict_SetItemString(retval
, (const char *) "subject", peer
) < 0) {
820 issuer
= _create_tuple_for_X509_NAME(
821 X509_get_issuer_name(certificate
));
824 if (PyDict_SetItemString(retval
, (const char *)"issuer", issuer
) < 0) {
830 version
= PyInt_FromLong(X509_get_version(certificate
) + 1);
831 if (PyDict_SetItemString(retval
, "version", version
) < 0) {
838 /* get a memory buffer */
839 biobuf
= BIO_new(BIO_s_mem());
843 (void) BIO_reset(biobuf
);
844 serialNumber
= X509_get_serialNumber(certificate
);
845 /* should not exceed 20 octets, 160 bits, so buf is big enough */
846 i2a_ASN1_INTEGER(biobuf
, serialNumber
);
847 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
849 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
852 sn_obj
= PyString_FromStringAndSize(buf
, len
);
855 if (PyDict_SetItemString(retval
, "serialNumber", sn_obj
) < 0) {
861 (void) BIO_reset(biobuf
);
862 notBefore
= X509_get_notBefore(certificate
);
863 ASN1_TIME_print(biobuf
, notBefore
);
864 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
866 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
869 pnotBefore
= PyString_FromStringAndSize(buf
, len
);
870 if (pnotBefore
== NULL
)
872 if (PyDict_SetItemString(retval
, "notBefore", pnotBefore
) < 0) {
873 Py_DECREF(pnotBefore
);
876 Py_DECREF(pnotBefore
);
879 (void) BIO_reset(biobuf
);
880 notAfter
= X509_get_notAfter(certificate
);
881 ASN1_TIME_print(biobuf
, notAfter
);
882 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
884 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
887 pnotAfter
= PyString_FromStringAndSize(buf
, len
);
888 if (pnotAfter
== NULL
)
890 if (PyDict_SetItemString(retval
, "notAfter", pnotAfter
) < 0) {
891 Py_DECREF(pnotAfter
);
894 Py_DECREF(pnotAfter
);
896 /* Now look for subjectAltName */
898 peer_alt_names
= _get_peer_alt_names(certificate
);
899 if (peer_alt_names
== NULL
)
901 else if (peer_alt_names
!= Py_None
) {
902 if (PyDict_SetItemString(retval
, "subjectAltName",
903 peer_alt_names
) < 0) {
904 Py_DECREF(peer_alt_names
);
907 Py_DECREF(peer_alt_names
);
923 PySSL_test_decode_certificate (PyObject
*mod
, PyObject
*args
) {
925 PyObject
*retval
= NULL
;
926 char *filename
= NULL
;
931 if (!PyArg_ParseTuple(args
, "s|i:test_decode_certificate", &filename
, &verbose
))
934 if ((cert
=BIO_new(BIO_s_file())) == NULL
) {
935 PyErr_SetString(PySSLErrorObject
, "Can't malloc memory to read file");
939 if (BIO_read_filename(cert
,filename
) <= 0) {
940 PyErr_SetString(PySSLErrorObject
, "Can't open file");
944 x
= PEM_read_bio_X509_AUX(cert
,NULL
, NULL
, NULL
);
946 PyErr_SetString(PySSLErrorObject
, "Error decoding PEM-encoded file");
950 retval
= _decode_certificate(x
, verbose
);
954 if (cert
!= NULL
) BIO_free(cert
);
960 PySSL_peercert(PySSLObject
*self
, PyObject
*args
)
962 PyObject
*retval
= NULL
;
965 PyObject
*binary_mode
= Py_None
;
967 if (!PyArg_ParseTuple(args
, "|O:peer_certificate", &binary_mode
))
970 if (!self
->peer_cert
)
973 if (PyObject_IsTrue(binary_mode
)) {
974 /* return cert in DER-encoded format */
976 unsigned char *bytes_buf
= NULL
;
979 len
= i2d_X509(self
->peer_cert
, &bytes_buf
);
981 PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
984 retval
= PyString_FromStringAndSize((const char *) bytes_buf
, len
);
985 OPENSSL_free(bytes_buf
);
990 verification
= SSL_CTX_get_verify_mode(self
->ctx
);
991 if ((verification
& SSL_VERIFY_PEER
) == 0)
994 return _decode_certificate (self
->peer_cert
, 0);
998 PyDoc_STRVAR(PySSL_peercert_doc
,
999 "peer_certificate([der=False]) -> certificate\n\
1001 Returns the certificate for the peer. If no certificate was provided,\n\
1002 returns None. If a certificate was provided, but not validated, returns\n\
1003 an empty dictionary. Otherwise returns a dict containing information\n\
1004 about the peer certificate.\n\
1006 If the optional argument is True, returns a DER-encoded copy of the\n\
1007 peer certificate, or None if no certificate was provided. This will\n\
1008 return the certificate even if it wasn't validated.");
1010 static PyObject
*PySSL_cipher (PySSLObject
*self
) {
1012 PyObject
*retval
, *v
;
1013 SSL_CIPHER
*current
;
1015 char *cipher_protocol
;
1017 if (self
->ssl
== NULL
)
1019 current
= SSL_get_current_cipher(self
->ssl
);
1020 if (current
== NULL
)
1023 retval
= PyTuple_New(3);
1027 cipher_name
= (char *) SSL_CIPHER_get_name(current
);
1028 if (cipher_name
== NULL
) {
1029 PyTuple_SET_ITEM(retval
, 0, Py_None
);
1031 v
= PyString_FromString(cipher_name
);
1034 PyTuple_SET_ITEM(retval
, 0, v
);
1036 cipher_protocol
= SSL_CIPHER_get_version(current
);
1037 if (cipher_protocol
== NULL
) {
1038 PyTuple_SET_ITEM(retval
, 1, Py_None
);
1040 v
= PyString_FromString(cipher_protocol
);
1043 PyTuple_SET_ITEM(retval
, 1, v
);
1045 v
= PyInt_FromLong(SSL_CIPHER_get_bits(current
, NULL
));
1048 PyTuple_SET_ITEM(retval
, 2, v
);
1056 static void PySSL_dealloc(PySSLObject
*self
)
1058 if (self
->peer_cert
) /* Possible not to have one? */
1059 X509_free (self
->peer_cert
);
1061 SSL_free(self
->ssl
);
1063 SSL_CTX_free(self
->ctx
);
1064 Py_XDECREF(self
->Socket
);
1068 /* If the socket has a timeout, do a select()/poll() on the socket.
1069 The argument writing indicates the direction.
1070 Returns one of the possibilities in the timeout_state enum (above).
1074 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
1080 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1081 if (s
->sock_timeout
< 0.0)
1082 return SOCKET_IS_BLOCKING
;
1083 else if (s
->sock_timeout
== 0.0)
1084 return SOCKET_IS_NONBLOCKING
;
1086 /* Guard against closed socket */
1088 return SOCKET_HAS_BEEN_CLOSED
;
1090 /* Prefer poll, if available, since you can poll() any fd
1091 * which can't be done with select(). */
1094 struct pollfd pollfd
;
1097 pollfd
.fd
= s
->sock_fd
;
1098 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
1100 /* s->sock_timeout is in seconds, timeout in ms */
1101 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
1102 PySSL_BEGIN_ALLOW_THREADS
1103 rc
= poll(&pollfd
, 1, timeout
);
1104 PySSL_END_ALLOW_THREADS
1110 /* Guard against socket too large for select*/
1111 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1112 if (s
->sock_fd
>= FD_SETSIZE
)
1113 return SOCKET_TOO_LARGE_FOR_SELECT
;
1116 /* Construct the arguments to select */
1117 tv
.tv_sec
= (int)s
->sock_timeout
;
1118 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1120 FD_SET(s
->sock_fd
, &fds
);
1122 /* See if the socket is ready */
1123 PySSL_BEGIN_ALLOW_THREADS
1125 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
1127 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
1128 PySSL_END_ALLOW_THREADS
1131 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1132 (when we are able to write or when there's something to read) */
1133 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
1136 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
1144 if (!PyArg_ParseTuple(args
, "s#:write", &data
, &count
))
1147 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1148 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1149 PyErr_SetString(PySSLErrorObject
,
1150 "The write operation timed out");
1152 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1153 PyErr_SetString(PySSLErrorObject
,
1154 "Underlying socket has been closed.");
1156 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1157 PyErr_SetString(PySSLErrorObject
,
1158 "Underlying socket too large for select().");
1163 PySSL_BEGIN_ALLOW_THREADS
1164 len
= SSL_write(self
->ssl
, data
, count
);
1165 err
= SSL_get_error(self
->ssl
, len
);
1166 PySSL_END_ALLOW_THREADS
1167 if(PyErr_CheckSignals()) {
1170 if (err
== SSL_ERROR_WANT_READ
) {
1172 check_socket_and_wait_for_timeout(self
->Socket
, 0);
1173 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1175 check_socket_and_wait_for_timeout(self
->Socket
, 1);
1177 sockstate
= SOCKET_OPERATION_OK
;
1179 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1180 PyErr_SetString(PySSLErrorObject
,
1181 "The write operation timed out");
1183 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1184 PyErr_SetString(PySSLErrorObject
,
1185 "Underlying socket has been closed.");
1187 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1190 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1192 return PyInt_FromLong(len
);
1194 return PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
1197 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
1200 Writes the string s into the SSL object. Returns the number\n\
1201 of bytes written.");
1203 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
1211 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
1214 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
1217 /* first check if there are bytes ready to be read */
1218 PySSL_BEGIN_ALLOW_THREADS
1219 count
= SSL_pending(self
->ssl
);
1220 PySSL_END_ALLOW_THREADS
1223 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1224 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1225 PyErr_SetString(PySSLErrorObject
,
1226 "The read operation timed out");
1229 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1230 PyErr_SetString(PySSLErrorObject
,
1231 "Underlying socket too large for select().");
1234 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1235 /* should contain a zero-length string */
1236 _PyString_Resize(&buf
, 0);
1242 PySSL_BEGIN_ALLOW_THREADS
1243 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
1244 err
= SSL_get_error(self
->ssl
, count
);
1245 PySSL_END_ALLOW_THREADS
1246 if(PyErr_CheckSignals()) {
1250 if (err
== SSL_ERROR_WANT_READ
) {
1252 check_socket_and_wait_for_timeout(self
->Socket
, 0);
1253 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1255 check_socket_and_wait_for_timeout(self
->Socket
, 1);
1256 } else if ((err
== SSL_ERROR_ZERO_RETURN
) &&
1257 (SSL_get_shutdown(self
->ssl
) ==
1258 SSL_RECEIVED_SHUTDOWN
))
1260 _PyString_Resize(&buf
, 0);
1263 sockstate
= SOCKET_OPERATION_OK
;
1265 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1266 PyErr_SetString(PySSLErrorObject
,
1267 "The read operation timed out");
1270 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1273 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1276 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
1279 _PyString_Resize(&buf
, count
);
1283 PyDoc_STRVAR(PySSL_SSLread_doc
,
1284 "read([len]) -> string\n\
1286 Read up to len bytes from the SSL socket.");
1288 static PyMethodDef PySSLMethods
[] = {
1289 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
1290 PySSL_SSLwrite_doc
},
1291 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
1293 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
1294 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
1295 {"peer_certificate", (PyCFunction
)PySSL_peercert
, METH_VARARGS
,
1296 PySSL_peercert_doc
},
1297 {"cipher", (PyCFunction
)PySSL_cipher
, METH_NOARGS
},
1301 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
1303 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
1306 static PyTypeObject PySSL_Type
= {
1307 PyVarObject_HEAD_INIT(NULL
, 0)
1308 "ssl.SSLContext", /*tp_name*/
1309 sizeof(PySSLObject
), /*tp_basicsize*/
1312 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
1314 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
1319 0, /*tp_as_sequence*/
1320 0, /*tp_as_mapping*/
1324 #ifdef HAVE_OPENSSL_RAND
1326 /* helper routines for seeding the SSL PRNG */
1328 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
1334 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
1336 RAND_add(buf
, len
, entropy
);
1341 PyDoc_STRVAR(PySSL_RAND_add_doc
,
1342 "RAND_add(string, entropy)\n\
1344 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1345 bound on the entropy contained in string. See RFC 1750.");
1348 PySSL_RAND_status(PyObject
*self
)
1350 return PyInt_FromLong(RAND_status());
1353 PyDoc_STRVAR(PySSL_RAND_status_doc
,
1354 "RAND_status() -> 0 or 1\n\
1356 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1357 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1358 using the ssl() function.");
1361 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
1365 if (!PyString_Check(arg
))
1366 return PyErr_Format(PyExc_TypeError
,
1367 "RAND_egd() expected string, found %s",
1368 Py_TYPE(arg
)->tp_name
);
1369 bytes
= RAND_egd(PyString_AS_STRING(arg
));
1371 PyErr_SetString(PySSLErrorObject
,
1372 "EGD connection failed or EGD did not return "
1373 "enough data to seed the PRNG");
1376 return PyInt_FromLong(bytes
);
1379 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
1380 "RAND_egd(path) -> bytes\n\
1382 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1383 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1384 fails or if it does provide enough data to seed PRNG.");
1388 /* List of functions exported by this module. */
1390 static PyMethodDef PySSL_methods
[] = {
1391 {"sslwrap", PySSL_sslwrap
,
1392 METH_VARARGS
, ssl_doc
},
1393 {"_test_decode_cert", PySSL_test_decode_certificate
,
1395 #ifdef HAVE_OPENSSL_RAND
1396 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
1397 PySSL_RAND_add_doc
},
1398 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
1399 PySSL_RAND_egd_doc
},
1400 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
1401 PySSL_RAND_status_doc
},
1403 {NULL
, NULL
} /* Sentinel */
1409 /* an implementation of OpenSSL threading operations in terms
1410 of the Python C thread library */
1412 static PyThread_type_lock
*_ssl_locks
= NULL
;
1414 static unsigned long _ssl_thread_id_function (void) {
1415 return PyThread_get_thread_ident();
1418 static void _ssl_thread_locking_function (int mode
, int n
, const char *file
, int line
) {
1419 /* this function is needed to perform locking on shared data
1420 structures. (Note that OpenSSL uses a number of global data
1421 structures that will be implicitly shared whenever multiple threads
1422 use OpenSSL.) Multi-threaded applications will crash at random if
1425 locking_function() must be able to handle up to CRYPTO_num_locks()
1426 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1427 releases it otherwise.
1429 file and line are the file number of the function setting the
1430 lock. They can be useful for debugging.
1433 if ((_ssl_locks
== NULL
) ||
1434 (n
< 0) || ((unsigned)n
>= _ssl_locks_count
))
1437 if (mode
& CRYPTO_LOCK
) {
1438 PyThread_acquire_lock(_ssl_locks
[n
], 1);
1440 PyThread_release_lock(_ssl_locks
[n
]);
1444 static int _setup_ssl_threads(void) {
1448 if (_ssl_locks
== NULL
) {
1449 _ssl_locks_count
= CRYPTO_num_locks();
1450 _ssl_locks
= (PyThread_type_lock
*)
1451 malloc(sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1452 if (_ssl_locks
== NULL
)
1454 memset(_ssl_locks
, 0, sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1455 for (i
= 0; i
< _ssl_locks_count
; i
++) {
1456 _ssl_locks
[i
] = PyThread_allocate_lock();
1457 if (_ssl_locks
[i
] == NULL
) {
1459 for (j
= 0; j
< i
; j
++) {
1460 PyThread_free_lock(_ssl_locks
[j
]);
1466 CRYPTO_set_locking_callback(_ssl_thread_locking_function
);
1467 CRYPTO_set_id_callback(_ssl_thread_id_function
);
1472 #endif /* def HAVE_THREAD */
1474 PyDoc_STRVAR(module_doc
,
1475 "Implementation module for SSL socket operations. See the socket module\n\
1476 for documentation.");
1483 Py_TYPE(&PySSL_Type
) = &PyType_Type
;
1485 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
1488 d
= PyModule_GetDict(m
);
1490 /* Load _socket module and its C API */
1491 if (PySocketModule_ImportModuleAndAPI())
1495 SSL_load_error_strings();
1497 /* note that this will start threading if not already started */
1498 if (!_setup_ssl_threads()) {
1502 SSLeay_add_ssl_algorithms();
1504 /* Add symbols to module dict */
1505 PySSLErrorObject
= PyErr_NewException("ssl.SSLError",
1506 PySocketModule
.error
,
1508 if (PySSLErrorObject
== NULL
)
1510 if (PyDict_SetItemString(d
, "SSLError", PySSLErrorObject
) != 0)
1512 if (PyDict_SetItemString(d
, "SSLType",
1513 (PyObject
*)&PySSL_Type
) != 0)
1515 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
1516 PY_SSL_ERROR_ZERO_RETURN
);
1517 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
1518 PY_SSL_ERROR_WANT_READ
);
1519 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
1520 PY_SSL_ERROR_WANT_WRITE
);
1521 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
1522 PY_SSL_ERROR_WANT_X509_LOOKUP
);
1523 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
1524 PY_SSL_ERROR_SYSCALL
);
1525 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
1527 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
1528 PY_SSL_ERROR_WANT_CONNECT
);
1529 /* non ssl.h errorcodes */
1530 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
1532 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
1533 PY_SSL_ERROR_INVALID_ERROR_CODE
);
1534 /* cert requirements */
1535 PyModule_AddIntConstant(m
, "CERT_NONE",
1537 PyModule_AddIntConstant(m
, "CERT_OPTIONAL",
1538 PY_SSL_CERT_OPTIONAL
);
1539 PyModule_AddIntConstant(m
, "CERT_REQUIRED",
1540 PY_SSL_CERT_REQUIRED
);
1542 /* protocol versions */
1543 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv2",
1544 PY_SSL_VERSION_SSL2
);
1545 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv3",
1546 PY_SSL_VERSION_SSL3
);
1547 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv23",
1548 PY_SSL_VERSION_SSL23
);
1549 PyModule_AddIntConstant(m
, "PROTOCOL_TLSv1",
1550 PY_SSL_VERSION_TLS1
);