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
5 certificate decoding. Chris Stawarz contributed some non-blocking
8 This module is imported by ssl.py. It should *not* be used
11 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
21 #define PySSL_BEGIN_ALLOW_THREADS { \
22 PyThreadState *_save = NULL; \
23 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24 #define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25 #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26 #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
29 #else /* no WITH_THREAD */
31 #define PySSL_BEGIN_ALLOW_THREADS
32 #define PySSL_BLOCK_THREADS
33 #define PySSL_UNBLOCK_THREADS
34 #define PySSL_END_ALLOW_THREADS
39 /* these mirror ssl.h */
42 PY_SSL_ERROR_WANT_READ
,
43 PY_SSL_ERROR_WANT_WRITE
,
44 PY_SSL_ERROR_WANT_X509_LOOKUP
,
45 PY_SSL_ERROR_SYSCALL
, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN
,
47 PY_SSL_ERROR_WANT_CONNECT
,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF
, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_INVALID_ERROR_CODE
53 enum py_ssl_server_or_client
{
58 enum py_ssl_cert_requirements
{
65 #ifndef OPENSSL_NO_SSL2
68 PY_SSL_VERSION_SSL3
=1,
73 /* Include symbols from _socket module */
74 #include "socketmodule.h"
76 #if defined(HAVE_POLL_H)
78 #elif defined(HAVE_SYS_POLL_H)
82 /* Include OpenSSL header files */
83 #include "openssl/rsa.h"
84 #include "openssl/crypto.h"
85 #include "openssl/x509.h"
86 #include "openssl/x509v3.h"
87 #include "openssl/pem.h"
88 #include "openssl/ssl.h"
89 #include "openssl/err.h"
90 #include "openssl/rand.h"
92 /* SSL error object */
93 static PyObject
*PySSLErrorObject
;
97 /* serves as a flag to see whether we've initialized the SSL thread support. */
98 /* 0 means no, greater than 0 means yes */
100 static unsigned int _ssl_locks_count
= 0;
102 #endif /* def WITH_THREAD */
104 /* SSL socket object */
106 #define X509_NAME_MAXLEN 256
108 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
109 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
110 # define HAVE_OPENSSL_RAND 1
112 # undef HAVE_OPENSSL_RAND
117 PySocketSockObject
*Socket
; /* Socket on which we're layered */
121 char server
[X509_NAME_MAXLEN
];
122 char issuer
[X509_NAME_MAXLEN
];
123 int shutdown_seen_zero
;
127 static PyTypeObject PySSL_Type
;
128 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
129 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
130 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
132 static PyObject
*PySSL_peercert(PySSLObject
*self
, PyObject
*args
);
133 static PyObject
*PySSL_cipher(PySSLObject
*self
);
135 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
138 SOCKET_IS_NONBLOCKING
,
140 SOCKET_HAS_TIMED_OUT
,
141 SOCKET_HAS_BEEN_CLOSED
,
142 SOCKET_TOO_LARGE_FOR_SELECT
,
146 /* Wrap error strings with filename and line # */
147 #define STRINGIFY1(x) #x
148 #define STRINGIFY2(x) STRINGIFY1(x)
149 #define ERRSTR1(x,y,z) (x ":" y ": " z)
150 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
152 /* XXX It might be helpful to augment the error message generated
153 below with the name of the SSL function that generated the error.
154 I expect it's obvious most of the time.
158 PySSL_SetError(PySSLObject
*obj
, int ret
, char *filename
, int lineno
)
164 enum py_ssl_error p
= PY_SSL_ERROR_NONE
;
168 if (obj
->ssl
!= NULL
) {
169 err
= SSL_get_error(obj
->ssl
, ret
);
172 case SSL_ERROR_ZERO_RETURN
:
173 errstr
= "TLS/SSL connection has been closed";
174 p
= PY_SSL_ERROR_ZERO_RETURN
;
176 case SSL_ERROR_WANT_READ
:
177 errstr
= "The operation did not complete (read)";
178 p
= PY_SSL_ERROR_WANT_READ
;
180 case SSL_ERROR_WANT_WRITE
:
181 p
= PY_SSL_ERROR_WANT_WRITE
;
182 errstr
= "The operation did not complete (write)";
184 case SSL_ERROR_WANT_X509_LOOKUP
:
185 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
186 errstr
= "The operation did not complete (X509 lookup)";
188 case SSL_ERROR_WANT_CONNECT
:
189 p
= PY_SSL_ERROR_WANT_CONNECT
;
190 errstr
= "The operation did not complete (connect)";
192 case SSL_ERROR_SYSCALL
:
194 unsigned long e
= ERR_get_error();
196 if (ret
== 0 || !obj
->Socket
) {
197 p
= PY_SSL_ERROR_EOF
;
198 errstr
= "EOF occurred in violation of protocol";
199 } else if (ret
== -1) {
200 /* underlying BIO reported an I/O error */
202 return obj
->Socket
->errorhandler();
203 } else { /* possible? */
204 p
= PY_SSL_ERROR_SYSCALL
;
205 errstr
= "Some I/O error occurred";
208 p
= PY_SSL_ERROR_SYSCALL
;
209 /* XXX Protected by global interpreter lock */
210 errstr
= ERR_error_string(e
, NULL
);
216 unsigned long e
= ERR_get_error();
217 p
= PY_SSL_ERROR_SSL
;
219 /* XXX Protected by global interpreter lock */
220 errstr
= ERR_error_string(e
, NULL
);
221 else { /* possible? */
222 errstr
= "A failure in the SSL library occurred";
227 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
228 errstr
= "Invalid error code";
231 errstr
= ERR_error_string(ERR_peek_last_error(), NULL
);
233 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
235 v
= Py_BuildValue("(is)", p
, buf
);
237 PyErr_SetObject(PySSLErrorObject
, v
);
244 _setSSLError (char *errstr
, int errcode
, char *filename
, int lineno
) {
249 if (errstr
== NULL
) {
250 errcode
= ERR_peek_last_error();
251 errstr
= ERR_error_string(errcode
, NULL
);
253 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
255 v
= Py_BuildValue("(is)", errcode
, buf
);
257 PyErr_SetObject(PySSLErrorObject
, v
);
264 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
,
265 enum py_ssl_server_or_client socket_type
,
266 enum py_ssl_cert_requirements certreq
,
267 enum py_ssl_version proto_version
,
268 char *cacerts_file
, char *ciphers
)
273 int verification_mode
;
275 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
278 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
279 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
280 self
->peer_cert
= NULL
;
285 /* Make sure the SSL error state is initialized */
286 (void) ERR_get_state();
289 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
290 errstr
= ERRSTR("Both the key & certificate files "
291 "must be specified");
295 if ((socket_type
== PY_SSL_SERVER
) &&
296 ((key_file
== NULL
) || (cert_file
== NULL
))) {
297 errstr
= ERRSTR("Both the key & certificate files "
298 "must be specified for server-side operation");
302 PySSL_BEGIN_ALLOW_THREADS
303 if (proto_version
== PY_SSL_VERSION_TLS1
)
304 self
->ctx
= SSL_CTX_new(TLSv1_method()); /* Set up context */
305 else if (proto_version
== PY_SSL_VERSION_SSL3
)
306 self
->ctx
= SSL_CTX_new(SSLv3_method()); /* Set up context */
307 #ifndef OPENSSL_NO_SSL2
308 else if (proto_version
== PY_SSL_VERSION_SSL2
)
309 self
->ctx
= SSL_CTX_new(SSLv2_method()); /* Set up context */
311 else if (proto_version
== PY_SSL_VERSION_SSL23
)
312 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
313 PySSL_END_ALLOW_THREADS
315 if (self
->ctx
== NULL
) {
316 errstr
= ERRSTR("Invalid SSL protocol variant specified.");
320 if (ciphers
!= NULL
) {
321 ret
= SSL_CTX_set_cipher_list(self
->ctx
, ciphers
);
323 errstr
= ERRSTR("No cipher can be selected.");
328 if (certreq
!= PY_SSL_CERT_NONE
) {
329 if (cacerts_file
== NULL
) {
330 errstr
= ERRSTR("No root certificates specified for "
331 "verification of other-side certificates.");
334 PySSL_BEGIN_ALLOW_THREADS
335 ret
= SSL_CTX_load_verify_locations(self
->ctx
,
338 PySSL_END_ALLOW_THREADS
340 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
346 PySSL_BEGIN_ALLOW_THREADS
347 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
349 PySSL_END_ALLOW_THREADS
351 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
355 PySSL_BEGIN_ALLOW_THREADS
356 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
358 PySSL_END_ALLOW_THREADS
361 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
362 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
364 if (ERR_peek_last_error() != 0) {
365 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
371 /* ssl compatibility */
372 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
);
374 verification_mode
= SSL_VERIFY_NONE
;
375 if (certreq
== PY_SSL_CERT_OPTIONAL
)
376 verification_mode
= SSL_VERIFY_PEER
;
377 else if (certreq
== PY_SSL_CERT_REQUIRED
)
378 verification_mode
= (SSL_VERIFY_PEER
|
379 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
);
380 SSL_CTX_set_verify(self
->ctx
, verification_mode
,
381 NULL
); /* set verify lvl */
383 PySSL_BEGIN_ALLOW_THREADS
384 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
385 PySSL_END_ALLOW_THREADS
386 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
387 #ifdef SSL_MODE_AUTO_RETRY
388 SSL_set_mode(self
->ssl
, SSL_MODE_AUTO_RETRY
);
391 /* If the socket is in non-blocking mode or timeout mode, set the BIO
392 * to non-blocking mode (blocking is the default)
394 if (Sock
->sock_timeout
>= 0.0) {
395 /* Set both the read and write BIO's to non-blocking mode */
396 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
397 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
400 PySSL_BEGIN_ALLOW_THREADS
401 if (socket_type
== PY_SSL_CLIENT
)
402 SSL_set_connect_state(self
->ssl
);
404 SSL_set_accept_state(self
->ssl
);
405 PySSL_END_ALLOW_THREADS
408 Py_INCREF(self
->Socket
);
412 PyErr_SetString(PySSLErrorObject
, errstr
);
418 PySSL_sslwrap(PyObject
*self
, PyObject
*args
)
420 PySocketSockObject
*Sock
;
422 int verification_mode
= PY_SSL_CERT_NONE
;
423 int protocol
= PY_SSL_VERSION_SSL23
;
424 char *key_file
= NULL
;
425 char *cert_file
= NULL
;
426 char *cacerts_file
= NULL
;
427 char *ciphers
= NULL
;
429 if (!PyArg_ParseTuple(args
, "O!i|zziizz:sslwrap",
430 PySocketModule
.Sock_Type
,
433 &key_file
, &cert_file
,
434 &verification_mode
, &protocol
,
435 &cacerts_file
, &ciphers
))
440 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
441 "protocol %d, certs %p\n",
442 server_side, key_file, cert_file, verification_mode,
443 protocol, cacerts_file);
446 return (PyObject
*) newPySSLObject(Sock
, key_file
, cert_file
,
447 server_side
, verification_mode
,
448 protocol
, cacerts_file
,
452 PyDoc_STRVAR(ssl_doc
,
453 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
454 " cacertsfile, ciphers]) -> sslobject");
456 /* SSL object methods */
458 static PyObject
*PySSL_SSLdo_handshake(PySSLObject
*self
)
462 int sockstate
, nonblocking
;
464 /* just in case the blocking state of the socket has been changed */
465 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
466 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
467 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
469 /* Actually negotiate SSL connection */
470 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
472 PySSL_BEGIN_ALLOW_THREADS
473 ret
= SSL_do_handshake(self
->ssl
);
474 err
= SSL_get_error(self
->ssl
, ret
);
475 PySSL_END_ALLOW_THREADS
476 if(PyErr_CheckSignals()) {
479 if (err
== SSL_ERROR_WANT_READ
) {
480 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
481 } else if (err
== SSL_ERROR_WANT_WRITE
) {
482 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
484 sockstate
= SOCKET_OPERATION_OK
;
486 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
487 PyErr_SetString(PySSLErrorObject
,
488 ERRSTR("The handshake operation timed out"));
490 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
491 PyErr_SetString(PySSLErrorObject
,
492 ERRSTR("Underlying socket has been closed."));
494 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
495 PyErr_SetString(PySSLErrorObject
,
496 ERRSTR("Underlying socket too large for select()."));
498 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
501 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
503 return PySSL_SetError(self
, ret
, __FILE__
, __LINE__
);
506 X509_free (self
->peer_cert
);
507 PySSL_BEGIN_ALLOW_THREADS
508 if ((self
->peer_cert
= SSL_get_peer_certificate(self
->ssl
))) {
509 X509_NAME_oneline(X509_get_subject_name(self
->peer_cert
),
510 self
->server
, X509_NAME_MAXLEN
);
511 X509_NAME_oneline(X509_get_issuer_name(self
->peer_cert
),
512 self
->issuer
, X509_NAME_MAXLEN
);
514 PySSL_END_ALLOW_THREADS
521 PySSL_server(PySSLObject
*self
)
523 return PyString_FromString(self
->server
);
527 PySSL_issuer(PySSLObject
*self
)
529 return PyString_FromString(self
->issuer
);
533 _create_tuple_for_attribute (ASN1_OBJECT
*name
, ASN1_STRING
*value
) {
535 char namebuf
[X509_NAME_MAXLEN
];
540 unsigned char *valuebuf
= NULL
;
542 buflen
= OBJ_obj2txt(namebuf
, sizeof(namebuf
), name
, 0);
544 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
547 name_obj
= PyString_FromStringAndSize(namebuf
, buflen
);
548 if (name_obj
== NULL
)
551 buflen
= ASN1_STRING_to_UTF8(&valuebuf
, value
);
553 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
557 value_obj
= PyUnicode_DecodeUTF8((char *) valuebuf
,
559 OPENSSL_free(valuebuf
);
560 if (value_obj
== NULL
) {
564 attr
= PyTuple_New(2);
567 Py_DECREF(value_obj
);
570 PyTuple_SET_ITEM(attr
, 0, name_obj
);
571 PyTuple_SET_ITEM(attr
, 1, value_obj
);
579 _create_tuple_for_X509_NAME (X509_NAME
*xname
)
581 PyObject
*dn
= NULL
; /* tuple which represents the "distinguished name" */
582 PyObject
*rdn
= NULL
; /* tuple to hold a "relative distinguished name" */
584 PyObject
*attr
= NULL
; /* tuple to hold an attribute */
585 int entry_count
= X509_NAME_entry_count(xname
);
586 X509_NAME_ENTRY
*entry
;
596 /* now create another tuple to hold the top-level RDN */
601 for (index_counter
= 0;
602 index_counter
< entry_count
;
605 entry
= X509_NAME_get_entry(xname
, index_counter
);
607 /* check to see if we've gotten to a new RDN */
608 if (rdn_level
>= 0) {
609 if (rdn_level
!= entry
->set
) {
611 /* add old RDN to DN */
612 rdnt
= PyList_AsTuple(rdn
);
616 retcode
= PyList_Append(dn
, rdnt
);
626 rdn_level
= entry
->set
;
628 /* now add this attribute to the current RDN */
629 name
= X509_NAME_ENTRY_get_object(entry
);
630 value
= X509_NAME_ENTRY_get_data(entry
);
631 attr
= _create_tuple_for_attribute(name
, value
);
633 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
635 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
636 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
640 retcode
= PyList_Append(rdn
, attr
);
645 /* now, there's typically a dangling RDN */
646 if ((rdn
!= NULL
) && (PyList_Size(rdn
) > 0)) {
647 rdnt
= PyList_AsTuple(rdn
);
651 retcode
= PyList_Append(dn
, rdnt
);
657 /* convert list to tuple */
658 rdnt
= PyList_AsTuple(dn
);
673 _get_peer_alt_names (X509
*certificate
) {
675 /* this code follows the procedure outlined in
676 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
677 function to extract the STACK_OF(GENERAL_NAME),
678 then iterates through the stack to add the
682 PyObject
*peer_alt_names
= Py_None
;
684 X509_EXTENSION
*ext
= NULL
;
685 GENERAL_NAMES
*names
= NULL
;
687 const X509V3_EXT_METHOD
*method
;
692 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
693 #if OPENSSL_VERSION_NUMBER >= 0x009060dfL
694 const unsigned char *p
;
699 if (certificate
== NULL
)
700 return peer_alt_names
;
702 /* get a memory buffer */
703 biobuf
= BIO_new(BIO_s_mem());
706 while ((i
= X509_get_ext_by_NID(
707 certificate
, NID_subject_alt_name
, i
)) >= 0) {
709 if (peer_alt_names
== Py_None
) {
710 peer_alt_names
= PyList_New(0);
711 if (peer_alt_names
== NULL
)
715 /* now decode the altName */
716 ext
= X509_get_ext(certificate
, i
);
717 if(!(method
= X509V3_EXT_get(ext
))) {
718 PyErr_SetString(PySSLErrorObject
,
719 ERRSTR("No method for internalizing subjectAltName!"));
723 p
= ext
->value
->data
;
725 names
= (GENERAL_NAMES
*) (ASN1_item_d2i(NULL
,
728 ASN1_ITEM_ptr(method
->it
)));
730 names
= (GENERAL_NAMES
*) (method
->d2i(NULL
,
732 ext
->value
->length
));
734 for(j
= 0; j
< sk_GENERAL_NAME_num(names
); j
++) {
736 /* get a rendering of each name in the set of names */
738 name
= sk_GENERAL_NAME_value(names
, j
);
739 if (name
->type
== GEN_DIRNAME
) {
741 /* we special-case DirName as a tuple of tuples of attributes */
748 v
= PyString_FromString("DirName");
753 PyTuple_SET_ITEM(t
, 0, v
);
755 v
= _create_tuple_for_X509_NAME (name
->d
.dirn
);
760 PyTuple_SET_ITEM(t
, 1, v
);
764 /* for everything else, we use the OpenSSL print form */
766 (void) BIO_reset(biobuf
);
767 GENERAL_NAME_print(biobuf
, name
);
768 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
770 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
773 vptr
= strchr(buf
, ':');
779 v
= PyString_FromStringAndSize(buf
, (vptr
- buf
));
784 PyTuple_SET_ITEM(t
, 0, v
);
785 v
= PyString_FromStringAndSize((vptr
+ 1), (len
- (vptr
- buf
+ 1)));
790 PyTuple_SET_ITEM(t
, 1, v
);
793 /* and add that rendering to the list */
795 if (PyList_Append(peer_alt_names
, t
) < 0) {
803 if (peer_alt_names
!= Py_None
) {
804 v
= PyList_AsTuple(peer_alt_names
);
805 Py_DECREF(peer_alt_names
);
808 return peer_alt_names
;
816 if (peer_alt_names
!= Py_None
) {
817 Py_XDECREF(peer_alt_names
);
824 _decode_certificate (X509
*certificate
, int verbose
) {
826 PyObject
*retval
= NULL
;
829 PyObject
*peer_alt_names
= NULL
;
833 ASN1_INTEGER
*serialNumber
;
836 ASN1_TIME
*notBefore
, *notAfter
;
837 PyObject
*pnotBefore
, *pnotAfter
;
839 retval
= PyDict_New();
843 peer
= _create_tuple_for_X509_NAME(
844 X509_get_subject_name(certificate
));
847 if (PyDict_SetItemString(retval
, (const char *) "subject", peer
) < 0) {
854 issuer
= _create_tuple_for_X509_NAME(
855 X509_get_issuer_name(certificate
));
858 if (PyDict_SetItemString(retval
, (const char *)"issuer", issuer
) < 0) {
864 version
= PyInt_FromLong(X509_get_version(certificate
) + 1);
865 if (PyDict_SetItemString(retval
, "version", version
) < 0) {
872 /* get a memory buffer */
873 biobuf
= BIO_new(BIO_s_mem());
877 (void) BIO_reset(biobuf
);
878 serialNumber
= X509_get_serialNumber(certificate
);
879 /* should not exceed 20 octets, 160 bits, so buf is big enough */
880 i2a_ASN1_INTEGER(biobuf
, serialNumber
);
881 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
883 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
886 sn_obj
= PyString_FromStringAndSize(buf
, len
);
889 if (PyDict_SetItemString(retval
, "serialNumber", sn_obj
) < 0) {
895 (void) BIO_reset(biobuf
);
896 notBefore
= X509_get_notBefore(certificate
);
897 ASN1_TIME_print(biobuf
, notBefore
);
898 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
900 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
903 pnotBefore
= PyString_FromStringAndSize(buf
, len
);
904 if (pnotBefore
== NULL
)
906 if (PyDict_SetItemString(retval
, "notBefore", pnotBefore
) < 0) {
907 Py_DECREF(pnotBefore
);
910 Py_DECREF(pnotBefore
);
913 (void) BIO_reset(biobuf
);
914 notAfter
= X509_get_notAfter(certificate
);
915 ASN1_TIME_print(biobuf
, notAfter
);
916 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
918 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
921 pnotAfter
= PyString_FromStringAndSize(buf
, len
);
922 if (pnotAfter
== NULL
)
924 if (PyDict_SetItemString(retval
, "notAfter", pnotAfter
) < 0) {
925 Py_DECREF(pnotAfter
);
928 Py_DECREF(pnotAfter
);
930 /* Now look for subjectAltName */
932 peer_alt_names
= _get_peer_alt_names(certificate
);
933 if (peer_alt_names
== NULL
)
935 else if (peer_alt_names
!= Py_None
) {
936 if (PyDict_SetItemString(retval
, "subjectAltName",
937 peer_alt_names
) < 0) {
938 Py_DECREF(peer_alt_names
);
941 Py_DECREF(peer_alt_names
);
957 PySSL_test_decode_certificate (PyObject
*mod
, PyObject
*args
) {
959 PyObject
*retval
= NULL
;
960 char *filename
= NULL
;
965 if (!PyArg_ParseTuple(args
, "s|i:test_decode_certificate", &filename
, &verbose
))
968 if ((cert
=BIO_new(BIO_s_file())) == NULL
) {
969 PyErr_SetString(PySSLErrorObject
, "Can't malloc memory to read file");
973 if (BIO_read_filename(cert
,filename
) <= 0) {
974 PyErr_SetString(PySSLErrorObject
, "Can't open file");
978 x
= PEM_read_bio_X509_AUX(cert
,NULL
, NULL
, NULL
);
980 PyErr_SetString(PySSLErrorObject
, "Error decoding PEM-encoded file");
984 retval
= _decode_certificate(x
, verbose
);
989 if (cert
!= NULL
) BIO_free(cert
);
995 PySSL_peercert(PySSLObject
*self
, PyObject
*args
)
997 PyObject
*retval
= NULL
;
1000 PyObject
*binary_mode
= Py_None
;
1002 if (!PyArg_ParseTuple(args
, "|O:peer_certificate", &binary_mode
))
1005 if (!self
->peer_cert
)
1008 if (PyObject_IsTrue(binary_mode
)) {
1009 /* return cert in DER-encoded format */
1011 unsigned char *bytes_buf
= NULL
;
1014 len
= i2d_X509(self
->peer_cert
, &bytes_buf
);
1016 PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
1019 retval
= PyString_FromStringAndSize((const char *) bytes_buf
, len
);
1020 OPENSSL_free(bytes_buf
);
1025 verification
= SSL_CTX_get_verify_mode(self
->ctx
);
1026 if ((verification
& SSL_VERIFY_PEER
) == 0)
1027 return PyDict_New();
1029 return _decode_certificate (self
->peer_cert
, 0);
1033 PyDoc_STRVAR(PySSL_peercert_doc
,
1034 "peer_certificate([der=False]) -> certificate\n\
1036 Returns the certificate for the peer. If no certificate was provided,\n\
1037 returns None. If a certificate was provided, but not validated, returns\n\
1038 an empty dictionary. Otherwise returns a dict containing information\n\
1039 about the peer certificate.\n\
1041 If the optional argument is True, returns a DER-encoded copy of the\n\
1042 peer certificate, or None if no certificate was provided. This will\n\
1043 return the certificate even if it wasn't validated.");
1045 static PyObject
*PySSL_cipher (PySSLObject
*self
) {
1047 PyObject
*retval
, *v
;
1048 const SSL_CIPHER
*current
;
1050 char *cipher_protocol
;
1052 if (self
->ssl
== NULL
)
1054 current
= SSL_get_current_cipher(self
->ssl
);
1055 if (current
== NULL
)
1058 retval
= PyTuple_New(3);
1062 cipher_name
= (char *) SSL_CIPHER_get_name(current
);
1063 if (cipher_name
== NULL
) {
1065 PyTuple_SET_ITEM(retval
, 0, Py_None
);
1067 v
= PyString_FromString(cipher_name
);
1070 PyTuple_SET_ITEM(retval
, 0, v
);
1072 cipher_protocol
= SSL_CIPHER_get_version(current
);
1073 if (cipher_protocol
== NULL
) {
1075 PyTuple_SET_ITEM(retval
, 1, Py_None
);
1077 v
= PyString_FromString(cipher_protocol
);
1080 PyTuple_SET_ITEM(retval
, 1, v
);
1082 v
= PyInt_FromLong(SSL_CIPHER_get_bits(current
, NULL
));
1085 PyTuple_SET_ITEM(retval
, 2, v
);
1093 static void PySSL_dealloc(PySSLObject
*self
)
1095 if (self
->peer_cert
) /* Possible not to have one? */
1096 X509_free (self
->peer_cert
);
1098 SSL_free(self
->ssl
);
1100 SSL_CTX_free(self
->ctx
);
1101 Py_XDECREF(self
->Socket
);
1105 /* If the socket has a timeout, do a select()/poll() on the socket.
1106 The argument writing indicates the direction.
1107 Returns one of the possibilities in the timeout_state enum (above).
1111 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
1117 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1118 if (s
->sock_timeout
< 0.0)
1119 return SOCKET_IS_BLOCKING
;
1120 else if (s
->sock_timeout
== 0.0)
1121 return SOCKET_IS_NONBLOCKING
;
1123 /* Guard against closed socket */
1125 return SOCKET_HAS_BEEN_CLOSED
;
1127 /* Prefer poll, if available, since you can poll() any fd
1128 * which can't be done with select(). */
1131 struct pollfd pollfd
;
1134 pollfd
.fd
= s
->sock_fd
;
1135 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
1137 /* s->sock_timeout is in seconds, timeout in ms */
1138 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
1139 PySSL_BEGIN_ALLOW_THREADS
1140 rc
= poll(&pollfd
, 1, timeout
);
1141 PySSL_END_ALLOW_THREADS
1147 /* Guard against socket too large for select*/
1148 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1149 if (s
->sock_fd
>= FD_SETSIZE
)
1150 return SOCKET_TOO_LARGE_FOR_SELECT
;
1153 /* Construct the arguments to select */
1154 tv
.tv_sec
= (int)s
->sock_timeout
;
1155 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1157 FD_SET(s
->sock_fd
, &fds
);
1159 /* See if the socket is ready */
1160 PySSL_BEGIN_ALLOW_THREADS
1162 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
1164 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
1165 PySSL_END_ALLOW_THREADS
1170 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1171 (when we are able to write or when there's something to read) */
1172 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
1175 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
1183 if (!PyArg_ParseTuple(args
, "s*:write", &buf
))
1186 /* just in case the blocking state of the socket has been changed */
1187 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1188 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1189 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1191 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1192 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1193 PyErr_SetString(PySSLErrorObject
,
1194 "The write operation timed out");
1196 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1197 PyErr_SetString(PySSLErrorObject
,
1198 "Underlying socket has been closed.");
1200 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1201 PyErr_SetString(PySSLErrorObject
,
1202 "Underlying socket too large for select().");
1206 PySSL_BEGIN_ALLOW_THREADS
1207 len
= SSL_write(self
->ssl
, buf
.buf
, buf
.len
);
1208 err
= SSL_get_error(self
->ssl
, len
);
1209 PySSL_END_ALLOW_THREADS
1210 if (PyErr_CheckSignals()) {
1213 if (err
== SSL_ERROR_WANT_READ
) {
1214 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1215 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1216 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1218 sockstate
= SOCKET_OPERATION_OK
;
1220 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1221 PyErr_SetString(PySSLErrorObject
,
1222 "The write operation timed out");
1224 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1225 PyErr_SetString(PySSLErrorObject
,
1226 "Underlying socket has been closed.");
1228 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1231 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1233 PyBuffer_Release(&buf
);
1235 return PyInt_FromLong(len
);
1237 return PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
1240 PyBuffer_Release(&buf
);
1244 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
1247 Writes the string s into the SSL object. Returns the number\n\
1248 of bytes written.");
1250 static PyObject
*PySSL_SSLpending(PySSLObject
*self
)
1254 PySSL_BEGIN_ALLOW_THREADS
1255 count
= SSL_pending(self
->ssl
);
1256 PySSL_END_ALLOW_THREADS
1258 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
1260 return PyInt_FromLong(count
);
1263 PyDoc_STRVAR(PySSL_SSLpending_doc
,
1264 "pending() -> count\n\
1266 Returns the number of already decrypted bytes available for read,\n\
1267 pending on the connection.\n");
1269 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
1278 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
1281 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
1284 /* just in case the blocking state of the socket has been changed */
1285 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1286 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1287 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1289 /* first check if there are bytes ready to be read */
1290 PySSL_BEGIN_ALLOW_THREADS
1291 count
= SSL_pending(self
->ssl
);
1292 PySSL_END_ALLOW_THREADS
1295 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1296 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1297 PyErr_SetString(PySSLErrorObject
,
1298 "The read operation timed out");
1301 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1302 PyErr_SetString(PySSLErrorObject
,
1303 "Underlying socket too large for select().");
1306 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1307 if (SSL_get_shutdown(self
->ssl
) !=
1308 SSL_RECEIVED_SHUTDOWN
)
1311 PyErr_SetString(PySSLErrorObject
,
1312 "Socket closed without SSL shutdown handshake");
1315 /* should contain a zero-length string */
1316 _PyString_Resize(&buf
, 0);
1322 PySSL_BEGIN_ALLOW_THREADS
1323 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
1324 err
= SSL_get_error(self
->ssl
, count
);
1325 PySSL_END_ALLOW_THREADS
1326 if(PyErr_CheckSignals()) {
1330 if (err
== SSL_ERROR_WANT_READ
) {
1331 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1332 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1333 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1334 } else if ((err
== SSL_ERROR_ZERO_RETURN
) &&
1335 (SSL_get_shutdown(self
->ssl
) ==
1336 SSL_RECEIVED_SHUTDOWN
))
1338 _PyString_Resize(&buf
, 0);
1341 sockstate
= SOCKET_OPERATION_OK
;
1343 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1344 PyErr_SetString(PySSLErrorObject
,
1345 "The read operation timed out");
1348 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1351 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1354 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
1357 _PyString_Resize(&buf
, count
);
1361 PyDoc_STRVAR(PySSL_SSLread_doc
,
1362 "read([len]) -> string\n\
1364 Read up to len bytes from the SSL socket.");
1366 static PyObject
*PySSL_SSLshutdown(PySSLObject
*self
)
1368 int err
, ssl_err
, sockstate
, nonblocking
;
1371 /* Guard against closed socket */
1372 if (self
->Socket
->sock_fd
< 0) {
1373 PyErr_SetString(PySSLErrorObject
,
1374 "Underlying socket has been closed.");
1378 /* Just in case the blocking state of the socket has been changed */
1379 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1380 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1381 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1384 PySSL_BEGIN_ALLOW_THREADS
1385 /* Disable read-ahead so that unwrap can work correctly.
1386 * Otherwise OpenSSL might read in too much data,
1387 * eating clear text data that happens to be
1388 * transmitted after the SSL shutdown.
1389 * Should be safe to call repeatedly everytime this
1390 * function is used and the shutdown_seen_zero != 0
1393 if (self
->shutdown_seen_zero
)
1394 SSL_set_read_ahead(self
->ssl
, 0);
1395 err
= SSL_shutdown(self
->ssl
);
1396 PySSL_END_ALLOW_THREADS
1397 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1401 /* Don't loop endlessly; instead preserve legacy
1402 behaviour of trying SSL_shutdown() only twice.
1403 This looks necessary for OpenSSL < 0.9.8m */
1406 /* Shutdown was sent, now try receiving */
1407 self
->shutdown_seen_zero
= 1;
1411 /* Possibly retry shutdown until timeout or failure */
1412 ssl_err
= SSL_get_error(self
->ssl
, err
);
1413 if (ssl_err
== SSL_ERROR_WANT_READ
)
1414 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1415 else if (ssl_err
== SSL_ERROR_WANT_WRITE
)
1416 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1419 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1420 if (ssl_err
== SSL_ERROR_WANT_READ
)
1421 PyErr_SetString(PySSLErrorObject
,
1422 "The read operation timed out");
1424 PyErr_SetString(PySSLErrorObject
,
1425 "The write operation timed out");
1428 else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1429 PyErr_SetString(PySSLErrorObject
,
1430 "Underlying socket too large for select().");
1433 else if (sockstate
!= SOCKET_OPERATION_OK
)
1434 /* Retain the SSL error code */
1439 return PySSL_SetError(self
, err
, __FILE__
, __LINE__
);
1441 Py_INCREF(self
->Socket
);
1442 return (PyObject
*) (self
->Socket
);
1446 PyDoc_STRVAR(PySSL_SSLshutdown_doc
,
1447 "shutdown(s) -> socket\n\
1449 Does the SSL shutdown handshake with the remote end, and returns\n\
1450 the underlying socket object.");
1452 static PyMethodDef PySSLMethods
[] = {
1453 {"do_handshake", (PyCFunction
)PySSL_SSLdo_handshake
, METH_NOARGS
},
1454 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
1455 PySSL_SSLwrite_doc
},
1456 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
1458 {"pending", (PyCFunction
)PySSL_SSLpending
, METH_NOARGS
,
1459 PySSL_SSLpending_doc
},
1460 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
1461 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
1462 {"peer_certificate", (PyCFunction
)PySSL_peercert
, METH_VARARGS
,
1463 PySSL_peercert_doc
},
1464 {"cipher", (PyCFunction
)PySSL_cipher
, METH_NOARGS
},
1465 {"shutdown", (PyCFunction
)PySSL_SSLshutdown
, METH_NOARGS
,
1466 PySSL_SSLshutdown_doc
},
1470 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
1472 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
1475 static PyTypeObject PySSL_Type
= {
1476 PyVarObject_HEAD_INIT(NULL
, 0)
1477 "ssl.SSLContext", /*tp_name*/
1478 sizeof(PySSLObject
), /*tp_basicsize*/
1481 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
1483 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
1488 0, /*tp_as_sequence*/
1489 0, /*tp_as_mapping*/
1493 #ifdef HAVE_OPENSSL_RAND
1495 /* helper routines for seeding the SSL PRNG */
1497 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
1503 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
1505 RAND_add(buf
, len
, entropy
);
1510 PyDoc_STRVAR(PySSL_RAND_add_doc
,
1511 "RAND_add(string, entropy)\n\
1513 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1514 bound on the entropy contained in string. See RFC 1750.");
1517 PySSL_RAND_status(PyObject
*self
)
1519 return PyInt_FromLong(RAND_status());
1522 PyDoc_STRVAR(PySSL_RAND_status_doc
,
1523 "RAND_status() -> 0 or 1\n\
1525 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1526 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1527 using the ssl() function.");
1530 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
1534 if (!PyString_Check(arg
))
1535 return PyErr_Format(PyExc_TypeError
,
1536 "RAND_egd() expected string, found %s",
1537 Py_TYPE(arg
)->tp_name
);
1538 bytes
= RAND_egd(PyString_AS_STRING(arg
));
1540 PyErr_SetString(PySSLErrorObject
,
1541 "EGD connection failed or EGD did not return "
1542 "enough data to seed the PRNG");
1545 return PyInt_FromLong(bytes
);
1548 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
1549 "RAND_egd(path) -> bytes\n\
1551 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1552 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1553 fails or if it does provide enough data to seed PRNG.");
1557 /* List of functions exported by this module. */
1559 static PyMethodDef PySSL_methods
[] = {
1560 {"sslwrap", PySSL_sslwrap
,
1561 METH_VARARGS
, ssl_doc
},
1562 {"_test_decode_cert", PySSL_test_decode_certificate
,
1564 #ifdef HAVE_OPENSSL_RAND
1565 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
1566 PySSL_RAND_add_doc
},
1567 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
1568 PySSL_RAND_egd_doc
},
1569 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
1570 PySSL_RAND_status_doc
},
1572 {NULL
, NULL
} /* Sentinel */
1578 /* an implementation of OpenSSL threading operations in terms
1579 of the Python C thread library */
1581 static PyThread_type_lock
*_ssl_locks
= NULL
;
1583 static unsigned long _ssl_thread_id_function (void) {
1584 return PyThread_get_thread_ident();
1587 static void _ssl_thread_locking_function (int mode
, int n
, const char *file
, int line
) {
1588 /* this function is needed to perform locking on shared data
1589 structures. (Note that OpenSSL uses a number of global data
1590 structures that will be implicitly shared whenever multiple threads
1591 use OpenSSL.) Multi-threaded applications will crash at random if
1594 locking_function() must be able to handle up to CRYPTO_num_locks()
1595 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1596 releases it otherwise.
1598 file and line are the file number of the function setting the
1599 lock. They can be useful for debugging.
1602 if ((_ssl_locks
== NULL
) ||
1603 (n
< 0) || ((unsigned)n
>= _ssl_locks_count
))
1606 if (mode
& CRYPTO_LOCK
) {
1607 PyThread_acquire_lock(_ssl_locks
[n
], 1);
1609 PyThread_release_lock(_ssl_locks
[n
]);
1613 static int _setup_ssl_threads(void) {
1617 if (_ssl_locks
== NULL
) {
1618 _ssl_locks_count
= CRYPTO_num_locks();
1619 _ssl_locks
= (PyThread_type_lock
*)
1620 malloc(sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1621 if (_ssl_locks
== NULL
)
1623 memset(_ssl_locks
, 0, sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1624 for (i
= 0; i
< _ssl_locks_count
; i
++) {
1625 _ssl_locks
[i
] = PyThread_allocate_lock();
1626 if (_ssl_locks
[i
] == NULL
) {
1628 for (j
= 0; j
< i
; j
++) {
1629 PyThread_free_lock(_ssl_locks
[j
]);
1635 CRYPTO_set_locking_callback(_ssl_thread_locking_function
);
1636 CRYPTO_set_id_callback(_ssl_thread_id_function
);
1641 #endif /* def HAVE_THREAD */
1643 PyDoc_STRVAR(module_doc
,
1644 "Implementation module for SSL socket operations. See the socket module\n\
1645 for documentation.");
1650 PyObject
*m
, *d
, *r
;
1651 unsigned long libver
;
1652 unsigned int major
, minor
, fix
, patch
, status
;
1654 Py_TYPE(&PySSL_Type
) = &PyType_Type
;
1656 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
1659 d
= PyModule_GetDict(m
);
1661 /* Load _socket module and its C API */
1662 if (PySocketModule_ImportModuleAndAPI())
1666 SSL_load_error_strings();
1669 /* note that this will start threading if not already started */
1670 if (!_setup_ssl_threads()) {
1674 OpenSSL_add_all_algorithms();
1676 /* Add symbols to module dict */
1677 PySSLErrorObject
= PyErr_NewException("ssl.SSLError",
1678 PySocketModule
.error
,
1680 if (PySSLErrorObject
== NULL
)
1682 if (PyDict_SetItemString(d
, "SSLError", PySSLErrorObject
) != 0)
1684 if (PyDict_SetItemString(d
, "SSLType",
1685 (PyObject
*)&PySSL_Type
) != 0)
1687 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
1688 PY_SSL_ERROR_ZERO_RETURN
);
1689 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
1690 PY_SSL_ERROR_WANT_READ
);
1691 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
1692 PY_SSL_ERROR_WANT_WRITE
);
1693 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
1694 PY_SSL_ERROR_WANT_X509_LOOKUP
);
1695 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
1696 PY_SSL_ERROR_SYSCALL
);
1697 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
1699 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
1700 PY_SSL_ERROR_WANT_CONNECT
);
1701 /* non ssl.h errorcodes */
1702 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
1704 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
1705 PY_SSL_ERROR_INVALID_ERROR_CODE
);
1706 /* cert requirements */
1707 PyModule_AddIntConstant(m
, "CERT_NONE",
1709 PyModule_AddIntConstant(m
, "CERT_OPTIONAL",
1710 PY_SSL_CERT_OPTIONAL
);
1711 PyModule_AddIntConstant(m
, "CERT_REQUIRED",
1712 PY_SSL_CERT_REQUIRED
);
1714 /* protocol versions */
1715 #ifndef OPENSSL_NO_SSL2
1716 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv2",
1717 PY_SSL_VERSION_SSL2
);
1719 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv3",
1720 PY_SSL_VERSION_SSL3
);
1721 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv23",
1722 PY_SSL_VERSION_SSL23
);
1723 PyModule_AddIntConstant(m
, "PROTOCOL_TLSv1",
1724 PY_SSL_VERSION_TLS1
);
1726 /* OpenSSL version */
1727 /* SSLeay() gives us the version of the library linked against,
1728 which could be different from the headers version.
1731 r
= PyLong_FromUnsignedLong(libver
);
1734 if (PyModule_AddObject(m
, "OPENSSL_VERSION_NUMBER", r
))
1736 status
= libver
& 0xF;
1738 patch
= libver
& 0xFF;
1740 fix
= libver
& 0xFF;
1742 minor
= libver
& 0xFF;
1744 major
= libver
& 0xFF;
1745 r
= Py_BuildValue("IIIII", major
, minor
, fix
, patch
, status
);
1746 if (r
== NULL
|| PyModule_AddObject(m
, "OPENSSL_VERSION_INFO", r
))
1748 r
= PyString_FromString(SSLeay_version(SSLEAY_VERSION
));
1749 if (r
== NULL
|| PyModule_AddObject(m
, "OPENSSL_VERSION", r
))