_ssl.c 47.5 KB
Newer Older
1
/* SSL socket module
2 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
Bill Janssen's avatar
Bill Janssen committed
5 6
   certificate decoding.  Chris Stawarz contributed some non-blocking
   patches.
7

8
   This module is imported by ssl.py. It should *not* be used
9 10
   directly.

11
   XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12 13 14

   XXX integrate several "shutdown modes" as suggested in
       http://bugs.python.org/issue8108#msg102867 ?
15 16 17
*/

#include "Python.h"
18

19 20 21
#ifdef WITH_THREAD
#include "pythread.h"
#define PySSL_BEGIN_ALLOW_THREADS { \
Bill Janssen's avatar
Bill Janssen committed
22
			PyThreadState *_save = NULL;  \
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
			if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
#define PySSL_BLOCK_THREADS	if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
#define PySSL_UNBLOCK_THREADS	if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
#define PySSL_END_ALLOW_THREADS	if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
		 }

#else	/* no WITH_THREAD */

#define PySSL_BEGIN_ALLOW_THREADS
#define PySSL_BLOCK_THREADS
#define PySSL_UNBLOCK_THREADS
#define PySSL_END_ALLOW_THREADS

#endif

38 39
enum py_ssl_error {
	/* these mirror ssl.h */
40 41 42 43 44
	PY_SSL_ERROR_NONE,
	PY_SSL_ERROR_SSL,
	PY_SSL_ERROR_WANT_READ,
	PY_SSL_ERROR_WANT_WRITE,
	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_NO_SOCKET,   /* socket has been GC'd */
51 52
	PY_SSL_ERROR_INVALID_ERROR_CODE
};
53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
enum py_ssl_server_or_client {
	PY_SSL_CLIENT,
	PY_SSL_SERVER
};

enum py_ssl_cert_requirements {
	PY_SSL_CERT_NONE,
	PY_SSL_CERT_OPTIONAL,
	PY_SSL_CERT_REQUIRED
};

enum py_ssl_version {
	PY_SSL_VERSION_SSL2,
	PY_SSL_VERSION_SSL3,
	PY_SSL_VERSION_SSL23,
	PY_SSL_VERSION_TLS1,
};

72 73 74
/* Include symbols from _socket module */
#include "socketmodule.h"

75 76
static PySocketModule_APIObject PySocketModule;

77
#if defined(HAVE_POLL_H)
78 79 80 81 82
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
#endif

83 84 85 86
/* Include OpenSSL header files */
#include "openssl/rsa.h"
#include "openssl/crypto.h"
#include "openssl/x509.h"
87
#include "openssl/x509v3.h"
88 89 90 91 92 93 94 95
#include "openssl/pem.h"
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "openssl/rand.h"

/* SSL error object */
static PyObject *PySSLErrorObject;

96 97 98 99 100 101 102 103 104
#ifdef WITH_THREAD

/* serves as a flag to see whether we've initialized the SSL thread support. */
/* 0 means no, greater than 0 means yes */

static unsigned int _ssl_locks_count = 0;

#endif /* def WITH_THREAD */

105 106 107 108 109 110 111 112 113 114 115 116 117
/* SSL socket object */

#define X509_NAME_MAXLEN 256

/* RAND_* APIs got added to OpenSSL in 0.9.5 */
#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
# define HAVE_OPENSSL_RAND 1
#else
# undef HAVE_OPENSSL_RAND
#endif

typedef struct {
	PyObject_HEAD
118
	PyObject        *Socket;	/* weakref to socket on which we're layered */
119 120 121
	SSL_CTX*	ctx;
	SSL*		ssl;
	X509*		peer_cert;
122
	int		shutdown_seen_zero;
123 124 125

} PySSLObject;

126 127 128
static PyTypeObject PySSL_Type;
static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
129
static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
130
					     int writing);
131 132
static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
static PyObject *PySSL_cipher(PySSLObject *self);
133

134
#define PySSLObject_Check(v)	(Py_TYPE(v) == &PySSL_Type)
135

136 137 138 139 140
typedef enum {
	SOCKET_IS_NONBLOCKING,
	SOCKET_IS_BLOCKING,
	SOCKET_HAS_TIMED_OUT,
	SOCKET_HAS_BEEN_CLOSED,
141
	SOCKET_TOO_LARGE_FOR_SELECT,
142 143 144
	SOCKET_OPERATION_OK
} timeout_state;

145 146 147 148 149 150
/* Wrap error strings with filename and line # */
#define STRINGIFY1(x) #x
#define STRINGIFY2(x) STRINGIFY1(x)
#define ERRSTR1(x,y,z) (x ":" y ": " z)
#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)

151 152 153 154 155 156
/* XXX It might be helpful to augment the error message generated
   below with the name of the SSL function that generated the error.
   I expect it's obvious most of the time.
*/

static PyObject *
157
PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
158
{
159 160
	PyObject *v;
	char buf[2048];
161 162
	char *errstr;
	int err;
163
	enum py_ssl_error p = PY_SSL_ERROR_NONE;
164 165

	assert(ret <= 0);
166

167
	if (obj->ssl != NULL) {
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
		err = SSL_get_error(obj->ssl, ret);

		switch (err) {
		case SSL_ERROR_ZERO_RETURN:
			errstr = "TLS/SSL connection has been closed";
			p = PY_SSL_ERROR_ZERO_RETURN;
			break;
		case SSL_ERROR_WANT_READ:
			errstr = "The operation did not complete (read)";
			p = PY_SSL_ERROR_WANT_READ;
			break;
		case SSL_ERROR_WANT_WRITE:
			p = PY_SSL_ERROR_WANT_WRITE;
			errstr = "The operation did not complete (write)";
			break;
		case SSL_ERROR_WANT_X509_LOOKUP:
			p = PY_SSL_ERROR_WANT_X509_LOOKUP;
			errstr =
                            "The operation did not complete (X509 lookup)";
			break;
		case SSL_ERROR_WANT_CONNECT:
			p = PY_SSL_ERROR_WANT_CONNECT;
			errstr = "The operation did not complete (connect)";
			break;
		case SSL_ERROR_SYSCALL:
		{
			unsigned long e = ERR_get_error();
			if (e == 0) {
196 197 198
                                PySocketSockObject *s
                                  = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
				if (ret == 0 || (((PyObject *)s) == Py_None)) {
199 200 201 202 203
				  p = PY_SSL_ERROR_EOF;
				  errstr =
                                      "EOF occurred in violation of protocol";
				} else if (ret == -1) {
				  /* underlying BIO reported an I/O error */
204
                                  return s->errorhandler();
205 206 207 208 209
				} else { /* possible? */
                                  p = PY_SSL_ERROR_SYSCALL;
                                  errstr = "Some I/O error occurred";
				}
			} else {
Jeremy Hylton's avatar
Jeremy Hylton committed
210
				p = PY_SSL_ERROR_SYSCALL;
211 212
				/* XXX Protected by global interpreter lock */
				errstr = ERR_error_string(e, NULL);
213
			}
214
			break;
215
		}
216 217 218 219 220 221 222 223 224 225 226 227
		case SSL_ERROR_SSL:
		{
			unsigned long e = ERR_get_error();
			p = PY_SSL_ERROR_SSL;
			if (e != 0)
				/* XXX Protected by global interpreter lock */
				errstr = ERR_error_string(e, NULL);
			else {	/* possible? */
				errstr =
                                    "A failure in the SSL library occurred";
			}
			break;
228
		}
229 230 231 232 233 234
		default:
			p = PY_SSL_ERROR_INVALID_ERROR_CODE;
			errstr = "Invalid error code";
		}
	} else {
		errstr = ERR_error_string(ERR_peek_last_error(), NULL);
235
	}
236 237 238 239
	PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
	v = Py_BuildValue("(is)", p, buf);
	if (v != NULL) {
		PyErr_SetObject(PySSLErrorObject, v);
240 241 242 243 244
		Py_DECREF(v);
	}
	return NULL;
}

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
static PyObject *
_setSSLError (char *errstr, int errcode, char *filename, int lineno) {

	char buf[2048];
	PyObject *v;

	if (errstr == NULL) {
		errcode = ERR_peek_last_error();
		errstr = ERR_error_string(errcode, NULL);
	}
	PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
	v = Py_BuildValue("(is)", errcode, buf);
	if (v != NULL) {
		PyErr_SetObject(PySSLErrorObject, v);
		Py_DECREF(v);
	}
	return NULL;
}

264
static PySSLObject *
265 266 267 268
newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
	       enum py_ssl_server_or_client socket_type,
	       enum py_ssl_cert_requirements certreq,
	       enum py_ssl_version proto_version,
269
	       char *cacerts_file, char *ciphers)
270 271 272 273
{
	PySSLObject *self;
	char *errstr = NULL;
	int ret;
274
	int verification_mode;
275

276
	self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
277 278
	if (self == NULL)
		return NULL;
279
	self->peer_cert = NULL;
280 281 282 283
	self->ssl = NULL;
	self->ctx = NULL;
	self->Socket = NULL;

284 285 286 287
	/* Make sure the SSL error state is initialized */
	(void) ERR_get_state();
	ERR_clear_error();

288
	if ((key_file && !cert_file) || (!key_file && cert_file)) {
289 290 291 292 293 294 295 296 297
		errstr = ERRSTR("Both the key & certificate files "
                                "must be specified");
		goto fail;
	}

	if ((socket_type == PY_SSL_SERVER) &&
	    ((key_file == NULL) || (cert_file == NULL))) {
		errstr = ERRSTR("Both the key & certificate files "
                                "must be specified for server-side operation");
298 299 300
		goto fail;
	}

301
	PySSL_BEGIN_ALLOW_THREADS
302 303 304 305 306 307
	if (proto_version == PY_SSL_VERSION_TLS1)
		self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
	else if (proto_version == PY_SSL_VERSION_SSL3)
		self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
	else if (proto_version == PY_SSL_VERSION_SSL2)
		self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
308
	else if (proto_version == PY_SSL_VERSION_SSL23)
309
		self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
310
	PySSL_END_ALLOW_THREADS
311

312
	if (self->ctx == NULL) {
313
		errstr = ERRSTR("Invalid SSL protocol variant specified.");
314 315 316
		goto fail;
	}

317 318 319 320 321 322 323 324
	if (ciphers != NULL) {
		ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
		if (ret == 0) {
			errstr = ERRSTR("No cipher can be selected.");
			goto fail;
		}
	}

325 326 327 328 329 330
	if (certreq != PY_SSL_CERT_NONE) {
		if (cacerts_file == NULL) {
			errstr = ERRSTR("No root certificates specified for "
                                  "verification of other-side certificates.");
			goto fail;
		} else {
331
			PySSL_BEGIN_ALLOW_THREADS
332 333 334
			ret = SSL_CTX_load_verify_locations(self->ctx,
							    cacerts_file,
                                                            NULL);
335
			PySSL_END_ALLOW_THREADS
336
			if (ret != 1) {
337
				_setSSLError(NULL, 0, __FILE__, __LINE__);
338 339 340 341
				goto fail;
			}
		}
	}
342
	if (key_file) {
343
		PySSL_BEGIN_ALLOW_THREADS
344
		ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
345
						  SSL_FILETYPE_PEM);
346
		PySSL_END_ALLOW_THREADS
347
		if (ret != 1) {
348
			_setSSLError(NULL, ret, __FILE__, __LINE__);
349 350 351
			goto fail;
		}

352
		PySSL_BEGIN_ALLOW_THREADS
353
		ret = SSL_CTX_use_certificate_chain_file(self->ctx,
354 355
							 cert_file);
		PySSL_END_ALLOW_THREADS
356
		if (ret != 1) {
357 358 359 360 361 362 363 364
			/*
			fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
				ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
				*/
			if (ERR_peek_last_error() != 0) {
				_setSSLError(NULL, ret, __FILE__, __LINE__);
				goto fail;
			}
365 366 367
		}
	}

368 369 370
        /* ssl compatibility */
        SSL_CTX_set_options(self->ctx, SSL_OP_ALL);

371 372 373 374 375 376 377 378 379
	verification_mode = SSL_VERIFY_NONE;
	if (certreq == PY_SSL_CERT_OPTIONAL)
		verification_mode = SSL_VERIFY_PEER;
	else if (certreq == PY_SSL_CERT_REQUIRED)
		verification_mode = (SSL_VERIFY_PEER |
				     SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
	SSL_CTX_set_verify(self->ctx, verification_mode,
			   NULL); /* set verify lvl */

380
	PySSL_BEGIN_ALLOW_THREADS
381
	self->ssl = SSL_new(self->ctx); /* New ssl struct */
382
	PySSL_END_ALLOW_THREADS
383
	SSL_set_fd(self->ssl, Sock->sock_fd);	/* Set the socket for SSL */
384
#ifdef SSL_MODE_AUTO_RETRY
385
	SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
386
#endif
387

388
	/* If the socket is in non-blocking mode or timeout mode, set the BIO
389 390 391 392 393 394 395 396
	 * to non-blocking mode (blocking is the default)
	 */
	if (Sock->sock_timeout >= 0.0) {
		/* Set both the read and write BIO's to non-blocking mode */
		BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
		BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
	}

397
	PySSL_BEGIN_ALLOW_THREADS
398 399 400 401
	if (socket_type == PY_SSL_CLIENT)
		SSL_set_connect_state(self->ssl);
	else
		SSL_set_accept_state(self->ssl);
402
	PySSL_END_ALLOW_THREADS
403

404
	self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
405 406 407 408 409 410 411 412 413
	return self;
 fail:
	if (errstr)
		PyErr_SetString(PySSLErrorObject, errstr);
	Py_DECREF(self);
	return NULL;
}

static PyObject *
414
PySSL_sslwrap(PyObject *self, PyObject *args)
415 416
{
	PySocketSockObject *Sock;
417 418 419
	int server_side = 0;
	int verification_mode = PY_SSL_CERT_NONE;
	int protocol = PY_SSL_VERSION_SSL23;
420 421
	char *key_file = NULL;
	char *cert_file = NULL;
422
	char *cacerts_file = NULL;
423
	char *ciphers = NULL;
424

425
	if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
426
			      PySocketModule.Sock_Type,
427
			      &Sock,
428 429 430
			      &server_side,
			      &key_file, &cert_file,
			      &verification_mode, &protocol,
431
			      &cacerts_file, &ciphers))
432 433
		return NULL;

434 435 436 437 438 439 440 441 442 443
	/*
	fprintf(stderr,
		"server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
		"protocol %d, certs %p\n",
		server_side, key_file, cert_file, verification_mode,
		protocol, cacerts_file);
	 */

	return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
					   server_side, verification_mode,
444 445
					   protocol, cacerts_file,
					   ciphers);
446 447
}

448
PyDoc_STRVAR(ssl_doc,
449
"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
450
"                              cacertsfile, ciphers]) -> sslobject");
451 452 453

/* SSL object methods */

Bill Janssen's avatar
Bill Janssen committed
454
static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
455
{
Bill Janssen's avatar
Bill Janssen committed
456 457
	int ret;
	int err;
458 459 460 461 462 463 464 465 466 467 468 469 470 471
	int sockstate, nonblocking;
        PySocketSockObject *sock
          = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);

	if (((PyObject*)sock) == Py_None) {
                _setSSLError("Underlying socket connection gone",
                             PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
                return NULL;
        }

	/* just in case the blocking state of the socket has been changed */
	nonblocking = (sock->sock_timeout >= 0.0);
	BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
	BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
472

Bill Janssen's avatar
Bill Janssen committed
473 474 475 476 477 478 479 480 481 482 483 484
	/* Actually negotiate SSL connection */
	/* XXX If SSL_do_handshake() returns 0, it's also a failure. */
	sockstate = 0;
	do {
		PySSL_BEGIN_ALLOW_THREADS
		ret = SSL_do_handshake(self->ssl);
		err = SSL_get_error(self->ssl, ret);
		PySSL_END_ALLOW_THREADS
		if(PyErr_CheckSignals()) {
			return NULL;
		}
		if (err == SSL_ERROR_WANT_READ) {
485
			sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen's avatar
Bill Janssen committed
486
		} else if (err == SSL_ERROR_WANT_WRITE) {
487
			sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen's avatar
Bill Janssen committed
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
		} else {
			sockstate = SOCKET_OPERATION_OK;
		}
		if (sockstate == SOCKET_HAS_TIMED_OUT) {
			PyErr_SetString(PySSLErrorObject,
				ERRSTR("The handshake operation timed out"));
			return NULL;
		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
			PyErr_SetString(PySSLErrorObject,
				ERRSTR("Underlying socket has been closed."));
			return NULL;
		} else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
			PyErr_SetString(PySSLErrorObject,
			  ERRSTR("Underlying socket too large for select()."));
			return NULL;
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
	if (ret < 1)
		return PySSL_SetError(self, ret, __FILE__, __LINE__);
	self->ssl->debug = 1;

	if (self->peer_cert)
		X509_free (self->peer_cert);
        PySSL_BEGIN_ALLOW_THREADS
	self->peer_cert = SSL_get_peer_certificate(self->ssl);
	PySSL_END_ALLOW_THREADS

	Py_INCREF(Py_None);
	return Py_None;
519 520
}

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
static PyObject *
_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {

	char namebuf[X509_NAME_MAXLEN];
	int buflen;
	PyObject *name_obj;
	PyObject *value_obj;
	PyObject *attr;
	unsigned char *valuebuf = NULL;

	buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
	if (buflen < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		goto fail;
	}
Bill Janssen's avatar
Bill Janssen committed
536
	name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
537 538
	if (name_obj == NULL)
		goto fail;
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
	buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
	if (buflen < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		Py_DECREF(name_obj);
		goto fail;
	}
	value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
						 buflen, "strict");
	OPENSSL_free(valuebuf);
	if (value_obj == NULL) {
		Py_DECREF(name_obj);
		goto fail;
	}
	attr = PyTuple_New(2);
	if (attr == NULL) {
		Py_DECREF(name_obj);
		Py_DECREF(value_obj);
		goto fail;
	}
	PyTuple_SET_ITEM(attr, 0, name_obj);
	PyTuple_SET_ITEM(attr, 1, value_obj);
	return attr;

  fail:
	return NULL;
}

567
static PyObject *
568
_create_tuple_for_X509_NAME (X509_NAME *xname)
569
{
570 571 572 573
	PyObject *dn = NULL;    /* tuple which represents the "distinguished name" */
        PyObject *rdn = NULL;   /* tuple to hold a "relative distinguished name" */
	PyObject *rdnt;
        PyObject *attr = NULL;   /* tuple to hold an attribute */
574
        int entry_count = X509_NAME_entry_count(xname);
575 576 577
	X509_NAME_ENTRY *entry;
	ASN1_OBJECT *name;
	ASN1_STRING *value;
578
	int index_counter;
579 580
	int rdn_level = -1;
	int retcode;
581

582 583
        dn = PyList_New(0);
	if (dn == NULL)
584
		return NULL;
585 586 587 588
        /* now create another tuple to hold the top-level RDN */
        rdn = PyList_New(0);
	if (rdn == NULL)
		goto fail0;
589 590

	for (index_counter = 0;
591
	     index_counter < entry_count;
592 593
	     index_counter++)
	{
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
		entry = X509_NAME_get_entry(xname, index_counter);

		/* check to see if we've gotten to a new RDN */
		if (rdn_level >= 0) {
			if (rdn_level != entry->set) {
				/* yes, new RDN */
				/* add old RDN to DN */
				rdnt = PyList_AsTuple(rdn);
				Py_DECREF(rdn);
				if (rdnt == NULL)
					goto fail0;
				retcode = PyList_Append(dn, rdnt);
				Py_DECREF(rdnt);
				if (retcode < 0)
					goto fail0;
				/* create new RDN */
				rdn = PyList_New(0);
				if (rdn == NULL)
					goto fail0;
			}
		}
		rdn_level = entry->set;
616

617 618
		/* now add this attribute to the current RDN */
		name = X509_NAME_ENTRY_get_object(entry);
619
		value = X509_NAME_ENTRY_get_data(entry);
620 621 622 623
		attr = _create_tuple_for_attribute(name, value);
                /*
                fprintf(stderr, "RDN level %d, attribute %s: %s\n",
                        entry->set,
624 625
                        PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
                        PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
626 627 628 629 630 631 632 633 634 635 636 637 638
                */
		if (attr == NULL)
			goto fail1;
                retcode = PyList_Append(rdn, attr);
		Py_DECREF(attr);
		if (retcode < 0)
			goto fail1;
	}
	/* now, there's typically a dangling RDN */
	if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
		rdnt = PyList_AsTuple(rdn);
		Py_DECREF(rdn);
		if (rdnt == NULL)
639
			goto fail0;
640 641 642
		retcode = PyList_Append(dn, rdnt);
		Py_DECREF(rdnt);
		if (retcode < 0)
643
			goto fail0;
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
	}

	/* convert list to tuple */
	rdnt = PyList_AsTuple(dn);
	Py_DECREF(dn);
	if (rdnt == NULL)
		return NULL;
	return rdnt;

  fail1:
	Py_XDECREF(rdn);

  fail0:
	Py_XDECREF(dn);
	return NULL;
}

static PyObject *
_get_peer_alt_names (X509 *certificate) {
663

664 665 666 667 668 669 670 671 672 673 674 675
	/* this code follows the procedure outlined in
	   OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
	   function to extract the STACK_OF(GENERAL_NAME),
	   then iterates through the stack to add the
	   names. */

	int i, j;
	PyObject *peer_alt_names = Py_None;
	PyObject *v, *t;
	X509_EXTENSION *ext = NULL;
	GENERAL_NAMES *names = NULL;
	GENERAL_NAME *name;
676
	X509V3_EXT_METHOD *method;
677 678 679 680
	BIO *biobuf = NULL;
	char buf[2048];
	char *vptr;
	int len;
681 682 683 684
	/* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
	const unsigned char *p;
#else
Benjamin Peterson's avatar
Benjamin Peterson committed
685
	unsigned char *p;
686
#endif
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

	if (certificate == NULL)
		return peer_alt_names;

	/* get a memory buffer */
	biobuf = BIO_new(BIO_s_mem());

	i = 0;
	while ((i = X509_get_ext_by_NID(
			certificate, NID_subject_alt_name, i)) >= 0) {

		if (peer_alt_names == Py_None) {
                        peer_alt_names = PyList_New(0);
                        if (peer_alt_names == NULL)
				goto fail;
702
		}
703

704 705 706
		/* now decode the altName */
		ext = X509_get_ext(certificate, i);
		if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen's avatar
Bill Janssen committed
707 708 709
			PyErr_SetString
                          (PySSLErrorObject,
                           ERRSTR("No method for internalizing subjectAltName!"));
710 711 712 713
			goto fail;
		}

		p = ext->value->data;
714
		if (method->it)
Bill Janssen's avatar
Bill Janssen committed
715 716 717 718 719
			names = (GENERAL_NAMES*)
                          (ASN1_item_d2i(NULL,
                                         &p,
                                         ext->value->length,
                                         ASN1_ITEM_ptr(method->it)));
720
		else
Bill Janssen's avatar
Bill Janssen committed
721 722 723 724
			names = (GENERAL_NAMES*)
                          (method->d2i(NULL,
                                       &p,
                                       ext->value->length));
725 726 727 728 729 730 731 732

		for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {

			/* get a rendering of each name in the set of names */

			name = sk_GENERAL_NAME_value(names, j);
			if (name->type == GEN_DIRNAME) {

Bill Janssen's avatar
Bill Janssen committed
733 734
				/* we special-case DirName as a tuple of
                                   tuples of attributes */
735 736 737 738 739 740

				t = PyTuple_New(2);
				if (t == NULL) {
					goto fail;
				}

Bill Janssen's avatar
Bill Janssen committed
741
				v = PyUnicode_FromString("DirName");
742 743 744 745 746 747 748 749 750 751 752 753
				if (v == NULL) {
					Py_DECREF(t);
					goto fail;
				}
				PyTuple_SET_ITEM(t, 0, v);

				v = _create_tuple_for_X509_NAME (name->d.dirn);
				if (v == NULL) {
					Py_DECREF(t);
					goto fail;
				}
				PyTuple_SET_ITEM(t, 1, v);
754

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
			} else {

				/* for everything else, we use the OpenSSL print form */

				(void) BIO_reset(biobuf);
				GENERAL_NAME_print(biobuf, name);
				len = BIO_gets(biobuf, buf, sizeof(buf)-1);
				if (len < 0) {
					_setSSLError(NULL, 0, __FILE__, __LINE__);
					goto fail;
				}
				vptr = strchr(buf, ':');
				if (vptr == NULL)
					goto fail;
				t = PyTuple_New(2);
				if (t == NULL)
					goto fail;
Bill Janssen's avatar
Bill Janssen committed
772
				v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
773 774 775 776 777
				if (v == NULL) {
					Py_DECREF(t);
					goto fail;
				}
				PyTuple_SET_ITEM(t, 0, v);
Bill Janssen's avatar
Bill Janssen committed
778 779
				v = PyUnicode_FromStringAndSize((vptr + 1),
                                                                (len - (vptr - buf + 1)));
780 781 782 783 784 785 786 787 788 789 790 791 792 793
				if (v == NULL) {
					Py_DECREF(t);
					goto fail;
				}
				PyTuple_SET_ITEM(t, 1, v);
			}

			/* and add that rendering to the list */

			if (PyList_Append(peer_alt_names, t) < 0) {
				Py_DECREF(t);
				goto fail;
			}
			Py_DECREF(t);
794 795
		}
	}
796 797 798 799 800 801 802 803
	BIO_free(biobuf);
	if (peer_alt_names != Py_None) {
		v = PyList_AsTuple(peer_alt_names);
		Py_DECREF(peer_alt_names);
		return v;
	} else {
		return peer_alt_names;
	}
804

805 806 807 808 809 810 811 812

  fail:
	if (biobuf != NULL)
		BIO_free(biobuf);

	if (peer_alt_names != Py_None) {
		Py_XDECREF(peer_alt_names);
	}
813 814 815 816 817

	return NULL;
}

static PyObject *
818 819
_decode_certificate (X509 *certificate, int verbose) {

820 821 822
	PyObject *retval = NULL;
	BIO *biobuf = NULL;
	PyObject *peer;
823
	PyObject *peer_alt_names = NULL;
824 825
	PyObject *issuer;
	PyObject *version;
826 827
	PyObject *sn_obj;
	ASN1_INTEGER *serialNumber;
828 829 830 831 832 833 834 835 836
	char buf[2048];
	int len;
	ASN1_TIME *notBefore, *notAfter;
	PyObject *pnotBefore, *pnotAfter;

	retval = PyDict_New();
	if (retval == NULL)
		return NULL;

837
	peer = _create_tuple_for_X509_NAME(
838
		X509_get_subject_name(certificate));
839 840 841 842 843 844 845 846
	if (peer == NULL)
		goto fail0;
	if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
		Py_DECREF(peer);
		goto fail0;
	}
	Py_DECREF(peer);

847 848 849 850 851 852 853 854 855
	if (verbose) {
		issuer = _create_tuple_for_X509_NAME(
			X509_get_issuer_name(certificate));
		if (issuer == NULL)
			goto fail0;
		if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
			Py_DECREF(issuer);
			goto fail0;
		}
856
		Py_DECREF(issuer);
857

858
		version = PyLong_FromLong(X509_get_version(certificate) + 1);
859 860 861 862
		if (PyDict_SetItemString(retval, "version", version) < 0) {
			Py_DECREF(version);
			goto fail0;
		}
863 864
		Py_DECREF(version);
	}
865

866 867
	/* get a memory buffer */
	biobuf = BIO_new(BIO_s_mem());
868

869 870 871 872 873 874 875 876 877 878 879
	if (verbose) {

		(void) BIO_reset(biobuf);
		serialNumber = X509_get_serialNumber(certificate);
		/* should not exceed 20 octets, 160 bits, so buf is big enough */
		i2a_ASN1_INTEGER(biobuf, serialNumber);
		len = BIO_gets(biobuf, buf, sizeof(buf)-1);
		if (len < 0) {
			_setSSLError(NULL, 0, __FILE__, __LINE__);
			goto fail1;
		}
Bill Janssen's avatar
Bill Janssen committed
880
		sn_obj = PyUnicode_FromStringAndSize(buf, len);
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
		if (sn_obj == NULL)
			goto fail1;
		if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
			Py_DECREF(sn_obj);
			goto fail1;
		}
		Py_DECREF(sn_obj);

		(void) BIO_reset(biobuf);
		notBefore = X509_get_notBefore(certificate);
		ASN1_TIME_print(biobuf, notBefore);
		len = BIO_gets(biobuf, buf, sizeof(buf)-1);
		if (len < 0) {
			_setSSLError(NULL, 0, __FILE__, __LINE__);
			goto fail1;
		}
Bill Janssen's avatar
Bill Janssen committed
897
		pnotBefore = PyUnicode_FromStringAndSize(buf, len);
898 899 900 901 902 903
		if (pnotBefore == NULL)
			goto fail1;
		if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
			Py_DECREF(pnotBefore);
			goto fail1;
		}
904 905 906 907
		Py_DECREF(pnotBefore);
	}

	(void) BIO_reset(biobuf);
908
	notAfter = X509_get_notAfter(certificate);
909 910
	ASN1_TIME_print(biobuf, notAfter);
	len = BIO_gets(biobuf, buf, sizeof(buf)-1);
911 912 913 914
	if (len < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		goto fail1;
	}
Bill Janssen's avatar
Bill Janssen committed
915
	pnotAfter = PyUnicode_FromStringAndSize(buf, len);
916
	if (pnotAfter == NULL)
917
		goto fail1;
918 919
	if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
		Py_DECREF(pnotAfter);
920
		goto fail1;
921 922
	}
	Py_DECREF(pnotAfter);
923 924 925 926 927 928 929 930 931 932 933 934 935 936

	/* Now look for subjectAltName */

	peer_alt_names = _get_peer_alt_names(certificate);
	if (peer_alt_names == NULL)
		goto fail1;
	else if (peer_alt_names != Py_None) {
		if (PyDict_SetItemString(retval, "subjectAltName",
					 peer_alt_names) < 0) {
			Py_DECREF(peer_alt_names);
			goto fail1;
		}
		Py_DECREF(peer_alt_names);
	}
937

938
	BIO_free(biobuf);
939 940 941 942 943 944 945 946 947
	return retval;

  fail1:
	if (biobuf != NULL)
		BIO_free(biobuf);
  fail0:
	Py_XDECREF(retval);
	return NULL;
}
948

949 950 951 952 953 954 955 956 957 958

static PyObject *
PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {

	PyObject *retval = NULL;
	char *filename = NULL;
	X509 *x=NULL;
	BIO *cert;
	int verbose = 1;

Bill Janssen's avatar
Bill Janssen committed
959 960
	if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
                              &filename, &verbose))
961 962 963
		return NULL;

	if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen's avatar
Bill Janssen committed
964 965
		PyErr_SetString(PySSLErrorObject,
                                "Can't malloc memory to read file");
966 967 968 969
		goto fail0;
	}

	if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen's avatar
Bill Janssen committed
970 971
		PyErr_SetString(PySSLErrorObject,
                                "Can't open file");
972 973 974 975 976
		goto fail0;
	}

	x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
	if (x == NULL) {
Bill Janssen's avatar
Bill Janssen committed
977 978
		PyErr_SetString(PySSLErrorObject,
                                "Error decoding PEM-encoded file");
979 980 981 982 983 984
		goto fail0;
	}

	retval = _decode_certificate(x, verbose);

  fail0:
985

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	if (cert != NULL) BIO_free(cert);
	return retval;
}


static PyObject *
PySSL_peercert(PySSLObject *self, PyObject *args)
{
	PyObject *retval = NULL;
	int len;
	int verification;
	PyObject *binary_mode = Py_None;

	if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
		return NULL;

	if (!self->peer_cert)
		Py_RETURN_NONE;

	if (PyObject_IsTrue(binary_mode)) {
		/* return cert in DER-encoded format */

		unsigned char *bytes_buf = NULL;

		bytes_buf = NULL;
		len = i2d_X509(self->peer_cert, &bytes_buf);
		if (len < 0) {
			PySSL_SetError(self, len, __FILE__, __LINE__);
			return NULL;
		}
Bill Janssen's avatar
Bill Janssen committed
1016
                /* this is actually an immutable bytes sequence */
1017
		retval = PyBytes_FromStringAndSize
Bill Janssen's avatar
Bill Janssen committed
1018
                  ((const char *) bytes_buf, len);
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
		OPENSSL_free(bytes_buf);
		return retval;

	} else {

		verification = SSL_CTX_get_verify_mode(self->ctx);
		if ((verification & SSL_VERIFY_PEER) == 0)
			return PyDict_New();
		else
			return _decode_certificate (self->peer_cert, 0);
	}
}

PyDoc_STRVAR(PySSL_peercert_doc,
"peer_certificate([der=False]) -> certificate\n\
\n\
Returns the certificate for the peer.  If no certificate was provided,\n\
returns None.  If a certificate was provided, but not validated, returns\n\
an empty dictionary.  Otherwise returns a dict containing information\n\
about the peer certificate.\n\
\n\
If the optional argument is True, returns a DER-encoded copy of the\n\
peer certificate, or None if no certificate was provided.  This will\n\
return the certificate even if it wasn't validated.");

static PyObject *PySSL_cipher (PySSLObject *self) {

	PyObject *retval, *v;
	SSL_CIPHER *current;
	char *cipher_name;
	char *cipher_protocol;

	if (self->ssl == NULL)
		return Py_None;
	current = SSL_get_current_cipher(self->ssl);
	if (current == NULL)
		return Py_None;

	retval = PyTuple_New(3);
	if (retval == NULL)
		return NULL;

	cipher_name = (char *) SSL_CIPHER_get_name(current);
	if (cipher_name == NULL) {
		PyTuple_SET_ITEM(retval, 0, Py_None);
	} else {
Bill Janssen's avatar
Bill Janssen committed
1065
		v = PyUnicode_FromString(cipher_name);
1066 1067 1068 1069 1070 1071 1072 1073
		if (v == NULL)
			goto fail0;
		PyTuple_SET_ITEM(retval, 0, v);
	}
	cipher_protocol = SSL_CIPHER_get_version(current);
	if (cipher_protocol == NULL) {
		PyTuple_SET_ITEM(retval, 1, Py_None);
	} else {
Bill Janssen's avatar
Bill Janssen committed
1074
		v = PyUnicode_FromString(cipher_protocol);
1075 1076 1077 1078
		if (v == NULL)
			goto fail0;
		PyTuple_SET_ITEM(retval, 1, v);
	}
1079
	v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1080 1081 1082 1083
	if (v == NULL)
		goto fail0;
	PyTuple_SET_ITEM(retval, 2, v);
	return retval;
1084

1085 1086 1087 1088 1089
  fail0:
	Py_DECREF(retval);
	return NULL;
}

1090
static void PySSL_dealloc(PySSLObject *self)
1091
{
1092
	if (self->peer_cert)	/* Possible not to have one? */
1093
		X509_free (self->peer_cert);
1094
	if (self->ssl)
1095
		SSL_free(self->ssl);
1096
	if (self->ctx)
1097
		SSL_CTX_free(self->ctx);
1098 1099
	Py_XDECREF(self->Socket);
	PyObject_Del(self);
1100 1101
}

1102
/* If the socket has a timeout, do a select()/poll() on the socket.
1103
   The argument writing indicates the direction.
1104
   Returns one of the possibilities in the timeout_state enum (above).
1105
 */
1106

1107
static int
1108
check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
1109 1110 1111 1112 1113 1114
{
	fd_set fds;
	struct timeval tv;
	int rc;

	/* Nothing to do unless we're in timeout mode (not non-blocking) */
1115 1116 1117 1118
	if (s->sock_timeout < 0.0)
		return SOCKET_IS_BLOCKING;
	else if (s->sock_timeout == 0.0)
		return SOCKET_IS_NONBLOCKING;
1119 1120 1121

	/* Guard against closed socket */
	if (s->sock_fd < 0)
1122
		return SOCKET_HAS_BEEN_CLOSED;
1123

1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
	/* Prefer poll, if available, since you can poll() any fd
	 * which can't be done with select(). */
#ifdef HAVE_POLL
	{
		struct pollfd pollfd;
		int timeout;

		pollfd.fd = s->sock_fd;
		pollfd.events = writing ? POLLOUT : POLLIN;

		/* s->sock_timeout is in seconds, timeout in ms */
		timeout = (int)(s->sock_timeout * 1000 + 0.5);
1136
		PySSL_BEGIN_ALLOW_THREADS
1137
		rc = poll(&pollfd, 1, timeout);
1138
		PySSL_END_ALLOW_THREADS
1139 1140 1141 1142 1143

		goto normal_return;
	}
#endif

1144
	/* Guard against socket too large for select*/
1145
#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
1146
	if (s->sock_fd >= FD_SETSIZE)
1147
		return SOCKET_TOO_LARGE_FOR_SELECT;
1148
#endif
1149

1150 1151 1152 1153 1154 1155 1156
	/* Construct the arguments to select */
	tv.tv_sec = (int)s->sock_timeout;
	tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
	FD_ZERO(&fds);
	FD_SET(s->sock_fd, &fds);

	/* See if the socket is ready */
1157
	PySSL_BEGIN_ALLOW_THREADS
1158 1159 1160 1161
	if (writing)
		rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
	else
		rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1162
	PySSL_END_ALLOW_THREADS
1163

Bill Janssen's avatar
Bill Janssen committed
1164
#ifdef HAVE_POLL
1165
normal_return:
Bill Janssen's avatar
Bill Janssen committed
1166
#endif
1167 1168 1169
	/* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
	   (when we are able to write or when there's something to read) */
	return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1170 1171
}

1172 1173
static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
{
1174
	Py_buffer buf;
1175
	int len;
1176
	int sockstate;
1177
	int err;
Bill Janssen's avatar
Bill Janssen committed
1178
        int nonblocking;
1179 1180 1181 1182 1183 1184 1185 1186
        PySocketSockObject *sock
          = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);

        if (((PyObject*)sock) == Py_None) {
                _setSSLError("Underlying socket connection gone",
                             PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
                return NULL;
        }
1187

1188
	if (!PyArg_ParseTuple(args, "y*:write", &buf))
1189 1190
		return NULL;

Bill Janssen's avatar
Bill Janssen committed
1191
        /* just in case the blocking state of the socket has been changed */
1192
	nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen's avatar
Bill Janssen committed
1193 1194 1195
        BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
        BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);

1196
	sockstate = check_socket_and_wait_for_timeout(sock, 1);
1197
	if (sockstate == SOCKET_HAS_TIMED_OUT) {
1198 1199
		PyErr_SetString(PySSLErrorObject,
                                "The write operation timed out");
1200
		goto error;
1201
	} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1202 1203
		PyErr_SetString(PySSLErrorObject,
                                "Underlying socket has been closed.");
1204
		goto error;
1205
	} else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1206 1207
		PyErr_SetString(PySSLErrorObject,
                                "Underlying socket too large for select().");
1208
		goto error;
1209
	}
1210 1211
	do {
		err = 0;
1212
		PySSL_BEGIN_ALLOW_THREADS
1213
		len = SSL_write(self->ssl, buf.buf, buf.len);
1214
		err = SSL_get_error(self->ssl, len);
1215
		PySSL_END_ALLOW_THREADS
1216 1217
		if (PyErr_CheckSignals()) {
			goto error;
1218
		}
1219
		if (err == SSL_ERROR_WANT_READ) {
1220
			sockstate =
1221
                            check_socket_and_wait_for_timeout(sock, 0);
1222
		} else if (err == SSL_ERROR_WANT_WRITE) {
1223
			sockstate =
1224
                            check_socket_and_wait_for_timeout(sock, 1);
1225 1226
		} else {
			sockstate = SOCKET_OPERATION_OK;
1227
		}
1228 1229 1230
		if (sockstate == SOCKET_HAS_TIMED_OUT) {
			PyErr_SetString(PySSLErrorObject,
                                        "The write operation timed out");
1231
			goto error;
1232
		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1233 1234
			PyErr_SetString(PySSLErrorObject,
                                        "Underlying socket has been closed.");
1235
			goto error;
1236 1237
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
1238 1239
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1240 1241

	PyBuffer_Release(&buf);
1242
	if (len > 0)
1243
		return PyLong_FromLong(len);
1244
	else
1245
		return PySSL_SetError(self, len, __FILE__, __LINE__);
1246 1247 1248 1249

error:
	PyBuffer_Release(&buf);
	return NULL;
1250 1251
}

1252
PyDoc_STRVAR(PySSL_SSLwrite_doc,
1253 1254 1255
"write(s) -> len\n\
\n\
Writes the string s into the SSL object.  Returns the number\n\
1256
of bytes written.");
1257

Bill Janssen's avatar
Bill Janssen committed
1258
static PyObject *PySSL_SSLpending(PySSLObject *self)
1259 1260
{
	int count = 0;
Bill Janssen's avatar
Bill Janssen committed
1261 1262 1263 1264 1265 1266 1267

	PySSL_BEGIN_ALLOW_THREADS
	count = SSL_pending(self->ssl);
	PySSL_END_ALLOW_THREADS
	if (count < 0)
		return PySSL_SetError(self, count, __FILE__, __LINE__);
	else
1268
		return PyLong_FromLong(count);
Bill Janssen's avatar
Bill Janssen committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
}

PyDoc_STRVAR(PySSL_SSLpending_doc,
"pending() -> count\n\
\n\
Returns the number of already decrypted bytes available for read,\n\
pending on the connection.\n");

static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
{
Benjamin Peterson's avatar
Benjamin Peterson committed
1279 1280
	PyObject *dest = NULL;
	Py_buffer buf;
Bill Janssen's avatar
Bill Janssen committed
1281 1282
	int buf_passed = 0;
	int count = -1;
Benjamin Peterson's avatar
Benjamin Peterson committed
1283 1284
	char *mem;
	/* XXX this should use Py_ssize_t */
1285
	int len = 1024;
1286
	int sockstate;
1287
	int err;
Bill Janssen's avatar
Bill Janssen committed
1288
        int nonblocking;
1289 1290 1291 1292 1293 1294 1295 1296
        PySocketSockObject *sock
          = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);

        if (((PyObject*)sock) == Py_None) {
                _setSSLError("Underlying socket connection gone",
                             PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
                return NULL;
        }
1297

Benjamin Peterson's avatar
Benjamin Peterson committed
1298
	if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1299
		return NULL;
Benjamin Peterson's avatar
Benjamin Peterson committed
1300 1301
        if ((dest == NULL) || (dest == Py_None)) {
		if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen's avatar
Bill Janssen committed
1302
			return NULL;
Benjamin Peterson's avatar
Benjamin Peterson committed
1303 1304 1305 1306
		mem = PyByteArray_AS_STRING(dest);
        } else if (PyLong_Check(dest)) {
		len = PyLong_AS_LONG(dest);
		if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen's avatar
Bill Janssen committed
1307
			return NULL;
Benjamin Peterson's avatar
Benjamin Peterson committed
1308
		mem = PyByteArray_AS_STRING(dest);
Bill Janssen's avatar
Bill Janssen committed
1309
	} else {
Benjamin Peterson's avatar
Benjamin Peterson committed
1310
		if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Bill Janssen's avatar
Bill Janssen committed
1311
			return NULL;
Benjamin Peterson's avatar
Benjamin Peterson committed
1312 1313
		mem = buf.buf;
		len = buf.len;
Bill Janssen's avatar
Bill Janssen committed
1314 1315 1316 1317 1318 1319
		if ((count > 0) && (count <= len))
			len = count;
		buf_passed = 1;
	}

        /* just in case the blocking state of the socket has been changed */
1320
	nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen's avatar
Bill Janssen committed
1321 1322
        BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
        BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1323

1324
	/* first check if there are bytes ready to be read */
1325
	PySSL_BEGIN_ALLOW_THREADS
1326
	count = SSL_pending(self->ssl);
1327
	PySSL_END_ALLOW_THREADS
1328

1329
	if (!count) {
1330
		sockstate = check_socket_and_wait_for_timeout(sock, 0);
1331
		if (sockstate == SOCKET_HAS_TIMED_OUT) {
1332 1333
			PyErr_SetString(PySSLErrorObject,
					"The read operation timed out");
Benjamin Peterson's avatar
Benjamin Peterson committed
1334
			goto error;
1335
		} else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1336 1337
			PyErr_SetString(PySSLErrorObject,
				"Underlying socket too large for select().");
Benjamin Peterson's avatar
Benjamin Peterson committed
1338
			goto error;
1339
		} else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1340 1341
			count = 0;
			goto done;
1342
		}
1343
	}
1344 1345
	do {
		err = 0;
1346
		PySSL_BEGIN_ALLOW_THREADS
Benjamin Peterson's avatar
Benjamin Peterson committed
1347
		count = SSL_read(self->ssl, mem, len);
1348
		err = SSL_get_error(self->ssl, count);
1349
		PySSL_END_ALLOW_THREADS
Benjamin Peterson's avatar
Benjamin Peterson committed
1350 1351
		if (PyErr_CheckSignals())
			goto error;
1352
		if (err == SSL_ERROR_WANT_READ) {
1353
			sockstate =
1354
			  check_socket_and_wait_for_timeout(sock, 0);
1355
		} else if (err == SSL_ERROR_WANT_WRITE) {
1356
			sockstate =
1357
			  check_socket_and_wait_for_timeout(sock, 1);
1358 1359 1360 1361
		} else if ((err == SSL_ERROR_ZERO_RETURN) &&
			   (SSL_get_shutdown(self->ssl) ==
			    SSL_RECEIVED_SHUTDOWN))
		{
1362 1363
			count = 0;
			goto done;
1364 1365
		} else {
			sockstate = SOCKET_OPERATION_OK;
1366
		}
1367 1368 1369
		if (sockstate == SOCKET_HAS_TIMED_OUT) {
			PyErr_SetString(PySSLErrorObject,
					"The read operation timed out");
Benjamin Peterson's avatar
Benjamin Peterson committed
1370
			goto error;
1371 1372
		} else if (sockstate == SOCKET_IS_NONBLOCKING) {
			break;
1373 1374
		}
	} while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1375
	if (count <= 0) {
Benjamin Peterson's avatar
Benjamin Peterson committed
1376 1377
		PySSL_SetError(self, count, __FILE__, __LINE__);
		goto error;
1378
	}
1379
  done:
Bill Janssen's avatar
Bill Janssen committed
1380
	if (!buf_passed) {
Benjamin Peterson's avatar
Benjamin Peterson committed
1381 1382
		PyObject *res = PyBytes_FromStringAndSize(mem, count);
		Py_DECREF(dest);
1383
		return res;
Bill Janssen's avatar
Bill Janssen committed
1384
	} else {
Benjamin Peterson's avatar
Benjamin Peterson committed
1385
		PyBuffer_Release(&buf);
1386
		return PyLong_FromLong(count);
Bill Janssen's avatar
Bill Janssen committed
1387
	}
Benjamin Peterson's avatar
Benjamin Peterson committed
1388 1389 1390 1391 1392 1393 1394
  error:
	if (!buf_passed) {
		Py_DECREF(dest);
	} else {
		PyBuffer_Release(&buf);
	}
	return NULL;
1395 1396
}

1397
PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen's avatar
Bill Janssen committed
1398
"read([len]) -> string\n\
1399
\n\
1400
Read up to len bytes from the SSL socket.");
1401

1402 1403
static PyObject *PySSL_SSLshutdown(PySSLObject *self)
{
1404 1405
	int err, ssl_err, sockstate, nonblocking;
	int zeros = 0;
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
        PySocketSockObject *sock
          = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);

	/* Guard against closed socket */
        if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
                _setSSLError("Underlying socket connection gone",
                             PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
                return NULL;
        }

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        /* Just in case the blocking state of the socket has been changed */
	nonblocking = (sock->sock_timeout >= 0.0);
	BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
	BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);

	while (1) {
		PySSL_BEGIN_ALLOW_THREADS
		/* Disable read-ahead so that unwrap can work correctly.
		 * Otherwise OpenSSL might read in too much data,
		 * eating clear text data that happens to be
		 * transmitted after the SSL shutdown.
		 * Should be safe to call repeatedly everytime this
		 * function is used and the shutdown_seen_zero != 0
		 * condition is met.
		 */
		if (self->shutdown_seen_zero)
			SSL_set_read_ahead(self->ssl, 0);
1433
		err = SSL_shutdown(self->ssl);
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
		PySSL_END_ALLOW_THREADS
		/* If err == 1, a secure shutdown with SSL_shutdown() is complete */
		if (err > 0)
			break;
		if (err == 0) {
			/* Don't loop endlessly; instead preserve legacy
			   behaviour of trying SSL_shutdown() only twice.
			   This looks necessary for OpenSSL < 0.9.8m */
			if (++zeros > 1)
				break;
			/* Shutdown was sent, now try receiving */
			self->shutdown_seen_zero = 1;
			continue;
		}

		/* Possibly retry shutdown until timeout or failure */
		ssl_err = SSL_get_error(self->ssl, err);
		if (ssl_err == SSL_ERROR_WANT_READ)
			sockstate = check_socket_and_wait_for_timeout(sock, 0);
		else if (ssl_err == SSL_ERROR_WANT_WRITE)
			sockstate = check_socket_and_wait_for_timeout(sock, 1);
		else
			break;
		if (sockstate == SOCKET_HAS_TIMED_OUT) {
			if (ssl_err == SSL_ERROR_WANT_READ)
				PyErr_SetString(PySSLErrorObject,
		                                "The read operation timed out");
			else
				PyErr_SetString(PySSLErrorObject,
		                                "The write operation timed out");
			return NULL;
		}
		else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
			PyErr_SetString(PySSLErrorObject,
	                                "Underlying socket too large for select().");
			return NULL;
		}
		else if (sockstate != SOCKET_OPERATION_OK)
			/* Retain the SSL error code */
			break;
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
	}

	if (err < 0)
		return PySSL_SetError(self, err, __FILE__, __LINE__);
	else {
                Py_INCREF(sock);
                return (PyObject *) sock;
	}
}

PyDoc_STRVAR(PySSL_SSLshutdown_doc,
"shutdown(s) -> socket\n\
\n\
Does the SSL shutdown handshake with the remote end, and returns\n\
the underlying socket object.");


1491
static PyMethodDef PySSLMethods[] = {
Bill Janssen's avatar
Bill Janssen committed
1492
	{"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1493
	{"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1494
	 PySSL_SSLwrite_doc},
1495
	{"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1496
	 PySSL_SSLread_doc},
Bill Janssen's avatar
Bill Janssen committed
1497 1498
	{"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
	 PySSL_SSLpending_doc},
1499 1500 1501
	{"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
	 PySSL_peercert_doc},
	{"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1502 1503
	{"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
	 PySSL_SSLshutdown_doc},
1504 1505 1506
	{NULL, NULL}
};

1507
static PyTypeObject PySSL_Type = {
1508
	PyVarObject_HEAD_INIT(NULL, 0)
1509
	"ssl.SSLContext",		/*tp_name*/
1510 1511 1512 1513 1514
	sizeof(PySSLObject),		/*tp_basicsize*/
	0,				/*tp_itemsize*/
	/* methods */
	(destructor)PySSL_dealloc,	/*tp_dealloc*/
	0,				/*tp_print*/
1515
	0,				/*tp_getattr*/
1516
	0,				/*tp_setattr*/
1517
	0,				/*tp_reserved*/
1518 1519 1520 1521 1522
	0,				/*tp_repr*/
	0,				/*tp_as_number*/
	0,				/*tp_as_sequence*/
	0,				/*tp_as_mapping*/
	0,				/*tp_hash*/
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
	0,				/*tp_call*/
	0,				/*tp_str*/
	0,				/*tp_getattro*/
	0,				/*tp_setattro*/
	0,				/*tp_as_buffer*/
	Py_TPFLAGS_DEFAULT,		/*tp_flags*/
	0,				/*tp_doc*/
	0,				/*tp_traverse*/
	0,				/*tp_clear*/
	0,				/*tp_richcompare*/
	0,				/*tp_weaklistoffset*/
	0,				/*tp_iter*/
	0,				/*tp_iternext*/
	PySSLMethods,			/*tp_methods*/
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
};

#ifdef HAVE_OPENSSL_RAND

/* helper routines for seeding the SSL PRNG */
static PyObject *
PySSL_RAND_add(PyObject *self, PyObject *args)
{
    char *buf;
    int len;
    double entropy;

    if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
	return NULL;
    RAND_add(buf, len, entropy);
    Py_INCREF(Py_None);
    return Py_None;
}

1556
PyDoc_STRVAR(PySSL_RAND_add_doc,
1557 1558 1559
"RAND_add(string, entropy)\n\
\n\
Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower\n\
1560
bound on the entropy contained in string.  See RFC 1750.");
1561 1562 1563 1564

static PyObject *
PySSL_RAND_status(PyObject *self)
{
1565
    return PyLong_FromLong(RAND_status());
1566 1567
}

1568
PyDoc_STRVAR(PySSL_RAND_status_doc,
1569 1570
"RAND_status() -> 0 or 1\n\
\n\
Bill Janssen's avatar
Bill Janssen committed
1571 1572 1573
Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
using the ssl() function.");
1574 1575 1576 1577 1578 1579

static PyObject *
PySSL_RAND_egd(PyObject *self, PyObject *arg)
{
    int bytes;

Bill Janssen's avatar
Bill Janssen committed
1580
    if (!PyUnicode_Check(arg))
1581 1582
	return PyErr_Format(PyExc_TypeError,
			    "RAND_egd() expected string, found %s",
1583
			    Py_TYPE(arg)->tp_name);
1584
    bytes = RAND_egd(_PyUnicode_AsString(arg));
1585 1586 1587 1588 1589 1590
    if (bytes == -1) {
	PyErr_SetString(PySSLErrorObject,
			"EGD connection failed or EGD did not return "
			"enough data to seed the PRNG");
	return NULL;
    }
1591
    return PyLong_FromLong(bytes);
1592 1593
}

1594
PyDoc_STRVAR(PySSL_RAND_egd_doc,
1595 1596
"RAND_egd(path) -> bytes\n\
\n\
1597 1598 1599
Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
Returns number of bytes read.  Raises SSLError if connection to EGD\n\
fails or if it does provide enough data to seed PRNG.");
1600 1601 1602

#endif

1603 1604


1605 1606 1607
/* List of functions exported by this module. */

static PyMethodDef PySSL_methods[] = {
1608 1609
	{"sslwrap",             PySSL_sslwrap,
         METH_VARARGS, ssl_doc},
1610 1611
	{"_test_decode_cert",	PySSL_test_decode_certificate,
	 METH_VARARGS},
1612
#ifdef HAVE_OPENSSL_RAND
1613
	{"RAND_add",            PySSL_RAND_add, METH_VARARGS,
1614 1615 1616 1617 1618 1619
	 PySSL_RAND_add_doc},
	{"RAND_egd",            PySSL_RAND_egd, METH_O,
	 PySSL_RAND_egd_doc},
	{"RAND_status",         (PyCFunction)PySSL_RAND_status, METH_NOARGS,
	 PySSL_RAND_status_doc},
#endif
1620
	{NULL,                  NULL}            /* Sentinel */
1621 1622 1623
};


1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
#ifdef WITH_THREAD

/* an implementation of OpenSSL threading operations in terms
   of the Python C thread library */

static PyThread_type_lock *_ssl_locks = NULL;

static unsigned long _ssl_thread_id_function (void) {
	return PyThread_get_thread_ident();
}

Bill Janssen's avatar
Bill Janssen committed
1635 1636
static void _ssl_thread_locking_function
        (int mode, int n, const char *file, int line) {
1637 1638
	/* this function is needed to perform locking on shared data
	   structures. (Note that OpenSSL uses a number of global data
Bill Janssen's avatar
Bill Janssen committed
1639 1640 1641
	   structures that will be implicitly shared whenever multiple
	   threads use OpenSSL.) Multi-threaded applications will
	   crash at random if it is not set.
1642

Bill Janssen's avatar
Bill Janssen committed
1643 1644 1645
	   locking_function() must be able to handle up to
	   CRYPTO_num_locks() different mutex locks. It sets the n-th
	   lock if mode & CRYPTO_LOCK, and releases it otherwise.
1646 1647 1648 1649 1650 1651

	   file and line are the file number of the function setting the
	   lock. They can be useful for debugging.
	*/

	if ((_ssl_locks == NULL) ||
1652
	    (n < 0) || ((unsigned)n >= _ssl_locks_count))
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
		return;

	if (mode & CRYPTO_LOCK) {
		PyThread_acquire_lock(_ssl_locks[n], 1);
	} else {
		PyThread_release_lock(_ssl_locks[n]);
	}
}

static int _setup_ssl_threads(void) {

1664
	unsigned int i;
1665 1666 1667 1668 1669 1670 1671

	if (_ssl_locks == NULL) {
		_ssl_locks_count = CRYPTO_num_locks();
		_ssl_locks = (PyThread_type_lock *)
			malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
		if (_ssl_locks == NULL)
			return 0;
Bill Janssen's avatar
Bill Janssen committed
1672 1673
		memset(_ssl_locks, 0,
                       sizeof(PyThread_type_lock) * _ssl_locks_count);
1674 1675 1676
		for (i = 0;  i < _ssl_locks_count;  i++) {
			_ssl_locks[i] = PyThread_allocate_lock();
			if (_ssl_locks[i] == NULL) {
1677
				unsigned int j;
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
				for (j = 0;  j < i;  j++) {
					PyThread_free_lock(_ssl_locks[j]);
				}
				free(_ssl_locks);
				return 0;
			}
		}
		CRYPTO_set_locking_callback(_ssl_thread_locking_function);
		CRYPTO_set_id_callback(_ssl_thread_id_function);
	}
	return 1;
}

#endif	/* def HAVE_THREAD */

1693
PyDoc_STRVAR(module_doc,
1694
"Implementation module for SSL socket operations.  See the socket module\n\
1695
for documentation.");
1696

1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709

static struct PyModuleDef _sslmodule = {
	PyModuleDef_HEAD_INIT,
	"_ssl",
	module_doc,
	-1,
	PySSL_methods,
	NULL,
	NULL,
	NULL,
	NULL
};

1710
PyMODINIT_FUNC
1711
PyInit__ssl(void)
1712
{
1713 1714 1715
	PyObject *m, *d, *r;
	unsigned long libver;
	unsigned int major, minor, fix, patch, status;
1716
        PySocketModule_APIObject *socket_api;
1717

1718 1719
	if (PyType_Ready(&PySSL_Type) < 0)
		return NULL;
1720

1721
	m = PyModule_Create(&_sslmodule);
1722
	if (m == NULL)
1723
		return NULL;
1724 1725 1726
	d = PyModule_GetDict(m);

	/* Load _socket module and its C API */
1727 1728
        socket_api = PySocketModule_ImportModuleAndAPI();
	if (!socket_api)
1729
		return NULL;
1730
        PySocketModule = *socket_api;
1731 1732 1733

	/* Init OpenSSL */
	SSL_load_error_strings();
1734
	SSL_library_init();
1735 1736 1737
#ifdef WITH_THREAD
	/* note that this will start threading if not already started */
	if (!_setup_ssl_threads()) {
1738
		return NULL;
1739 1740
	}
#endif
1741
	OpenSSL_add_all_algorithms();
1742 1743

	/* Add symbols to module dict */
1744
	PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1745 1746
					      PySocketModule.error,
					      NULL);
1747
	if (PySSLErrorObject == NULL)
1748
		return NULL;
1749
	if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1750
		return NULL;
1751 1752
	if (PyDict_SetItemString(d, "SSLType",
				 (PyObject *)&PySSL_Type) != 0)
1753
		return NULL;
1754
	PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1755
				PY_SSL_ERROR_ZERO_RETURN);
1756
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1757
				PY_SSL_ERROR_WANT_READ);
1758
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1759
				PY_SSL_ERROR_WANT_WRITE);
1760
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1761
				PY_SSL_ERROR_WANT_X509_LOOKUP);
1762
	PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1763
				PY_SSL_ERROR_SYSCALL);
1764
	PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1765 1766 1767 1768 1769 1770 1771 1772
				PY_SSL_ERROR_SSL);
	PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
				PY_SSL_ERROR_WANT_CONNECT);
	/* non ssl.h errorcodes */
	PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
				PY_SSL_ERROR_EOF);
	PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
				PY_SSL_ERROR_INVALID_ERROR_CODE);
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
	/* cert requirements */
	PyModule_AddIntConstant(m, "CERT_NONE",
				PY_SSL_CERT_NONE);
	PyModule_AddIntConstant(m, "CERT_OPTIONAL",
				PY_SSL_CERT_OPTIONAL);
	PyModule_AddIntConstant(m, "CERT_REQUIRED",
				PY_SSL_CERT_REQUIRED);

	/* protocol versions */
	PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
				PY_SSL_VERSION_SSL2);
	PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
				PY_SSL_VERSION_SSL3);
	PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
				PY_SSL_VERSION_SSL23);
	PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
				PY_SSL_VERSION_TLS1);
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

	/* OpenSSL version */
	/* SSLeay() gives us the version of the library linked against,
	   which could be different from the headers version.
	*/
	libver = SSLeay();
	r = PyLong_FromUnsignedLong(libver);
	if (r == NULL)
		return NULL;
	if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
		return NULL;
	status = libver & 0xF;
	libver >>= 4;
	patch = libver & 0xFF;
	libver >>= 8;
	fix = libver & 0xFF;
	libver >>= 8;
	minor = libver & 0xFF;
	libver >>= 8;
	major = libver & 0xFF;
	r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
	if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
		return NULL;
	r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
	if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
		return NULL;

1817
	return m;
1818
}