blob: 3c7e939de6e6ad5d2d4b14dbba6ef9cc5072f061 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000022 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);} \
27 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000039 /* these mirror ssl.h */
40 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
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_NO_SOCKET, /* socket has been GC'd */
51 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000052};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
116typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000117 PyObject_HEAD
118 PyObject *Socket; /* weakref to socket on which we're layered */
119 SSL_CTX* ctx;
120 SSL* ssl;
121 X509* peer_cert;
122 int shutdown_seen_zero;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123
124} PySSLObject;
125
Jeremy Hylton938ace62002-07-17 16:30:39 +0000126static PyTypeObject PySSL_Type;
127static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000129static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000130 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000131static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
132static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000134#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000136typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000137 SOCKET_IS_NONBLOCKING,
138 SOCKET_IS_BLOCKING,
139 SOCKET_HAS_TIMED_OUT,
140 SOCKET_HAS_BEEN_CLOSED,
141 SOCKET_TOO_LARGE_FOR_SELECT,
142 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000143} timeout_state;
144
Thomas Woutersed03b412007-08-28 21:37:11 +0000145/* Wrap error strings with filename and line # */
146#define STRINGIFY1(x) #x
147#define STRINGIFY2(x) STRINGIFY1(x)
148#define ERRSTR1(x,y,z) (x ":" y ": " z)
149#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
150
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000151/* XXX It might be helpful to augment the error message generated
152 below with the name of the SSL function that generated the error.
153 I expect it's obvious most of the time.
154*/
155
156static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000157PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000159 PyObject *v;
160 char buf[2048];
161 char *errstr;
162 int err;
163 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000165 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000167 if (obj->ssl != NULL) {
168 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000170 switch (err) {
171 case SSL_ERROR_ZERO_RETURN:
172 errstr = "TLS/SSL connection has been closed";
173 p = PY_SSL_ERROR_ZERO_RETURN;
174 break;
175 case SSL_ERROR_WANT_READ:
176 errstr = "The operation did not complete (read)";
177 p = PY_SSL_ERROR_WANT_READ;
178 break;
179 case SSL_ERROR_WANT_WRITE:
180 p = PY_SSL_ERROR_WANT_WRITE;
181 errstr = "The operation did not complete (write)";
182 break;
183 case SSL_ERROR_WANT_X509_LOOKUP:
184 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
185 errstr =
186 "The operation did not complete (X509 lookup)";
187 break;
188 case SSL_ERROR_WANT_CONNECT:
189 p = PY_SSL_ERROR_WANT_CONNECT;
190 errstr = "The operation did not complete (connect)";
191 break;
192 case SSL_ERROR_SYSCALL:
193 {
194 unsigned long e = ERR_get_error();
195 if (e == 0) {
196 PySocketSockObject *s
197 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
198 if (ret == 0 || (((PyObject *)s) == Py_None)) {
199 p = PY_SSL_ERROR_EOF;
200 errstr =
201 "EOF occurred in violation of protocol";
202 } else if (ret == -1) {
203 /* underlying BIO reported an I/O error */
204 return s->errorhandler();
205 } else { /* possible? */
206 p = PY_SSL_ERROR_SYSCALL;
207 errstr = "Some I/O error occurred";
208 }
209 } else {
210 p = PY_SSL_ERROR_SYSCALL;
211 /* XXX Protected by global interpreter lock */
212 errstr = ERR_error_string(e, NULL);
213 }
214 break;
215 }
216 case SSL_ERROR_SSL:
217 {
218 unsigned long e = ERR_get_error();
219 p = PY_SSL_ERROR_SSL;
220 if (e != 0)
221 /* XXX Protected by global interpreter lock */
222 errstr = ERR_error_string(e, NULL);
223 else { /* possible? */
224 errstr =
225 "A failure in the SSL library occurred";
226 }
227 break;
228 }
229 default:
230 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
231 errstr = "Invalid error code";
232 }
233 } else {
234 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
235 }
236 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
237 v = Py_BuildValue("(is)", p, buf);
238 if (v != NULL) {
239 PyErr_SetObject(PySSLErrorObject, v);
240 Py_DECREF(v);
241 }
242 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000243}
244
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245static PyObject *
246_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000248 char buf[2048];
249 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000251 if (errstr == NULL) {
252 errcode = ERR_peek_last_error();
253 errstr = ERR_error_string(errcode, NULL);
254 }
255 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
256 v = Py_BuildValue("(is)", errcode, buf);
257 if (v != NULL) {
258 PyErr_SetObject(PySSLErrorObject, v);
259 Py_DECREF(v);
260 }
261 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262}
263
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000264static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000265newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 enum py_ssl_server_or_client socket_type,
267 enum py_ssl_cert_requirements certreq,
268 enum py_ssl_version proto_version,
269 char *cacerts_file, char *ciphers)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000270{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000271 PySSLObject *self;
272 char *errstr = NULL;
273 int ret;
274 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000276 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
277 if (self == NULL)
278 return NULL;
279 self->peer_cert = NULL;
280 self->ssl = NULL;
281 self->ctx = NULL;
282 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 /* Make sure the SSL error state is initialized */
285 (void) ERR_get_state();
286 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000288 if ((key_file && !cert_file) || (!key_file && cert_file)) {
289 errstr = ERRSTR("Both the key & certificate files "
290 "must be specified");
291 goto fail;
292 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000294 if ((socket_type == PY_SSL_SERVER) &&
295 ((key_file == NULL) || (cert_file == NULL))) {
296 errstr = ERRSTR("Both the key & certificate files "
297 "must be specified for server-side operation");
298 goto fail;
299 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000301 PySSL_BEGIN_ALLOW_THREADS
302 if (proto_version == PY_SSL_VERSION_TLS1)
303 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
304 else if (proto_version == PY_SSL_VERSION_SSL3)
305 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
306 else if (proto_version == PY_SSL_VERSION_SSL2)
307 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
Thomas Woutersed03b412007-08-28 21:37:11 +0000311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000312 if (self->ctx == NULL) {
313 errstr = ERRSTR("Invalid SSL protocol variant specified.");
314 goto fail;
315 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000317 if (ciphers != NULL) {
318 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
319 if (ret == 0) {
320 errstr = ERRSTR("No cipher can be selected.");
321 goto fail;
322 }
323 }
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000324
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000325 if (certreq != PY_SSL_CERT_NONE) {
326 if (cacerts_file == NULL) {
327 errstr = ERRSTR("No root certificates specified for "
328 "verification of other-side certificates.");
329 goto fail;
330 } else {
331 PySSL_BEGIN_ALLOW_THREADS
332 ret = SSL_CTX_load_verify_locations(self->ctx,
333 cacerts_file,
334 NULL);
335 PySSL_END_ALLOW_THREADS
336 if (ret != 1) {
337 _setSSLError(NULL, 0, __FILE__, __LINE__);
338 goto fail;
339 }
340 }
341 }
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 goto fail;
350 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 PySSL_BEGIN_ALLOW_THREADS
353 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
354 cert_file);
355 PySSL_END_ALLOW_THREADS
356 if (ret != 1) {
357 /*
358 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
359 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
360 */
361 if (ERR_peek_last_error() != 0) {
362 _setSSLError(NULL, ret, __FILE__, __LINE__);
363 goto fail;
364 }
365 }
366 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 /* ssl compatibility */
369 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000371 verification_mode = SSL_VERIFY_NONE;
372 if (certreq == PY_SSL_CERT_OPTIONAL)
373 verification_mode = SSL_VERIFY_PEER;
374 else if (certreq == PY_SSL_CERT_REQUIRED)
375 verification_mode = (SSL_VERIFY_PEER |
376 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
377 SSL_CTX_set_verify(self->ctx, verification_mode,
378 NULL); /* set verify lvl */
Thomas Woutersed03b412007-08-28 21:37:11 +0000379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000380 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 */
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000384#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000386#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000387
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 /* If the socket is in non-blocking mode or timeout mode, set the BIO
389 * to non-blocking mode (blocking is the default)
390 */
391 if (Sock->sock_timeout >= 0.0) {
392 /* Set both the read and write BIO's to non-blocking mode */
393 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
394 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
395 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000397 PySSL_BEGIN_ALLOW_THREADS
398 if (socket_type == PY_SSL_CLIENT)
399 SSL_set_connect_state(self->ssl);
400 else
401 SSL_set_accept_state(self->ssl);
402 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
405 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 if (errstr)
408 PyErr_SetString(PySSLErrorObject, errstr);
409 Py_DECREF(self);
410 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000411}
412
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000413static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000414PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 PySocketSockObject *Sock;
417 int server_side = 0;
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;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
426 PySocketModule.Sock_Type,
427 &Sock,
428 &server_side,
429 &key_file, &cert_file,
430 &verification_mode, &protocol,
431 &cacerts_file, &ciphers))
432 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 /*
435 fprintf(stderr,
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);
440 */
Thomas Woutersed03b412007-08-28 21:37:11 +0000441
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
443 server_side, verification_mode,
444 protocol, cacerts_file,
445 ciphers);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000446}
447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000448PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000449"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000450" cacertsfile, ciphers]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451
452/* SSL object methods */
453
Bill Janssen6e027db2007-11-15 22:23:56 +0000454static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 int ret;
457 int err;
458 int sockstate, nonblocking;
459 PySocketSockObject *sock
460 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000461
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000462 if (((PyObject*)sock) == Py_None) {
463 _setSSLError("Underlying socket connection gone",
464 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
465 return NULL;
466 }
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 /* just in case the blocking state of the socket has been changed */
469 nonblocking = (sock->sock_timeout >= 0.0);
470 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
471 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000473 /* Actually negotiate SSL connection */
474 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
475 sockstate = 0;
476 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000477 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 ret = SSL_do_handshake(self->ssl);
479 err = SSL_get_error(self->ssl, ret);
480 PySSL_END_ALLOW_THREADS
481 if(PyErr_CheckSignals()) {
482 return NULL;
483 }
484 if (err == SSL_ERROR_WANT_READ) {
485 sockstate = check_socket_and_wait_for_timeout(sock, 0);
486 } else if (err == SSL_ERROR_WANT_WRITE) {
487 sockstate = check_socket_and_wait_for_timeout(sock, 1);
488 } else {
489 sockstate = SOCKET_OPERATION_OK;
490 }
491 if (sockstate == SOCKET_HAS_TIMED_OUT) {
492 PyErr_SetString(PySSLErrorObject,
493 ERRSTR("The handshake operation timed out"));
494 return NULL;
495 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
496 PyErr_SetString(PySSLErrorObject,
497 ERRSTR("Underlying socket has been closed."));
498 return NULL;
499 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
500 PyErr_SetString(PySSLErrorObject,
501 ERRSTR("Underlying socket too large for select()."));
502 return NULL;
503 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
504 break;
505 }
506 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
507 if (ret < 1)
508 return PySSL_SetError(self, ret, __FILE__, __LINE__);
509 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 if (self->peer_cert)
512 X509_free (self->peer_cert);
513 PySSL_BEGIN_ALLOW_THREADS
514 self->peer_cert = SSL_get_peer_certificate(self->ssl);
515 PySSL_END_ALLOW_THREADS
516
517 Py_INCREF(Py_None);
518 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000519}
520
Thomas Woutersed03b412007-08-28 21:37:11 +0000521static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000524 char namebuf[X509_NAME_MAXLEN];
525 int buflen;
526 PyObject *name_obj;
527 PyObject *value_obj;
528 PyObject *attr;
529 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000530
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
532 if (buflen < 0) {
533 _setSSLError(NULL, 0, __FILE__, __LINE__);
534 goto fail;
535 }
536 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
537 if (name_obj == NULL)
538 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
541 if (buflen < 0) {
542 _setSSLError(NULL, 0, __FILE__, __LINE__);
543 Py_DECREF(name_obj);
544 goto fail;
545 }
546 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
547 buflen, "strict");
548 OPENSSL_free(valuebuf);
549 if (value_obj == NULL) {
550 Py_DECREF(name_obj);
551 goto fail;
552 }
553 attr = PyTuple_New(2);
554 if (attr == NULL) {
555 Py_DECREF(name_obj);
556 Py_DECREF(value_obj);
557 goto fail;
558 }
559 PyTuple_SET_ITEM(attr, 0, name_obj);
560 PyTuple_SET_ITEM(attr, 1, value_obj);
561 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000562
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000565}
566
567static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000569{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
571 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
572 PyObject *rdnt;
573 PyObject *attr = NULL; /* tuple to hold an attribute */
574 int entry_count = X509_NAME_entry_count(xname);
575 X509_NAME_ENTRY *entry;
576 ASN1_OBJECT *name;
577 ASN1_STRING *value;
578 int index_counter;
579 int rdn_level = -1;
580 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 dn = PyList_New(0);
583 if (dn == NULL)
584 return NULL;
585 /* now create another tuple to hold the top-level RDN */
586 rdn = PyList_New(0);
587 if (rdn == NULL)
588 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 for (index_counter = 0;
591 index_counter < entry_count;
592 index_counter++)
593 {
594 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 /* check to see if we've gotten to a new RDN */
597 if (rdn_level >= 0) {
598 if (rdn_level != entry->set) {
599 /* yes, new RDN */
600 /* add old RDN to DN */
601 rdnt = PyList_AsTuple(rdn);
602 Py_DECREF(rdn);
603 if (rdnt == NULL)
604 goto fail0;
605 retcode = PyList_Append(dn, rdnt);
606 Py_DECREF(rdnt);
607 if (retcode < 0)
608 goto fail0;
609 /* create new RDN */
610 rdn = PyList_New(0);
611 if (rdn == NULL)
612 goto fail0;
613 }
614 }
615 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 /* now add this attribute to the current RDN */
618 name = X509_NAME_ENTRY_get_object(entry);
619 value = X509_NAME_ENTRY_get_data(entry);
620 attr = _create_tuple_for_attribute(name, value);
621 /*
622 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
623 entry->set,
624 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
625 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
626 */
627 if (attr == NULL)
628 goto fail1;
629 retcode = PyList_Append(rdn, attr);
630 Py_DECREF(attr);
631 if (retcode < 0)
632 goto fail1;
633 }
634 /* now, there's typically a dangling RDN */
635 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
636 rdnt = PyList_AsTuple(rdn);
637 Py_DECREF(rdn);
638 if (rdnt == NULL)
639 goto fail0;
640 retcode = PyList_Append(dn, rdnt);
641 Py_DECREF(rdnt);
642 if (retcode < 0)
643 goto fail0;
644 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 /* convert list to tuple */
647 rdnt = PyList_AsTuple(dn);
648 Py_DECREF(dn);
649 if (rdnt == NULL)
650 return NULL;
651 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
653 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
656 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 Py_XDECREF(dn);
658 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659}
660
661static PyObject *
662_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 /* this code follows the procedure outlined in
665 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
666 function to extract the STACK_OF(GENERAL_NAME),
667 then iterates through the stack to add the
668 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 int i, j;
671 PyObject *peer_alt_names = Py_None;
672 PyObject *v, *t;
673 X509_EXTENSION *ext = NULL;
674 GENERAL_NAMES *names = NULL;
675 GENERAL_NAME *name;
676 X509V3_EXT_METHOD *method;
677 BIO *biobuf = NULL;
678 char buf[2048];
679 char *vptr;
680 int len;
681 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000682#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000684#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000686#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 if (certificate == NULL)
689 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 /* get a memory buffer */
692 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 i = 0;
695 while ((i = X509_get_ext_by_NID(
696 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 if (peer_alt_names == Py_None) {
699 peer_alt_names = PyList_New(0);
700 if (peer_alt_names == NULL)
701 goto fail;
702 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 /* now decode the altName */
705 ext = X509_get_ext(certificate, i);
706 if(!(method = X509V3_EXT_get(ext))) {
707 PyErr_SetString
708 (PySSLErrorObject,
709 ERRSTR("No method for internalizing subjectAltName!"));
710 goto fail;
711 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 p = ext->value->data;
714 if (method->it)
715 names = (GENERAL_NAMES*)
716 (ASN1_item_d2i(NULL,
717 &p,
718 ext->value->length,
719 ASN1_ITEM_ptr(method->it)));
720 else
721 names = (GENERAL_NAMES*)
722 (method->d2i(NULL,
723 &p,
724 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000727
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 name = sk_GENERAL_NAME_value(names, j);
731 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 /* we special-case DirName as a tuple of
734 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 t = PyTuple_New(2);
737 if (t == NULL) {
738 goto fail;
739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 v = PyUnicode_FromString("DirName");
742 if (v == NULL) {
743 Py_DECREF(t);
744 goto fail;
745 }
746 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 v = _create_tuple_for_X509_NAME (name->d.dirn);
749 if (v == NULL) {
750 Py_DECREF(t);
751 goto fail;
752 }
753 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 (void) BIO_reset(biobuf);
760 GENERAL_NAME_print(biobuf, name);
761 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
762 if (len < 0) {
763 _setSSLError(NULL, 0, __FILE__, __LINE__);
764 goto fail;
765 }
766 vptr = strchr(buf, ':');
767 if (vptr == NULL)
768 goto fail;
769 t = PyTuple_New(2);
770 if (t == NULL)
771 goto fail;
772 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
773 if (v == NULL) {
774 Py_DECREF(t);
775 goto fail;
776 }
777 PyTuple_SET_ITEM(t, 0, v);
778 v = PyUnicode_FromStringAndSize((vptr + 1),
779 (len - (vptr - buf + 1)));
780 if (v == NULL) {
781 Py_DECREF(t);
782 goto fail;
783 }
784 PyTuple_SET_ITEM(t, 1, v);
785 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 if (PyList_Append(peer_alt_names, t) < 0) {
790 Py_DECREF(t);
791 goto fail;
792 }
793 Py_DECREF(t);
794 }
795 }
796 BIO_free(biobuf);
797 if (peer_alt_names != Py_None) {
798 v = PyList_AsTuple(peer_alt_names);
799 Py_DECREF(peer_alt_names);
800 return v;
801 } else {
802 return peer_alt_names;
803 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000804
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
806 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 if (biobuf != NULL)
808 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 if (peer_alt_names != Py_None) {
811 Py_XDECREF(peer_alt_names);
812 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815}
816
817static PyObject *
818_decode_certificate (X509 *certificate, int verbose) {
819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 PyObject *retval = NULL;
821 BIO *biobuf = NULL;
822 PyObject *peer;
823 PyObject *peer_alt_names = NULL;
824 PyObject *issuer;
825 PyObject *version;
826 PyObject *sn_obj;
827 ASN1_INTEGER *serialNumber;
828 char buf[2048];
829 int len;
830 ASN1_TIME *notBefore, *notAfter;
831 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 retval = PyDict_New();
834 if (retval == NULL)
835 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 peer = _create_tuple_for_X509_NAME(
838 X509_get_subject_name(certificate));
839 if (peer == NULL)
840 goto fail0;
841 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
842 Py_DECREF(peer);
843 goto fail0;
844 }
845 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 if (verbose) {
848 issuer = _create_tuple_for_X509_NAME(
849 X509_get_issuer_name(certificate));
850 if (issuer == NULL)
851 goto fail0;
852 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
853 Py_DECREF(issuer);
854 goto fail0;
855 }
856 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 version = PyLong_FromLong(X509_get_version(certificate) + 1);
859 if (PyDict_SetItemString(retval, "version", version) < 0) {
860 Py_DECREF(version);
861 goto fail0;
862 }
863 Py_DECREF(version);
864 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 /* get a memory buffer */
867 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 (void) BIO_reset(biobuf);
872 serialNumber = X509_get_serialNumber(certificate);
873 /* should not exceed 20 octets, 160 bits, so buf is big enough */
874 i2a_ASN1_INTEGER(biobuf, serialNumber);
875 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
876 if (len < 0) {
877 _setSSLError(NULL, 0, __FILE__, __LINE__);
878 goto fail1;
879 }
880 sn_obj = PyUnicode_FromStringAndSize(buf, len);
881 if (sn_obj == NULL)
882 goto fail1;
883 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
884 Py_DECREF(sn_obj);
885 goto fail1;
886 }
887 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 (void) BIO_reset(biobuf);
890 notBefore = X509_get_notBefore(certificate);
891 ASN1_TIME_print(biobuf, notBefore);
892 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
893 if (len < 0) {
894 _setSSLError(NULL, 0, __FILE__, __LINE__);
895 goto fail1;
896 }
897 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
898 if (pnotBefore == NULL)
899 goto fail1;
900 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
901 Py_DECREF(pnotBefore);
902 goto fail1;
903 }
904 Py_DECREF(pnotBefore);
905 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 (void) BIO_reset(biobuf);
908 notAfter = X509_get_notAfter(certificate);
909 ASN1_TIME_print(biobuf, notAfter);
910 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
911 if (len < 0) {
912 _setSSLError(NULL, 0, __FILE__, __LINE__);
913 goto fail1;
914 }
915 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
916 if (pnotAfter == NULL)
917 goto fail1;
918 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
919 Py_DECREF(pnotAfter);
920 goto fail1;
921 }
922 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 peer_alt_names = _get_peer_alt_names(certificate);
927 if (peer_alt_names == NULL)
928 goto fail1;
929 else if (peer_alt_names != Py_None) {
930 if (PyDict_SetItemString(retval, "subjectAltName",
931 peer_alt_names) < 0) {
932 Py_DECREF(peer_alt_names);
933 goto fail1;
934 }
935 Py_DECREF(peer_alt_names);
936 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 BIO_free(biobuf);
939 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000940
941 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 if (biobuf != NULL)
943 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000944 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 Py_XDECREF(retval);
946 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000947}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000948
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
950static PyObject *
951PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 PyObject *retval = NULL;
954 char *filename = NULL;
955 X509 *x=NULL;
956 BIO *cert;
957 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
960 &filename, &verbose))
961 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000962
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 if ((cert=BIO_new(BIO_s_file())) == NULL) {
964 PyErr_SetString(PySSLErrorObject,
965 "Can't malloc memory to read file");
966 goto fail0;
967 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 if (BIO_read_filename(cert,filename) <= 0) {
970 PyErr_SetString(PySSLErrorObject,
971 "Can't open file");
972 goto fail0;
973 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
976 if (x == NULL) {
977 PyErr_SetString(PySSLErrorObject,
978 "Error decoding PEM-encoded file");
979 goto fail0;
980 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
984 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 if (cert != NULL) BIO_free(cert);
987 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000988}
989
990
991static PyObject *
992PySSL_peercert(PySSLObject *self, PyObject *args)
993{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 PyObject *retval = NULL;
995 int len;
996 int verification;
997 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1000 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 if (!self->peer_cert)
1003 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 if (PyObject_IsTrue(binary_mode)) {
1006 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 bytes_buf = NULL;
1011 len = i2d_X509(self->peer_cert, &bytes_buf);
1012 if (len < 0) {
1013 PySSL_SetError(self, len, __FILE__, __LINE__);
1014 return NULL;
1015 }
1016 /* this is actually an immutable bytes sequence */
1017 retval = PyBytes_FromStringAndSize
1018 ((const char *) bytes_buf, len);
1019 OPENSSL_free(bytes_buf);
1020 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 verification = SSL_CTX_get_verify_mode(self->ctx);
1025 if ((verification & SSL_VERIFY_PEER) == 0)
1026 return PyDict_New();
1027 else
1028 return _decode_certificate (self->peer_cert, 0);
1029 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001030}
1031
1032PyDoc_STRVAR(PySSL_peercert_doc,
1033"peer_certificate([der=False]) -> certificate\n\
1034\n\
1035Returns the certificate for the peer. If no certificate was provided,\n\
1036returns None. If a certificate was provided, but not validated, returns\n\
1037an empty dictionary. Otherwise returns a dict containing information\n\
1038about the peer certificate.\n\
1039\n\
1040If the optional argument is True, returns a DER-encoded copy of the\n\
1041peer certificate, or None if no certificate was provided. This will\n\
1042return the certificate even if it wasn't validated.");
1043
1044static PyObject *PySSL_cipher (PySSLObject *self) {
1045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 PyObject *retval, *v;
1047 SSL_CIPHER *current;
1048 char *cipher_name;
1049 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 if (self->ssl == NULL)
1052 return Py_None;
1053 current = SSL_get_current_cipher(self->ssl);
1054 if (current == NULL)
1055 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 retval = PyTuple_New(3);
1058 if (retval == NULL)
1059 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 cipher_name = (char *) SSL_CIPHER_get_name(current);
1062 if (cipher_name == NULL) {
1063 PyTuple_SET_ITEM(retval, 0, Py_None);
1064 } else {
1065 v = PyUnicode_FromString(cipher_name);
1066 if (v == NULL)
1067 goto fail0;
1068 PyTuple_SET_ITEM(retval, 0, v);
1069 }
1070 cipher_protocol = SSL_CIPHER_get_version(current);
1071 if (cipher_protocol == NULL) {
1072 PyTuple_SET_ITEM(retval, 1, Py_None);
1073 } else {
1074 v = PyUnicode_FromString(cipher_protocol);
1075 if (v == NULL)
1076 goto fail0;
1077 PyTuple_SET_ITEM(retval, 1, v);
1078 }
1079 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1080 if (v == NULL)
1081 goto fail0;
1082 PyTuple_SET_ITEM(retval, 2, v);
1083 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001084
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 Py_DECREF(retval);
1087 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088}
1089
Guido van Rossume6650f92007-12-06 19:05:55 +00001090static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001091{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 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 Py_XDECREF(self->Socket);
1099 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001100}
1101
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001103 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001104 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001105 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001106
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001107static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001108check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001109{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 fd_set fds;
1111 struct timeval tv;
1112 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1115 if (s->sock_timeout < 0.0)
1116 return SOCKET_IS_BLOCKING;
1117 else if (s->sock_timeout == 0.0)
1118 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 /* Guard against closed socket */
1121 if (s->sock_fd < 0)
1122 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 /* Prefer poll, if available, since you can poll() any fd
1125 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001126#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 {
1128 struct pollfd pollfd;
1129 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 pollfd.fd = s->sock_fd;
1132 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 /* s->sock_timeout is in seconds, timeout in ms */
1135 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1136 PySSL_BEGIN_ALLOW_THREADS
1137 rc = poll(&pollfd, 1, timeout);
1138 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 goto normal_return;
1141 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001142#endif
1143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001145#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 if (s->sock_fd >= FD_SETSIZE)
1147 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001148#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 /* Construct the arguments to select */
1151 tv.tv_sec = (int)s->sock_timeout;
1152 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1153 FD_ZERO(&fds);
1154 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 /* See if the socket is ready */
1157 PySSL_BEGIN_ALLOW_THREADS
1158 if (writing)
1159 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1160 else
1161 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1162 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001163
Bill Janssen6e027db2007-11-15 22:23:56 +00001164#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001165normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001166#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1168 (when we are able to write or when there's something to read) */
1169 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001170}
1171
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001172static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1173{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 Py_buffer buf;
1175 int len;
1176 int sockstate;
1177 int err;
1178 int nonblocking;
1179 PySocketSockObject *sock
1180 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 if (((PyObject*)sock) == Py_None) {
1183 _setSSLError("Underlying socket connection gone",
1184 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1185 return NULL;
1186 }
1187
1188 if (!PyArg_ParseTuple(args, "y*:write", &buf))
1189 return NULL;
1190
1191 /* just in case the blocking state of the socket has been changed */
1192 nonblocking = (sock->sock_timeout >= 0.0);
1193 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1194 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1195
1196 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1197 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1198 PyErr_SetString(PySSLErrorObject,
1199 "The write operation timed out");
1200 goto error;
1201 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1202 PyErr_SetString(PySSLErrorObject,
1203 "Underlying socket has been closed.");
1204 goto error;
1205 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1206 PyErr_SetString(PySSLErrorObject,
1207 "Underlying socket too large for select().");
1208 goto error;
1209 }
1210 do {
1211 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 if (PyErr_CheckSignals()) {
1217 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001218 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 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 } else {
1226 sockstate = SOCKET_OPERATION_OK;
1227 }
1228 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1229 PyErr_SetString(PySSLErrorObject,
1230 "The write operation timed out");
1231 goto error;
1232 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1233 PyErr_SetString(PySSLErrorObject,
1234 "Underlying socket has been closed.");
1235 goto error;
1236 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1237 break;
1238 }
1239 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 PyBuffer_Release(&buf);
1242 if (len > 0)
1243 return PyLong_FromLong(len);
1244 else
1245 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001246
1247error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 PyBuffer_Release(&buf);
1249 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001250}
1251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001252PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001253"write(s) -> len\n\
1254\n\
1255Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001256of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001257
Bill Janssen6e027db2007-11-15 22:23:56 +00001258static PyObject *PySSL_SSLpending(PySSLObject *self)
1259{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 PySSL_BEGIN_ALLOW_THREADS
1263 count = SSL_pending(self->ssl);
1264 PySSL_END_ALLOW_THREADS
1265 if (count < 0)
1266 return PySSL_SetError(self, count, __FILE__, __LINE__);
1267 else
1268 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001269}
1270
1271PyDoc_STRVAR(PySSL_SSLpending_doc,
1272"pending() -> count\n\
1273\n\
1274Returns the number of already decrypted bytes available for read,\n\
1275pending on the connection.\n");
1276
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001277static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1278{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 PyObject *dest = NULL;
1280 Py_buffer buf;
1281 int buf_passed = 0;
1282 int count = -1;
1283 char *mem;
1284 /* XXX this should use Py_ssize_t */
1285 int len = 1024;
1286 int sockstate;
1287 int err;
1288 int nonblocking;
1289 PySocketSockObject *sock
1290 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 if (((PyObject*)sock) == Py_None) {
1293 _setSSLError("Underlying socket connection gone",
1294 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1295 return NULL;
1296 }
1297
1298 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1299 return NULL;
1300 if ((dest == NULL) || (dest == Py_None)) {
1301 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1302 return NULL;
1303 mem = PyByteArray_AS_STRING(dest);
1304 } else if (PyLong_Check(dest)) {
1305 len = PyLong_AS_LONG(dest);
1306 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1307 return NULL;
1308 mem = PyByteArray_AS_STRING(dest);
1309 } else {
1310 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1311 return NULL;
1312 mem = buf.buf;
1313 len = buf.len;
1314 if ((count > 0) && (count <= len))
1315 len = count;
1316 buf_passed = 1;
1317 }
1318
1319 /* just in case the blocking state of the socket has been changed */
1320 nonblocking = (sock->sock_timeout >= 0.0);
1321 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1322 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 PyErr_SetString(PySSLErrorObject,
1333 "The read operation timed out");
1334 goto error;
1335 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1336 PyErr_SetString(PySSLErrorObject,
1337 "Underlying socket too large for select().");
1338 goto error;
1339 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1340 count = 0;
1341 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001342 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 }
1344 do {
1345 err = 0;
1346 PySSL_BEGIN_ALLOW_THREADS
1347 count = SSL_read(self->ssl, mem, len);
1348 err = SSL_get_error(self->ssl, count);
1349 PySSL_END_ALLOW_THREADS
1350 if (PyErr_CheckSignals())
1351 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 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1359 (SSL_get_shutdown(self->ssl) ==
1360 SSL_RECEIVED_SHUTDOWN))
1361 {
1362 count = 0;
1363 goto done;
1364 } else {
1365 sockstate = SOCKET_OPERATION_OK;
1366 }
1367 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1368 PyErr_SetString(PySSLErrorObject,
1369 "The read operation timed out");
1370 goto error;
1371 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1372 break;
1373 }
1374 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1375 if (count <= 0) {
1376 PySSL_SetError(self, count, __FILE__, __LINE__);
1377 goto error;
1378 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001379 done:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 if (!buf_passed) {
1381 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1382 Py_DECREF(dest);
1383 return res;
1384 } else {
1385 PyBuffer_Release(&buf);
1386 return PyLong_FromLong(count);
1387 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001388 error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 if (!buf_passed) {
1390 Py_DECREF(dest);
1391 } else {
1392 PyBuffer_Release(&buf);
1393 }
1394 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395}
1396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001397PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001398"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001399\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001400Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001401
Bill Janssen40a0f662008-08-12 16:56:25 +00001402static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1403{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 int err, ssl_err, sockstate, nonblocking;
1405 int zeros = 0;
1406 PySocketSockObject *sock
1407 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 /* Guard against closed socket */
1410 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1411 _setSSLError("Underlying socket connection gone",
1412 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1413 return NULL;
1414 }
1415
1416 /* Just in case the blocking state of the socket has been changed */
1417 nonblocking = (sock->sock_timeout >= 0.0);
1418 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1419 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1420
1421 while (1) {
1422 PySSL_BEGIN_ALLOW_THREADS
1423 /* Disable read-ahead so that unwrap can work correctly.
1424 * Otherwise OpenSSL might read in too much data,
1425 * eating clear text data that happens to be
1426 * transmitted after the SSL shutdown.
1427 * Should be safe to call repeatedly everytime this
1428 * function is used and the shutdown_seen_zero != 0
1429 * condition is met.
1430 */
1431 if (self->shutdown_seen_zero)
1432 SSL_set_read_ahead(self->ssl, 0);
1433 err = SSL_shutdown(self->ssl);
1434 PySSL_END_ALLOW_THREADS
1435 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1436 if (err > 0)
1437 break;
1438 if (err == 0) {
1439 /* Don't loop endlessly; instead preserve legacy
1440 behaviour of trying SSL_shutdown() only twice.
1441 This looks necessary for OpenSSL < 0.9.8m */
1442 if (++zeros > 1)
1443 break;
1444 /* Shutdown was sent, now try receiving */
1445 self->shutdown_seen_zero = 1;
1446 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001447 }
1448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 /* Possibly retry shutdown until timeout or failure */
1450 ssl_err = SSL_get_error(self->ssl, err);
1451 if (ssl_err == SSL_ERROR_WANT_READ)
1452 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1453 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1454 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1455 else
1456 break;
1457 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1458 if (ssl_err == SSL_ERROR_WANT_READ)
1459 PyErr_SetString(PySSLErrorObject,
1460 "The read operation timed out");
1461 else
1462 PyErr_SetString(PySSLErrorObject,
1463 "The write operation timed out");
1464 return NULL;
1465 }
1466 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1467 PyErr_SetString(PySSLErrorObject,
1468 "Underlying socket too large for select().");
1469 return NULL;
1470 }
1471 else if (sockstate != SOCKET_OPERATION_OK)
1472 /* Retain the SSL error code */
1473 break;
1474 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 if (err < 0)
1477 return PySSL_SetError(self, err, __FILE__, __LINE__);
1478 else {
1479 Py_INCREF(sock);
1480 return (PyObject *) sock;
1481 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001482}
1483
1484PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1485"shutdown(s) -> socket\n\
1486\n\
1487Does the SSL shutdown handshake with the remote end, and returns\n\
1488the underlying socket object.");
1489
1490
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001491static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 {"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},
1497 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1498 PySSL_SSLpending_doc},
1499 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1500 PySSL_peercert_doc},
1501 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1502 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1503 PySSL_SSLshutdown_doc},
1504 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001505};
1506
Jeremy Hylton938ace62002-07-17 16:30:39 +00001507static PyTypeObject PySSL_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 PyVarObject_HEAD_INIT(NULL, 0)
1509 "ssl.SSLContext", /*tp_name*/
1510 sizeof(PySSLObject), /*tp_basicsize*/
1511 0, /*tp_itemsize*/
1512 /* methods */
1513 (destructor)PySSL_dealloc, /*tp_dealloc*/
1514 0, /*tp_print*/
1515 0, /*tp_getattr*/
1516 0, /*tp_setattr*/
1517 0, /*tp_reserved*/
1518 0, /*tp_repr*/
1519 0, /*tp_as_number*/
1520 0, /*tp_as_sequence*/
1521 0, /*tp_as_mapping*/
1522 0, /*tp_hash*/
1523 0, /*tp_call*/
1524 0, /*tp_str*/
1525 0, /*tp_getattro*/
1526 0, /*tp_setattro*/
1527 0, /*tp_as_buffer*/
1528 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1529 0, /*tp_doc*/
1530 0, /*tp_traverse*/
1531 0, /*tp_clear*/
1532 0, /*tp_richcompare*/
1533 0, /*tp_weaklistoffset*/
1534 0, /*tp_iter*/
1535 0, /*tp_iternext*/
1536 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001537};
1538
1539#ifdef HAVE_OPENSSL_RAND
1540
1541/* helper routines for seeding the SSL PRNG */
1542static PyObject *
1543PySSL_RAND_add(PyObject *self, PyObject *args)
1544{
1545 char *buf;
1546 int len;
1547 double entropy;
1548
1549 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001551 RAND_add(buf, len, entropy);
1552 Py_INCREF(Py_None);
1553 return Py_None;
1554}
1555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001556PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001557"RAND_add(string, entropy)\n\
1558\n\
1559Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001560bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001561
1562static PyObject *
1563PySSL_RAND_status(PyObject *self)
1564{
Christian Heimes217cfd12007-12-02 14:31:20 +00001565 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001566}
1567
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001568PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001569"RAND_status() -> 0 or 1\n\
1570\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001571Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1572It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1573using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001574
1575static PyObject *
1576PySSL_RAND_egd(PyObject *self, PyObject *arg)
1577{
1578 int bytes;
1579
Bill Janssen6e027db2007-11-15 22:23:56 +00001580 if (!PyUnicode_Check(arg))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 return PyErr_Format(PyExc_TypeError,
1582 "RAND_egd() expected string, found %s",
1583 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001584 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001585 if (bytes == -1) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 PyErr_SetString(PySSLErrorObject,
1587 "EGD connection failed or EGD did not return "
1588 "enough data to seed the PRNG");
1589 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001590 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001591 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001592}
1593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001594PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001595"RAND_egd(path) -> bytes\n\
1596\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001597Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1598Returns number of bytes read. Raises SSLError if connection to EGD\n\
1599fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001600
1601#endif
1602
Bill Janssen40a0f662008-08-12 16:56:25 +00001603
1604
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001605/* List of functions exported by this module. */
1606
1607static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001608 {"sslwrap", PySSL_sslwrap,
1609 METH_VARARGS, ssl_doc},
1610 {"_test_decode_cert", PySSL_test_decode_certificate,
1611 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1614 PySSL_RAND_add_doc},
1615 {"RAND_egd", PySSL_RAND_egd, METH_O,
1616 PySSL_RAND_egd_doc},
1617 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1618 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001619#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001621};
1622
1623
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624#ifdef WITH_THREAD
1625
1626/* an implementation of OpenSSL threading operations in terms
1627 of the Python C thread library */
1628
1629static PyThread_type_lock *_ssl_locks = NULL;
1630
1631static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001633}
1634
Bill Janssen6e027db2007-11-15 22:23:56 +00001635static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 (int mode, int n, const char *file, int line) {
1637 /* this function is needed to perform locking on shared data
1638 structures. (Note that OpenSSL uses a number of global data
1639 structures that will be implicitly shared whenever multiple
1640 threads use OpenSSL.) Multi-threaded applications will
1641 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643 locking_function() must be able to handle up to
1644 CRYPTO_num_locks() different mutex locks. It sets the n-th
1645 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 file and line are the file number of the function setting the
1648 lock. They can be useful for debugging.
1649 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001651 if ((_ssl_locks == NULL) ||
1652 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1653 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 if (mode & CRYPTO_LOCK) {
1656 PyThread_acquire_lock(_ssl_locks[n], 1);
1657 } else {
1658 PyThread_release_lock(_ssl_locks[n]);
1659 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660}
1661
1662static int _setup_ssl_threads(void) {
1663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 if (_ssl_locks == NULL) {
1667 _ssl_locks_count = CRYPTO_num_locks();
1668 _ssl_locks = (PyThread_type_lock *)
1669 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1670 if (_ssl_locks == NULL)
1671 return 0;
1672 memset(_ssl_locks, 0,
1673 sizeof(PyThread_type_lock) * _ssl_locks_count);
1674 for (i = 0; i < _ssl_locks_count; i++) {
1675 _ssl_locks[i] = PyThread_allocate_lock();
1676 if (_ssl_locks[i] == NULL) {
1677 unsigned int j;
1678 for (j = 0; j < i; j++) {
1679 PyThread_free_lock(_ssl_locks[j]);
1680 }
1681 free(_ssl_locks);
1682 return 0;
1683 }
1684 }
1685 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1686 CRYPTO_set_id_callback(_ssl_thread_id_function);
1687 }
1688 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689}
1690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001693PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001694"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001695for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001696
Martin v. Löwis1a214512008-06-11 05:26:20 +00001697
1698static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 PyModuleDef_HEAD_INIT,
1700 "_ssl",
1701 module_doc,
1702 -1,
1703 PySSL_methods,
1704 NULL,
1705 NULL,
1706 NULL,
1707 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001708};
1709
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001710PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001711PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001712{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 PyObject *m, *d, *r;
1714 unsigned long libver;
1715 unsigned int major, minor, fix, patch, status;
1716 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001718 if (PyType_Ready(&PySSL_Type) < 0)
1719 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 m = PyModule_Create(&_sslmodule);
1722 if (m == NULL)
1723 return NULL;
1724 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 /* Load _socket module and its C API */
1727 socket_api = PySocketModule_ImportModuleAndAPI();
1728 if (!socket_api)
1729 return NULL;
1730 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 /* Init OpenSSL */
1733 SSL_load_error_strings();
1734 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 /* note that this will start threading if not already started */
1737 if (!_setup_ssl_threads()) {
1738 return NULL;
1739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 /* Add symbols to module dict */
1744 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1745 PySocketModule.error,
1746 NULL);
1747 if (PySSLErrorObject == NULL)
1748 return NULL;
1749 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1750 return NULL;
1751 if (PyDict_SetItemString(d, "SSLType",
1752 (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 PY_SSL_ERROR_SSL);
1766 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1767 PY_SSL_ERROR_WANT_CONNECT);
1768 /* non ssl.h errorcodes */
1769 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1770 PY_SSL_ERROR_EOF);
1771 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1772 PY_SSL_ERROR_INVALID_ERROR_CODE);
1773 /* cert requirements */
1774 PyModule_AddIntConstant(m, "CERT_NONE",
1775 PY_SSL_CERT_NONE);
1776 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1777 PY_SSL_CERT_OPTIONAL);
1778 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1779 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 /* protocol versions */
1782 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1783 PY_SSL_VERSION_SSL2);
1784 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1785 PY_SSL_VERSION_SSL3);
1786 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1787 PY_SSL_VERSION_SSL23);
1788 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1789 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791 /* OpenSSL version */
1792 /* SSLeay() gives us the version of the library linked against,
1793 which could be different from the headers version.
1794 */
1795 libver = SSLeay();
1796 r = PyLong_FromUnsignedLong(libver);
1797 if (r == NULL)
1798 return NULL;
1799 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1800 return NULL;
1801 status = libver & 0xF;
1802 libver >>= 4;
1803 patch = libver & 0xFF;
1804 libver >>= 8;
1805 fix = libver & 0xFF;
1806 libver >>= 8;
1807 minor = libver & 0xFF;
1808 libver >>= 8;
1809 major = libver & 0xFF;
1810 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1811 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1812 return NULL;
1813 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1814 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1815 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001818}