blob: 9ab184b0304c0ccf21a8cc6e04bdd537dbd90fd9 [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;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000185 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000186 break;
187 case SSL_ERROR_WANT_CONNECT:
188 p = PY_SSL_ERROR_WANT_CONNECT;
189 errstr = "The operation did not complete (connect)";
190 break;
191 case SSL_ERROR_SYSCALL:
192 {
193 unsigned long e = ERR_get_error();
194 if (e == 0) {
195 PySocketSockObject *s
196 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
197 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000198 p = PY_SSL_ERROR_EOF;
199 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000200 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000201 /* underlying BIO reported an I/O error */
202 return s->errorhandler();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000203 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000204 p = PY_SSL_ERROR_SYSCALL;
205 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 }
207 } else {
208 p = PY_SSL_ERROR_SYSCALL;
209 /* XXX Protected by global interpreter lock */
210 errstr = ERR_error_string(e, NULL);
211 }
212 break;
213 }
214 case SSL_ERROR_SSL:
215 {
216 unsigned long e = ERR_get_error();
217 p = PY_SSL_ERROR_SSL;
218 if (e != 0)
219 /* XXX Protected by global interpreter lock */
220 errstr = ERR_error_string(e, NULL);
221 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000222 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000223 }
224 break;
225 }
226 default:
227 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
228 errstr = "Invalid error code";
229 }
230 } else {
231 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
232 }
233 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
234 v = Py_BuildValue("(is)", p, buf);
235 if (v != NULL) {
236 PyErr_SetObject(PySSLErrorObject, v);
237 Py_DECREF(v);
238 }
239 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000240}
241
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000242static PyObject *
243_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000245 char buf[2048];
246 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000248 if (errstr == NULL) {
249 errcode = ERR_peek_last_error();
250 errstr = ERR_error_string(errcode, NULL);
251 }
252 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
253 v = Py_BuildValue("(is)", errcode, buf);
254 if (v != NULL) {
255 PyErr_SetObject(PySSLErrorObject, v);
256 Py_DECREF(v);
257 }
258 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000259}
260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000262newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000263 enum py_ssl_server_or_client socket_type,
264 enum py_ssl_cert_requirements certreq,
265 enum py_ssl_version proto_version,
266 char *cacerts_file, char *ciphers)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000267{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 PySSLObject *self;
269 char *errstr = NULL;
270 int ret;
271 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000273 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
274 if (self == NULL)
275 return NULL;
276 self->peer_cert = NULL;
277 self->ssl = NULL;
278 self->ctx = NULL;
279 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000281 /* Make sure the SSL error state is initialized */
282 (void) ERR_get_state();
283 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000285 if ((key_file && !cert_file) || (!key_file && cert_file)) {
286 errstr = ERRSTR("Both the key & certificate files "
287 "must be specified");
288 goto fail;
289 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000291 if ((socket_type == PY_SSL_SERVER) &&
292 ((key_file == NULL) || (cert_file == NULL))) {
293 errstr = ERRSTR("Both the key & certificate files "
294 "must be specified for server-side operation");
295 goto fail;
296 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PySSL_BEGIN_ALLOW_THREADS
299 if (proto_version == PY_SSL_VERSION_TLS1)
300 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
301 else if (proto_version == PY_SSL_VERSION_SSL3)
302 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
303 else if (proto_version == PY_SSL_VERSION_SSL2)
304 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
305 else if (proto_version == PY_SSL_VERSION_SSL23)
306 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
307 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 if (self->ctx == NULL) {
310 errstr = ERRSTR("Invalid SSL protocol variant specified.");
311 goto fail;
312 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 if (ciphers != NULL) {
315 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
316 if (ret == 0) {
317 errstr = ERRSTR("No cipher can be selected.");
318 goto fail;
319 }
320 }
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 if (certreq != PY_SSL_CERT_NONE) {
323 if (cacerts_file == NULL) {
324 errstr = ERRSTR("No root certificates specified for "
Antoine Pitrou525807b2010-05-12 14:05:24 +0000325 "verification of other-side certificates.");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000326 goto fail;
327 } else {
328 PySSL_BEGIN_ALLOW_THREADS
329 ret = SSL_CTX_load_verify_locations(self->ctx,
330 cacerts_file,
331 NULL);
332 PySSL_END_ALLOW_THREADS
333 if (ret != 1) {
334 _setSSLError(NULL, 0, __FILE__, __LINE__);
335 goto fail;
336 }
337 }
338 }
339 if (key_file) {
340 PySSL_BEGIN_ALLOW_THREADS
341 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
342 SSL_FILETYPE_PEM);
343 PySSL_END_ALLOW_THREADS
344 if (ret != 1) {
345 _setSSLError(NULL, ret, __FILE__, __LINE__);
346 goto fail;
347 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000349 PySSL_BEGIN_ALLOW_THREADS
350 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
351 cert_file);
352 PySSL_END_ALLOW_THREADS
353 if (ret != 1) {
354 /*
355 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
356 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
357 */
358 if (ERR_peek_last_error() != 0) {
359 _setSSLError(NULL, ret, __FILE__, __LINE__);
360 goto fail;
361 }
362 }
363 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000365 /* ssl compatibility */
366 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 verification_mode = SSL_VERIFY_NONE;
369 if (certreq == PY_SSL_CERT_OPTIONAL)
370 verification_mode = SSL_VERIFY_PEER;
371 else if (certreq == PY_SSL_CERT_REQUIRED)
372 verification_mode = (SSL_VERIFY_PEER |
373 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
374 SSL_CTX_set_verify(self->ctx, verification_mode,
375 NULL); /* set verify lvl */
Thomas Woutersed03b412007-08-28 21:37:11 +0000376
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 PySSL_BEGIN_ALLOW_THREADS
378 self->ssl = SSL_new(self->ctx); /* New ssl struct */
379 PySSL_END_ALLOW_THREADS
380 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000381#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000383#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 /* If the socket is in non-blocking mode or timeout mode, set the BIO
386 * to non-blocking mode (blocking is the default)
387 */
388 if (Sock->sock_timeout >= 0.0) {
389 /* Set both the read and write BIO's to non-blocking mode */
390 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
391 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
392 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 PySSL_BEGIN_ALLOW_THREADS
395 if (socket_type == PY_SSL_CLIENT)
396 SSL_set_connect_state(self->ssl);
397 else
398 SSL_set_accept_state(self->ssl);
399 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
402 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 if (errstr)
405 PyErr_SetString(PySSLErrorObject, errstr);
406 Py_DECREF(self);
407 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408}
409
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000411PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000412{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 PySocketSockObject *Sock;
414 int server_side = 0;
415 int verification_mode = PY_SSL_CERT_NONE;
416 int protocol = PY_SSL_VERSION_SSL23;
417 char *key_file = NULL;
418 char *cert_file = NULL;
419 char *cacerts_file = NULL;
420 char *ciphers = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
423 PySocketModule.Sock_Type,
424 &Sock,
425 &server_side,
426 &key_file, &cert_file,
427 &verification_mode, &protocol,
428 &cacerts_file, &ciphers))
429 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000430
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000431 /*
432 fprintf(stderr,
433 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
434 "protocol %d, certs %p\n",
435 server_side, key_file, cert_file, verification_mode,
436 protocol, cacerts_file);
437 */
Thomas Woutersed03b412007-08-28 21:37:11 +0000438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
440 server_side, verification_mode,
441 protocol, cacerts_file,
442 ciphers);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443}
444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000445PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000446"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000447" cacertsfile, ciphers]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448
449/* SSL object methods */
450
Bill Janssen6e027db2007-11-15 22:23:56 +0000451static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000453 int ret;
454 int err;
455 int sockstate, nonblocking;
456 PySocketSockObject *sock
457 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 if (((PyObject*)sock) == Py_None) {
460 _setSSLError("Underlying socket connection gone",
461 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
462 return NULL;
463 }
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 /* just in case the blocking state of the socket has been changed */
466 nonblocking = (sock->sock_timeout >= 0.0);
467 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
468 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000469
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 /* Actually negotiate SSL connection */
471 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
472 sockstate = 0;
473 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000474 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000475 ret = SSL_do_handshake(self->ssl);
476 err = SSL_get_error(self->ssl, ret);
477 PySSL_END_ALLOW_THREADS
478 if(PyErr_CheckSignals()) {
479 return NULL;
480 }
481 if (err == SSL_ERROR_WANT_READ) {
482 sockstate = check_socket_and_wait_for_timeout(sock, 0);
483 } else if (err == SSL_ERROR_WANT_WRITE) {
484 sockstate = check_socket_and_wait_for_timeout(sock, 1);
485 } else {
486 sockstate = SOCKET_OPERATION_OK;
487 }
488 if (sockstate == SOCKET_HAS_TIMED_OUT) {
489 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000490 ERRSTR("The handshake operation timed out"));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 return NULL;
492 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
493 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000494 ERRSTR("Underlying socket has been closed."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 return NULL;
496 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
497 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000498 ERRSTR("Underlying socket too large for select()."));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 return NULL;
500 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
501 break;
502 }
503 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
504 if (ret < 1)
505 return PySSL_SetError(self, ret, __FILE__, __LINE__);
506 self->ssl->debug = 1;
Bill Janssen6e027db2007-11-15 22:23:56 +0000507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 if (self->peer_cert)
509 X509_free (self->peer_cert);
510 PySSL_BEGIN_ALLOW_THREADS
511 self->peer_cert = SSL_get_peer_certificate(self->ssl);
512 PySSL_END_ALLOW_THREADS
513
514 Py_INCREF(Py_None);
515 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000516}
517
Thomas Woutersed03b412007-08-28 21:37:11 +0000518static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 char namebuf[X509_NAME_MAXLEN];
522 int buflen;
523 PyObject *name_obj;
524 PyObject *value_obj;
525 PyObject *attr;
526 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000528 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
529 if (buflen < 0) {
530 _setSSLError(NULL, 0, __FILE__, __LINE__);
531 goto fail;
532 }
533 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
534 if (name_obj == NULL)
535 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000537 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
538 if (buflen < 0) {
539 _setSSLError(NULL, 0, __FILE__, __LINE__);
540 Py_DECREF(name_obj);
541 goto fail;
542 }
543 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000544 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 OPENSSL_free(valuebuf);
546 if (value_obj == NULL) {
547 Py_DECREF(name_obj);
548 goto fail;
549 }
550 attr = PyTuple_New(2);
551 if (attr == NULL) {
552 Py_DECREF(name_obj);
553 Py_DECREF(value_obj);
554 goto fail;
555 }
556 PyTuple_SET_ITEM(attr, 0, name_obj);
557 PyTuple_SET_ITEM(attr, 1, value_obj);
558 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000559
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000562}
563
564static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000566{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
568 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
569 PyObject *rdnt;
570 PyObject *attr = NULL; /* tuple to hold an attribute */
571 int entry_count = X509_NAME_entry_count(xname);
572 X509_NAME_ENTRY *entry;
573 ASN1_OBJECT *name;
574 ASN1_STRING *value;
575 int index_counter;
576 int rdn_level = -1;
577 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 dn = PyList_New(0);
580 if (dn == NULL)
581 return NULL;
582 /* now create another tuple to hold the top-level RDN */
583 rdn = PyList_New(0);
584 if (rdn == NULL)
585 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 for (index_counter = 0;
588 index_counter < entry_count;
589 index_counter++)
590 {
591 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 /* check to see if we've gotten to a new RDN */
594 if (rdn_level >= 0) {
595 if (rdn_level != entry->set) {
596 /* yes, new RDN */
597 /* add old RDN to DN */
598 rdnt = PyList_AsTuple(rdn);
599 Py_DECREF(rdn);
600 if (rdnt == NULL)
601 goto fail0;
602 retcode = PyList_Append(dn, rdnt);
603 Py_DECREF(rdnt);
604 if (retcode < 0)
605 goto fail0;
606 /* create new RDN */
607 rdn = PyList_New(0);
608 if (rdn == NULL)
609 goto fail0;
610 }
611 }
612 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 /* now add this attribute to the current RDN */
615 name = X509_NAME_ENTRY_get_object(entry);
616 value = X509_NAME_ENTRY_get_data(entry);
617 attr = _create_tuple_for_attribute(name, value);
618 /*
619 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
620 entry->set,
621 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
622 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
623 */
624 if (attr == NULL)
625 goto fail1;
626 retcode = PyList_Append(rdn, attr);
627 Py_DECREF(attr);
628 if (retcode < 0)
629 goto fail1;
630 }
631 /* now, there's typically a dangling RDN */
632 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
633 rdnt = PyList_AsTuple(rdn);
634 Py_DECREF(rdn);
635 if (rdnt == NULL)
636 goto fail0;
637 retcode = PyList_Append(dn, rdnt);
638 Py_DECREF(rdnt);
639 if (retcode < 0)
640 goto fail0;
641 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* convert list to tuple */
644 rdnt = PyList_AsTuple(dn);
645 Py_DECREF(dn);
646 if (rdnt == NULL)
647 return NULL;
648 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649
650 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
653 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 Py_XDECREF(dn);
655 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656}
657
658static PyObject *
659_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 /* this code follows the procedure outlined in
662 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
663 function to extract the STACK_OF(GENERAL_NAME),
664 then iterates through the stack to add the
665 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 int i, j;
668 PyObject *peer_alt_names = Py_None;
669 PyObject *v, *t;
670 X509_EXTENSION *ext = NULL;
671 GENERAL_NAMES *names = NULL;
672 GENERAL_NAME *name;
673 X509V3_EXT_METHOD *method;
674 BIO *biobuf = NULL;
675 char buf[2048];
676 char *vptr;
677 int len;
678 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000679#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000681#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000683#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 if (certificate == NULL)
686 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 /* get a memory buffer */
689 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 i = 0;
692 while ((i = X509_get_ext_by_NID(
693 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000695 if (peer_alt_names == Py_None) {
696 peer_alt_names = PyList_New(0);
697 if (peer_alt_names == NULL)
698 goto fail;
699 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 /* now decode the altName */
702 ext = X509_get_ext(certificate, i);
703 if(!(method = X509V3_EXT_get(ext))) {
704 PyErr_SetString
705 (PySSLErrorObject,
706 ERRSTR("No method for internalizing subjectAltName!"));
707 goto fail;
708 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 p = ext->value->data;
711 if (method->it)
712 names = (GENERAL_NAMES*)
713 (ASN1_item_d2i(NULL,
714 &p,
715 ext->value->length,
716 ASN1_ITEM_ptr(method->it)));
717 else
718 names = (GENERAL_NAMES*)
719 (method->d2i(NULL,
720 &p,
721 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 name = sk_GENERAL_NAME_value(names, j);
728 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 /* we special-case DirName as a tuple of
731 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 t = PyTuple_New(2);
734 if (t == NULL) {
735 goto fail;
736 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 v = PyUnicode_FromString("DirName");
739 if (v == NULL) {
740 Py_DECREF(t);
741 goto fail;
742 }
743 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 v = _create_tuple_for_X509_NAME (name->d.dirn);
746 if (v == NULL) {
747 Py_DECREF(t);
748 goto fail;
749 }
750 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 (void) BIO_reset(biobuf);
757 GENERAL_NAME_print(biobuf, name);
758 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
759 if (len < 0) {
760 _setSSLError(NULL, 0, __FILE__, __LINE__);
761 goto fail;
762 }
763 vptr = strchr(buf, ':');
764 if (vptr == NULL)
765 goto fail;
766 t = PyTuple_New(2);
767 if (t == NULL)
768 goto fail;
769 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
770 if (v == NULL) {
771 Py_DECREF(t);
772 goto fail;
773 }
774 PyTuple_SET_ITEM(t, 0, v);
775 v = PyUnicode_FromStringAndSize((vptr + 1),
776 (len - (vptr - buf + 1)));
777 if (v == NULL) {
778 Py_DECREF(t);
779 goto fail;
780 }
781 PyTuple_SET_ITEM(t, 1, v);
782 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 if (PyList_Append(peer_alt_names, t) < 0) {
787 Py_DECREF(t);
788 goto fail;
789 }
790 Py_DECREF(t);
791 }
792 }
793 BIO_free(biobuf);
794 if (peer_alt_names != Py_None) {
795 v = PyList_AsTuple(peer_alt_names);
796 Py_DECREF(peer_alt_names);
797 return v;
798 } else {
799 return peer_alt_names;
800 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000801
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
803 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 if (biobuf != NULL)
805 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 if (peer_alt_names != Py_None) {
808 Py_XDECREF(peer_alt_names);
809 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812}
813
814static PyObject *
815_decode_certificate (X509 *certificate, int verbose) {
816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 PyObject *retval = NULL;
818 BIO *biobuf = NULL;
819 PyObject *peer;
820 PyObject *peer_alt_names = NULL;
821 PyObject *issuer;
822 PyObject *version;
823 PyObject *sn_obj;
824 ASN1_INTEGER *serialNumber;
825 char buf[2048];
826 int len;
827 ASN1_TIME *notBefore, *notAfter;
828 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 retval = PyDict_New();
831 if (retval == NULL)
832 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 peer = _create_tuple_for_X509_NAME(
835 X509_get_subject_name(certificate));
836 if (peer == NULL)
837 goto fail0;
838 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
839 Py_DECREF(peer);
840 goto fail0;
841 }
842 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 if (verbose) {
845 issuer = _create_tuple_for_X509_NAME(
846 X509_get_issuer_name(certificate));
847 if (issuer == NULL)
848 goto fail0;
849 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
850 Py_DECREF(issuer);
851 goto fail0;
852 }
853 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 version = PyLong_FromLong(X509_get_version(certificate) + 1);
856 if (PyDict_SetItemString(retval, "version", version) < 0) {
857 Py_DECREF(version);
858 goto fail0;
859 }
860 Py_DECREF(version);
861 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 /* get a memory buffer */
864 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 (void) BIO_reset(biobuf);
869 serialNumber = X509_get_serialNumber(certificate);
870 /* should not exceed 20 octets, 160 bits, so buf is big enough */
871 i2a_ASN1_INTEGER(biobuf, serialNumber);
872 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
873 if (len < 0) {
874 _setSSLError(NULL, 0, __FILE__, __LINE__);
875 goto fail1;
876 }
877 sn_obj = PyUnicode_FromStringAndSize(buf, len);
878 if (sn_obj == NULL)
879 goto fail1;
880 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
881 Py_DECREF(sn_obj);
882 goto fail1;
883 }
884 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 (void) BIO_reset(biobuf);
887 notBefore = X509_get_notBefore(certificate);
888 ASN1_TIME_print(biobuf, notBefore);
889 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
890 if (len < 0) {
891 _setSSLError(NULL, 0, __FILE__, __LINE__);
892 goto fail1;
893 }
894 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
895 if (pnotBefore == NULL)
896 goto fail1;
897 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
898 Py_DECREF(pnotBefore);
899 goto fail1;
900 }
901 Py_DECREF(pnotBefore);
902 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 (void) BIO_reset(biobuf);
905 notAfter = X509_get_notAfter(certificate);
906 ASN1_TIME_print(biobuf, notAfter);
907 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
908 if (len < 0) {
909 _setSSLError(NULL, 0, __FILE__, __LINE__);
910 goto fail1;
911 }
912 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
913 if (pnotAfter == NULL)
914 goto fail1;
915 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
916 Py_DECREF(pnotAfter);
917 goto fail1;
918 }
919 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 peer_alt_names = _get_peer_alt_names(certificate);
924 if (peer_alt_names == NULL)
925 goto fail1;
926 else if (peer_alt_names != Py_None) {
927 if (PyDict_SetItemString(retval, "subjectAltName",
928 peer_alt_names) < 0) {
929 Py_DECREF(peer_alt_names);
930 goto fail1;
931 }
932 Py_DECREF(peer_alt_names);
933 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 BIO_free(biobuf);
936 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000937
938 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 if (biobuf != NULL)
940 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000941 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 Py_XDECREF(retval);
943 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000944}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000945
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946
947static PyObject *
948PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 PyObject *retval = NULL;
951 char *filename = NULL;
952 X509 *x=NULL;
953 BIO *cert;
954 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
957 &filename, &verbose))
958 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 if ((cert=BIO_new(BIO_s_file())) == NULL) {
961 PyErr_SetString(PySSLErrorObject,
962 "Can't malloc memory to read file");
963 goto fail0;
964 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 if (BIO_read_filename(cert,filename) <= 0) {
967 PyErr_SetString(PySSLErrorObject,
968 "Can't open file");
969 goto fail0;
970 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
973 if (x == NULL) {
974 PyErr_SetString(PySSLErrorObject,
975 "Error decoding PEM-encoded file");
976 goto fail0;
977 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 retval = _decode_certificate(x, verbose);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980
981 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 if (cert != NULL) BIO_free(cert);
984 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985}
986
987
988static PyObject *
989PySSL_peercert(PySSLObject *self, PyObject *args)
990{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 PyObject *retval = NULL;
992 int len;
993 int verification;
994 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
997 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 if (!self->peer_cert)
1000 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 if (PyObject_IsTrue(binary_mode)) {
1003 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 bytes_buf = NULL;
1008 len = i2d_X509(self->peer_cert, &bytes_buf);
1009 if (len < 0) {
1010 PySSL_SetError(self, len, __FILE__, __LINE__);
1011 return NULL;
1012 }
1013 /* this is actually an immutable bytes sequence */
1014 retval = PyBytes_FromStringAndSize
1015 ((const char *) bytes_buf, len);
1016 OPENSSL_free(bytes_buf);
1017 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 verification = SSL_CTX_get_verify_mode(self->ctx);
1022 if ((verification & SSL_VERIFY_PEER) == 0)
1023 return PyDict_New();
1024 else
1025 return _decode_certificate (self->peer_cert, 0);
1026 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001027}
1028
1029PyDoc_STRVAR(PySSL_peercert_doc,
1030"peer_certificate([der=False]) -> certificate\n\
1031\n\
1032Returns the certificate for the peer. If no certificate was provided,\n\
1033returns None. If a certificate was provided, but not validated, returns\n\
1034an empty dictionary. Otherwise returns a dict containing information\n\
1035about the peer certificate.\n\
1036\n\
1037If the optional argument is True, returns a DER-encoded copy of the\n\
1038peer certificate, or None if no certificate was provided. This will\n\
1039return the certificate even if it wasn't validated.");
1040
1041static PyObject *PySSL_cipher (PySSLObject *self) {
1042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 PyObject *retval, *v;
1044 SSL_CIPHER *current;
1045 char *cipher_name;
1046 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 if (self->ssl == NULL)
1049 return Py_None;
1050 current = SSL_get_current_cipher(self->ssl);
1051 if (current == NULL)
1052 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 retval = PyTuple_New(3);
1055 if (retval == NULL)
1056 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 cipher_name = (char *) SSL_CIPHER_get_name(current);
1059 if (cipher_name == NULL) {
1060 PyTuple_SET_ITEM(retval, 0, Py_None);
1061 } else {
1062 v = PyUnicode_FromString(cipher_name);
1063 if (v == NULL)
1064 goto fail0;
1065 PyTuple_SET_ITEM(retval, 0, v);
1066 }
1067 cipher_protocol = SSL_CIPHER_get_version(current);
1068 if (cipher_protocol == NULL) {
1069 PyTuple_SET_ITEM(retval, 1, Py_None);
1070 } else {
1071 v = PyUnicode_FromString(cipher_protocol);
1072 if (v == NULL)
1073 goto fail0;
1074 PyTuple_SET_ITEM(retval, 1, v);
1075 }
1076 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1077 if (v == NULL)
1078 goto fail0;
1079 PyTuple_SET_ITEM(retval, 2, v);
1080 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001081
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 Py_DECREF(retval);
1084 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085}
1086
Guido van Rossume6650f92007-12-06 19:05:55 +00001087static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001088{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (self->peer_cert) /* Possible not to have one? */
1090 X509_free (self->peer_cert);
1091 if (self->ssl)
1092 SSL_free(self->ssl);
1093 if (self->ctx)
1094 SSL_CTX_free(self->ctx);
1095 Py_XDECREF(self->Socket);
1096 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001097}
1098
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001099/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001100 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001101 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001102 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001103
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001104static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001105check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001106{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 fd_set fds;
1108 struct timeval tv;
1109 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1112 if (s->sock_timeout < 0.0)
1113 return SOCKET_IS_BLOCKING;
1114 else if (s->sock_timeout == 0.0)
1115 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 /* Guard against closed socket */
1118 if (s->sock_fd < 0)
1119 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 /* Prefer poll, if available, since you can poll() any fd
1122 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001123#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 {
1125 struct pollfd pollfd;
1126 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001127
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 pollfd.fd = s->sock_fd;
1129 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 /* s->sock_timeout is in seconds, timeout in ms */
1132 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1133 PySSL_BEGIN_ALLOW_THREADS
1134 rc = poll(&pollfd, 1, timeout);
1135 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 goto normal_return;
1138 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001139#endif
1140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001142#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 if (s->sock_fd >= FD_SETSIZE)
1144 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001145#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 /* Construct the arguments to select */
1148 tv.tv_sec = (int)s->sock_timeout;
1149 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1150 FD_ZERO(&fds);
1151 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 /* See if the socket is ready */
1154 PySSL_BEGIN_ALLOW_THREADS
1155 if (writing)
1156 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1157 else
1158 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1159 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001160
Bill Janssen6e027db2007-11-15 22:23:56 +00001161#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001162normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001163#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1165 (when we are able to write or when there's something to read) */
1166 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001167}
1168
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001169static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1170{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 Py_buffer buf;
1172 int len;
1173 int sockstate;
1174 int err;
1175 int nonblocking;
1176 PySocketSockObject *sock
1177 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 if (((PyObject*)sock) == Py_None) {
1180 _setSSLError("Underlying socket connection gone",
1181 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1182 return NULL;
1183 }
1184
1185 if (!PyArg_ParseTuple(args, "y*:write", &buf))
1186 return NULL;
1187
1188 /* just in case the blocking state of the socket has been changed */
1189 nonblocking = (sock->sock_timeout >= 0.0);
1190 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1191 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1192
1193 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1194 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1195 PyErr_SetString(PySSLErrorObject,
1196 "The write operation timed out");
1197 goto error;
1198 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1199 PyErr_SetString(PySSLErrorObject,
1200 "Underlying socket has been closed.");
1201 goto error;
1202 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1203 PyErr_SetString(PySSLErrorObject,
1204 "Underlying socket too large for select().");
1205 goto error;
1206 }
1207 do {
1208 err = 0;
1209 PySSL_BEGIN_ALLOW_THREADS
1210 len = SSL_write(self->ssl, buf.buf, buf.len);
1211 err = SSL_get_error(self->ssl, len);
1212 PySSL_END_ALLOW_THREADS
1213 if (PyErr_CheckSignals()) {
1214 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001215 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001217 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001219 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 } else {
1221 sockstate = SOCKET_OPERATION_OK;
1222 }
1223 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1224 PyErr_SetString(PySSLErrorObject,
1225 "The write operation timed out");
1226 goto error;
1227 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1228 PyErr_SetString(PySSLErrorObject,
1229 "Underlying socket has been closed.");
1230 goto error;
1231 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1232 break;
1233 }
1234 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 PyBuffer_Release(&buf);
1237 if (len > 0)
1238 return PyLong_FromLong(len);
1239 else
1240 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001241
1242error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 PyBuffer_Release(&buf);
1244 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001245}
1246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001248"write(s) -> len\n\
1249\n\
1250Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001251of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001252
Bill Janssen6e027db2007-11-15 22:23:56 +00001253static PyObject *PySSL_SSLpending(PySSLObject *self)
1254{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 PySSL_BEGIN_ALLOW_THREADS
1258 count = SSL_pending(self->ssl);
1259 PySSL_END_ALLOW_THREADS
1260 if (count < 0)
1261 return PySSL_SetError(self, count, __FILE__, __LINE__);
1262 else
1263 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001264}
1265
1266PyDoc_STRVAR(PySSL_SSLpending_doc,
1267"pending() -> count\n\
1268\n\
1269Returns the number of already decrypted bytes available for read,\n\
1270pending on the connection.\n");
1271
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001272static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1273{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 PyObject *dest = NULL;
1275 Py_buffer buf;
1276 int buf_passed = 0;
1277 int count = -1;
1278 char *mem;
1279 /* XXX this should use Py_ssize_t */
1280 int len = 1024;
1281 int sockstate;
1282 int err;
1283 int nonblocking;
1284 PySocketSockObject *sock
1285 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 if (((PyObject*)sock) == Py_None) {
1288 _setSSLError("Underlying socket connection gone",
1289 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1290 return NULL;
1291 }
1292
1293 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
1294 return NULL;
1295 if ((dest == NULL) || (dest == Py_None)) {
1296 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1297 return NULL;
1298 mem = PyByteArray_AS_STRING(dest);
1299 } else if (PyLong_Check(dest)) {
1300 len = PyLong_AS_LONG(dest);
1301 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
1302 return NULL;
1303 mem = PyByteArray_AS_STRING(dest);
1304 } else {
1305 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
1306 return NULL;
1307 mem = buf.buf;
1308 len = buf.len;
1309 if ((count > 0) && (count <= len))
1310 len = count;
1311 buf_passed = 1;
1312 }
1313
1314 /* just in case the blocking state of the socket has been changed */
1315 nonblocking = (sock->sock_timeout >= 0.0);
1316 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1317 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1318
1319 /* first check if there are bytes ready to be read */
1320 PySSL_BEGIN_ALLOW_THREADS
1321 count = SSL_pending(self->ssl);
1322 PySSL_END_ALLOW_THREADS
1323
1324 if (!count) {
1325 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1326 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1327 PyErr_SetString(PySSLErrorObject,
1328 "The read operation timed out");
1329 goto error;
1330 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1331 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001332 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 goto error;
1334 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1335 count = 0;
1336 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001337 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 }
1339 do {
1340 err = 0;
1341 PySSL_BEGIN_ALLOW_THREADS
1342 count = SSL_read(self->ssl, mem, len);
1343 err = SSL_get_error(self->ssl, count);
1344 PySSL_END_ALLOW_THREADS
1345 if (PyErr_CheckSignals())
1346 goto error;
1347 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001348 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001350 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1352 (SSL_get_shutdown(self->ssl) ==
1353 SSL_RECEIVED_SHUTDOWN))
1354 {
1355 count = 0;
1356 goto done;
1357 } else {
1358 sockstate = SOCKET_OPERATION_OK;
1359 }
1360 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1361 PyErr_SetString(PySSLErrorObject,
1362 "The read operation timed out");
1363 goto error;
1364 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1365 break;
1366 }
1367 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1368 if (count <= 0) {
1369 PySSL_SetError(self, count, __FILE__, __LINE__);
1370 goto error;
1371 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001372 done:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 if (!buf_passed) {
1374 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1375 Py_DECREF(dest);
1376 return res;
1377 } else {
1378 PyBuffer_Release(&buf);
1379 return PyLong_FromLong(count);
1380 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001381 error:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 if (!buf_passed) {
1383 Py_DECREF(dest);
1384 } else {
1385 PyBuffer_Release(&buf);
1386 }
1387 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001388}
1389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001390PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001391"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001392\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001393Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001394
Bill Janssen40a0f662008-08-12 16:56:25 +00001395static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1396{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 int err, ssl_err, sockstate, nonblocking;
1398 int zeros = 0;
1399 PySocketSockObject *sock
1400 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001401
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 /* Guard against closed socket */
1403 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1404 _setSSLError("Underlying socket connection gone",
1405 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1406 return NULL;
1407 }
1408
1409 /* Just in case the blocking state of the socket has been changed */
1410 nonblocking = (sock->sock_timeout >= 0.0);
1411 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1412 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1413
1414 while (1) {
1415 PySSL_BEGIN_ALLOW_THREADS
1416 /* Disable read-ahead so that unwrap can work correctly.
1417 * Otherwise OpenSSL might read in too much data,
1418 * eating clear text data that happens to be
1419 * transmitted after the SSL shutdown.
1420 * Should be safe to call repeatedly everytime this
1421 * function is used and the shutdown_seen_zero != 0
1422 * condition is met.
1423 */
1424 if (self->shutdown_seen_zero)
1425 SSL_set_read_ahead(self->ssl, 0);
1426 err = SSL_shutdown(self->ssl);
1427 PySSL_END_ALLOW_THREADS
1428 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1429 if (err > 0)
1430 break;
1431 if (err == 0) {
1432 /* Don't loop endlessly; instead preserve legacy
1433 behaviour of trying SSL_shutdown() only twice.
1434 This looks necessary for OpenSSL < 0.9.8m */
1435 if (++zeros > 1)
1436 break;
1437 /* Shutdown was sent, now try receiving */
1438 self->shutdown_seen_zero = 1;
1439 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001440 }
1441
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 /* Possibly retry shutdown until timeout or failure */
1443 ssl_err = SSL_get_error(self->ssl, err);
1444 if (ssl_err == SSL_ERROR_WANT_READ)
1445 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1446 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1447 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1448 else
1449 break;
1450 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1451 if (ssl_err == SSL_ERROR_WANT_READ)
1452 PyErr_SetString(PySSLErrorObject,
1453 "The read operation timed out");
1454 else
1455 PyErr_SetString(PySSLErrorObject,
1456 "The write operation timed out");
1457 return NULL;
1458 }
1459 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1460 PyErr_SetString(PySSLErrorObject,
1461 "Underlying socket too large for select().");
1462 return NULL;
1463 }
1464 else if (sockstate != SOCKET_OPERATION_OK)
1465 /* Retain the SSL error code */
1466 break;
1467 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 if (err < 0)
1470 return PySSL_SetError(self, err, __FILE__, __LINE__);
1471 else {
1472 Py_INCREF(sock);
1473 return (PyObject *) sock;
1474 }
Bill Janssen40a0f662008-08-12 16:56:25 +00001475}
1476
1477PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1478"shutdown(s) -> socket\n\
1479\n\
1480Does the SSL shutdown handshake with the remote end, and returns\n\
1481the underlying socket object.");
1482
1483
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001484static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1486 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1487 PySSL_SSLwrite_doc},
1488 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1489 PySSL_SSLread_doc},
1490 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1491 PySSL_SSLpending_doc},
1492 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1493 PySSL_peercert_doc},
1494 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1495 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1496 PySSL_SSLshutdown_doc},
1497 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001498};
1499
Jeremy Hylton938ace62002-07-17 16:30:39 +00001500static PyTypeObject PySSL_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 PyVarObject_HEAD_INIT(NULL, 0)
1502 "ssl.SSLContext", /*tp_name*/
1503 sizeof(PySSLObject), /*tp_basicsize*/
1504 0, /*tp_itemsize*/
1505 /* methods */
1506 (destructor)PySSL_dealloc, /*tp_dealloc*/
1507 0, /*tp_print*/
1508 0, /*tp_getattr*/
1509 0, /*tp_setattr*/
1510 0, /*tp_reserved*/
1511 0, /*tp_repr*/
1512 0, /*tp_as_number*/
1513 0, /*tp_as_sequence*/
1514 0, /*tp_as_mapping*/
1515 0, /*tp_hash*/
1516 0, /*tp_call*/
1517 0, /*tp_str*/
1518 0, /*tp_getattro*/
1519 0, /*tp_setattro*/
1520 0, /*tp_as_buffer*/
1521 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1522 0, /*tp_doc*/
1523 0, /*tp_traverse*/
1524 0, /*tp_clear*/
1525 0, /*tp_richcompare*/
1526 0, /*tp_weaklistoffset*/
1527 0, /*tp_iter*/
1528 0, /*tp_iternext*/
1529 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001530};
1531
1532#ifdef HAVE_OPENSSL_RAND
1533
1534/* helper routines for seeding the SSL PRNG */
1535static PyObject *
1536PySSL_RAND_add(PyObject *self, PyObject *args)
1537{
1538 char *buf;
1539 int len;
1540 double entropy;
1541
1542 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001543 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001544 RAND_add(buf, len, entropy);
1545 Py_INCREF(Py_None);
1546 return Py_None;
1547}
1548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001550"RAND_add(string, entropy)\n\
1551\n\
1552Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001553bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001554
1555static PyObject *
1556PySSL_RAND_status(PyObject *self)
1557{
Christian Heimes217cfd12007-12-02 14:31:20 +00001558 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001559}
1560
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001561PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001562"RAND_status() -> 0 or 1\n\
1563\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001564Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1565It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1566using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001567
1568static PyObject *
1569PySSL_RAND_egd(PyObject *self, PyObject *arg)
1570{
1571 int bytes;
1572
Bill Janssen6e027db2007-11-15 22:23:56 +00001573 if (!PyUnicode_Check(arg))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001574 return PyErr_Format(PyExc_TypeError,
1575 "RAND_egd() expected string, found %s",
1576 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001577 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001578 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001579 PyErr_SetString(PySSLErrorObject,
1580 "EGD connection failed or EGD did not return "
1581 "enough data to seed the PRNG");
1582 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001583 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001584 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001585}
1586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001587PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001588"RAND_egd(path) -> bytes\n\
1589\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1591Returns number of bytes read. Raises SSLError if connection to EGD\n\
1592fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001593
1594#endif
1595
Bill Janssen40a0f662008-08-12 16:56:25 +00001596
1597
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001598/* List of functions exported by this module. */
1599
1600static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 {"sslwrap", PySSL_sslwrap,
1602 METH_VARARGS, ssl_doc},
1603 {"_test_decode_cert", PySSL_test_decode_certificate,
1604 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001605#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1607 PySSL_RAND_add_doc},
1608 {"RAND_egd", PySSL_RAND_egd, METH_O,
1609 PySSL_RAND_egd_doc},
1610 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1611 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001612#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001614};
1615
1616
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617#ifdef WITH_THREAD
1618
1619/* an implementation of OpenSSL threading operations in terms
1620 of the Python C thread library */
1621
1622static PyThread_type_lock *_ssl_locks = NULL;
1623
1624static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626}
1627
Bill Janssen6e027db2007-11-15 22:23:56 +00001628static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 (int mode, int n, const char *file, int line) {
1630 /* this function is needed to perform locking on shared data
1631 structures. (Note that OpenSSL uses a number of global data
1632 structures that will be implicitly shared whenever multiple
1633 threads use OpenSSL.) Multi-threaded applications will
1634 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 locking_function() must be able to handle up to
1637 CRYPTO_num_locks() different mutex locks. It sets the n-th
1638 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 file and line are the file number of the function setting the
1641 lock. They can be useful for debugging.
1642 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 if ((_ssl_locks == NULL) ||
1645 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1646 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 if (mode & CRYPTO_LOCK) {
1649 PyThread_acquire_lock(_ssl_locks[n], 1);
1650 } else {
1651 PyThread_release_lock(_ssl_locks[n]);
1652 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001653}
1654
1655static int _setup_ssl_threads(void) {
1656
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001657 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 if (_ssl_locks == NULL) {
1660 _ssl_locks_count = CRYPTO_num_locks();
1661 _ssl_locks = (PyThread_type_lock *)
1662 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1663 if (_ssl_locks == NULL)
1664 return 0;
1665 memset(_ssl_locks, 0,
1666 sizeof(PyThread_type_lock) * _ssl_locks_count);
1667 for (i = 0; i < _ssl_locks_count; i++) {
1668 _ssl_locks[i] = PyThread_allocate_lock();
1669 if (_ssl_locks[i] == NULL) {
1670 unsigned int j;
1671 for (j = 0; j < i; j++) {
1672 PyThread_free_lock(_ssl_locks[j]);
1673 }
1674 free(_ssl_locks);
1675 return 0;
1676 }
1677 }
1678 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1679 CRYPTO_set_id_callback(_ssl_thread_id_function);
1680 }
1681 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682}
1683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001685
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001686PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001687"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001688for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689
Martin v. Löwis1a214512008-06-11 05:26:20 +00001690
1691static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 PyModuleDef_HEAD_INIT,
1693 "_ssl",
1694 module_doc,
1695 -1,
1696 PySSL_methods,
1697 NULL,
1698 NULL,
1699 NULL,
1700 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001701};
1702
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001703PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001704PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001705{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001706 PyObject *m, *d, *r;
1707 unsigned long libver;
1708 unsigned int major, minor, fix, patch, status;
1709 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 if (PyType_Ready(&PySSL_Type) < 0)
1712 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 m = PyModule_Create(&_sslmodule);
1715 if (m == NULL)
1716 return NULL;
1717 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 /* Load _socket module and its C API */
1720 socket_api = PySocketModule_ImportModuleAndAPI();
1721 if (!socket_api)
1722 return NULL;
1723 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 /* Init OpenSSL */
1726 SSL_load_error_strings();
1727 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 /* note that this will start threading if not already started */
1730 if (!_setup_ssl_threads()) {
1731 return NULL;
1732 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 /* Add symbols to module dict */
1737 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1738 PySocketModule.error,
1739 NULL);
1740 if (PySSLErrorObject == NULL)
1741 return NULL;
1742 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1743 return NULL;
1744 if (PyDict_SetItemString(d, "SSLType",
1745 (PyObject *)&PySSL_Type) != 0)
1746 return NULL;
1747 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
1748 PY_SSL_ERROR_ZERO_RETURN);
1749 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
1750 PY_SSL_ERROR_WANT_READ);
1751 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
1752 PY_SSL_ERROR_WANT_WRITE);
1753 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
1754 PY_SSL_ERROR_WANT_X509_LOOKUP);
1755 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
1756 PY_SSL_ERROR_SYSCALL);
1757 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
1758 PY_SSL_ERROR_SSL);
1759 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1760 PY_SSL_ERROR_WANT_CONNECT);
1761 /* non ssl.h errorcodes */
1762 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1763 PY_SSL_ERROR_EOF);
1764 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1765 PY_SSL_ERROR_INVALID_ERROR_CODE);
1766 /* cert requirements */
1767 PyModule_AddIntConstant(m, "CERT_NONE",
1768 PY_SSL_CERT_NONE);
1769 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1770 PY_SSL_CERT_OPTIONAL);
1771 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1772 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 /* protocol versions */
1775 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1776 PY_SSL_VERSION_SSL2);
1777 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1778 PY_SSL_VERSION_SSL3);
1779 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1780 PY_SSL_VERSION_SSL23);
1781 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1782 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 /* OpenSSL version */
1785 /* SSLeay() gives us the version of the library linked against,
1786 which could be different from the headers version.
1787 */
1788 libver = SSLeay();
1789 r = PyLong_FromUnsignedLong(libver);
1790 if (r == NULL)
1791 return NULL;
1792 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1793 return NULL;
1794 status = libver & 0xF;
1795 libver >>= 4;
1796 patch = libver & 0xFF;
1797 libver >>= 8;
1798 fix = libver & 0xFF;
1799 libver >>= 8;
1800 minor = libver & 0xFF;
1801 libver >>= 8;
1802 major = libver & 0xFF;
1803 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1804 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1805 return NULL;
1806 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1807 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1808 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001811}