blob: a41fd17cc717ffdd3df7258412cbd8de6b3a660e [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?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000012*/
13
14#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000015
Thomas Wouters1b7f8912007-09-19 03:06:30 +000016#ifdef WITH_THREAD
17#include "pythread.h"
18#define PySSL_BEGIN_ALLOW_THREADS { \
Bill Janssen6e027db2007-11-15 22:23:56 +000019 PyThreadState *_save = NULL; \
Thomas Wouters1b7f8912007-09-19 03:06:30 +000020 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
21#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
22#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
23#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
24 }
25
26#else /* no WITH_THREAD */
27
28#define PySSL_BEGIN_ALLOW_THREADS
29#define PySSL_BLOCK_THREADS
30#define PySSL_UNBLOCK_THREADS
31#define PySSL_END_ALLOW_THREADS
32
33#endif
34
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000035enum py_ssl_error {
36 /* these mirror ssl.h */
Thomas Woutersed03b412007-08-28 21:37:11 +000037 PY_SSL_ERROR_NONE,
38 PY_SSL_ERROR_SSL,
39 PY_SSL_ERROR_WANT_READ,
40 PY_SSL_ERROR_WANT_WRITE,
41 PY_SSL_ERROR_WANT_X509_LOOKUP,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000042 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
Thomas Woutersed03b412007-08-28 21:37:11 +000043 PY_SSL_ERROR_ZERO_RETURN,
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000044 PY_SSL_ERROR_WANT_CONNECT,
Thomas Woutersed03b412007-08-28 21:37:11 +000045 /* start of non ssl.h errorcodes */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000046 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
Bill Janssen54cc54c2007-12-14 22:08:56 +000047 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000048 PY_SSL_ERROR_INVALID_ERROR_CODE
49};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000050
Thomas Woutersed03b412007-08-28 21:37:11 +000051enum py_ssl_server_or_client {
52 PY_SSL_CLIENT,
53 PY_SSL_SERVER
54};
55
56enum py_ssl_cert_requirements {
57 PY_SSL_CERT_NONE,
58 PY_SSL_CERT_OPTIONAL,
59 PY_SSL_CERT_REQUIRED
60};
61
62enum py_ssl_version {
63 PY_SSL_VERSION_SSL2,
64 PY_SSL_VERSION_SSL3,
65 PY_SSL_VERSION_SSL23,
66 PY_SSL_VERSION_TLS1,
67};
68
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000069/* Include symbols from _socket module */
70#include "socketmodule.h"
71
Benjamin Petersonb173f782009-05-05 22:31:58 +000072static PySocketModule_APIObject PySocketModule;
73
Thomas Woutersed03b412007-08-28 21:37:11 +000074#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000075#include <poll.h>
76#elif defined(HAVE_SYS_POLL_H)
77#include <sys/poll.h>
78#endif
79
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000080/* Include OpenSSL header files */
81#include "openssl/rsa.h"
82#include "openssl/crypto.h"
83#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000084#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000085#include "openssl/pem.h"
86#include "openssl/ssl.h"
87#include "openssl/err.h"
88#include "openssl/rand.h"
89
90/* SSL error object */
91static PyObject *PySSLErrorObject;
92
Thomas Wouters1b7f8912007-09-19 03:06:30 +000093#ifdef WITH_THREAD
94
95/* serves as a flag to see whether we've initialized the SSL thread support. */
96/* 0 means no, greater than 0 means yes */
97
98static unsigned int _ssl_locks_count = 0;
99
100#endif /* def WITH_THREAD */
101
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000102/* SSL socket object */
103
104#define X509_NAME_MAXLEN 256
105
106/* RAND_* APIs got added to OpenSSL in 0.9.5 */
107#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
108# define HAVE_OPENSSL_RAND 1
109#else
110# undef HAVE_OPENSSL_RAND
111#endif
112
113typedef struct {
114 PyObject_HEAD
Bill Janssen54cc54c2007-12-14 22:08:56 +0000115 PyObject *Socket; /* weakref to socket on which we're layered */
Thomas Woutersed03b412007-08-28 21:37:11 +0000116 SSL_CTX* ctx;
117 SSL* ssl;
118 X509* peer_cert;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000119
120} PySSLObject;
121
Jeremy Hylton938ace62002-07-17 16:30:39 +0000122static PyTypeObject PySSL_Type;
123static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);
124static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000125static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000126 int writing);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000127static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);
128static PyObject *PySSL_cipher(PySSLObject *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
Christian Heimes90aa7642007-12-19 02:45:37 +0000130#define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000132typedef enum {
133 SOCKET_IS_NONBLOCKING,
134 SOCKET_IS_BLOCKING,
135 SOCKET_HAS_TIMED_OUT,
136 SOCKET_HAS_BEEN_CLOSED,
Neal Norwitz389cea82006-02-13 00:35:21 +0000137 SOCKET_TOO_LARGE_FOR_SELECT,
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000138 SOCKET_OPERATION_OK
139} timeout_state;
140
Thomas Woutersed03b412007-08-28 21:37:11 +0000141/* Wrap error strings with filename and line # */
142#define STRINGIFY1(x) #x
143#define STRINGIFY2(x) STRINGIFY1(x)
144#define ERRSTR1(x,y,z) (x ":" y ": " z)
145#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
146
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147/* XXX It might be helpful to augment the error message generated
148 below with the name of the SSL function that generated the error.
149 I expect it's obvious most of the time.
150*/
151
152static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000153PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000154{
Thomas Woutersed03b412007-08-28 21:37:11 +0000155 PyObject *v;
156 char buf[2048];
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000157 char *errstr;
158 int err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000159 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160
161 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000162
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000163 if (obj->ssl != NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000164 err = SSL_get_error(obj->ssl, ret);
165
166 switch (err) {
167 case SSL_ERROR_ZERO_RETURN:
168 errstr = "TLS/SSL connection has been closed";
169 p = PY_SSL_ERROR_ZERO_RETURN;
170 break;
171 case SSL_ERROR_WANT_READ:
172 errstr = "The operation did not complete (read)";
173 p = PY_SSL_ERROR_WANT_READ;
174 break;
175 case SSL_ERROR_WANT_WRITE:
176 p = PY_SSL_ERROR_WANT_WRITE;
177 errstr = "The operation did not complete (write)";
178 break;
179 case SSL_ERROR_WANT_X509_LOOKUP:
180 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
181 errstr =
182 "The operation did not complete (X509 lookup)";
183 break;
184 case SSL_ERROR_WANT_CONNECT:
185 p = PY_SSL_ERROR_WANT_CONNECT;
186 errstr = "The operation did not complete (connect)";
187 break;
188 case SSL_ERROR_SYSCALL:
189 {
190 unsigned long e = ERR_get_error();
191 if (e == 0) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000192 PySocketSockObject *s
193 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
194 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000195 p = PY_SSL_ERROR_EOF;
196 errstr =
197 "EOF occurred in violation of protocol";
198 } else if (ret == -1) {
199 /* underlying BIO reported an I/O error */
Bill Janssen54cc54c2007-12-14 22:08:56 +0000200 return s->errorhandler();
Thomas Woutersed03b412007-08-28 21:37:11 +0000201 } else { /* possible? */
202 p = PY_SSL_ERROR_SYSCALL;
203 errstr = "Some I/O error occurred";
204 }
205 } else {
Jeremy Hylton4e547302002-07-02 18:25:00 +0000206 p = PY_SSL_ERROR_SYSCALL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000207 /* XXX Protected by global interpreter lock */
208 errstr = ERR_error_string(e, NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000209 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000210 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000211 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000212 case SSL_ERROR_SSL:
213 {
214 unsigned long e = ERR_get_error();
215 p = PY_SSL_ERROR_SSL;
216 if (e != 0)
217 /* XXX Protected by global interpreter lock */
218 errstr = ERR_error_string(e, NULL);
219 else { /* possible? */
220 errstr =
221 "A failure in the SSL library occurred";
222 }
223 break;
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000224 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000225 default:
226 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
227 errstr = "Invalid error code";
228 }
229 } else {
230 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000231 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000232 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
233 v = Py_BuildValue("(is)", p, buf);
234 if (v != NULL) {
235 PyErr_SetObject(PySSLErrorObject, v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000236 Py_DECREF(v);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238 return NULL;
239}
240
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000241static PyObject *
242_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
243
244 char buf[2048];
245 PyObject *v;
246
247 if (errstr == NULL) {
248 errcode = ERR_peek_last_error();
249 errstr = ERR_error_string(errcode, NULL);
250 }
251 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
252 v = Py_BuildValue("(is)", errcode, buf);
253 if (v != NULL) {
254 PyErr_SetObject(PySSLErrorObject, v);
255 Py_DECREF(v);
256 }
257 return NULL;
258}
259
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000260static PySSLObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000261newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,
262 enum py_ssl_server_or_client socket_type,
263 enum py_ssl_cert_requirements certreq,
264 enum py_ssl_version proto_version,
265 char *cacerts_file)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000266{
267 PySSLObject *self;
268 char *errstr = NULL;
269 int ret;
Thomas Woutersed03b412007-08-28 21:37:11 +0000270 int verification_mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000271
Guido van Rossume6650f92007-12-06 19:05:55 +0000272 self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 if (self == NULL)
274 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000275 self->peer_cert = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000276 self->ssl = NULL;
277 self->ctx = NULL;
278 self->Socket = NULL;
279
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000280 /* Make sure the SSL error state is initialized */
281 (void) ERR_get_state();
282 ERR_clear_error();
283
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000284 if ((key_file && !cert_file) || (!key_file && cert_file)) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000285 errstr = ERRSTR("Both the key & certificate files "
286 "must be specified");
287 goto fail;
288 }
289
290 if ((socket_type == PY_SSL_SERVER) &&
291 ((key_file == NULL) || (cert_file == NULL))) {
292 errstr = ERRSTR("Both the key & certificate files "
293 "must be specified for server-side operation");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000294 goto fail;
295 }
296
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000298 if (proto_version == PY_SSL_VERSION_TLS1)
299 self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
300 else if (proto_version == PY_SSL_VERSION_SSL3)
301 self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
302 else if (proto_version == PY_SSL_VERSION_SSL2)
303 self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000304 else if (proto_version == PY_SSL_VERSION_SSL23)
Thomas Woutersed03b412007-08-28 21:37:11 +0000305 self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000306 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000307
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000308 if (self->ctx == NULL) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000309 errstr = ERRSTR("Invalid SSL protocol variant specified.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310 goto fail;
311 }
312
Thomas Woutersed03b412007-08-28 21:37:11 +0000313 if (certreq != PY_SSL_CERT_NONE) {
314 if (cacerts_file == NULL) {
315 errstr = ERRSTR("No root certificates specified for "
316 "verification of other-side certificates.");
317 goto fail;
318 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000319 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000320 ret = SSL_CTX_load_verify_locations(self->ctx,
321 cacerts_file,
322 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000323 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000324 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000325 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000326 goto fail;
327 }
328 }
329 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000330 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000332 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000333 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000335 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000337 goto fail;
338 }
339
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000340 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000341 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 cert_file);
343 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000344 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345 /*
346 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
347 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
348 */
349 if (ERR_peek_last_error() != 0) {
350 _setSSLError(NULL, ret, __FILE__, __LINE__);
351 goto fail;
352 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353 }
354 }
355
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000356 /* ssl compatibility */
357 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
358
Thomas Woutersed03b412007-08-28 21:37:11 +0000359 verification_mode = SSL_VERIFY_NONE;
360 if (certreq == PY_SSL_CERT_OPTIONAL)
361 verification_mode = SSL_VERIFY_PEER;
362 else if (certreq == PY_SSL_CERT_REQUIRED)
363 verification_mode = (SSL_VERIFY_PEER |
364 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
365 SSL_CTX_set_verify(self->ctx, verification_mode,
366 NULL); /* set verify lvl */
367
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000368 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou5f1c38f2010-03-26 19:32:24 +0000372 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000373
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000374 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000375 * to non-blocking mode (blocking is the default)
376 */
377 if (Sock->sock_timeout >= 0.0) {
378 /* Set both the read and write BIO's to non-blocking mode */
379 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
380 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
381 }
382
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000384 if (socket_type == PY_SSL_CLIENT)
385 SSL_set_connect_state(self->ssl);
386 else
387 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000388 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000389
Bill Janssen54cc54c2007-12-14 22:08:56 +0000390 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000391 return self;
392 fail:
393 if (errstr)
394 PyErr_SetString(PySSLErrorObject, errstr);
395 Py_DECREF(self);
396 return NULL;
397}
398
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000399static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000400PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000401{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000402 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000403 int server_side = 0;
404 int verification_mode = PY_SSL_CERT_NONE;
405 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406 char *key_file = NULL;
407 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000408 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000409
Thomas Woutersed03b412007-08-28 21:37:11 +0000410 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000411 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000413 &server_side,
414 &key_file, &cert_file,
415 &verification_mode, &protocol,
416 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000417 return NULL;
418
Thomas Woutersed03b412007-08-28 21:37:11 +0000419 /*
420 fprintf(stderr,
421 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
422 "protocol %d, certs %p\n",
423 server_side, key_file, cert_file, verification_mode,
424 protocol, cacerts_file);
425 */
426
427 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
428 server_side, verification_mode,
429 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000430}
431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000432PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000433"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
434" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000435
436/* SSL object methods */
437
Bill Janssen6e027db2007-11-15 22:23:56 +0000438static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000439{
Bill Janssen6e027db2007-11-15 22:23:56 +0000440 int ret;
441 int err;
442 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443
Bill Janssen6e027db2007-11-15 22:23:56 +0000444 /* Actually negotiate SSL connection */
445 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
446 sockstate = 0;
447 do {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000448 PySocketSockObject *sock
449 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
450 if (((PyObject*)sock) == Py_None) {
451 _setSSLError("Underlying socket connection gone",
452 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
453 return NULL;
454 }
455
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 PySSL_BEGIN_ALLOW_THREADS
457 ret = SSL_do_handshake(self->ssl);
458 err = SSL_get_error(self->ssl, ret);
459 PySSL_END_ALLOW_THREADS
460 if(PyErr_CheckSignals()) {
461 return NULL;
462 }
463 if (err == SSL_ERROR_WANT_READ) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000464 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen6e027db2007-11-15 22:23:56 +0000465 } else if (err == SSL_ERROR_WANT_WRITE) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000466 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen6e027db2007-11-15 22:23:56 +0000467 } else {
468 sockstate = SOCKET_OPERATION_OK;
469 }
470 if (sockstate == SOCKET_HAS_TIMED_OUT) {
471 PyErr_SetString(PySSLErrorObject,
472 ERRSTR("The handshake operation timed out"));
473 return NULL;
474 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
475 PyErr_SetString(PySSLErrorObject,
476 ERRSTR("Underlying socket has been closed."));
477 return NULL;
478 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
479 PyErr_SetString(PySSLErrorObject,
480 ERRSTR("Underlying socket too large for select()."));
481 return NULL;
482 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
483 break;
484 }
485 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
486 if (ret < 1)
487 return PySSL_SetError(self, ret, __FILE__, __LINE__);
488 self->ssl->debug = 1;
489
490 if (self->peer_cert)
491 X509_free (self->peer_cert);
492 PySSL_BEGIN_ALLOW_THREADS
493 self->peer_cert = SSL_get_peer_certificate(self->ssl);
494 PySSL_END_ALLOW_THREADS
495
496 Py_INCREF(Py_None);
497 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000498}
499
Thomas Woutersed03b412007-08-28 21:37:11 +0000500static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000502
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503 char namebuf[X509_NAME_MAXLEN];
504 int buflen;
505 PyObject *name_obj;
506 PyObject *value_obj;
507 PyObject *attr;
508 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000509
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
511 if (buflen < 0) {
512 _setSSLError(NULL, 0, __FILE__, __LINE__);
513 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000514 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000515 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516 if (name_obj == NULL)
517 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000518
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
520 if (buflen < 0) {
521 _setSSLError(NULL, 0, __FILE__, __LINE__);
522 Py_DECREF(name_obj);
523 goto fail;
524 }
525 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
526 buflen, "strict");
527 OPENSSL_free(valuebuf);
528 if (value_obj == NULL) {
529 Py_DECREF(name_obj);
530 goto fail;
531 }
532 attr = PyTuple_New(2);
533 if (attr == NULL) {
534 Py_DECREF(name_obj);
535 Py_DECREF(value_obj);
536 goto fail;
537 }
538 PyTuple_SET_ITEM(attr, 0, name_obj);
539 PyTuple_SET_ITEM(attr, 1, value_obj);
540 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000541
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000543 return NULL;
544}
545
546static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000548{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
550 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
551 PyObject *rdnt;
552 PyObject *attr = NULL; /* tuple to hold an attribute */
553 int entry_count = X509_NAME_entry_count(xname);
554 X509_NAME_ENTRY *entry;
555 ASN1_OBJECT *name;
556 ASN1_STRING *value;
557 int index_counter;
558 int rdn_level = -1;
559 int retcode;
560
561 dn = PyList_New(0);
562 if (dn == NULL)
563 return NULL;
564 /* now create another tuple to hold the top-level RDN */
565 rdn = PyList_New(0);
566 if (rdn == NULL)
567 goto fail0;
568
569 for (index_counter = 0;
570 index_counter < entry_count;
571 index_counter++)
572 {
573 entry = X509_NAME_get_entry(xname, index_counter);
574
575 /* check to see if we've gotten to a new RDN */
576 if (rdn_level >= 0) {
577 if (rdn_level != entry->set) {
578 /* yes, new RDN */
579 /* add old RDN to DN */
580 rdnt = PyList_AsTuple(rdn);
581 Py_DECREF(rdn);
582 if (rdnt == NULL)
583 goto fail0;
584 retcode = PyList_Append(dn, rdnt);
585 Py_DECREF(rdnt);
586 if (retcode < 0)
587 goto fail0;
588 /* create new RDN */
589 rdn = PyList_New(0);
590 if (rdn == NULL)
591 goto fail0;
592 }
593 }
594 rdn_level = entry->set;
595
596 /* now add this attribute to the current RDN */
597 name = X509_NAME_ENTRY_get_object(entry);
598 value = X509_NAME_ENTRY_get_data(entry);
599 attr = _create_tuple_for_attribute(name, value);
600 /*
601 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
602 entry->set,
Christian Heimes72b710a2008-05-26 13:28:38 +0000603 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
604 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605 */
606 if (attr == NULL)
607 goto fail1;
608 retcode = PyList_Append(rdn, attr);
609 Py_DECREF(attr);
610 if (retcode < 0)
611 goto fail1;
612 }
613 /* now, there's typically a dangling RDN */
614 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
615 rdnt = PyList_AsTuple(rdn);
616 Py_DECREF(rdn);
617 if (rdnt == NULL)
618 goto fail0;
619 retcode = PyList_Append(dn, rdnt);
620 Py_DECREF(rdnt);
621 if (retcode < 0)
622 goto fail0;
623 }
624
625 /* convert list to tuple */
626 rdnt = PyList_AsTuple(dn);
627 Py_DECREF(dn);
628 if (rdnt == NULL)
629 return NULL;
630 return rdnt;
631
632 fail1:
633 Py_XDECREF(rdn);
634
635 fail0:
636 Py_XDECREF(dn);
637 return NULL;
638}
639
640static PyObject *
641_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000642
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643 /* this code follows the procedure outlined in
644 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
645 function to extract the STACK_OF(GENERAL_NAME),
646 then iterates through the stack to add the
647 names. */
648
649 int i, j;
650 PyObject *peer_alt_names = Py_None;
651 PyObject *v, *t;
652 X509_EXTENSION *ext = NULL;
653 GENERAL_NAMES *names = NULL;
654 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000655 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656 BIO *biobuf = NULL;
657 char buf[2048];
658 char *vptr;
659 int len;
Victor Stinner7124a412010-03-02 22:48:17 +0000660 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
661#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
662 const unsigned char *p;
663#else
Benjamin Peterson0289b152009-06-28 17:22:03 +0000664 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000665#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
667 if (certificate == NULL)
668 return peer_alt_names;
669
670 /* get a memory buffer */
671 biobuf = BIO_new(BIO_s_mem());
672
673 i = 0;
674 while ((i = X509_get_ext_by_NID(
675 certificate, NID_subject_alt_name, i)) >= 0) {
676
677 if (peer_alt_names == Py_None) {
678 peer_alt_names = PyList_New(0);
679 if (peer_alt_names == NULL)
680 goto fail;
681 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000682
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683 /* now decode the altName */
684 ext = X509_get_ext(certificate, i);
685 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000686 PyErr_SetString
687 (PySSLErrorObject,
688 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689 goto fail;
690 }
691
692 p = ext->value->data;
Christian Heimes412dc9c2008-01-27 18:55:54 +0000693 if (method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000694 names = (GENERAL_NAMES*)
695 (ASN1_item_d2i(NULL,
696 &p,
697 ext->value->length,
698 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000700 names = (GENERAL_NAMES*)
701 (method->d2i(NULL,
702 &p,
703 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704
705 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
706
707 /* get a rendering of each name in the set of names */
708
709 name = sk_GENERAL_NAME_value(names, j);
710 if (name->type == GEN_DIRNAME) {
711
Bill Janssen6e027db2007-11-15 22:23:56 +0000712 /* we special-case DirName as a tuple of
713 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
715 t = PyTuple_New(2);
716 if (t == NULL) {
717 goto fail;
718 }
719
Bill Janssen6e027db2007-11-15 22:23:56 +0000720 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721 if (v == NULL) {
722 Py_DECREF(t);
723 goto fail;
724 }
725 PyTuple_SET_ITEM(t, 0, v);
726
727 v = _create_tuple_for_X509_NAME (name->d.dirn);
728 if (v == NULL) {
729 Py_DECREF(t);
730 goto fail;
731 }
732 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000733
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734 } else {
735
736 /* for everything else, we use the OpenSSL print form */
737
738 (void) BIO_reset(biobuf);
739 GENERAL_NAME_print(biobuf, name);
740 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
741 if (len < 0) {
742 _setSSLError(NULL, 0, __FILE__, __LINE__);
743 goto fail;
744 }
745 vptr = strchr(buf, ':');
746 if (vptr == NULL)
747 goto fail;
748 t = PyTuple_New(2);
749 if (t == NULL)
750 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000751 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752 if (v == NULL) {
753 Py_DECREF(t);
754 goto fail;
755 }
756 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000757 v = PyUnicode_FromStringAndSize((vptr + 1),
758 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759 if (v == NULL) {
760 Py_DECREF(t);
761 goto fail;
762 }
763 PyTuple_SET_ITEM(t, 1, v);
764 }
765
766 /* and add that rendering to the list */
767
768 if (PyList_Append(peer_alt_names, t) < 0) {
769 Py_DECREF(t);
770 goto fail;
771 }
772 Py_DECREF(t);
773 }
774 }
775 BIO_free(biobuf);
776 if (peer_alt_names != Py_None) {
777 v = PyList_AsTuple(peer_alt_names);
778 Py_DECREF(peer_alt_names);
779 return v;
780 } else {
781 return peer_alt_names;
782 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000783
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
785 fail:
786 if (biobuf != NULL)
787 BIO_free(biobuf);
788
789 if (peer_alt_names != Py_None) {
790 Py_XDECREF(peer_alt_names);
791 }
792
793 return NULL;
794}
795
796static PyObject *
797_decode_certificate (X509 *certificate, int verbose) {
798
Thomas Woutersed03b412007-08-28 21:37:11 +0000799 PyObject *retval = NULL;
800 BIO *biobuf = NULL;
801 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000803 PyObject *issuer;
804 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805 PyObject *sn_obj;
806 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000807 char buf[2048];
808 int len;
809 ASN1_TIME *notBefore, *notAfter;
810 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000811
812 retval = PyDict_New();
813 if (retval == NULL)
814 return NULL;
815
Thomas Wouters89d996e2007-09-08 17:39:28 +0000816 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000818 if (peer == NULL)
819 goto fail0;
820 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
821 Py_DECREF(peer);
822 goto fail0;
823 }
824 Py_DECREF(peer);
825
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826 if (verbose) {
827 issuer = _create_tuple_for_X509_NAME(
828 X509_get_issuer_name(certificate));
829 if (issuer == NULL)
830 goto fail0;
831 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
832 Py_DECREF(issuer);
833 goto fail0;
834 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000835 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000836
Christian Heimes217cfd12007-12-02 14:31:20 +0000837 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838 if (PyDict_SetItemString(retval, "version", version) < 0) {
839 Py_DECREF(version);
840 goto fail0;
841 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000842 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000843 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000844
Thomas Woutersed03b412007-08-28 21:37:11 +0000845 /* get a memory buffer */
846 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000847
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000849
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850 (void) BIO_reset(biobuf);
851 serialNumber = X509_get_serialNumber(certificate);
852 /* should not exceed 20 octets, 160 bits, so buf is big enough */
853 i2a_ASN1_INTEGER(biobuf, serialNumber);
854 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
855 if (len < 0) {
856 _setSSLError(NULL, 0, __FILE__, __LINE__);
857 goto fail1;
858 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000859 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860 if (sn_obj == NULL)
861 goto fail1;
862 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
863 Py_DECREF(sn_obj);
864 goto fail1;
865 }
866 Py_DECREF(sn_obj);
867
868 (void) BIO_reset(biobuf);
869 notBefore = X509_get_notBefore(certificate);
870 ASN1_TIME_print(biobuf, notBefore);
871 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
872 if (len < 0) {
873 _setSSLError(NULL, 0, __FILE__, __LINE__);
874 goto fail1;
875 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000876 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877 if (pnotBefore == NULL)
878 goto fail1;
879 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
880 Py_DECREF(pnotBefore);
881 goto fail1;
882 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000883 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000884 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000885
886 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000888 ASN1_TIME_print(biobuf, notAfter);
889 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890 if (len < 0) {
891 _setSSLError(NULL, 0, __FILE__, __LINE__);
892 goto fail1;
893 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000894 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000895 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000897 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
898 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000900 }
901 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902
903 /* Now look for subjectAltName */
904
905 peer_alt_names = _get_peer_alt_names(certificate);
906 if (peer_alt_names == NULL)
907 goto fail1;
908 else if (peer_alt_names != Py_None) {
909 if (PyDict_SetItemString(retval, "subjectAltName",
910 peer_alt_names) < 0) {
911 Py_DECREF(peer_alt_names);
912 goto fail1;
913 }
914 Py_DECREF(peer_alt_names);
915 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000916
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000918 return retval;
919
920 fail1:
921 if (biobuf != NULL)
922 BIO_free(biobuf);
923 fail0:
924 Py_XDECREF(retval);
925 return NULL;
926}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000927
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
929static PyObject *
930PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
931
932 PyObject *retval = NULL;
933 char *filename = NULL;
934 X509 *x=NULL;
935 BIO *cert;
936 int verbose = 1;
937
Bill Janssen6e027db2007-11-15 22:23:56 +0000938 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
939 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940 return NULL;
941
942 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000943 PyErr_SetString(PySSLErrorObject,
944 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945 goto fail0;
946 }
947
948 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000949 PyErr_SetString(PySSLErrorObject,
950 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951 goto fail0;
952 }
953
954 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
955 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000956 PyErr_SetString(PySSLErrorObject,
957 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958 goto fail0;
959 }
960
961 retval = _decode_certificate(x, verbose);
962
963 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000964
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965 if (cert != NULL) BIO_free(cert);
966 return retval;
967}
968
969
970static PyObject *
971PySSL_peercert(PySSLObject *self, PyObject *args)
972{
973 PyObject *retval = NULL;
974 int len;
975 int verification;
976 PyObject *binary_mode = Py_None;
977
978 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
979 return NULL;
980
981 if (!self->peer_cert)
982 Py_RETURN_NONE;
983
984 if (PyObject_IsTrue(binary_mode)) {
985 /* return cert in DER-encoded format */
986
987 unsigned char *bytes_buf = NULL;
988
989 bytes_buf = NULL;
990 len = i2d_X509(self->peer_cert, &bytes_buf);
991 if (len < 0) {
992 PySSL_SetError(self, len, __FILE__, __LINE__);
993 return NULL;
994 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000995 /* this is actually an immutable bytes sequence */
Christian Heimes72b710a2008-05-26 13:28:38 +0000996 retval = PyBytes_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +0000997 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998 OPENSSL_free(bytes_buf);
999 return retval;
1000
1001 } else {
1002
1003 verification = SSL_CTX_get_verify_mode(self->ctx);
1004 if ((verification & SSL_VERIFY_PEER) == 0)
1005 return PyDict_New();
1006 else
1007 return _decode_certificate (self->peer_cert, 0);
1008 }
1009}
1010
1011PyDoc_STRVAR(PySSL_peercert_doc,
1012"peer_certificate([der=False]) -> certificate\n\
1013\n\
1014Returns the certificate for the peer. If no certificate was provided,\n\
1015returns None. If a certificate was provided, but not validated, returns\n\
1016an empty dictionary. Otherwise returns a dict containing information\n\
1017about the peer certificate.\n\
1018\n\
1019If the optional argument is True, returns a DER-encoded copy of the\n\
1020peer certificate, or None if no certificate was provided. This will\n\
1021return the certificate even if it wasn't validated.");
1022
1023static PyObject *PySSL_cipher (PySSLObject *self) {
1024
1025 PyObject *retval, *v;
1026 SSL_CIPHER *current;
1027 char *cipher_name;
1028 char *cipher_protocol;
1029
1030 if (self->ssl == NULL)
1031 return Py_None;
1032 current = SSL_get_current_cipher(self->ssl);
1033 if (current == NULL)
1034 return Py_None;
1035
1036 retval = PyTuple_New(3);
1037 if (retval == NULL)
1038 return NULL;
1039
1040 cipher_name = (char *) SSL_CIPHER_get_name(current);
1041 if (cipher_name == NULL) {
1042 PyTuple_SET_ITEM(retval, 0, Py_None);
1043 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001044 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001045 if (v == NULL)
1046 goto fail0;
1047 PyTuple_SET_ITEM(retval, 0, v);
1048 }
1049 cipher_protocol = SSL_CIPHER_get_version(current);
1050 if (cipher_protocol == NULL) {
1051 PyTuple_SET_ITEM(retval, 1, Py_None);
1052 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001053 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054 if (v == NULL)
1055 goto fail0;
1056 PyTuple_SET_ITEM(retval, 1, v);
1057 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001058 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059 if (v == NULL)
1060 goto fail0;
1061 PyTuple_SET_ITEM(retval, 2, v);
1062 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001063
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064 fail0:
1065 Py_DECREF(retval);
1066 return NULL;
1067}
1068
Guido van Rossume6650f92007-12-06 19:05:55 +00001069static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001070{
Thomas Woutersed03b412007-08-28 21:37:11 +00001071 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossume6650f92007-12-06 19:05:55 +00001072 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001073 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001074 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001075 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001076 SSL_CTX_free(self->ctx);
Guido van Rossume6650f92007-12-06 19:05:55 +00001077 Py_XDECREF(self->Socket);
1078 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001079}
1080
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001081/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001082 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001083 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001084 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001085
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001086static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001087check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001088{
1089 fd_set fds;
1090 struct timeval tv;
1091 int rc;
1092
1093 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001094 if (s->sock_timeout < 0.0)
1095 return SOCKET_IS_BLOCKING;
1096 else if (s->sock_timeout == 0.0)
1097 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001098
1099 /* Guard against closed socket */
1100 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001101 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001102
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001103 /* Prefer poll, if available, since you can poll() any fd
1104 * which can't be done with select(). */
1105#ifdef HAVE_POLL
1106 {
1107 struct pollfd pollfd;
1108 int timeout;
1109
1110 pollfd.fd = s->sock_fd;
1111 pollfd.events = writing ? POLLOUT : POLLIN;
1112
1113 /* s->sock_timeout is in seconds, timeout in ms */
1114 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001115 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001118
1119 goto normal_return;
1120 }
1121#endif
1122
Neal Norwitz082b2df2006-02-07 07:04:46 +00001123 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001124#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001125 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001126 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001127#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001128
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001129 /* Construct the arguments to select */
1130 tv.tv_sec = (int)s->sock_timeout;
1131 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1132 FD_ZERO(&fds);
1133 FD_SET(s->sock_fd, &fds);
1134
1135 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001137 if (writing)
1138 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1139 else
1140 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001142
Bill Janssen6e027db2007-11-15 22:23:56 +00001143#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001144normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001145#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001146 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1147 (when we are able to write or when there's something to read) */
1148 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001149}
1150
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001151static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1152{
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001153 Py_buffer buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001154 int len;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001155 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001156 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001157 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001158 PySocketSockObject *sock
1159 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1160
1161 if (((PyObject*)sock) == Py_None) {
1162 _setSSLError("Underlying socket connection gone",
1163 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1164 return NULL;
1165 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001166
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001167 if (!PyArg_ParseTuple(args, "y*:write", &buf))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001168 return NULL;
1169
Bill Janssen6e027db2007-11-15 22:23:56 +00001170 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001171 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001172 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1173 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1174
Bill Janssen54cc54c2007-12-14 22:08:56 +00001175 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001176 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001177 PyErr_SetString(PySSLErrorObject,
1178 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001179 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001180 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001181 PyErr_SetString(PySSLErrorObject,
1182 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001183 goto error;
Neal Norwitz389cea82006-02-13 00:35:21 +00001184 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001185 PyErr_SetString(PySSLErrorObject,
1186 "Underlying socket too large for select().");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001187 goto error;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001188 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001189 do {
1190 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001192 len = SSL_write(self->ssl, buf.buf, buf.len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001193 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001194 PySSL_END_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001195 if (PyErr_CheckSignals()) {
1196 goto error;
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001197 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001198 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001199 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001200 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001201 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001202 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001203 check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001204 } else {
1205 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001206 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001207 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1208 PyErr_SetString(PySSLErrorObject,
1209 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001210 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001211 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001212 PyErr_SetString(PySSLErrorObject,
1213 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001214 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001215 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1216 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001217 }
1218 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001219
1220 PyBuffer_Release(&buf);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001221 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001222 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001223 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001224 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001225
1226error:
1227 PyBuffer_Release(&buf);
1228 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001229}
1230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001232"write(s) -> len\n\
1233\n\
1234Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001235of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001236
Bill Janssen6e027db2007-11-15 22:23:56 +00001237static PyObject *PySSL_SSLpending(PySSLObject *self)
1238{
1239 int count = 0;
1240
1241 PySSL_BEGIN_ALLOW_THREADS
1242 count = SSL_pending(self->ssl);
1243 PySSL_END_ALLOW_THREADS
1244 if (count < 0)
1245 return PySSL_SetError(self, count, __FILE__, __LINE__);
1246 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001247 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001248}
1249
1250PyDoc_STRVAR(PySSL_SSLpending_doc,
1251"pending() -> count\n\
1252\n\
1253Returns the number of already decrypted bytes available for read,\n\
1254pending on the connection.\n");
1255
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001256static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1257{
Benjamin Peterson56420b42009-02-28 19:06:54 +00001258 PyObject *dest = NULL;
1259 Py_buffer buf;
Bill Janssen6e027db2007-11-15 22:23:56 +00001260 int buf_passed = 0;
1261 int count = -1;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001262 char *mem;
1263 /* XXX this should use Py_ssize_t */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001264 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001265 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001266 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001267 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001268 PySocketSockObject *sock
1269 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1270
1271 if (((PyObject*)sock) == Py_None) {
1272 _setSSLError("Underlying socket connection gone",
1273 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1274 return NULL;
1275 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001276
Benjamin Peterson56420b42009-02-28 19:06:54 +00001277 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001278 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001279 if ((dest == NULL) || (dest == Py_None)) {
1280 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001281 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001282 mem = PyByteArray_AS_STRING(dest);
1283 } else if (PyLong_Check(dest)) {
1284 len = PyLong_AS_LONG(dest);
1285 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001286 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001287 mem = PyByteArray_AS_STRING(dest);
Bill Janssen6e027db2007-11-15 22:23:56 +00001288 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001289 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Bill Janssen6e027db2007-11-15 22:23:56 +00001290 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001291 mem = buf.buf;
1292 len = buf.len;
Bill Janssen6e027db2007-11-15 22:23:56 +00001293 if ((count > 0) && (count <= len))
1294 len = count;
1295 buf_passed = 1;
1296 }
1297
1298 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001299 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001300 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1301 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001302
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001303 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001304 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001305 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001307
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001308 if (!count) {
Bill Janssen54cc54c2007-12-14 22:08:56 +00001309 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001310 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001311 PyErr_SetString(PySSLErrorObject,
1312 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001313 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001314 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001315 PyErr_SetString(PySSLErrorObject,
1316 "Underlying socket too large for select().");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001317 goto error;
Thomas Woutersed03b412007-08-28 21:37:11 +00001318 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001319 count = 0;
1320 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001321 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001322 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001323 do {
1324 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325 PySSL_BEGIN_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001326 count = SSL_read(self->ssl, mem, len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001327 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328 PySSL_END_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001329 if (PyErr_CheckSignals())
1330 goto error;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001331 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001332 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001333 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001334 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001335 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001336 check_socket_and_wait_for_timeout(sock, 1);
Thomas Woutersed03b412007-08-28 21:37:11 +00001337 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1338 (SSL_get_shutdown(self->ssl) ==
1339 SSL_RECEIVED_SHUTDOWN))
1340 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001341 count = 0;
1342 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001343 } else {
1344 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001345 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001346 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001349 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001350 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1351 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001352 }
1353 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001354 if (count <= 0) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001355 PySSL_SetError(self, count, __FILE__, __LINE__);
1356 goto error;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001357 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001358 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001359 if (!buf_passed) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001360 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1361 Py_DECREF(dest);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001362 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001363 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001364 PyBuffer_Release(&buf);
Christian Heimes217cfd12007-12-02 14:31:20 +00001365 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001366 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001367 error:
1368 if (!buf_passed) {
1369 Py_DECREF(dest);
1370 } else {
1371 PyBuffer_Release(&buf);
1372 }
1373 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001374}
1375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001376PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001377"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001379Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001380
Bill Janssen40a0f662008-08-12 16:56:25 +00001381static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1382{
1383 int err;
1384 PySocketSockObject *sock
1385 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1386
1387 /* Guard against closed socket */
1388 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1389 _setSSLError("Underlying socket connection gone",
1390 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1391 return NULL;
1392 }
1393
1394 PySSL_BEGIN_ALLOW_THREADS
1395 err = SSL_shutdown(self->ssl);
1396 if (err == 0) {
1397 /* we need to call it again to finish the shutdown */
1398 err = SSL_shutdown(self->ssl);
1399 }
1400 PySSL_END_ALLOW_THREADS
1401
1402 if (err < 0)
1403 return PySSL_SetError(self, err, __FILE__, __LINE__);
1404 else {
1405 Py_INCREF(sock);
1406 return (PyObject *) sock;
1407 }
1408}
1409
1410PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1411"shutdown(s) -> socket\n\
1412\n\
1413Does the SSL shutdown handshake with the remote end, and returns\n\
1414the underlying socket object.");
1415
1416
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001417static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001418 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001419 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001421 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001423 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1424 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1426 PySSL_peercert_doc},
1427 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Bill Janssen40a0f662008-08-12 16:56:25 +00001428 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1429 PySSL_SSLshutdown_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430 {NULL, NULL}
1431};
1432
Jeremy Hylton938ace62002-07-17 16:30:39 +00001433static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001434 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossume6650f92007-12-06 19:05:55 +00001435 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001436 sizeof(PySSLObject), /*tp_basicsize*/
1437 0, /*tp_itemsize*/
1438 /* methods */
1439 (destructor)PySSL_dealloc, /*tp_dealloc*/
1440 0, /*tp_print*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001441 0, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001442 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00001443 0, /*tp_reserved*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001444 0, /*tp_repr*/
1445 0, /*tp_as_number*/
1446 0, /*tp_as_sequence*/
1447 0, /*tp_as_mapping*/
1448 0, /*tp_hash*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001449 0, /*tp_call*/
1450 0, /*tp_str*/
1451 0, /*tp_getattro*/
1452 0, /*tp_setattro*/
1453 0, /*tp_as_buffer*/
1454 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1455 0, /*tp_doc*/
1456 0, /*tp_traverse*/
1457 0, /*tp_clear*/
1458 0, /*tp_richcompare*/
1459 0, /*tp_weaklistoffset*/
1460 0, /*tp_iter*/
1461 0, /*tp_iternext*/
1462 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001463};
1464
1465#ifdef HAVE_OPENSSL_RAND
1466
1467/* helper routines for seeding the SSL PRNG */
1468static PyObject *
1469PySSL_RAND_add(PyObject *self, PyObject *args)
1470{
1471 char *buf;
1472 int len;
1473 double entropy;
1474
1475 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1476 return NULL;
1477 RAND_add(buf, len, entropy);
1478 Py_INCREF(Py_None);
1479 return Py_None;
1480}
1481
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001482PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001483"RAND_add(string, entropy)\n\
1484\n\
1485Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487
1488static PyObject *
1489PySSL_RAND_status(PyObject *self)
1490{
Christian Heimes217cfd12007-12-02 14:31:20 +00001491 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001492}
1493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001494PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001495"RAND_status() -> 0 or 1\n\
1496\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001497Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1498It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1499using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001500
1501static PyObject *
1502PySSL_RAND_egd(PyObject *self, PyObject *arg)
1503{
1504 int bytes;
1505
Bill Janssen6e027db2007-11-15 22:23:56 +00001506 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001507 return PyErr_Format(PyExc_TypeError,
1508 "RAND_egd() expected string, found %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001509 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001510 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001511 if (bytes == -1) {
1512 PyErr_SetString(PySSLErrorObject,
1513 "EGD connection failed or EGD did not return "
1514 "enough data to seed the PRNG");
1515 return NULL;
1516 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001517 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001518}
1519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001520PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001521"RAND_egd(path) -> bytes\n\
1522\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001523Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1524Returns number of bytes read. Raises SSLError if connection to EGD\n\
1525fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001526
1527#endif
1528
Bill Janssen40a0f662008-08-12 16:56:25 +00001529
1530
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001531/* List of functions exported by this module. */
1532
1533static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001534 {"sslwrap", PySSL_sslwrap,
1535 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536 {"_test_decode_cert", PySSL_test_decode_certificate,
1537 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001538#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001539 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001540 PySSL_RAND_add_doc},
1541 {"RAND_egd", PySSL_RAND_egd, METH_O,
1542 PySSL_RAND_egd_doc},
1543 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1544 PySSL_RAND_status_doc},
1545#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001546 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547};
1548
1549
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001550#ifdef WITH_THREAD
1551
1552/* an implementation of OpenSSL threading operations in terms
1553 of the Python C thread library */
1554
1555static PyThread_type_lock *_ssl_locks = NULL;
1556
1557static unsigned long _ssl_thread_id_function (void) {
1558 return PyThread_get_thread_ident();
1559}
1560
Bill Janssen6e027db2007-11-15 22:23:56 +00001561static void _ssl_thread_locking_function
1562 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001563 /* this function is needed to perform locking on shared data
1564 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001565 structures that will be implicitly shared whenever multiple
1566 threads use OpenSSL.) Multi-threaded applications will
1567 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568
Bill Janssen6e027db2007-11-15 22:23:56 +00001569 locking_function() must be able to handle up to
1570 CRYPTO_num_locks() different mutex locks. It sets the n-th
1571 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572
1573 file and line are the file number of the function setting the
1574 lock. They can be useful for debugging.
1575 */
1576
1577 if ((_ssl_locks == NULL) ||
Christian Heimesba4af492008-03-28 00:55:15 +00001578 (n < 0) || ((unsigned)n >= _ssl_locks_count))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001579 return;
1580
1581 if (mode & CRYPTO_LOCK) {
1582 PyThread_acquire_lock(_ssl_locks[n], 1);
1583 } else {
1584 PyThread_release_lock(_ssl_locks[n]);
1585 }
1586}
1587
1588static int _setup_ssl_threads(void) {
1589
Christian Heimesba4af492008-03-28 00:55:15 +00001590 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591
1592 if (_ssl_locks == NULL) {
1593 _ssl_locks_count = CRYPTO_num_locks();
1594 _ssl_locks = (PyThread_type_lock *)
1595 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1596 if (_ssl_locks == NULL)
1597 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001598 memset(_ssl_locks, 0,
1599 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001600 for (i = 0; i < _ssl_locks_count; i++) {
1601 _ssl_locks[i] = PyThread_allocate_lock();
1602 if (_ssl_locks[i] == NULL) {
Raymond Hettinger26dd7602009-01-26 16:53:29 +00001603 unsigned int j;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604 for (j = 0; j < i; j++) {
1605 PyThread_free_lock(_ssl_locks[j]);
1606 }
1607 free(_ssl_locks);
1608 return 0;
1609 }
1610 }
1611 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1612 CRYPTO_set_id_callback(_ssl_thread_id_function);
1613 }
1614 return 1;
1615}
1616
1617#endif /* def HAVE_THREAD */
1618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001619PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622
Martin v. Löwis1a214512008-06-11 05:26:20 +00001623
1624static struct PyModuleDef _sslmodule = {
1625 PyModuleDef_HEAD_INIT,
1626 "_ssl",
1627 module_doc,
1628 -1,
1629 PySSL_methods,
1630 NULL,
1631 NULL,
1632 NULL,
1633 NULL
1634};
1635
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001636PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001637PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001638{
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001639 PyObject *m, *d, *r;
1640 unsigned long libver;
1641 unsigned int major, minor, fix, patch, status;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001642 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001643
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001644 if (PyType_Ready(&PySSL_Type) < 0)
1645 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001646
Martin v. Löwis1a214512008-06-11 05:26:20 +00001647 m = PyModule_Create(&_sslmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001648 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001649 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001650 d = PyModule_GetDict(m);
1651
1652 /* Load _socket module and its C API */
Benjamin Petersonb173f782009-05-05 22:31:58 +00001653 socket_api = PySocketModule_ImportModuleAndAPI();
1654 if (!socket_api)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001655 return NULL;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001656 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001657
1658 /* Init OpenSSL */
1659 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660#ifdef WITH_THREAD
1661 /* note that this will start threading if not already started */
1662 if (!_setup_ssl_threads()) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00001663 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664 }
1665#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001666 SSLeay_add_ssl_algorithms();
1667
1668 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001670 PySocketModule.error,
1671 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001672 if (PySSLErrorObject == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001673 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001674 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001675 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001676 if (PyDict_SetItemString(d, "SSLType",
1677 (PyObject *)&PySSL_Type) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001678 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001679 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001680 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001681 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001682 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001683 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001684 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001685 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001686 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001687 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001688 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001690 PY_SSL_ERROR_SSL);
1691 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1692 PY_SSL_ERROR_WANT_CONNECT);
1693 /* non ssl.h errorcodes */
1694 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1695 PY_SSL_ERROR_EOF);
1696 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1697 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001698 /* cert requirements */
1699 PyModule_AddIntConstant(m, "CERT_NONE",
1700 PY_SSL_CERT_NONE);
1701 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1702 PY_SSL_CERT_OPTIONAL);
1703 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1704 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001705
Thomas Woutersed03b412007-08-28 21:37:11 +00001706 /* protocol versions */
1707 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1708 PY_SSL_VERSION_SSL2);
1709 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1710 PY_SSL_VERSION_SSL3);
1711 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1712 PY_SSL_VERSION_SSL23);
1713 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1714 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001715
1716 /* OpenSSL version */
1717 /* SSLeay() gives us the version of the library linked against,
1718 which could be different from the headers version.
1719 */
1720 libver = SSLeay();
1721 r = PyLong_FromUnsignedLong(libver);
1722 if (r == NULL)
1723 return NULL;
1724 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1725 return NULL;
1726 status = libver & 0xF;
1727 libver >>= 4;
1728 patch = libver & 0xFF;
1729 libver >>= 8;
1730 fix = libver & 0xFF;
1731 libver >>= 8;
1732 minor = libver & 0xFF;
1733 libver >>= 8;
1734 major = libver & 0xFF;
1735 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1736 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1737 return NULL;
1738 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1739 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1740 return NULL;
1741
Martin v. Löwis1a214512008-06-11 05:26:20 +00001742 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001743}