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
{
71 /* Include symbols from _socket module */
72 #include "socketmodule.h"
74 #if defined(HAVE_POLL_H)
76 #elif defined(HAVE_SYS_POLL_H)
80 /* Include OpenSSL header files */
81 #include "openssl/rsa.h"
82 #include "openssl/crypto.h"
83 #include "openssl/x509.h"
84 #include "openssl/x509v3.h"
85 #include "openssl/pem.h"
86 #include "openssl/ssl.h"
87 #include "openssl/err.h"
88 #include "openssl/rand.h"
90 /* SSL error object */
91 static PyObject
*PySSLErrorObject
;
95 /* serves as a flag to see whether we've initialized the SSL thread support. */
96 /* 0 means no, greater than 0 means yes */
98 static unsigned int _ssl_locks_count
= 0;
100 #endif /* def WITH_THREAD */
102 /* SSL socket object */
104 #define X509_NAME_MAXLEN 256
106 /* RAND_* APIs got added to OpenSSL in 0.9.5 */
107 #if OPENSSL_VERSION_NUMBER >= 0x0090500fL
108 # define HAVE_OPENSSL_RAND 1
110 # undef HAVE_OPENSSL_RAND
115 PySocketSockObject
*Socket
; /* Socket on which we're layered */
119 char server
[X509_NAME_MAXLEN
];
120 char issuer
[X509_NAME_MAXLEN
];
121 int shutdown_seen_zero
;
125 static PyTypeObject PySSL_Type
;
126 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
);
127 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
);
128 static int check_socket_and_wait_for_timeout(PySocketSockObject
*s
,
130 static PyObject
*PySSL_peercert(PySSLObject
*self
, PyObject
*args
);
131 static PyObject
*PySSL_cipher(PySSLObject
*self
);
133 #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
136 SOCKET_IS_NONBLOCKING
,
138 SOCKET_HAS_TIMED_OUT
,
139 SOCKET_HAS_BEEN_CLOSED
,
140 SOCKET_TOO_LARGE_FOR_SELECT
,
144 /* Wrap error strings with filename and line # */
145 #define STRINGIFY1(x) #x
146 #define STRINGIFY2(x) STRINGIFY1(x)
147 #define ERRSTR1(x,y,z) (x ":" y ": " z)
148 #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
150 /* XXX It might be helpful to augment the error message generated
151 below with the name of the SSL function that generated the error.
152 I expect it's obvious most of the time.
156 PySSL_SetError(PySSLObject
*obj
, int ret
, char *filename
, int lineno
)
162 enum py_ssl_error p
= PY_SSL_ERROR_NONE
;
166 if (obj
->ssl
!= NULL
) {
167 err
= SSL_get_error(obj
->ssl
, ret
);
170 case SSL_ERROR_ZERO_RETURN
:
171 errstr
= "TLS/SSL connection has been closed";
172 p
= PY_SSL_ERROR_ZERO_RETURN
;
174 case SSL_ERROR_WANT_READ
:
175 errstr
= "The operation did not complete (read)";
176 p
= PY_SSL_ERROR_WANT_READ
;
178 case SSL_ERROR_WANT_WRITE
:
179 p
= PY_SSL_ERROR_WANT_WRITE
;
180 errstr
= "The operation did not complete (write)";
182 case SSL_ERROR_WANT_X509_LOOKUP
:
183 p
= PY_SSL_ERROR_WANT_X509_LOOKUP
;
184 errstr
= "The operation did not complete (X509 lookup)";
186 case SSL_ERROR_WANT_CONNECT
:
187 p
= PY_SSL_ERROR_WANT_CONNECT
;
188 errstr
= "The operation did not complete (connect)";
190 case SSL_ERROR_SYSCALL
:
192 unsigned long e
= ERR_get_error();
194 if (ret
== 0 || !obj
->Socket
) {
195 p
= PY_SSL_ERROR_EOF
;
196 errstr
= "EOF occurred in violation of protocol";
197 } else if (ret
== -1) {
198 /* underlying BIO reported an I/O error */
200 return obj
->Socket
->errorhandler();
201 } else { /* possible? */
202 p
= PY_SSL_ERROR_SYSCALL
;
203 errstr
= "Some I/O error occurred";
206 p
= PY_SSL_ERROR_SYSCALL
;
207 /* XXX Protected by global interpreter lock */
208 errstr
= ERR_error_string(e
, NULL
);
214 unsigned long e
= ERR_get_error();
215 p
= PY_SSL_ERROR_SSL
;
217 /* XXX Protected by global interpreter lock */
218 errstr
= ERR_error_string(e
, NULL
);
219 else { /* possible? */
220 errstr
= "A failure in the SSL library occurred";
225 p
= PY_SSL_ERROR_INVALID_ERROR_CODE
;
226 errstr
= "Invalid error code";
229 errstr
= ERR_error_string(ERR_peek_last_error(), NULL
);
231 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
233 v
= Py_BuildValue("(is)", p
, buf
);
235 PyErr_SetObject(PySSLErrorObject
, v
);
242 _setSSLError (char *errstr
, int errcode
, char *filename
, int lineno
) {
247 if (errstr
== NULL
) {
248 errcode
= ERR_peek_last_error();
249 errstr
= ERR_error_string(errcode
, NULL
);
251 PyOS_snprintf(buf
, sizeof(buf
), "_ssl.c:%d: %s", lineno
, errstr
);
253 v
= Py_BuildValue("(is)", errcode
, buf
);
255 PyErr_SetObject(PySSLErrorObject
, v
);
262 newPySSLObject(PySocketSockObject
*Sock
, char *key_file
, char *cert_file
,
263 enum py_ssl_server_or_client socket_type
,
264 enum py_ssl_cert_requirements certreq
,
265 enum py_ssl_version proto_version
,
266 char *cacerts_file
, char *ciphers
)
271 int verification_mode
;
273 self
= PyObject_New(PySSLObject
, &PySSL_Type
); /* Create new object */
276 memset(self
->server
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
277 memset(self
->issuer
, '\0', sizeof(char) * X509_NAME_MAXLEN
);
278 self
->peer_cert
= NULL
;
283 /* Make sure the SSL error state is initialized */
284 (void) ERR_get_state();
287 if ((key_file
&& !cert_file
) || (!key_file
&& cert_file
)) {
288 errstr
= ERRSTR("Both the key & certificate files "
289 "must be specified");
293 if ((socket_type
== PY_SSL_SERVER
) &&
294 ((key_file
== NULL
) || (cert_file
== NULL
))) {
295 errstr
= ERRSTR("Both the key & certificate files "
296 "must be specified for server-side operation");
300 PySSL_BEGIN_ALLOW_THREADS
301 if (proto_version
== PY_SSL_VERSION_TLS1
)
302 self
->ctx
= SSL_CTX_new(TLSv1_method()); /* Set up context */
303 else if (proto_version
== PY_SSL_VERSION_SSL3
)
304 self
->ctx
= SSL_CTX_new(SSLv3_method()); /* Set up context */
305 else if (proto_version
== PY_SSL_VERSION_SSL2
)
306 self
->ctx
= SSL_CTX_new(SSLv2_method()); /* Set up context */
307 else if (proto_version
== PY_SSL_VERSION_SSL23
)
308 self
->ctx
= SSL_CTX_new(SSLv23_method()); /* Set up context */
309 PySSL_END_ALLOW_THREADS
311 if (self
->ctx
== NULL
) {
312 errstr
= ERRSTR("Invalid SSL protocol variant specified.");
316 if (ciphers
!= NULL
) {
317 ret
= SSL_CTX_set_cipher_list(self
->ctx
, ciphers
);
319 errstr
= ERRSTR("No cipher can be selected.");
324 if (certreq
!= PY_SSL_CERT_NONE
) {
325 if (cacerts_file
== NULL
) {
326 errstr
= ERRSTR("No root certificates specified for "
327 "verification of other-side certificates.");
330 PySSL_BEGIN_ALLOW_THREADS
331 ret
= SSL_CTX_load_verify_locations(self
->ctx
,
334 PySSL_END_ALLOW_THREADS
336 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
342 PySSL_BEGIN_ALLOW_THREADS
343 ret
= SSL_CTX_use_PrivateKey_file(self
->ctx
, key_file
,
345 PySSL_END_ALLOW_THREADS
347 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
351 PySSL_BEGIN_ALLOW_THREADS
352 ret
= SSL_CTX_use_certificate_chain_file(self
->ctx
,
354 PySSL_END_ALLOW_THREADS
357 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
358 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
360 if (ERR_peek_last_error() != 0) {
361 _setSSLError(NULL
, ret
, __FILE__
, __LINE__
);
367 /* ssl compatibility */
368 SSL_CTX_set_options(self
->ctx
, SSL_OP_ALL
);
370 verification_mode
= SSL_VERIFY_NONE
;
371 if (certreq
== PY_SSL_CERT_OPTIONAL
)
372 verification_mode
= SSL_VERIFY_PEER
;
373 else if (certreq
== PY_SSL_CERT_REQUIRED
)
374 verification_mode
= (SSL_VERIFY_PEER
|
375 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
);
376 SSL_CTX_set_verify(self
->ctx
, verification_mode
,
377 NULL
); /* set verify lvl */
379 PySSL_BEGIN_ALLOW_THREADS
380 self
->ssl
= SSL_new(self
->ctx
); /* New ssl struct */
381 PySSL_END_ALLOW_THREADS
382 SSL_set_fd(self
->ssl
, Sock
->sock_fd
); /* Set the socket for SSL */
383 #ifdef SSL_MODE_AUTO_RETRY
384 SSL_set_mode(self
->ssl
, SSL_MODE_AUTO_RETRY
);
387 /* If the socket is in non-blocking mode or timeout mode, set the BIO
388 * to non-blocking mode (blocking is the default)
390 if (Sock
->sock_timeout
>= 0.0) {
391 /* Set both the read and write BIO's to non-blocking mode */
392 BIO_set_nbio(SSL_get_rbio(self
->ssl
), 1);
393 BIO_set_nbio(SSL_get_wbio(self
->ssl
), 1);
396 PySSL_BEGIN_ALLOW_THREADS
397 if (socket_type
== PY_SSL_CLIENT
)
398 SSL_set_connect_state(self
->ssl
);
400 SSL_set_accept_state(self
->ssl
);
401 PySSL_END_ALLOW_THREADS
404 Py_INCREF(self
->Socket
);
408 PyErr_SetString(PySSLErrorObject
, errstr
);
414 PySSL_sslwrap(PyObject
*self
, PyObject
*args
)
416 PySocketSockObject
*Sock
;
418 int verification_mode
= PY_SSL_CERT_NONE
;
419 int protocol
= PY_SSL_VERSION_SSL23
;
420 char *key_file
= NULL
;
421 char *cert_file
= NULL
;
422 char *cacerts_file
= NULL
;
423 char *ciphers
= NULL
;
425 if (!PyArg_ParseTuple(args
, "O!i|zziizz:sslwrap",
426 PySocketModule
.Sock_Type
,
429 &key_file
, &cert_file
,
430 &verification_mode
, &protocol
,
431 &cacerts_file
, &ciphers
))
436 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
437 "protocol %d, certs %p\n",
438 server_side, key_file, cert_file, verification_mode,
439 protocol, cacerts_file);
442 return (PyObject
*) newPySSLObject(Sock
, key_file
, cert_file
,
443 server_side
, verification_mode
,
444 protocol
, cacerts_file
,
448 PyDoc_STRVAR(ssl_doc
,
449 "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
450 " cacertsfile, ciphers]) -> sslobject");
452 /* SSL object methods */
454 static PyObject
*PySSL_SSLdo_handshake(PySSLObject
*self
)
458 int sockstate
, nonblocking
;
460 /* just in case the blocking state of the socket has been changed */
461 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
462 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
463 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
465 /* Actually negotiate SSL connection */
466 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
468 PySSL_BEGIN_ALLOW_THREADS
469 ret
= SSL_do_handshake(self
->ssl
);
470 err
= SSL_get_error(self
->ssl
, ret
);
471 PySSL_END_ALLOW_THREADS
472 if(PyErr_CheckSignals()) {
475 if (err
== SSL_ERROR_WANT_READ
) {
476 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
477 } else if (err
== SSL_ERROR_WANT_WRITE
) {
478 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
480 sockstate
= SOCKET_OPERATION_OK
;
482 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
483 PyErr_SetString(PySSLErrorObject
,
484 ERRSTR("The handshake operation timed out"));
486 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
487 PyErr_SetString(PySSLErrorObject
,
488 ERRSTR("Underlying socket has been closed."));
490 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
491 PyErr_SetString(PySSLErrorObject
,
492 ERRSTR("Underlying socket too large for select()."));
494 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
497 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
499 return PySSL_SetError(self
, ret
, __FILE__
, __LINE__
);
502 X509_free (self
->peer_cert
);
503 PySSL_BEGIN_ALLOW_THREADS
504 if ((self
->peer_cert
= SSL_get_peer_certificate(self
->ssl
))) {
505 X509_NAME_oneline(X509_get_subject_name(self
->peer_cert
),
506 self
->server
, X509_NAME_MAXLEN
);
507 X509_NAME_oneline(X509_get_issuer_name(self
->peer_cert
),
508 self
->issuer
, X509_NAME_MAXLEN
);
510 PySSL_END_ALLOW_THREADS
517 PySSL_server(PySSLObject
*self
)
519 return PyString_FromString(self
->server
);
523 PySSL_issuer(PySSLObject
*self
)
525 return PyString_FromString(self
->issuer
);
529 _create_tuple_for_attribute (ASN1_OBJECT
*name
, ASN1_STRING
*value
) {
531 char namebuf
[X509_NAME_MAXLEN
];
536 unsigned char *valuebuf
= NULL
;
538 buflen
= OBJ_obj2txt(namebuf
, sizeof(namebuf
), name
, 0);
540 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
543 name_obj
= PyString_FromStringAndSize(namebuf
, buflen
);
544 if (name_obj
== NULL
)
547 buflen
= ASN1_STRING_to_UTF8(&valuebuf
, value
);
549 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
553 value_obj
= PyUnicode_DecodeUTF8((char *) valuebuf
,
555 OPENSSL_free(valuebuf
);
556 if (value_obj
== NULL
) {
560 attr
= PyTuple_New(2);
563 Py_DECREF(value_obj
);
566 PyTuple_SET_ITEM(attr
, 0, name_obj
);
567 PyTuple_SET_ITEM(attr
, 1, value_obj
);
575 _create_tuple_for_X509_NAME (X509_NAME
*xname
)
577 PyObject
*dn
= NULL
; /* tuple which represents the "distinguished name" */
578 PyObject
*rdn
= NULL
; /* tuple to hold a "relative distinguished name" */
580 PyObject
*attr
= NULL
; /* tuple to hold an attribute */
581 int entry_count
= X509_NAME_entry_count(xname
);
582 X509_NAME_ENTRY
*entry
;
592 /* now create another tuple to hold the top-level RDN */
597 for (index_counter
= 0;
598 index_counter
< entry_count
;
601 entry
= X509_NAME_get_entry(xname
, index_counter
);
603 /* check to see if we've gotten to a new RDN */
604 if (rdn_level
>= 0) {
605 if (rdn_level
!= entry
->set
) {
607 /* add old RDN to DN */
608 rdnt
= PyList_AsTuple(rdn
);
612 retcode
= PyList_Append(dn
, rdnt
);
622 rdn_level
= entry
->set
;
624 /* now add this attribute to the current RDN */
625 name
= X509_NAME_ENTRY_get_object(entry
);
626 value
= X509_NAME_ENTRY_get_data(entry
);
627 attr
= _create_tuple_for_attribute(name
, value
);
629 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
631 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
632 PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
636 retcode
= PyList_Append(rdn
, attr
);
641 /* now, there's typically a dangling RDN */
642 if ((rdn
!= NULL
) && (PyList_Size(rdn
) > 0)) {
643 rdnt
= PyList_AsTuple(rdn
);
647 retcode
= PyList_Append(dn
, rdnt
);
653 /* convert list to tuple */
654 rdnt
= PyList_AsTuple(dn
);
669 _get_peer_alt_names (X509
*certificate
) {
671 /* this code follows the procedure outlined in
672 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
673 function to extract the STACK_OF(GENERAL_NAME),
674 then iterates through the stack to add the
678 PyObject
*peer_alt_names
= Py_None
;
680 X509_EXTENSION
*ext
= NULL
;
681 GENERAL_NAMES
*names
= NULL
;
683 X509V3_EXT_METHOD
*method
;
688 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
689 #if OPENSSL_VERSION_NUMBER >= 0x009060dfL
690 const unsigned char *p
;
695 if (certificate
== NULL
)
696 return peer_alt_names
;
698 /* get a memory buffer */
699 biobuf
= BIO_new(BIO_s_mem());
702 while ((i
= X509_get_ext_by_NID(
703 certificate
, NID_subject_alt_name
, i
)) >= 0) {
705 if (peer_alt_names
== Py_None
) {
706 peer_alt_names
= PyList_New(0);
707 if (peer_alt_names
== NULL
)
711 /* now decode the altName */
712 ext
= X509_get_ext(certificate
, i
);
713 if(!(method
= X509V3_EXT_get(ext
))) {
714 PyErr_SetString(PySSLErrorObject
,
715 ERRSTR("No method for internalizing subjectAltName!"));
719 p
= ext
->value
->data
;
721 names
= (GENERAL_NAMES
*) (ASN1_item_d2i(NULL
,
724 ASN1_ITEM_ptr(method
->it
)));
726 names
= (GENERAL_NAMES
*) (method
->d2i(NULL
,
728 ext
->value
->length
));
730 for(j
= 0; j
< sk_GENERAL_NAME_num(names
); j
++) {
732 /* get a rendering of each name in the set of names */
734 name
= sk_GENERAL_NAME_value(names
, j
);
735 if (name
->type
== GEN_DIRNAME
) {
737 /* we special-case DirName as a tuple of tuples of attributes */
744 v
= PyString_FromString("DirName");
749 PyTuple_SET_ITEM(t
, 0, v
);
751 v
= _create_tuple_for_X509_NAME (name
->d
.dirn
);
756 PyTuple_SET_ITEM(t
, 1, v
);
760 /* for everything else, we use the OpenSSL print form */
762 (void) BIO_reset(biobuf
);
763 GENERAL_NAME_print(biobuf
, name
);
764 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
766 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
769 vptr
= strchr(buf
, ':');
775 v
= PyString_FromStringAndSize(buf
, (vptr
- buf
));
780 PyTuple_SET_ITEM(t
, 0, v
);
781 v
= PyString_FromStringAndSize((vptr
+ 1), (len
- (vptr
- buf
+ 1)));
786 PyTuple_SET_ITEM(t
, 1, v
);
789 /* and add that rendering to the list */
791 if (PyList_Append(peer_alt_names
, t
) < 0) {
799 if (peer_alt_names
!= Py_None
) {
800 v
= PyList_AsTuple(peer_alt_names
);
801 Py_DECREF(peer_alt_names
);
804 return peer_alt_names
;
812 if (peer_alt_names
!= Py_None
) {
813 Py_XDECREF(peer_alt_names
);
820 _decode_certificate (X509
*certificate
, int verbose
) {
822 PyObject
*retval
= NULL
;
825 PyObject
*peer_alt_names
= NULL
;
829 ASN1_INTEGER
*serialNumber
;
832 ASN1_TIME
*notBefore
, *notAfter
;
833 PyObject
*pnotBefore
, *pnotAfter
;
835 retval
= PyDict_New();
839 peer
= _create_tuple_for_X509_NAME(
840 X509_get_subject_name(certificate
));
843 if (PyDict_SetItemString(retval
, (const char *) "subject", peer
) < 0) {
850 issuer
= _create_tuple_for_X509_NAME(
851 X509_get_issuer_name(certificate
));
854 if (PyDict_SetItemString(retval
, (const char *)"issuer", issuer
) < 0) {
860 version
= PyInt_FromLong(X509_get_version(certificate
) + 1);
861 if (PyDict_SetItemString(retval
, "version", version
) < 0) {
868 /* get a memory buffer */
869 biobuf
= BIO_new(BIO_s_mem());
873 (void) BIO_reset(biobuf
);
874 serialNumber
= X509_get_serialNumber(certificate
);
875 /* should not exceed 20 octets, 160 bits, so buf is big enough */
876 i2a_ASN1_INTEGER(biobuf
, serialNumber
);
877 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
879 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
882 sn_obj
= PyString_FromStringAndSize(buf
, len
);
885 if (PyDict_SetItemString(retval
, "serialNumber", sn_obj
) < 0) {
891 (void) BIO_reset(biobuf
);
892 notBefore
= X509_get_notBefore(certificate
);
893 ASN1_TIME_print(biobuf
, notBefore
);
894 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
896 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
899 pnotBefore
= PyString_FromStringAndSize(buf
, len
);
900 if (pnotBefore
== NULL
)
902 if (PyDict_SetItemString(retval
, "notBefore", pnotBefore
) < 0) {
903 Py_DECREF(pnotBefore
);
906 Py_DECREF(pnotBefore
);
909 (void) BIO_reset(biobuf
);
910 notAfter
= X509_get_notAfter(certificate
);
911 ASN1_TIME_print(biobuf
, notAfter
);
912 len
= BIO_gets(biobuf
, buf
, sizeof(buf
)-1);
914 _setSSLError(NULL
, 0, __FILE__
, __LINE__
);
917 pnotAfter
= PyString_FromStringAndSize(buf
, len
);
918 if (pnotAfter
== NULL
)
920 if (PyDict_SetItemString(retval
, "notAfter", pnotAfter
) < 0) {
921 Py_DECREF(pnotAfter
);
924 Py_DECREF(pnotAfter
);
926 /* Now look for subjectAltName */
928 peer_alt_names
= _get_peer_alt_names(certificate
);
929 if (peer_alt_names
== NULL
)
931 else if (peer_alt_names
!= Py_None
) {
932 if (PyDict_SetItemString(retval
, "subjectAltName",
933 peer_alt_names
) < 0) {
934 Py_DECREF(peer_alt_names
);
937 Py_DECREF(peer_alt_names
);
953 PySSL_test_decode_certificate (PyObject
*mod
, PyObject
*args
) {
955 PyObject
*retval
= NULL
;
956 char *filename
= NULL
;
961 if (!PyArg_ParseTuple(args
, "s|i:test_decode_certificate", &filename
, &verbose
))
964 if ((cert
=BIO_new(BIO_s_file())) == NULL
) {
965 PyErr_SetString(PySSLErrorObject
, "Can't malloc memory to read file");
969 if (BIO_read_filename(cert
,filename
) <= 0) {
970 PyErr_SetString(PySSLErrorObject
, "Can't open file");
974 x
= PEM_read_bio_X509_AUX(cert
,NULL
, NULL
, NULL
);
976 PyErr_SetString(PySSLErrorObject
, "Error decoding PEM-encoded file");
980 retval
= _decode_certificate(x
, verbose
);
984 if (cert
!= NULL
) BIO_free(cert
);
990 PySSL_peercert(PySSLObject
*self
, PyObject
*args
)
992 PyObject
*retval
= NULL
;
995 PyObject
*binary_mode
= Py_None
;
997 if (!PyArg_ParseTuple(args
, "|O:peer_certificate", &binary_mode
))
1000 if (!self
->peer_cert
)
1003 if (PyObject_IsTrue(binary_mode
)) {
1004 /* return cert in DER-encoded format */
1006 unsigned char *bytes_buf
= NULL
;
1009 len
= i2d_X509(self
->peer_cert
, &bytes_buf
);
1011 PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
1014 retval
= PyString_FromStringAndSize((const char *) bytes_buf
, len
);
1015 OPENSSL_free(bytes_buf
);
1020 verification
= SSL_CTX_get_verify_mode(self
->ctx
);
1021 if ((verification
& SSL_VERIFY_PEER
) == 0)
1022 return PyDict_New();
1024 return _decode_certificate (self
->peer_cert
, 0);
1028 PyDoc_STRVAR(PySSL_peercert_doc
,
1029 "peer_certificate([der=False]) -> certificate\n\
1031 Returns the certificate for the peer. If no certificate was provided,\n\
1032 returns None. If a certificate was provided, but not validated, returns\n\
1033 an empty dictionary. Otherwise returns a dict containing information\n\
1034 about the peer certificate.\n\
1036 If the optional argument is True, returns a DER-encoded copy of the\n\
1037 peer certificate, or None if no certificate was provided. This will\n\
1038 return the certificate even if it wasn't validated.");
1040 static PyObject
*PySSL_cipher (PySSLObject
*self
) {
1042 PyObject
*retval
, *v
;
1043 SSL_CIPHER
*current
;
1045 char *cipher_protocol
;
1047 if (self
->ssl
== NULL
)
1049 current
= SSL_get_current_cipher(self
->ssl
);
1050 if (current
== NULL
)
1053 retval
= PyTuple_New(3);
1057 cipher_name
= (char *) SSL_CIPHER_get_name(current
);
1058 if (cipher_name
== NULL
) {
1059 PyTuple_SET_ITEM(retval
, 0, Py_None
);
1061 v
= PyString_FromString(cipher_name
);
1064 PyTuple_SET_ITEM(retval
, 0, v
);
1066 cipher_protocol
= SSL_CIPHER_get_version(current
);
1067 if (cipher_protocol
== NULL
) {
1068 PyTuple_SET_ITEM(retval
, 1, Py_None
);
1070 v
= PyString_FromString(cipher_protocol
);
1073 PyTuple_SET_ITEM(retval
, 1, v
);
1075 v
= PyInt_FromLong(SSL_CIPHER_get_bits(current
, NULL
));
1078 PyTuple_SET_ITEM(retval
, 2, v
);
1086 static void PySSL_dealloc(PySSLObject
*self
)
1088 if (self
->peer_cert
) /* Possible not to have one? */
1089 X509_free (self
->peer_cert
);
1091 SSL_free(self
->ssl
);
1093 SSL_CTX_free(self
->ctx
);
1094 Py_XDECREF(self
->Socket
);
1098 /* If the socket has a timeout, do a select()/poll() on the socket.
1099 The argument writing indicates the direction.
1100 Returns one of the possibilities in the timeout_state enum (above).
1104 check_socket_and_wait_for_timeout(PySocketSockObject
*s
, int writing
)
1110 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1111 if (s
->sock_timeout
< 0.0)
1112 return SOCKET_IS_BLOCKING
;
1113 else if (s
->sock_timeout
== 0.0)
1114 return SOCKET_IS_NONBLOCKING
;
1116 /* Guard against closed socket */
1118 return SOCKET_HAS_BEEN_CLOSED
;
1120 /* Prefer poll, if available, since you can poll() any fd
1121 * which can't be done with select(). */
1124 struct pollfd pollfd
;
1127 pollfd
.fd
= s
->sock_fd
;
1128 pollfd
.events
= writing
? POLLOUT
: POLLIN
;
1130 /* s->sock_timeout is in seconds, timeout in ms */
1131 timeout
= (int)(s
->sock_timeout
* 1000 + 0.5);
1132 PySSL_BEGIN_ALLOW_THREADS
1133 rc
= poll(&pollfd
, 1, timeout
);
1134 PySSL_END_ALLOW_THREADS
1140 /* Guard against socket too large for select*/
1141 #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1142 if (s
->sock_fd
>= FD_SETSIZE
)
1143 return SOCKET_TOO_LARGE_FOR_SELECT
;
1146 /* Construct the arguments to select */
1147 tv
.tv_sec
= (int)s
->sock_timeout
;
1148 tv
.tv_usec
= (int)((s
->sock_timeout
- tv
.tv_sec
) * 1e6
);
1150 FD_SET(s
->sock_fd
, &fds
);
1152 /* See if the socket is ready */
1153 PySSL_BEGIN_ALLOW_THREADS
1155 rc
= select(s
->sock_fd
+1, NULL
, &fds
, NULL
, &tv
);
1157 rc
= select(s
->sock_fd
+1, &fds
, NULL
, NULL
, &tv
);
1158 PySSL_END_ALLOW_THREADS
1163 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1164 (when we are able to write or when there's something to read) */
1165 return rc
== 0 ? SOCKET_HAS_TIMED_OUT
: SOCKET_OPERATION_OK
;
1168 static PyObject
*PySSL_SSLwrite(PySSLObject
*self
, PyObject
*args
)
1176 if (!PyArg_ParseTuple(args
, "s*:write", &buf
))
1179 /* just in case the blocking state of the socket has been changed */
1180 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1181 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1182 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1184 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1185 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1186 PyErr_SetString(PySSLErrorObject
,
1187 "The write operation timed out");
1189 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1190 PyErr_SetString(PySSLErrorObject
,
1191 "Underlying socket has been closed.");
1193 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1194 PyErr_SetString(PySSLErrorObject
,
1195 "Underlying socket too large for select().");
1199 PySSL_BEGIN_ALLOW_THREADS
1200 len
= SSL_write(self
->ssl
, buf
.buf
, buf
.len
);
1201 err
= SSL_get_error(self
->ssl
, len
);
1202 PySSL_END_ALLOW_THREADS
1203 if (PyErr_CheckSignals()) {
1206 if (err
== SSL_ERROR_WANT_READ
) {
1207 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1208 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1209 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1211 sockstate
= SOCKET_OPERATION_OK
;
1213 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1214 PyErr_SetString(PySSLErrorObject
,
1215 "The write operation timed out");
1217 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1218 PyErr_SetString(PySSLErrorObject
,
1219 "Underlying socket has been closed.");
1221 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1224 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1226 PyBuffer_Release(&buf
);
1228 return PyInt_FromLong(len
);
1230 return PySSL_SetError(self
, len
, __FILE__
, __LINE__
);
1233 PyBuffer_Release(&buf
);
1237 PyDoc_STRVAR(PySSL_SSLwrite_doc
,
1240 Writes the string s into the SSL object. Returns the number\n\
1241 of bytes written.");
1243 static PyObject
*PySSL_SSLpending(PySSLObject
*self
)
1247 PySSL_BEGIN_ALLOW_THREADS
1248 count
= SSL_pending(self
->ssl
);
1249 PySSL_END_ALLOW_THREADS
1251 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
1253 return PyInt_FromLong(count
);
1256 PyDoc_STRVAR(PySSL_SSLpending_doc
,
1257 "pending() -> count\n\
1259 Returns the number of already decrypted bytes available for read,\n\
1260 pending on the connection.\n");
1262 static PyObject
*PySSL_SSLread(PySSLObject
*self
, PyObject
*args
)
1271 if (!PyArg_ParseTuple(args
, "|i:read", &len
))
1274 if (!(buf
= PyString_FromStringAndSize((char *) 0, len
)))
1277 /* just in case the blocking state of the socket has been changed */
1278 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1279 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1280 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1282 /* first check if there are bytes ready to be read */
1283 PySSL_BEGIN_ALLOW_THREADS
1284 count
= SSL_pending(self
->ssl
);
1285 PySSL_END_ALLOW_THREADS
1288 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1289 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1290 PyErr_SetString(PySSLErrorObject
,
1291 "The read operation timed out");
1294 } else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1295 PyErr_SetString(PySSLErrorObject
,
1296 "Underlying socket too large for select().");
1299 } else if (sockstate
== SOCKET_HAS_BEEN_CLOSED
) {
1300 if (SSL_get_shutdown(self
->ssl
) !=
1301 SSL_RECEIVED_SHUTDOWN
)
1304 PyErr_SetString(PySSLErrorObject
,
1305 "Socket closed without SSL shutdown handshake");
1308 /* should contain a zero-length string */
1309 _PyString_Resize(&buf
, 0);
1315 PySSL_BEGIN_ALLOW_THREADS
1316 count
= SSL_read(self
->ssl
, PyString_AsString(buf
), len
);
1317 err
= SSL_get_error(self
->ssl
, count
);
1318 PySSL_END_ALLOW_THREADS
1319 if(PyErr_CheckSignals()) {
1323 if (err
== SSL_ERROR_WANT_READ
) {
1324 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1325 } else if (err
== SSL_ERROR_WANT_WRITE
) {
1326 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1327 } else if ((err
== SSL_ERROR_ZERO_RETURN
) &&
1328 (SSL_get_shutdown(self
->ssl
) ==
1329 SSL_RECEIVED_SHUTDOWN
))
1331 _PyString_Resize(&buf
, 0);
1334 sockstate
= SOCKET_OPERATION_OK
;
1336 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1337 PyErr_SetString(PySSLErrorObject
,
1338 "The read operation timed out");
1341 } else if (sockstate
== SOCKET_IS_NONBLOCKING
) {
1344 } while (err
== SSL_ERROR_WANT_READ
|| err
== SSL_ERROR_WANT_WRITE
);
1347 return PySSL_SetError(self
, count
, __FILE__
, __LINE__
);
1350 _PyString_Resize(&buf
, count
);
1354 PyDoc_STRVAR(PySSL_SSLread_doc
,
1355 "read([len]) -> string\n\
1357 Read up to len bytes from the SSL socket.");
1359 static PyObject
*PySSL_SSLshutdown(PySSLObject
*self
)
1361 int err
, ssl_err
, sockstate
, nonblocking
;
1364 /* Guard against closed socket */
1365 if (self
->Socket
->sock_fd
< 0) {
1366 PyErr_SetString(PySSLErrorObject
,
1367 "Underlying socket has been closed.");
1371 /* Just in case the blocking state of the socket has been changed */
1372 nonblocking
= (self
->Socket
->sock_timeout
>= 0.0);
1373 BIO_set_nbio(SSL_get_rbio(self
->ssl
), nonblocking
);
1374 BIO_set_nbio(SSL_get_wbio(self
->ssl
), nonblocking
);
1377 PySSL_BEGIN_ALLOW_THREADS
1378 /* Disable read-ahead so that unwrap can work correctly.
1379 * Otherwise OpenSSL might read in too much data,
1380 * eating clear text data that happens to be
1381 * transmitted after the SSL shutdown.
1382 * Should be safe to call repeatedly everytime this
1383 * function is used and the shutdown_seen_zero != 0
1386 if (self
->shutdown_seen_zero
)
1387 SSL_set_read_ahead(self
->ssl
, 0);
1388 err
= SSL_shutdown(self
->ssl
);
1389 PySSL_END_ALLOW_THREADS
1390 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1394 /* Don't loop endlessly; instead preserve legacy
1395 behaviour of trying SSL_shutdown() only twice.
1396 This looks necessary for OpenSSL < 0.9.8m */
1399 /* Shutdown was sent, now try receiving */
1400 self
->shutdown_seen_zero
= 1;
1404 /* Possibly retry shutdown until timeout or failure */
1405 ssl_err
= SSL_get_error(self
->ssl
, err
);
1406 if (ssl_err
== SSL_ERROR_WANT_READ
)
1407 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 0);
1408 else if (ssl_err
== SSL_ERROR_WANT_WRITE
)
1409 sockstate
= check_socket_and_wait_for_timeout(self
->Socket
, 1);
1412 if (sockstate
== SOCKET_HAS_TIMED_OUT
) {
1413 if (ssl_err
== SSL_ERROR_WANT_READ
)
1414 PyErr_SetString(PySSLErrorObject
,
1415 "The read operation timed out");
1417 PyErr_SetString(PySSLErrorObject
,
1418 "The write operation timed out");
1421 else if (sockstate
== SOCKET_TOO_LARGE_FOR_SELECT
) {
1422 PyErr_SetString(PySSLErrorObject
,
1423 "Underlying socket too large for select().");
1426 else if (sockstate
!= SOCKET_OPERATION_OK
)
1427 /* Retain the SSL error code */
1432 return PySSL_SetError(self
, err
, __FILE__
, __LINE__
);
1434 Py_INCREF(self
->Socket
);
1435 return (PyObject
*) (self
->Socket
);
1439 PyDoc_STRVAR(PySSL_SSLshutdown_doc
,
1440 "shutdown(s) -> socket\n\
1442 Does the SSL shutdown handshake with the remote end, and returns\n\
1443 the underlying socket object.");
1445 static PyMethodDef PySSLMethods
[] = {
1446 {"do_handshake", (PyCFunction
)PySSL_SSLdo_handshake
, METH_NOARGS
},
1447 {"write", (PyCFunction
)PySSL_SSLwrite
, METH_VARARGS
,
1448 PySSL_SSLwrite_doc
},
1449 {"read", (PyCFunction
)PySSL_SSLread
, METH_VARARGS
,
1451 {"pending", (PyCFunction
)PySSL_SSLpending
, METH_NOARGS
,
1452 PySSL_SSLpending_doc
},
1453 {"server", (PyCFunction
)PySSL_server
, METH_NOARGS
},
1454 {"issuer", (PyCFunction
)PySSL_issuer
, METH_NOARGS
},
1455 {"peer_certificate", (PyCFunction
)PySSL_peercert
, METH_VARARGS
,
1456 PySSL_peercert_doc
},
1457 {"cipher", (PyCFunction
)PySSL_cipher
, METH_NOARGS
},
1458 {"shutdown", (PyCFunction
)PySSL_SSLshutdown
, METH_NOARGS
,
1459 PySSL_SSLshutdown_doc
},
1463 static PyObject
*PySSL_getattr(PySSLObject
*self
, char *name
)
1465 return Py_FindMethod(PySSLMethods
, (PyObject
*)self
, name
);
1468 static PyTypeObject PySSL_Type
= {
1469 PyVarObject_HEAD_INIT(NULL
, 0)
1470 "ssl.SSLContext", /*tp_name*/
1471 sizeof(PySSLObject
), /*tp_basicsize*/
1474 (destructor
)PySSL_dealloc
, /*tp_dealloc*/
1476 (getattrfunc
)PySSL_getattr
, /*tp_getattr*/
1481 0, /*tp_as_sequence*/
1482 0, /*tp_as_mapping*/
1486 #ifdef HAVE_OPENSSL_RAND
1488 /* helper routines for seeding the SSL PRNG */
1490 PySSL_RAND_add(PyObject
*self
, PyObject
*args
)
1496 if (!PyArg_ParseTuple(args
, "s#d:RAND_add", &buf
, &len
, &entropy
))
1498 RAND_add(buf
, len
, entropy
);
1503 PyDoc_STRVAR(PySSL_RAND_add_doc
,
1504 "RAND_add(string, entropy)\n\
1506 Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
1507 bound on the entropy contained in string. See RFC 1750.");
1510 PySSL_RAND_status(PyObject
*self
)
1512 return PyInt_FromLong(RAND_status());
1515 PyDoc_STRVAR(PySSL_RAND_status_doc
,
1516 "RAND_status() -> 0 or 1\n\
1518 Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1519 It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1520 using the ssl() function.");
1523 PySSL_RAND_egd(PyObject
*self
, PyObject
*arg
)
1527 if (!PyString_Check(arg
))
1528 return PyErr_Format(PyExc_TypeError
,
1529 "RAND_egd() expected string, found %s",
1530 Py_TYPE(arg
)->tp_name
);
1531 bytes
= RAND_egd(PyString_AS_STRING(arg
));
1533 PyErr_SetString(PySSLErrorObject
,
1534 "EGD connection failed or EGD did not return "
1535 "enough data to seed the PRNG");
1538 return PyInt_FromLong(bytes
);
1541 PyDoc_STRVAR(PySSL_RAND_egd_doc
,
1542 "RAND_egd(path) -> bytes\n\
1544 Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1545 Returns number of bytes read. Raises SSLError if connection to EGD\n\
1546 fails or if it does provide enough data to seed PRNG.");
1550 /* List of functions exported by this module. */
1552 static PyMethodDef PySSL_methods
[] = {
1553 {"sslwrap", PySSL_sslwrap
,
1554 METH_VARARGS
, ssl_doc
},
1555 {"_test_decode_cert", PySSL_test_decode_certificate
,
1557 #ifdef HAVE_OPENSSL_RAND
1558 {"RAND_add", PySSL_RAND_add
, METH_VARARGS
,
1559 PySSL_RAND_add_doc
},
1560 {"RAND_egd", PySSL_RAND_egd
, METH_O
,
1561 PySSL_RAND_egd_doc
},
1562 {"RAND_status", (PyCFunction
)PySSL_RAND_status
, METH_NOARGS
,
1563 PySSL_RAND_status_doc
},
1565 {NULL
, NULL
} /* Sentinel */
1571 /* an implementation of OpenSSL threading operations in terms
1572 of the Python C thread library */
1574 static PyThread_type_lock
*_ssl_locks
= NULL
;
1576 static unsigned long _ssl_thread_id_function (void) {
1577 return PyThread_get_thread_ident();
1580 static void _ssl_thread_locking_function (int mode
, int n
, const char *file
, int line
) {
1581 /* this function is needed to perform locking on shared data
1582 structures. (Note that OpenSSL uses a number of global data
1583 structures that will be implicitly shared whenever multiple threads
1584 use OpenSSL.) Multi-threaded applications will crash at random if
1587 locking_function() must be able to handle up to CRYPTO_num_locks()
1588 different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and
1589 releases it otherwise.
1591 file and line are the file number of the function setting the
1592 lock. They can be useful for debugging.
1595 if ((_ssl_locks
== NULL
) ||
1596 (n
< 0) || ((unsigned)n
>= _ssl_locks_count
))
1599 if (mode
& CRYPTO_LOCK
) {
1600 PyThread_acquire_lock(_ssl_locks
[n
], 1);
1602 PyThread_release_lock(_ssl_locks
[n
]);
1606 static int _setup_ssl_threads(void) {
1610 if (_ssl_locks
== NULL
) {
1611 _ssl_locks_count
= CRYPTO_num_locks();
1612 _ssl_locks
= (PyThread_type_lock
*)
1613 malloc(sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1614 if (_ssl_locks
== NULL
)
1616 memset(_ssl_locks
, 0, sizeof(PyThread_type_lock
) * _ssl_locks_count
);
1617 for (i
= 0; i
< _ssl_locks_count
; i
++) {
1618 _ssl_locks
[i
] = PyThread_allocate_lock();
1619 if (_ssl_locks
[i
] == NULL
) {
1621 for (j
= 0; j
< i
; j
++) {
1622 PyThread_free_lock(_ssl_locks
[j
]);
1628 CRYPTO_set_locking_callback(_ssl_thread_locking_function
);
1629 CRYPTO_set_id_callback(_ssl_thread_id_function
);
1634 #endif /* def HAVE_THREAD */
1636 PyDoc_STRVAR(module_doc
,
1637 "Implementation module for SSL socket operations. See the socket module\n\
1638 for documentation.");
1643 PyObject
*m
, *d
, *r
;
1644 unsigned long libver
;
1645 unsigned int major
, minor
, fix
, patch
, status
;
1647 Py_TYPE(&PySSL_Type
) = &PyType_Type
;
1649 m
= Py_InitModule3("_ssl", PySSL_methods
, module_doc
);
1652 d
= PyModule_GetDict(m
);
1654 /* Load _socket module and its C API */
1655 if (PySocketModule_ImportModuleAndAPI())
1659 SSL_load_error_strings();
1662 /* note that this will start threading if not already started */
1663 if (!_setup_ssl_threads()) {
1667 OpenSSL_add_all_algorithms();
1669 /* Add symbols to module dict */
1670 PySSLErrorObject
= PyErr_NewException("ssl.SSLError",
1671 PySocketModule
.error
,
1673 if (PySSLErrorObject
== NULL
)
1675 if (PyDict_SetItemString(d
, "SSLError", PySSLErrorObject
) != 0)
1677 if (PyDict_SetItemString(d
, "SSLType",
1678 (PyObject
*)&PySSL_Type
) != 0)
1680 PyModule_AddIntConstant(m
, "SSL_ERROR_ZERO_RETURN",
1681 PY_SSL_ERROR_ZERO_RETURN
);
1682 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_READ",
1683 PY_SSL_ERROR_WANT_READ
);
1684 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_WRITE",
1685 PY_SSL_ERROR_WANT_WRITE
);
1686 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_X509_LOOKUP",
1687 PY_SSL_ERROR_WANT_X509_LOOKUP
);
1688 PyModule_AddIntConstant(m
, "SSL_ERROR_SYSCALL",
1689 PY_SSL_ERROR_SYSCALL
);
1690 PyModule_AddIntConstant(m
, "SSL_ERROR_SSL",
1692 PyModule_AddIntConstant(m
, "SSL_ERROR_WANT_CONNECT",
1693 PY_SSL_ERROR_WANT_CONNECT
);
1694 /* non ssl.h errorcodes */
1695 PyModule_AddIntConstant(m
, "SSL_ERROR_EOF",
1697 PyModule_AddIntConstant(m
, "SSL_ERROR_INVALID_ERROR_CODE",
1698 PY_SSL_ERROR_INVALID_ERROR_CODE
);
1699 /* cert requirements */
1700 PyModule_AddIntConstant(m
, "CERT_NONE",
1702 PyModule_AddIntConstant(m
, "CERT_OPTIONAL",
1703 PY_SSL_CERT_OPTIONAL
);
1704 PyModule_AddIntConstant(m
, "CERT_REQUIRED",
1705 PY_SSL_CERT_REQUIRED
);
1707 /* protocol versions */
1708 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv2",
1709 PY_SSL_VERSION_SSL2
);
1710 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv3",
1711 PY_SSL_VERSION_SSL3
);
1712 PyModule_AddIntConstant(m
, "PROTOCOL_SSLv23",
1713 PY_SSL_VERSION_SSL23
);
1714 PyModule_AddIntConstant(m
, "PROTOCOL_TLSv1",
1715 PY_SSL_VERSION_TLS1
);
1717 /* OpenSSL version */
1718 /* SSLeay() gives us the version of the library linked against,
1719 which could be different from the headers version.
1722 r
= PyLong_FromUnsignedLong(libver
);
1725 if (PyModule_AddObject(m
, "OPENSSL_VERSION_NUMBER", r
))
1727 status
= libver
& 0xF;
1729 patch
= libver
& 0xFF;
1731 fix
= libver
& 0xFF;
1733 minor
= libver
& 0xFF;
1735 major
= libver
& 0xFF;
1736 r
= Py_BuildValue("IIIII", major
, minor
, fix
, patch
, status
);
1737 if (r
== NULL
|| PyModule_AddObject(m
, "OPENSSL_VERSION_INFO", r
))
1739 r
= PyString_FromString(SSLeay_version(SSLEAY_VERSION
));
1740 if (r
== NULL
|| PyModule_AddObject(m
, "OPENSSL_VERSION", r
))