blob: 5cb7e0a191fee349949b04e383dc96c4155ac491 [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 Pitrou0ae7b582010-04-09 20:42:09 +0000372#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou5f1c38f2010-03-26 19:32:24 +0000373 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000374#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000375
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000376 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000377 * to non-blocking mode (blocking is the default)
378 */
379 if (Sock->sock_timeout >= 0.0) {
380 /* Set both the read and write BIO's to non-blocking mode */
381 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
382 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
383 }
384
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000386 if (socket_type == PY_SSL_CLIENT)
387 SSL_set_connect_state(self->ssl);
388 else
389 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000390 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000391
Bill Janssen54cc54c2007-12-14 22:08:56 +0000392 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000393 return self;
394 fail:
395 if (errstr)
396 PyErr_SetString(PySSLErrorObject, errstr);
397 Py_DECREF(self);
398 return NULL;
399}
400
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000401static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000402PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000405 int server_side = 0;
406 int verification_mode = PY_SSL_CERT_NONE;
407 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408 char *key_file = NULL;
409 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000410 char *cacerts_file = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000411
Thomas Woutersed03b412007-08-28 21:37:11 +0000412 if (!PyArg_ParseTuple(args, "O!i|zziiz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000413 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000414 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000415 &server_side,
416 &key_file, &cert_file,
417 &verification_mode, &protocol,
418 &cacerts_file))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000419 return NULL;
420
Thomas Woutersed03b412007-08-28 21:37:11 +0000421 /*
422 fprintf(stderr,
423 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
424 "protocol %d, certs %p\n",
425 server_side, key_file, cert_file, verification_mode,
426 protocol, cacerts_file);
427 */
428
429 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
430 server_side, verification_mode,
431 protocol, cacerts_file);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000432}
433
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000434PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000435"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
436" cacertsfile]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437
438/* SSL object methods */
439
Bill Janssen6e027db2007-11-15 22:23:56 +0000440static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000441{
Bill Janssen6e027db2007-11-15 22:23:56 +0000442 int ret;
443 int err;
444 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000445
Bill Janssen6e027db2007-11-15 22:23:56 +0000446 /* Actually negotiate SSL connection */
447 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
448 sockstate = 0;
449 do {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000450 PySocketSockObject *sock
451 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
452 if (((PyObject*)sock) == Py_None) {
453 _setSSLError("Underlying socket connection gone",
454 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
455 return NULL;
456 }
457
Bill Janssen6e027db2007-11-15 22:23:56 +0000458 PySSL_BEGIN_ALLOW_THREADS
459 ret = SSL_do_handshake(self->ssl);
460 err = SSL_get_error(self->ssl, ret);
461 PySSL_END_ALLOW_THREADS
462 if(PyErr_CheckSignals()) {
463 return NULL;
464 }
465 if (err == SSL_ERROR_WANT_READ) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000466 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen6e027db2007-11-15 22:23:56 +0000467 } else if (err == SSL_ERROR_WANT_WRITE) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000468 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen6e027db2007-11-15 22:23:56 +0000469 } else {
470 sockstate = SOCKET_OPERATION_OK;
471 }
472 if (sockstate == SOCKET_HAS_TIMED_OUT) {
473 PyErr_SetString(PySSLErrorObject,
474 ERRSTR("The handshake operation timed out"));
475 return NULL;
476 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
477 PyErr_SetString(PySSLErrorObject,
478 ERRSTR("Underlying socket has been closed."));
479 return NULL;
480 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
481 PyErr_SetString(PySSLErrorObject,
482 ERRSTR("Underlying socket too large for select()."));
483 return NULL;
484 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
485 break;
486 }
487 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
488 if (ret < 1)
489 return PySSL_SetError(self, ret, __FILE__, __LINE__);
490 self->ssl->debug = 1;
491
492 if (self->peer_cert)
493 X509_free (self->peer_cert);
494 PySSL_BEGIN_ALLOW_THREADS
495 self->peer_cert = SSL_get_peer_certificate(self->ssl);
496 PySSL_END_ALLOW_THREADS
497
498 Py_INCREF(Py_None);
499 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000500}
501
Thomas Woutersed03b412007-08-28 21:37:11 +0000502static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000504
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505 char namebuf[X509_NAME_MAXLEN];
506 int buflen;
507 PyObject *name_obj;
508 PyObject *value_obj;
509 PyObject *attr;
510 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
513 if (buflen < 0) {
514 _setSSLError(NULL, 0, __FILE__, __LINE__);
515 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000516 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000517 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518 if (name_obj == NULL)
519 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000520
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
522 if (buflen < 0) {
523 _setSSLError(NULL, 0, __FILE__, __LINE__);
524 Py_DECREF(name_obj);
525 goto fail;
526 }
527 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
528 buflen, "strict");
529 OPENSSL_free(valuebuf);
530 if (value_obj == NULL) {
531 Py_DECREF(name_obj);
532 goto fail;
533 }
534 attr = PyTuple_New(2);
535 if (attr == NULL) {
536 Py_DECREF(name_obj);
537 Py_DECREF(value_obj);
538 goto fail;
539 }
540 PyTuple_SET_ITEM(attr, 0, name_obj);
541 PyTuple_SET_ITEM(attr, 1, value_obj);
542 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000543
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000545 return NULL;
546}
547
548static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000550{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
552 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
553 PyObject *rdnt;
554 PyObject *attr = NULL; /* tuple to hold an attribute */
555 int entry_count = X509_NAME_entry_count(xname);
556 X509_NAME_ENTRY *entry;
557 ASN1_OBJECT *name;
558 ASN1_STRING *value;
559 int index_counter;
560 int rdn_level = -1;
561 int retcode;
562
563 dn = PyList_New(0);
564 if (dn == NULL)
565 return NULL;
566 /* now create another tuple to hold the top-level RDN */
567 rdn = PyList_New(0);
568 if (rdn == NULL)
569 goto fail0;
570
571 for (index_counter = 0;
572 index_counter < entry_count;
573 index_counter++)
574 {
575 entry = X509_NAME_get_entry(xname, index_counter);
576
577 /* check to see if we've gotten to a new RDN */
578 if (rdn_level >= 0) {
579 if (rdn_level != entry->set) {
580 /* yes, new RDN */
581 /* add old RDN to DN */
582 rdnt = PyList_AsTuple(rdn);
583 Py_DECREF(rdn);
584 if (rdnt == NULL)
585 goto fail0;
586 retcode = PyList_Append(dn, rdnt);
587 Py_DECREF(rdnt);
588 if (retcode < 0)
589 goto fail0;
590 /* create new RDN */
591 rdn = PyList_New(0);
592 if (rdn == NULL)
593 goto fail0;
594 }
595 }
596 rdn_level = entry->set;
597
598 /* now add this attribute to the current RDN */
599 name = X509_NAME_ENTRY_get_object(entry);
600 value = X509_NAME_ENTRY_get_data(entry);
601 attr = _create_tuple_for_attribute(name, value);
602 /*
603 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
604 entry->set,
Christian Heimes72b710a2008-05-26 13:28:38 +0000605 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
606 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607 */
608 if (attr == NULL)
609 goto fail1;
610 retcode = PyList_Append(rdn, attr);
611 Py_DECREF(attr);
612 if (retcode < 0)
613 goto fail1;
614 }
615 /* now, there's typically a dangling RDN */
616 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
617 rdnt = PyList_AsTuple(rdn);
618 Py_DECREF(rdn);
619 if (rdnt == NULL)
620 goto fail0;
621 retcode = PyList_Append(dn, rdnt);
622 Py_DECREF(rdnt);
623 if (retcode < 0)
624 goto fail0;
625 }
626
627 /* convert list to tuple */
628 rdnt = PyList_AsTuple(dn);
629 Py_DECREF(dn);
630 if (rdnt == NULL)
631 return NULL;
632 return rdnt;
633
634 fail1:
635 Py_XDECREF(rdn);
636
637 fail0:
638 Py_XDECREF(dn);
639 return NULL;
640}
641
642static PyObject *
643_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000644
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645 /* this code follows the procedure outlined in
646 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
647 function to extract the STACK_OF(GENERAL_NAME),
648 then iterates through the stack to add the
649 names. */
650
651 int i, j;
652 PyObject *peer_alt_names = Py_None;
653 PyObject *v, *t;
654 X509_EXTENSION *ext = NULL;
655 GENERAL_NAMES *names = NULL;
656 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000657 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658 BIO *biobuf = NULL;
659 char buf[2048];
660 char *vptr;
661 int len;
Victor Stinner7124a412010-03-02 22:48:17 +0000662 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
663#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
664 const unsigned char *p;
665#else
Benjamin Peterson0289b152009-06-28 17:22:03 +0000666 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000667#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
669 if (certificate == NULL)
670 return peer_alt_names;
671
672 /* get a memory buffer */
673 biobuf = BIO_new(BIO_s_mem());
674
675 i = 0;
676 while ((i = X509_get_ext_by_NID(
677 certificate, NID_subject_alt_name, i)) >= 0) {
678
679 if (peer_alt_names == Py_None) {
680 peer_alt_names = PyList_New(0);
681 if (peer_alt_names == NULL)
682 goto fail;
683 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000684
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685 /* now decode the altName */
686 ext = X509_get_ext(certificate, i);
687 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000688 PyErr_SetString
689 (PySSLErrorObject,
690 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691 goto fail;
692 }
693
694 p = ext->value->data;
Christian Heimes412dc9c2008-01-27 18:55:54 +0000695 if (method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000696 names = (GENERAL_NAMES*)
697 (ASN1_item_d2i(NULL,
698 &p,
699 ext->value->length,
700 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000702 names = (GENERAL_NAMES*)
703 (method->d2i(NULL,
704 &p,
705 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
707 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
708
709 /* get a rendering of each name in the set of names */
710
711 name = sk_GENERAL_NAME_value(names, j);
712 if (name->type == GEN_DIRNAME) {
713
Bill Janssen6e027db2007-11-15 22:23:56 +0000714 /* we special-case DirName as a tuple of
715 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716
717 t = PyTuple_New(2);
718 if (t == NULL) {
719 goto fail;
720 }
721
Bill Janssen6e027db2007-11-15 22:23:56 +0000722 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723 if (v == NULL) {
724 Py_DECREF(t);
725 goto fail;
726 }
727 PyTuple_SET_ITEM(t, 0, v);
728
729 v = _create_tuple_for_X509_NAME (name->d.dirn);
730 if (v == NULL) {
731 Py_DECREF(t);
732 goto fail;
733 }
734 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000735
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736 } else {
737
738 /* for everything else, we use the OpenSSL print form */
739
740 (void) BIO_reset(biobuf);
741 GENERAL_NAME_print(biobuf, name);
742 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
743 if (len < 0) {
744 _setSSLError(NULL, 0, __FILE__, __LINE__);
745 goto fail;
746 }
747 vptr = strchr(buf, ':');
748 if (vptr == NULL)
749 goto fail;
750 t = PyTuple_New(2);
751 if (t == NULL)
752 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000753 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754 if (v == NULL) {
755 Py_DECREF(t);
756 goto fail;
757 }
758 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000759 v = PyUnicode_FromStringAndSize((vptr + 1),
760 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000761 if (v == NULL) {
762 Py_DECREF(t);
763 goto fail;
764 }
765 PyTuple_SET_ITEM(t, 1, v);
766 }
767
768 /* and add that rendering to the list */
769
770 if (PyList_Append(peer_alt_names, t) < 0) {
771 Py_DECREF(t);
772 goto fail;
773 }
774 Py_DECREF(t);
775 }
776 }
777 BIO_free(biobuf);
778 if (peer_alt_names != Py_None) {
779 v = PyList_AsTuple(peer_alt_names);
780 Py_DECREF(peer_alt_names);
781 return v;
782 } else {
783 return peer_alt_names;
784 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000785
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
787 fail:
788 if (biobuf != NULL)
789 BIO_free(biobuf);
790
791 if (peer_alt_names != Py_None) {
792 Py_XDECREF(peer_alt_names);
793 }
794
795 return NULL;
796}
797
798static PyObject *
799_decode_certificate (X509 *certificate, int verbose) {
800
Thomas Woutersed03b412007-08-28 21:37:11 +0000801 PyObject *retval = NULL;
802 BIO *biobuf = NULL;
803 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000805 PyObject *issuer;
806 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 PyObject *sn_obj;
808 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000809 char buf[2048];
810 int len;
811 ASN1_TIME *notBefore, *notAfter;
812 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000813
814 retval = PyDict_New();
815 if (retval == NULL)
816 return NULL;
817
Thomas Wouters89d996e2007-09-08 17:39:28 +0000818 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000820 if (peer == NULL)
821 goto fail0;
822 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
823 Py_DECREF(peer);
824 goto fail0;
825 }
826 Py_DECREF(peer);
827
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828 if (verbose) {
829 issuer = _create_tuple_for_X509_NAME(
830 X509_get_issuer_name(certificate));
831 if (issuer == NULL)
832 goto fail0;
833 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
834 Py_DECREF(issuer);
835 goto fail0;
836 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000837 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000838
Christian Heimes217cfd12007-12-02 14:31:20 +0000839 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840 if (PyDict_SetItemString(retval, "version", version) < 0) {
841 Py_DECREF(version);
842 goto fail0;
843 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000844 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000845 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000846
Thomas Woutersed03b412007-08-28 21:37:11 +0000847 /* get a memory buffer */
848 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000849
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000851
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000852 (void) BIO_reset(biobuf);
853 serialNumber = X509_get_serialNumber(certificate);
854 /* should not exceed 20 octets, 160 bits, so buf is big enough */
855 i2a_ASN1_INTEGER(biobuf, serialNumber);
856 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
857 if (len < 0) {
858 _setSSLError(NULL, 0, __FILE__, __LINE__);
859 goto fail1;
860 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000861 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862 if (sn_obj == NULL)
863 goto fail1;
864 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
865 Py_DECREF(sn_obj);
866 goto fail1;
867 }
868 Py_DECREF(sn_obj);
869
870 (void) BIO_reset(biobuf);
871 notBefore = X509_get_notBefore(certificate);
872 ASN1_TIME_print(biobuf, notBefore);
873 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
874 if (len < 0) {
875 _setSSLError(NULL, 0, __FILE__, __LINE__);
876 goto fail1;
877 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000878 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879 if (pnotBefore == NULL)
880 goto fail1;
881 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
882 Py_DECREF(pnotBefore);
883 goto fail1;
884 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000885 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000886 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000887
888 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000890 ASN1_TIME_print(biobuf, notAfter);
891 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892 if (len < 0) {
893 _setSSLError(NULL, 0, __FILE__, __LINE__);
894 goto fail1;
895 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000896 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000897 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000899 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
900 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000902 }
903 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904
905 /* Now look for subjectAltName */
906
907 peer_alt_names = _get_peer_alt_names(certificate);
908 if (peer_alt_names == NULL)
909 goto fail1;
910 else if (peer_alt_names != Py_None) {
911 if (PyDict_SetItemString(retval, "subjectAltName",
912 peer_alt_names) < 0) {
913 Py_DECREF(peer_alt_names);
914 goto fail1;
915 }
916 Py_DECREF(peer_alt_names);
917 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000918
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000920 return retval;
921
922 fail1:
923 if (biobuf != NULL)
924 BIO_free(biobuf);
925 fail0:
926 Py_XDECREF(retval);
927 return NULL;
928}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000929
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
931static PyObject *
932PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
933
934 PyObject *retval = NULL;
935 char *filename = NULL;
936 X509 *x=NULL;
937 BIO *cert;
938 int verbose = 1;
939
Bill Janssen6e027db2007-11-15 22:23:56 +0000940 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
941 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942 return NULL;
943
944 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000945 PyErr_SetString(PySSLErrorObject,
946 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947 goto fail0;
948 }
949
950 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000951 PyErr_SetString(PySSLErrorObject,
952 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000953 goto fail0;
954 }
955
956 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
957 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000958 PyErr_SetString(PySSLErrorObject,
959 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960 goto fail0;
961 }
962
963 retval = _decode_certificate(x, verbose);
964
965 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000966
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967 if (cert != NULL) BIO_free(cert);
968 return retval;
969}
970
971
972static PyObject *
973PySSL_peercert(PySSLObject *self, PyObject *args)
974{
975 PyObject *retval = NULL;
976 int len;
977 int verification;
978 PyObject *binary_mode = Py_None;
979
980 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
981 return NULL;
982
983 if (!self->peer_cert)
984 Py_RETURN_NONE;
985
986 if (PyObject_IsTrue(binary_mode)) {
987 /* return cert in DER-encoded format */
988
989 unsigned char *bytes_buf = NULL;
990
991 bytes_buf = NULL;
992 len = i2d_X509(self->peer_cert, &bytes_buf);
993 if (len < 0) {
994 PySSL_SetError(self, len, __FILE__, __LINE__);
995 return NULL;
996 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000997 /* this is actually an immutable bytes sequence */
Christian Heimes72b710a2008-05-26 13:28:38 +0000998 retval = PyBytes_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +0000999 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000 OPENSSL_free(bytes_buf);
1001 return retval;
1002
1003 } else {
1004
1005 verification = SSL_CTX_get_verify_mode(self->ctx);
1006 if ((verification & SSL_VERIFY_PEER) == 0)
1007 return PyDict_New();
1008 else
1009 return _decode_certificate (self->peer_cert, 0);
1010 }
1011}
1012
1013PyDoc_STRVAR(PySSL_peercert_doc,
1014"peer_certificate([der=False]) -> certificate\n\
1015\n\
1016Returns the certificate for the peer. If no certificate was provided,\n\
1017returns None. If a certificate was provided, but not validated, returns\n\
1018an empty dictionary. Otherwise returns a dict containing information\n\
1019about the peer certificate.\n\
1020\n\
1021If the optional argument is True, returns a DER-encoded copy of the\n\
1022peer certificate, or None if no certificate was provided. This will\n\
1023return the certificate even if it wasn't validated.");
1024
1025static PyObject *PySSL_cipher (PySSLObject *self) {
1026
1027 PyObject *retval, *v;
1028 SSL_CIPHER *current;
1029 char *cipher_name;
1030 char *cipher_protocol;
1031
1032 if (self->ssl == NULL)
1033 return Py_None;
1034 current = SSL_get_current_cipher(self->ssl);
1035 if (current == NULL)
1036 return Py_None;
1037
1038 retval = PyTuple_New(3);
1039 if (retval == NULL)
1040 return NULL;
1041
1042 cipher_name = (char *) SSL_CIPHER_get_name(current);
1043 if (cipher_name == NULL) {
1044 PyTuple_SET_ITEM(retval, 0, Py_None);
1045 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001046 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047 if (v == NULL)
1048 goto fail0;
1049 PyTuple_SET_ITEM(retval, 0, v);
1050 }
1051 cipher_protocol = SSL_CIPHER_get_version(current);
1052 if (cipher_protocol == NULL) {
1053 PyTuple_SET_ITEM(retval, 1, Py_None);
1054 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001055 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056 if (v == NULL)
1057 goto fail0;
1058 PyTuple_SET_ITEM(retval, 1, v);
1059 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001060 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061 if (v == NULL)
1062 goto fail0;
1063 PyTuple_SET_ITEM(retval, 2, v);
1064 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001065
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066 fail0:
1067 Py_DECREF(retval);
1068 return NULL;
1069}
1070
Guido van Rossume6650f92007-12-06 19:05:55 +00001071static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001072{
Thomas Woutersed03b412007-08-28 21:37:11 +00001073 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossume6650f92007-12-06 19:05:55 +00001074 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001075 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001076 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001077 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001078 SSL_CTX_free(self->ctx);
Guido van Rossume6650f92007-12-06 19:05:55 +00001079 Py_XDECREF(self->Socket);
1080 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001081}
1082
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001083/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001084 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001085 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001086 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001087
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001088static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001089check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001090{
1091 fd_set fds;
1092 struct timeval tv;
1093 int rc;
1094
1095 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001096 if (s->sock_timeout < 0.0)
1097 return SOCKET_IS_BLOCKING;
1098 else if (s->sock_timeout == 0.0)
1099 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001100
1101 /* Guard against closed socket */
1102 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001103 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001104
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105 /* Prefer poll, if available, since you can poll() any fd
1106 * which can't be done with select(). */
1107#ifdef HAVE_POLL
1108 {
1109 struct pollfd pollfd;
1110 int timeout;
1111
1112 pollfd.fd = s->sock_fd;
1113 pollfd.events = writing ? POLLOUT : POLLIN;
1114
1115 /* s->sock_timeout is in seconds, timeout in ms */
1116 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001118 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120
1121 goto normal_return;
1122 }
1123#endif
1124
Neal Norwitz082b2df2006-02-07 07:04:46 +00001125 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001126#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001127 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001128 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001129#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001130
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001131 /* Construct the arguments to select */
1132 tv.tv_sec = (int)s->sock_timeout;
1133 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1134 FD_ZERO(&fds);
1135 FD_SET(s->sock_fd, &fds);
1136
1137 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001139 if (writing)
1140 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1141 else
1142 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001144
Bill Janssen6e027db2007-11-15 22:23:56 +00001145#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001146normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001147#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001148 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1149 (when we are able to write or when there's something to read) */
1150 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001151}
1152
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001153static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1154{
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001155 Py_buffer buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001156 int len;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001157 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001158 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001159 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001160 PySocketSockObject *sock
1161 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1162
1163 if (((PyObject*)sock) == Py_None) {
1164 _setSSLError("Underlying socket connection gone",
1165 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1166 return NULL;
1167 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001168
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001169 if (!PyArg_ParseTuple(args, "y*:write", &buf))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001170 return NULL;
1171
Bill Janssen6e027db2007-11-15 22:23:56 +00001172 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001173 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001174 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1175 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1176
Bill Janssen54cc54c2007-12-14 22:08:56 +00001177 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001178 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001179 PyErr_SetString(PySSLErrorObject,
1180 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001181 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001182 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001183 PyErr_SetString(PySSLErrorObject,
1184 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001185 goto error;
Neal Norwitz389cea82006-02-13 00:35:21 +00001186 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001187 PyErr_SetString(PySSLErrorObject,
1188 "Underlying socket too large for select().");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001189 goto error;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001190 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001191 do {
1192 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001194 len = SSL_write(self->ssl, buf.buf, buf.len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001195 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196 PySSL_END_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001197 if (PyErr_CheckSignals()) {
1198 goto error;
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001199 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001200 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001201 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001202 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001203 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001204 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001205 check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001206 } else {
1207 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001208 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001209 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1210 PyErr_SetString(PySSLErrorObject,
1211 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001212 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001213 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001214 PyErr_SetString(PySSLErrorObject,
1215 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001216 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001217 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1218 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001219 }
1220 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001221
1222 PyBuffer_Release(&buf);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001223 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001224 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001225 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001226 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001227
1228error:
1229 PyBuffer_Release(&buf);
1230 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001231}
1232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001233PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001234"write(s) -> len\n\
1235\n\
1236Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001237of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001238
Bill Janssen6e027db2007-11-15 22:23:56 +00001239static PyObject *PySSL_SSLpending(PySSLObject *self)
1240{
1241 int count = 0;
1242
1243 PySSL_BEGIN_ALLOW_THREADS
1244 count = SSL_pending(self->ssl);
1245 PySSL_END_ALLOW_THREADS
1246 if (count < 0)
1247 return PySSL_SetError(self, count, __FILE__, __LINE__);
1248 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001249 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001250}
1251
1252PyDoc_STRVAR(PySSL_SSLpending_doc,
1253"pending() -> count\n\
1254\n\
1255Returns the number of already decrypted bytes available for read,\n\
1256pending on the connection.\n");
1257
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001258static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1259{
Benjamin Peterson56420b42009-02-28 19:06:54 +00001260 PyObject *dest = NULL;
1261 Py_buffer buf;
Bill Janssen6e027db2007-11-15 22:23:56 +00001262 int buf_passed = 0;
1263 int count = -1;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001264 char *mem;
1265 /* XXX this should use Py_ssize_t */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001266 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001267 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001268 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001269 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001270 PySocketSockObject *sock
1271 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1272
1273 if (((PyObject*)sock) == Py_None) {
1274 _setSSLError("Underlying socket connection gone",
1275 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1276 return NULL;
1277 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001278
Benjamin Peterson56420b42009-02-28 19:06:54 +00001279 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001280 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001281 if ((dest == NULL) || (dest == Py_None)) {
1282 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001283 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001284 mem = PyByteArray_AS_STRING(dest);
1285 } else if (PyLong_Check(dest)) {
1286 len = PyLong_AS_LONG(dest);
1287 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001288 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001289 mem = PyByteArray_AS_STRING(dest);
Bill Janssen6e027db2007-11-15 22:23:56 +00001290 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001291 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Bill Janssen6e027db2007-11-15 22:23:56 +00001292 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001293 mem = buf.buf;
1294 len = buf.len;
Bill Janssen6e027db2007-11-15 22:23:56 +00001295 if ((count > 0) && (count <= len))
1296 len = count;
1297 buf_passed = 1;
1298 }
1299
1300 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001301 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001302 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1303 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001304
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001305 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001307 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001309
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001310 if (!count) {
Bill Janssen54cc54c2007-12-14 22:08:56 +00001311 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001312 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001313 PyErr_SetString(PySSLErrorObject,
1314 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001315 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001316 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001317 PyErr_SetString(PySSLErrorObject,
1318 "Underlying socket too large for select().");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001319 goto error;
Thomas Woutersed03b412007-08-28 21:37:11 +00001320 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001321 count = 0;
1322 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001323 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001324 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001325 do {
1326 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327 PySSL_BEGIN_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001328 count = SSL_read(self->ssl, mem, len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001329 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330 PySSL_END_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001331 if (PyErr_CheckSignals())
1332 goto error;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001333 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001334 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001335 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001336 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001337 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001338 check_socket_and_wait_for_timeout(sock, 1);
Thomas Woutersed03b412007-08-28 21:37:11 +00001339 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1340 (SSL_get_shutdown(self->ssl) ==
1341 SSL_RECEIVED_SHUTDOWN))
1342 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001343 count = 0;
1344 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001345 } else {
1346 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001347 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001348 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1349 PyErr_SetString(PySSLErrorObject,
1350 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001351 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001352 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1353 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001354 }
1355 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001356 if (count <= 0) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001357 PySSL_SetError(self, count, __FILE__, __LINE__);
1358 goto error;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001359 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001360 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001361 if (!buf_passed) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001362 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1363 Py_DECREF(dest);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001364 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001365 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001366 PyBuffer_Release(&buf);
Christian Heimes217cfd12007-12-02 14:31:20 +00001367 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001368 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001369 error:
1370 if (!buf_passed) {
1371 Py_DECREF(dest);
1372 } else {
1373 PyBuffer_Release(&buf);
1374 }
1375 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001376}
1377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001378PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001379"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001380\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001381Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001382
Bill Janssen40a0f662008-08-12 16:56:25 +00001383static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1384{
1385 int err;
1386 PySocketSockObject *sock
1387 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1388
1389 /* Guard against closed socket */
1390 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1391 _setSSLError("Underlying socket connection gone",
1392 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1393 return NULL;
1394 }
1395
1396 PySSL_BEGIN_ALLOW_THREADS
1397 err = SSL_shutdown(self->ssl);
1398 if (err == 0) {
1399 /* we need to call it again to finish the shutdown */
1400 err = SSL_shutdown(self->ssl);
1401 }
1402 PySSL_END_ALLOW_THREADS
1403
1404 if (err < 0)
1405 return PySSL_SetError(self, err, __FILE__, __LINE__);
1406 else {
1407 Py_INCREF(sock);
1408 return (PyObject *) sock;
1409 }
1410}
1411
1412PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1413"shutdown(s) -> socket\n\
1414\n\
1415Does the SSL shutdown handshake with the remote end, and returns\n\
1416the underlying socket object.");
1417
1418
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001419static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001420 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001421 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001423 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001425 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1426 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1428 PySSL_peercert_doc},
1429 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Bill Janssen40a0f662008-08-12 16:56:25 +00001430 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1431 PySSL_SSLshutdown_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001432 {NULL, NULL}
1433};
1434
Jeremy Hylton938ace62002-07-17 16:30:39 +00001435static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001436 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossume6650f92007-12-06 19:05:55 +00001437 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001438 sizeof(PySSLObject), /*tp_basicsize*/
1439 0, /*tp_itemsize*/
1440 /* methods */
1441 (destructor)PySSL_dealloc, /*tp_dealloc*/
1442 0, /*tp_print*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001443 0, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001444 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00001445 0, /*tp_reserved*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001446 0, /*tp_repr*/
1447 0, /*tp_as_number*/
1448 0, /*tp_as_sequence*/
1449 0, /*tp_as_mapping*/
1450 0, /*tp_hash*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001451 0, /*tp_call*/
1452 0, /*tp_str*/
1453 0, /*tp_getattro*/
1454 0, /*tp_setattro*/
1455 0, /*tp_as_buffer*/
1456 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1457 0, /*tp_doc*/
1458 0, /*tp_traverse*/
1459 0, /*tp_clear*/
1460 0, /*tp_richcompare*/
1461 0, /*tp_weaklistoffset*/
1462 0, /*tp_iter*/
1463 0, /*tp_iternext*/
1464 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001465};
1466
1467#ifdef HAVE_OPENSSL_RAND
1468
1469/* helper routines for seeding the SSL PRNG */
1470static PyObject *
1471PySSL_RAND_add(PyObject *self, PyObject *args)
1472{
1473 char *buf;
1474 int len;
1475 double entropy;
1476
1477 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1478 return NULL;
1479 RAND_add(buf, len, entropy);
1480 Py_INCREF(Py_None);
1481 return Py_None;
1482}
1483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485"RAND_add(string, entropy)\n\
1486\n\
1487Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001488bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001489
1490static PyObject *
1491PySSL_RAND_status(PyObject *self)
1492{
Christian Heimes217cfd12007-12-02 14:31:20 +00001493 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001494}
1495
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001496PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001497"RAND_status() -> 0 or 1\n\
1498\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001499Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1500It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1501using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001502
1503static PyObject *
1504PySSL_RAND_egd(PyObject *self, PyObject *arg)
1505{
1506 int bytes;
1507
Bill Janssen6e027db2007-11-15 22:23:56 +00001508 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001509 return PyErr_Format(PyExc_TypeError,
1510 "RAND_egd() expected string, found %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001511 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001512 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001513 if (bytes == -1) {
1514 PyErr_SetString(PySSLErrorObject,
1515 "EGD connection failed or EGD did not return "
1516 "enough data to seed the PRNG");
1517 return NULL;
1518 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001519 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001520}
1521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001522PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001523"RAND_egd(path) -> bytes\n\
1524\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1526Returns number of bytes read. Raises SSLError if connection to EGD\n\
1527fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001528
1529#endif
1530
Bill Janssen40a0f662008-08-12 16:56:25 +00001531
1532
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001533/* List of functions exported by this module. */
1534
1535static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001536 {"sslwrap", PySSL_sslwrap,
1537 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538 {"_test_decode_cert", PySSL_test_decode_certificate,
1539 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001540#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001541 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001542 PySSL_RAND_add_doc},
1543 {"RAND_egd", PySSL_RAND_egd, METH_O,
1544 PySSL_RAND_egd_doc},
1545 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1546 PySSL_RAND_status_doc},
1547#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001548 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001549};
1550
1551
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552#ifdef WITH_THREAD
1553
1554/* an implementation of OpenSSL threading operations in terms
1555 of the Python C thread library */
1556
1557static PyThread_type_lock *_ssl_locks = NULL;
1558
1559static unsigned long _ssl_thread_id_function (void) {
1560 return PyThread_get_thread_ident();
1561}
1562
Bill Janssen6e027db2007-11-15 22:23:56 +00001563static void _ssl_thread_locking_function
1564 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565 /* this function is needed to perform locking on shared data
1566 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001567 structures that will be implicitly shared whenever multiple
1568 threads use OpenSSL.) Multi-threaded applications will
1569 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570
Bill Janssen6e027db2007-11-15 22:23:56 +00001571 locking_function() must be able to handle up to
1572 CRYPTO_num_locks() different mutex locks. It sets the n-th
1573 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574
1575 file and line are the file number of the function setting the
1576 lock. They can be useful for debugging.
1577 */
1578
1579 if ((_ssl_locks == NULL) ||
Christian Heimesba4af492008-03-28 00:55:15 +00001580 (n < 0) || ((unsigned)n >= _ssl_locks_count))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581 return;
1582
1583 if (mode & CRYPTO_LOCK) {
1584 PyThread_acquire_lock(_ssl_locks[n], 1);
1585 } else {
1586 PyThread_release_lock(_ssl_locks[n]);
1587 }
1588}
1589
1590static int _setup_ssl_threads(void) {
1591
Christian Heimesba4af492008-03-28 00:55:15 +00001592 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001593
1594 if (_ssl_locks == NULL) {
1595 _ssl_locks_count = CRYPTO_num_locks();
1596 _ssl_locks = (PyThread_type_lock *)
1597 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1598 if (_ssl_locks == NULL)
1599 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001600 memset(_ssl_locks, 0,
1601 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001602 for (i = 0; i < _ssl_locks_count; i++) {
1603 _ssl_locks[i] = PyThread_allocate_lock();
1604 if (_ssl_locks[i] == NULL) {
Raymond Hettinger26dd7602009-01-26 16:53:29 +00001605 unsigned int j;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001606 for (j = 0; j < i; j++) {
1607 PyThread_free_lock(_ssl_locks[j]);
1608 }
1609 free(_ssl_locks);
1610 return 0;
1611 }
1612 }
1613 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1614 CRYPTO_set_id_callback(_ssl_thread_id_function);
1615 }
1616 return 1;
1617}
1618
1619#endif /* def HAVE_THREAD */
1620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001622"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001623for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001624
Martin v. Löwis1a214512008-06-11 05:26:20 +00001625
1626static struct PyModuleDef _sslmodule = {
1627 PyModuleDef_HEAD_INIT,
1628 "_ssl",
1629 module_doc,
1630 -1,
1631 PySSL_methods,
1632 NULL,
1633 NULL,
1634 NULL,
1635 NULL
1636};
1637
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001638PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001639PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001640{
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001641 PyObject *m, *d, *r;
1642 unsigned long libver;
1643 unsigned int major, minor, fix, patch, status;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001644 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001645
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001646 if (PyType_Ready(&PySSL_Type) < 0)
1647 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001648
Martin v. Löwis1a214512008-06-11 05:26:20 +00001649 m = PyModule_Create(&_sslmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001650 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001651 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001652 d = PyModule_GetDict(m);
1653
1654 /* Load _socket module and its C API */
Benjamin Petersonb173f782009-05-05 22:31:58 +00001655 socket_api = PySocketModule_ImportModuleAndAPI();
1656 if (!socket_api)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001657 return NULL;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001658 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001659
1660 /* Init OpenSSL */
1661 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662#ifdef WITH_THREAD
1663 /* note that this will start threading if not already started */
1664 if (!_setup_ssl_threads()) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00001665 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001666 }
1667#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001668 SSLeay_add_ssl_algorithms();
1669
1670 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001672 PySocketModule.error,
1673 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001674 if (PySSLErrorObject == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001675 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001677 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001678 if (PyDict_SetItemString(d, "SSLType",
1679 (PyObject *)&PySSL_Type) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001680 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001681 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001682 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001683 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001684 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001685 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001686 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001687 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001688 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001690 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001691 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001692 PY_SSL_ERROR_SSL);
1693 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1694 PY_SSL_ERROR_WANT_CONNECT);
1695 /* non ssl.h errorcodes */
1696 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1697 PY_SSL_ERROR_EOF);
1698 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1699 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001700 /* cert requirements */
1701 PyModule_AddIntConstant(m, "CERT_NONE",
1702 PY_SSL_CERT_NONE);
1703 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1704 PY_SSL_CERT_OPTIONAL);
1705 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1706 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001707
Thomas Woutersed03b412007-08-28 21:37:11 +00001708 /* protocol versions */
1709 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1710 PY_SSL_VERSION_SSL2);
1711 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1712 PY_SSL_VERSION_SSL3);
1713 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1714 PY_SSL_VERSION_SSL23);
1715 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1716 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001717
1718 /* OpenSSL version */
1719 /* SSLeay() gives us the version of the library linked against,
1720 which could be different from the headers version.
1721 */
1722 libver = SSLeay();
1723 r = PyLong_FromUnsignedLong(libver);
1724 if (r == NULL)
1725 return NULL;
1726 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1727 return NULL;
1728 status = libver & 0xF;
1729 libver >>= 4;
1730 patch = libver & 0xFF;
1731 libver >>= 8;
1732 fix = libver & 0xFF;
1733 libver >>= 8;
1734 minor = libver & 0xFF;
1735 libver >>= 8;
1736 major = libver & 0xFF;
1737 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1738 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1739 return NULL;
1740 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1741 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1742 return NULL;
1743
Martin v. Löwis1a214512008-06-11 05:26:20 +00001744 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001745}