blob: 87849724ef43f65b5dbc7b11190d21e683e63031 [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,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000265 char *cacerts_file, char *ciphers)
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
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000313 if (ciphers != NULL) {
314 ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);
315 if (ret == 0) {
316 errstr = ERRSTR("No cipher can be selected.");
317 goto fail;
318 }
319 }
320
Thomas Woutersed03b412007-08-28 21:37:11 +0000321 if (certreq != PY_SSL_CERT_NONE) {
322 if (cacerts_file == NULL) {
323 errstr = ERRSTR("No root certificates specified for "
324 "verification of other-side certificates.");
325 goto fail;
326 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000327 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000328 ret = SSL_CTX_load_verify_locations(self->ctx,
329 cacerts_file,
330 NULL);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000332 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000333 _setSSLError(NULL, 0, __FILE__, __LINE__);
Thomas Woutersed03b412007-08-28 21:37:11 +0000334 goto fail;
335 }
336 }
337 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000338 if (key_file) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000340 ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,
Thomas Woutersed03b412007-08-28 21:37:11 +0000341 SSL_FILETYPE_PEM);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000343 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 _setSSLError(NULL, ret, __FILE__, __LINE__);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000345 goto fail;
346 }
347
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000348 PySSL_BEGIN_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000349 ret = SSL_CTX_use_certificate_chain_file(self->ctx,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000350 cert_file);
351 PySSL_END_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000352 if (ret != 1) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000353 /*
354 fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
355 ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
356 */
357 if (ERR_peek_last_error() != 0) {
358 _setSSLError(NULL, ret, __FILE__, __LINE__);
359 goto fail;
360 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000361 }
362 }
363
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000364 /* ssl compatibility */
365 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
366
Thomas Woutersed03b412007-08-28 21:37:11 +0000367 verification_mode = SSL_VERIFY_NONE;
368 if (certreq == PY_SSL_CERT_OPTIONAL)
369 verification_mode = SSL_VERIFY_PEER;
370 else if (certreq == PY_SSL_CERT_REQUIRED)
371 verification_mode = (SSL_VERIFY_PEER |
372 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
373 SSL_CTX_set_verify(self->ctx, verification_mode,
374 NULL); /* set verify lvl */
375
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000376 PySSL_BEGIN_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377 self->ssl = SSL_new(self->ctx); /* New ssl struct */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000378 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379 SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000380#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou5f1c38f2010-03-26 19:32:24 +0000381 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000382#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000383
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000384 /* If the socket is in non-blocking mode or timeout mode, set the BIO
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000385 * to non-blocking mode (blocking is the default)
386 */
387 if (Sock->sock_timeout >= 0.0) {
388 /* Set both the read and write BIO's to non-blocking mode */
389 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
390 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
391 }
392
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393 PySSL_BEGIN_ALLOW_THREADS
Thomas Woutersed03b412007-08-28 21:37:11 +0000394 if (socket_type == PY_SSL_CLIENT)
395 SSL_set_connect_state(self->ssl);
396 else
397 SSL_set_accept_state(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000399
Bill Janssen54cc54c2007-12-14 22:08:56 +0000400 self->Socket = PyWeakref_NewRef((PyObject *) Sock, Py_None);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000401 return self;
402 fail:
403 if (errstr)
404 PyErr_SetString(PySSLErrorObject, errstr);
405 Py_DECREF(self);
406 return NULL;
407}
408
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000409static PyObject *
Thomas Woutersed03b412007-08-28 21:37:11 +0000410PySSL_sslwrap(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000411{
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000412 PySocketSockObject *Sock;
Thomas Woutersed03b412007-08-28 21:37:11 +0000413 int server_side = 0;
414 int verification_mode = PY_SSL_CERT_NONE;
415 int protocol = PY_SSL_VERSION_SSL23;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416 char *key_file = NULL;
417 char *cert_file = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000418 char *cacerts_file = NULL;
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000419 char *ciphers = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000420
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000421 if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000422 PySocketModule.Sock_Type,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000423 &Sock,
Thomas Woutersed03b412007-08-28 21:37:11 +0000424 &server_side,
425 &key_file, &cert_file,
426 &verification_mode, &protocol,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000427 &cacerts_file, &ciphers))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428 return NULL;
429
Thomas Woutersed03b412007-08-28 21:37:11 +0000430 /*
431 fprintf(stderr,
432 "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "
433 "protocol %d, certs %p\n",
434 server_side, key_file, cert_file, verification_mode,
435 protocol, cacerts_file);
436 */
437
438 return (PyObject *) newPySSLObject(Sock, key_file, cert_file,
439 server_side, verification_mode,
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000440 protocol, cacerts_file,
441 ciphers);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000442}
443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000444PyDoc_STRVAR(ssl_doc,
Thomas Woutersed03b412007-08-28 21:37:11 +0000445"sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"
Antoine Pitrou2d9cb9c2010-04-17 17:40:45 +0000446" cacertsfile, ciphers]) -> sslobject");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000447
448/* SSL object methods */
449
Bill Janssen6e027db2007-11-15 22:23:56 +0000450static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451{
Bill Janssen6e027db2007-11-15 22:23:56 +0000452 int ret;
453 int err;
454 int sockstate;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455
Bill Janssen6e027db2007-11-15 22:23:56 +0000456 /* Actually negotiate SSL connection */
457 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
458 sockstate = 0;
459 do {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000460 PySocketSockObject *sock
461 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
462 if (((PyObject*)sock) == Py_None) {
463 _setSSLError("Underlying socket connection gone",
464 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
465 return NULL;
466 }
467
Bill Janssen6e027db2007-11-15 22:23:56 +0000468 PySSL_BEGIN_ALLOW_THREADS
469 ret = SSL_do_handshake(self->ssl);
470 err = SSL_get_error(self->ssl, ret);
471 PySSL_END_ALLOW_THREADS
472 if(PyErr_CheckSignals()) {
473 return NULL;
474 }
475 if (err == SSL_ERROR_WANT_READ) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000476 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Bill Janssen6e027db2007-11-15 22:23:56 +0000477 } else if (err == SSL_ERROR_WANT_WRITE) {
Bill Janssen54cc54c2007-12-14 22:08:56 +0000478 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Bill Janssen6e027db2007-11-15 22:23:56 +0000479 } else {
480 sockstate = SOCKET_OPERATION_OK;
481 }
482 if (sockstate == SOCKET_HAS_TIMED_OUT) {
483 PyErr_SetString(PySSLErrorObject,
484 ERRSTR("The handshake operation timed out"));
485 return NULL;
486 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
487 PyErr_SetString(PySSLErrorObject,
488 ERRSTR("Underlying socket has been closed."));
489 return NULL;
490 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
491 PyErr_SetString(PySSLErrorObject,
492 ERRSTR("Underlying socket too large for select()."));
493 return NULL;
494 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
495 break;
496 }
497 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
498 if (ret < 1)
499 return PySSL_SetError(self, ret, __FILE__, __LINE__);
500 self->ssl->debug = 1;
501
502 if (self->peer_cert)
503 X509_free (self->peer_cert);
504 PySSL_BEGIN_ALLOW_THREADS
505 self->peer_cert = SSL_get_peer_certificate(self->ssl);
506 PySSL_END_ALLOW_THREADS
507
508 Py_INCREF(Py_None);
509 return Py_None;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000510}
511
Thomas Woutersed03b412007-08-28 21:37:11 +0000512static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000514
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515 char namebuf[X509_NAME_MAXLEN];
516 int buflen;
517 PyObject *name_obj;
518 PyObject *value_obj;
519 PyObject *attr;
520 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000521
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
523 if (buflen < 0) {
524 _setSSLError(NULL, 0, __FILE__, __LINE__);
525 goto fail;
Thomas Woutersed03b412007-08-28 21:37:11 +0000526 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000527 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528 if (name_obj == NULL)
529 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000530
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
532 if (buflen < 0) {
533 _setSSLError(NULL, 0, __FILE__, __LINE__);
534 Py_DECREF(name_obj);
535 goto fail;
536 }
537 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
538 buflen, "strict");
539 OPENSSL_free(valuebuf);
540 if (value_obj == NULL) {
541 Py_DECREF(name_obj);
542 goto fail;
543 }
544 attr = PyTuple_New(2);
545 if (attr == NULL) {
546 Py_DECREF(name_obj);
547 Py_DECREF(value_obj);
548 goto fail;
549 }
550 PyTuple_SET_ITEM(attr, 0, name_obj);
551 PyTuple_SET_ITEM(attr, 1, value_obj);
552 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000553
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554 fail:
Thomas Woutersed03b412007-08-28 21:37:11 +0000555 return NULL;
556}
557
558static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000560{
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
562 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
563 PyObject *rdnt;
564 PyObject *attr = NULL; /* tuple to hold an attribute */
565 int entry_count = X509_NAME_entry_count(xname);
566 X509_NAME_ENTRY *entry;
567 ASN1_OBJECT *name;
568 ASN1_STRING *value;
569 int index_counter;
570 int rdn_level = -1;
571 int retcode;
572
573 dn = PyList_New(0);
574 if (dn == NULL)
575 return NULL;
576 /* now create another tuple to hold the top-level RDN */
577 rdn = PyList_New(0);
578 if (rdn == NULL)
579 goto fail0;
580
581 for (index_counter = 0;
582 index_counter < entry_count;
583 index_counter++)
584 {
585 entry = X509_NAME_get_entry(xname, index_counter);
586
587 /* check to see if we've gotten to a new RDN */
588 if (rdn_level >= 0) {
589 if (rdn_level != entry->set) {
590 /* yes, new RDN */
591 /* add old RDN to DN */
592 rdnt = PyList_AsTuple(rdn);
593 Py_DECREF(rdn);
594 if (rdnt == NULL)
595 goto fail0;
596 retcode = PyList_Append(dn, rdnt);
597 Py_DECREF(rdnt);
598 if (retcode < 0)
599 goto fail0;
600 /* create new RDN */
601 rdn = PyList_New(0);
602 if (rdn == NULL)
603 goto fail0;
604 }
605 }
606 rdn_level = entry->set;
607
608 /* now add this attribute to the current RDN */
609 name = X509_NAME_ENTRY_get_object(entry);
610 value = X509_NAME_ENTRY_get_data(entry);
611 attr = _create_tuple_for_attribute(name, value);
612 /*
613 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
614 entry->set,
Christian Heimes72b710a2008-05-26 13:28:38 +0000615 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
616 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617 */
618 if (attr == NULL)
619 goto fail1;
620 retcode = PyList_Append(rdn, attr);
621 Py_DECREF(attr);
622 if (retcode < 0)
623 goto fail1;
624 }
625 /* now, there's typically a dangling RDN */
626 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
627 rdnt = PyList_AsTuple(rdn);
628 Py_DECREF(rdn);
629 if (rdnt == NULL)
630 goto fail0;
631 retcode = PyList_Append(dn, rdnt);
632 Py_DECREF(rdnt);
633 if (retcode < 0)
634 goto fail0;
635 }
636
637 /* convert list to tuple */
638 rdnt = PyList_AsTuple(dn);
639 Py_DECREF(dn);
640 if (rdnt == NULL)
641 return NULL;
642 return rdnt;
643
644 fail1:
645 Py_XDECREF(rdn);
646
647 fail0:
648 Py_XDECREF(dn);
649 return NULL;
650}
651
652static PyObject *
653_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000654
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655 /* this code follows the procedure outlined in
656 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
657 function to extract the STACK_OF(GENERAL_NAME),
658 then iterates through the stack to add the
659 names. */
660
661 int i, j;
662 PyObject *peer_alt_names = Py_None;
663 PyObject *v, *t;
664 X509_EXTENSION *ext = NULL;
665 GENERAL_NAMES *names = NULL;
666 GENERAL_NAME *name;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000667 X509V3_EXT_METHOD *method;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 BIO *biobuf = NULL;
669 char buf[2048];
670 char *vptr;
671 int len;
Victor Stinner7124a412010-03-02 22:48:17 +0000672 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
673#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
674 const unsigned char *p;
675#else
Benjamin Peterson0289b152009-06-28 17:22:03 +0000676 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000677#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
679 if (certificate == NULL)
680 return peer_alt_names;
681
682 /* get a memory buffer */
683 biobuf = BIO_new(BIO_s_mem());
684
685 i = 0;
686 while ((i = X509_get_ext_by_NID(
687 certificate, NID_subject_alt_name, i)) >= 0) {
688
689 if (peer_alt_names == Py_None) {
690 peer_alt_names = PyList_New(0);
691 if (peer_alt_names == NULL)
692 goto fail;
693 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000694
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695 /* now decode the altName */
696 ext = X509_get_ext(certificate, i);
697 if(!(method = X509V3_EXT_get(ext))) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000698 PyErr_SetString
699 (PySSLErrorObject,
700 ERRSTR("No method for internalizing subjectAltName!"));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701 goto fail;
702 }
703
704 p = ext->value->data;
Christian Heimes412dc9c2008-01-27 18:55:54 +0000705 if (method->it)
Bill Janssen6e027db2007-11-15 22:23:56 +0000706 names = (GENERAL_NAMES*)
707 (ASN1_item_d2i(NULL,
708 &p,
709 ext->value->length,
710 ASN1_ITEM_ptr(method->it)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711 else
Bill Janssen6e027db2007-11-15 22:23:56 +0000712 names = (GENERAL_NAMES*)
713 (method->d2i(NULL,
714 &p,
715 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716
717 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
718
719 /* get a rendering of each name in the set of names */
720
721 name = sk_GENERAL_NAME_value(names, j);
722 if (name->type == GEN_DIRNAME) {
723
Bill Janssen6e027db2007-11-15 22:23:56 +0000724 /* we special-case DirName as a tuple of
725 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
727 t = PyTuple_New(2);
728 if (t == NULL) {
729 goto fail;
730 }
731
Bill Janssen6e027db2007-11-15 22:23:56 +0000732 v = PyUnicode_FromString("DirName");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733 if (v == NULL) {
734 Py_DECREF(t);
735 goto fail;
736 }
737 PyTuple_SET_ITEM(t, 0, v);
738
739 v = _create_tuple_for_X509_NAME (name->d.dirn);
740 if (v == NULL) {
741 Py_DECREF(t);
742 goto fail;
743 }
744 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000745
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746 } else {
747
748 /* for everything else, we use the OpenSSL print form */
749
750 (void) BIO_reset(biobuf);
751 GENERAL_NAME_print(biobuf, name);
752 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
753 if (len < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto fail;
756 }
757 vptr = strchr(buf, ':');
758 if (vptr == NULL)
759 goto fail;
760 t = PyTuple_New(2);
761 if (t == NULL)
762 goto fail;
Bill Janssen6e027db2007-11-15 22:23:56 +0000763 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764 if (v == NULL) {
765 Py_DECREF(t);
766 goto fail;
767 }
768 PyTuple_SET_ITEM(t, 0, v);
Bill Janssen6e027db2007-11-15 22:23:56 +0000769 v = PyUnicode_FromStringAndSize((vptr + 1),
770 (len - (vptr - buf + 1)));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771 if (v == NULL) {
772 Py_DECREF(t);
773 goto fail;
774 }
775 PyTuple_SET_ITEM(t, 1, v);
776 }
777
778 /* and add that rendering to the list */
779
780 if (PyList_Append(peer_alt_names, t) < 0) {
781 Py_DECREF(t);
782 goto fail;
783 }
784 Py_DECREF(t);
785 }
786 }
787 BIO_free(biobuf);
788 if (peer_alt_names != Py_None) {
789 v = PyList_AsTuple(peer_alt_names);
790 Py_DECREF(peer_alt_names);
791 return v;
792 } else {
793 return peer_alt_names;
794 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000795
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
797 fail:
798 if (biobuf != NULL)
799 BIO_free(biobuf);
800
801 if (peer_alt_names != Py_None) {
802 Py_XDECREF(peer_alt_names);
803 }
804
805 return NULL;
806}
807
808static PyObject *
809_decode_certificate (X509 *certificate, int verbose) {
810
Thomas Woutersed03b412007-08-28 21:37:11 +0000811 PyObject *retval = NULL;
812 BIO *biobuf = NULL;
813 PyObject *peer;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814 PyObject *peer_alt_names = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000815 PyObject *issuer;
816 PyObject *version;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817 PyObject *sn_obj;
818 ASN1_INTEGER *serialNumber;
Thomas Woutersed03b412007-08-28 21:37:11 +0000819 char buf[2048];
820 int len;
821 ASN1_TIME *notBefore, *notAfter;
822 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000823
824 retval = PyDict_New();
825 if (retval == NULL)
826 return NULL;
827
Thomas Wouters89d996e2007-09-08 17:39:28 +0000828 peer = _create_tuple_for_X509_NAME(
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829 X509_get_subject_name(certificate));
Thomas Woutersed03b412007-08-28 21:37:11 +0000830 if (peer == NULL)
831 goto fail0;
832 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
833 Py_DECREF(peer);
834 goto fail0;
835 }
836 Py_DECREF(peer);
837
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838 if (verbose) {
839 issuer = _create_tuple_for_X509_NAME(
840 X509_get_issuer_name(certificate));
841 if (issuer == NULL)
842 goto fail0;
843 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
844 Py_DECREF(issuer);
845 goto fail0;
846 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000847 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000848
Christian Heimes217cfd12007-12-02 14:31:20 +0000849 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850 if (PyDict_SetItemString(retval, "version", version) < 0) {
851 Py_DECREF(version);
852 goto fail0;
853 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000854 Py_DECREF(version);
Thomas Woutersed03b412007-08-28 21:37:11 +0000855 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000856
Thomas Woutersed03b412007-08-28 21:37:11 +0000857 /* get a memory buffer */
858 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000859
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000861
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862 (void) BIO_reset(biobuf);
863 serialNumber = X509_get_serialNumber(certificate);
864 /* should not exceed 20 octets, 160 bits, so buf is big enough */
865 i2a_ASN1_INTEGER(biobuf, serialNumber);
866 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
867 if (len < 0) {
868 _setSSLError(NULL, 0, __FILE__, __LINE__);
869 goto fail1;
870 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000871 sn_obj = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872 if (sn_obj == NULL)
873 goto fail1;
874 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
875 Py_DECREF(sn_obj);
876 goto fail1;
877 }
878 Py_DECREF(sn_obj);
879
880 (void) BIO_reset(biobuf);
881 notBefore = X509_get_notBefore(certificate);
882 ASN1_TIME_print(biobuf, notBefore);
883 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
884 if (len < 0) {
885 _setSSLError(NULL, 0, __FILE__, __LINE__);
886 goto fail1;
887 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000888 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889 if (pnotBefore == NULL)
890 goto fail1;
891 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
892 Py_DECREF(pnotBefore);
893 goto fail1;
894 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000895 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000896 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000897
898 (void) BIO_reset(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899 notAfter = X509_get_notAfter(certificate);
Thomas Woutersed03b412007-08-28 21:37:11 +0000900 ASN1_TIME_print(biobuf, notAfter);
901 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902 if (len < 0) {
903 _setSSLError(NULL, 0, __FILE__, __LINE__);
904 goto fail1;
905 }
Bill Janssen6e027db2007-11-15 22:23:56 +0000906 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
Thomas Woutersed03b412007-08-28 21:37:11 +0000907 if (pnotAfter == NULL)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000909 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
910 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 goto fail1;
Thomas Woutersed03b412007-08-28 21:37:11 +0000912 }
913 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
915 /* Now look for subjectAltName */
916
917 peer_alt_names = _get_peer_alt_names(certificate);
918 if (peer_alt_names == NULL)
919 goto fail1;
920 else if (peer_alt_names != Py_None) {
921 if (PyDict_SetItemString(retval, "subjectAltName",
922 peer_alt_names) < 0) {
923 Py_DECREF(peer_alt_names);
924 goto fail1;
925 }
926 Py_DECREF(peer_alt_names);
927 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000928
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000930 return retval;
931
932 fail1:
933 if (biobuf != NULL)
934 BIO_free(biobuf);
935 fail0:
936 Py_XDECREF(retval);
937 return NULL;
938}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000939
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
941static PyObject *
942PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
943
944 PyObject *retval = NULL;
945 char *filename = NULL;
946 X509 *x=NULL;
947 BIO *cert;
948 int verbose = 1;
949
Bill Janssen6e027db2007-11-15 22:23:56 +0000950 if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate",
951 &filename, &verbose))
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952 return NULL;
953
954 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000955 PyErr_SetString(PySSLErrorObject,
956 "Can't malloc memory to read file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957 goto fail0;
958 }
959
960 if (BIO_read_filename(cert,filename) <= 0) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000961 PyErr_SetString(PySSLErrorObject,
962 "Can't open file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963 goto fail0;
964 }
965
966 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
967 if (x == NULL) {
Bill Janssen6e027db2007-11-15 22:23:56 +0000968 PyErr_SetString(PySSLErrorObject,
969 "Error decoding PEM-encoded file");
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970 goto fail0;
971 }
972
973 retval = _decode_certificate(x, verbose);
974
975 fail0:
Guido van Rossumf06628b2007-11-21 20:01:53 +0000976
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977 if (cert != NULL) BIO_free(cert);
978 return retval;
979}
980
981
982static PyObject *
983PySSL_peercert(PySSLObject *self, PyObject *args)
984{
985 PyObject *retval = NULL;
986 int len;
987 int verification;
988 PyObject *binary_mode = Py_None;
989
990 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
991 return NULL;
992
993 if (!self->peer_cert)
994 Py_RETURN_NONE;
995
996 if (PyObject_IsTrue(binary_mode)) {
997 /* return cert in DER-encoded format */
998
999 unsigned char *bytes_buf = NULL;
1000
1001 bytes_buf = NULL;
1002 len = i2d_X509(self->peer_cert, &bytes_buf);
1003 if (len < 0) {
1004 PySSL_SetError(self, len, __FILE__, __LINE__);
1005 return NULL;
1006 }
Bill Janssen6e027db2007-11-15 22:23:56 +00001007 /* this is actually an immutable bytes sequence */
Christian Heimes72b710a2008-05-26 13:28:38 +00001008 retval = PyBytes_FromStringAndSize
Bill Janssen6e027db2007-11-15 22:23:56 +00001009 ((const char *) bytes_buf, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001010 OPENSSL_free(bytes_buf);
1011 return retval;
1012
1013 } else {
1014
1015 verification = SSL_CTX_get_verify_mode(self->ctx);
1016 if ((verification & SSL_VERIFY_PEER) == 0)
1017 return PyDict_New();
1018 else
1019 return _decode_certificate (self->peer_cert, 0);
1020 }
1021}
1022
1023PyDoc_STRVAR(PySSL_peercert_doc,
1024"peer_certificate([der=False]) -> certificate\n\
1025\n\
1026Returns the certificate for the peer. If no certificate was provided,\n\
1027returns None. If a certificate was provided, but not validated, returns\n\
1028an empty dictionary. Otherwise returns a dict containing information\n\
1029about the peer certificate.\n\
1030\n\
1031If the optional argument is True, returns a DER-encoded copy of the\n\
1032peer certificate, or None if no certificate was provided. This will\n\
1033return the certificate even if it wasn't validated.");
1034
1035static PyObject *PySSL_cipher (PySSLObject *self) {
1036
1037 PyObject *retval, *v;
1038 SSL_CIPHER *current;
1039 char *cipher_name;
1040 char *cipher_protocol;
1041
1042 if (self->ssl == NULL)
1043 return Py_None;
1044 current = SSL_get_current_cipher(self->ssl);
1045 if (current == NULL)
1046 return Py_None;
1047
1048 retval = PyTuple_New(3);
1049 if (retval == NULL)
1050 return NULL;
1051
1052 cipher_name = (char *) SSL_CIPHER_get_name(current);
1053 if (cipher_name == NULL) {
1054 PyTuple_SET_ITEM(retval, 0, Py_None);
1055 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001056 v = PyUnicode_FromString(cipher_name);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057 if (v == NULL)
1058 goto fail0;
1059 PyTuple_SET_ITEM(retval, 0, v);
1060 }
1061 cipher_protocol = SSL_CIPHER_get_version(current);
1062 if (cipher_protocol == NULL) {
1063 PyTuple_SET_ITEM(retval, 1, Py_None);
1064 } else {
Bill Janssen6e027db2007-11-15 22:23:56 +00001065 v = PyUnicode_FromString(cipher_protocol);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066 if (v == NULL)
1067 goto fail0;
1068 PyTuple_SET_ITEM(retval, 1, v);
1069 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001070 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071 if (v == NULL)
1072 goto fail0;
1073 PyTuple_SET_ITEM(retval, 2, v);
1074 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001075
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076 fail0:
1077 Py_DECREF(retval);
1078 return NULL;
1079}
1080
Guido van Rossume6650f92007-12-06 19:05:55 +00001081static void PySSL_dealloc(PySSLObject *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001082{
Thomas Woutersed03b412007-08-28 21:37:11 +00001083 if (self->peer_cert) /* Possible not to have one? */
Guido van Rossume6650f92007-12-06 19:05:55 +00001084 X509_free (self->peer_cert);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001085 if (self->ssl)
Thomas Woutersed03b412007-08-28 21:37:11 +00001086 SSL_free(self->ssl);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001087 if (self->ctx)
Thomas Woutersed03b412007-08-28 21:37:11 +00001088 SSL_CTX_free(self->ctx);
Guido van Rossume6650f92007-12-06 19:05:55 +00001089 Py_XDECREF(self->Socket);
1090 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001091}
1092
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001093/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001094 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001095 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001096 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001097
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001098static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001099check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001100{
1101 fd_set fds;
1102 struct timeval tv;
1103 int rc;
1104
1105 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001106 if (s->sock_timeout < 0.0)
1107 return SOCKET_IS_BLOCKING;
1108 else if (s->sock_timeout == 0.0)
1109 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001110
1111 /* Guard against closed socket */
1112 if (s->sock_fd < 0)
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001113 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001114
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001115 /* Prefer poll, if available, since you can poll() any fd
1116 * which can't be done with select(). */
1117#ifdef HAVE_POLL
1118 {
1119 struct pollfd pollfd;
1120 int timeout;
1121
1122 pollfd.fd = s->sock_fd;
1123 pollfd.events = writing ? POLLOUT : POLLIN;
1124
1125 /* s->sock_timeout is in seconds, timeout in ms */
1126 timeout = (int)(s->sock_timeout * 1000 + 0.5);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128 rc = poll(&pollfd, 1, timeout);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130
1131 goto normal_return;
1132 }
1133#endif
1134
Neal Norwitz082b2df2006-02-07 07:04:46 +00001135 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001136#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Neal Norwitz082b2df2006-02-07 07:04:46 +00001137 if (s->sock_fd >= FD_SETSIZE)
Neal Norwitz389cea82006-02-13 00:35:21 +00001138 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001139#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001140
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001141 /* Construct the arguments to select */
1142 tv.tv_sec = (int)s->sock_timeout;
1143 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1144 FD_ZERO(&fds);
1145 FD_SET(s->sock_fd, &fds);
1146
1147 /* See if the socket is ready */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148 PySSL_BEGIN_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001149 if (writing)
1150 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1151 else
1152 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001154
Bill Janssen6e027db2007-11-15 22:23:56 +00001155#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001156normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001157#endif
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001158 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1159 (when we are able to write or when there's something to read) */
1160 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001161}
1162
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001163static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)
1164{
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001165 Py_buffer buf;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001166 int len;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001167 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001168 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001169 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001170 PySocketSockObject *sock
1171 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1172
1173 if (((PyObject*)sock) == Py_None) {
1174 _setSSLError("Underlying socket connection gone",
1175 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1176 return NULL;
1177 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001178
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001179 if (!PyArg_ParseTuple(args, "y*:write", &buf))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001180 return NULL;
1181
Bill Janssen6e027db2007-11-15 22:23:56 +00001182 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001183 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001184 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1185 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1186
Bill Janssen54cc54c2007-12-14 22:08:56 +00001187 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001188 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001189 PyErr_SetString(PySSLErrorObject,
1190 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001191 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001192 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001193 PyErr_SetString(PySSLErrorObject,
1194 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001195 goto error;
Neal Norwitz389cea82006-02-13 00:35:21 +00001196 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001197 PyErr_SetString(PySSLErrorObject,
1198 "Underlying socket too large for select().");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001199 goto error;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001200 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001201 do {
1202 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001204 len = SSL_write(self->ssl, buf.buf, buf.len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001205 err = SSL_get_error(self->ssl, len);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206 PySSL_END_ALLOW_THREADS
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001207 if (PyErr_CheckSignals()) {
1208 goto error;
Martin v. Löwisafec8e32003-06-28 07:40:23 +00001209 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001210 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001211 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001212 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001213 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001214 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001215 check_socket_and_wait_for_timeout(sock, 1);
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001216 } else {
1217 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001218 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001219 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1220 PyErr_SetString(PySSLErrorObject,
1221 "The write operation timed out");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001222 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001223 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001224 PyErr_SetString(PySSLErrorObject,
1225 "Underlying socket has been closed.");
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001226 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001227 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1228 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001229 }
1230 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001231
1232 PyBuffer_Release(&buf);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001233 if (len > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00001234 return PyLong_FromLong(len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001235 else
Thomas Woutersed03b412007-08-28 21:37:11 +00001236 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001237
1238error:
1239 PyBuffer_Release(&buf);
1240 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001241}
1242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001243PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001244"write(s) -> len\n\
1245\n\
1246Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001247of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001248
Bill Janssen6e027db2007-11-15 22:23:56 +00001249static PyObject *PySSL_SSLpending(PySSLObject *self)
1250{
1251 int count = 0;
1252
1253 PySSL_BEGIN_ALLOW_THREADS
1254 count = SSL_pending(self->ssl);
1255 PySSL_END_ALLOW_THREADS
1256 if (count < 0)
1257 return PySSL_SetError(self, count, __FILE__, __LINE__);
1258 else
Christian Heimes217cfd12007-12-02 14:31:20 +00001259 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001260}
1261
1262PyDoc_STRVAR(PySSL_SSLpending_doc,
1263"pending() -> count\n\
1264\n\
1265Returns the number of already decrypted bytes available for read,\n\
1266pending on the connection.\n");
1267
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001268static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)
1269{
Benjamin Peterson56420b42009-02-28 19:06:54 +00001270 PyObject *dest = NULL;
1271 Py_buffer buf;
Bill Janssen6e027db2007-11-15 22:23:56 +00001272 int buf_passed = 0;
1273 int count = -1;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001274 char *mem;
1275 /* XXX this should use Py_ssize_t */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001276 int len = 1024;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001277 int sockstate;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001278 int err;
Bill Janssen6e027db2007-11-15 22:23:56 +00001279 int nonblocking;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001280 PySocketSockObject *sock
1281 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1282
1283 if (((PyObject*)sock) == Py_None) {
1284 _setSSLError("Underlying socket connection gone",
1285 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1286 return NULL;
1287 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001288
Benjamin Peterson56420b42009-02-28 19:06:54 +00001289 if (!PyArg_ParseTuple(args, "|Oi:read", &dest, &count))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001290 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001291 if ((dest == NULL) || (dest == Py_None)) {
1292 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001293 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001294 mem = PyByteArray_AS_STRING(dest);
1295 } else if (PyLong_Check(dest)) {
1296 len = PyLong_AS_LONG(dest);
1297 if (!(dest = PyByteArray_FromStringAndSize((char *) 0, len)))
Bill Janssen6e027db2007-11-15 22:23:56 +00001298 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001299 mem = PyByteArray_AS_STRING(dest);
Bill Janssen6e027db2007-11-15 22:23:56 +00001300 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001301 if (PyObject_GetBuffer(dest, &buf, PyBUF_CONTIG) < 0)
Bill Janssen6e027db2007-11-15 22:23:56 +00001302 return NULL;
Benjamin Peterson56420b42009-02-28 19:06:54 +00001303 mem = buf.buf;
1304 len = buf.len;
Bill Janssen6e027db2007-11-15 22:23:56 +00001305 if ((count > 0) && (count <= len))
1306 len = count;
1307 buf_passed = 1;
1308 }
1309
1310 /* just in case the blocking state of the socket has been changed */
Bill Janssen54cc54c2007-12-14 22:08:56 +00001311 nonblocking = (sock->sock_timeout >= 0.0);
Bill Janssen6e027db2007-11-15 22:23:56 +00001312 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1313 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Thomas Woutersed03b412007-08-28 21:37:11 +00001314
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001315 /* first check if there are bytes ready to be read */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316 PySSL_BEGIN_ALLOW_THREADS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317 count = SSL_pending(self->ssl);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318 PySSL_END_ALLOW_THREADS
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001319
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001320 if (!count) {
Bill Janssen54cc54c2007-12-14 22:08:56 +00001321 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001323 PyErr_SetString(PySSLErrorObject,
1324 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001325 goto error;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001326 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001327 PyErr_SetString(PySSLErrorObject,
1328 "Underlying socket too large for select().");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001329 goto error;
Thomas Woutersed03b412007-08-28 21:37:11 +00001330 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001331 count = 0;
1332 goto done;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001333 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001334 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001335 do {
1336 err = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001337 PySSL_BEGIN_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001338 count = SSL_read(self->ssl, mem, len);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001339 err = SSL_get_error(self->ssl, count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001340 PySSL_END_ALLOW_THREADS
Benjamin Peterson56420b42009-02-28 19:06:54 +00001341 if (PyErr_CheckSignals())
1342 goto error;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001343 if (err == SSL_ERROR_WANT_READ) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001344 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001345 check_socket_and_wait_for_timeout(sock, 0);
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001346 } else if (err == SSL_ERROR_WANT_WRITE) {
Thomas Woutersed03b412007-08-28 21:37:11 +00001347 sockstate =
Bill Janssen54cc54c2007-12-14 22:08:56 +00001348 check_socket_and_wait_for_timeout(sock, 1);
Thomas Woutersed03b412007-08-28 21:37:11 +00001349 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1350 (SSL_get_shutdown(self->ssl) ==
1351 SSL_RECEIVED_SHUTDOWN))
1352 {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001353 count = 0;
1354 goto done;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001355 } else {
1356 sockstate = SOCKET_OPERATION_OK;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001357 }
Thomas Woutersed03b412007-08-28 21:37:11 +00001358 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1359 PyErr_SetString(PySSLErrorObject,
1360 "The read operation timed out");
Benjamin Peterson56420b42009-02-28 19:06:54 +00001361 goto error;
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001362 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1363 break;
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001364 }
1365 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001366 if (count <= 0) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001367 PySSL_SetError(self, count, __FILE__, __LINE__);
1368 goto error;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001369 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001370 done:
Bill Janssen6e027db2007-11-15 22:23:56 +00001371 if (!buf_passed) {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001372 PyObject *res = PyBytes_FromStringAndSize(mem, count);
1373 Py_DECREF(dest);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001374 return res;
Bill Janssen6e027db2007-11-15 22:23:56 +00001375 } else {
Benjamin Peterson56420b42009-02-28 19:06:54 +00001376 PyBuffer_Release(&buf);
Christian Heimes217cfd12007-12-02 14:31:20 +00001377 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001378 }
Benjamin Peterson56420b42009-02-28 19:06:54 +00001379 error:
1380 if (!buf_passed) {
1381 Py_DECREF(dest);
1382 } else {
1383 PyBuffer_Release(&buf);
1384 }
1385 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001386}
1387
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001388PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001389"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001390\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001391Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001392
Bill Janssen40a0f662008-08-12 16:56:25 +00001393static PyObject *PySSL_SSLshutdown(PySSLObject *self)
1394{
1395 int err;
1396 PySocketSockObject *sock
1397 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
1398
1399 /* Guard against closed socket */
1400 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1401 _setSSLError("Underlying socket connection gone",
1402 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1403 return NULL;
1404 }
1405
1406 PySSL_BEGIN_ALLOW_THREADS
1407 err = SSL_shutdown(self->ssl);
1408 if (err == 0) {
1409 /* we need to call it again to finish the shutdown */
1410 err = SSL_shutdown(self->ssl);
1411 }
1412 PySSL_END_ALLOW_THREADS
1413
1414 if (err < 0)
1415 return PySSL_SetError(self, err, __FILE__, __LINE__);
1416 else {
1417 Py_INCREF(sock);
1418 return (PyObject *) sock;
1419 }
1420}
1421
1422PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1423"shutdown(s) -> socket\n\
1424\n\
1425Does the SSL shutdown handshake with the remote end, and returns\n\
1426the underlying socket object.");
1427
1428
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001429static PyMethodDef PySSLMethods[] = {
Bill Janssen6e027db2007-11-15 22:23:56 +00001430 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001431 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432 PySSL_SSLwrite_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001433 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001434 PySSL_SSLread_doc},
Bill Janssen6e027db2007-11-15 22:23:56 +00001435 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1436 PySSL_SSLpending_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1438 PySSL_peercert_doc},
1439 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Bill Janssen40a0f662008-08-12 16:56:25 +00001440 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1441 PySSL_SSLshutdown_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001442 {NULL, NULL}
1443};
1444
Jeremy Hylton938ace62002-07-17 16:30:39 +00001445static PyTypeObject PySSL_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001446 PyVarObject_HEAD_INIT(NULL, 0)
Guido van Rossume6650f92007-12-06 19:05:55 +00001447 "ssl.SSLContext", /*tp_name*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001448 sizeof(PySSLObject), /*tp_basicsize*/
1449 0, /*tp_itemsize*/
1450 /* methods */
1451 (destructor)PySSL_dealloc, /*tp_dealloc*/
1452 0, /*tp_print*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001453 0, /*tp_getattr*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001454 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00001455 0, /*tp_reserved*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001456 0, /*tp_repr*/
1457 0, /*tp_as_number*/
1458 0, /*tp_as_sequence*/
1459 0, /*tp_as_mapping*/
1460 0, /*tp_hash*/
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001461 0, /*tp_call*/
1462 0, /*tp_str*/
1463 0, /*tp_getattro*/
1464 0, /*tp_setattro*/
1465 0, /*tp_as_buffer*/
1466 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1467 0, /*tp_doc*/
1468 0, /*tp_traverse*/
1469 0, /*tp_clear*/
1470 0, /*tp_richcompare*/
1471 0, /*tp_weaklistoffset*/
1472 0, /*tp_iter*/
1473 0, /*tp_iternext*/
1474 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001475};
1476
1477#ifdef HAVE_OPENSSL_RAND
1478
1479/* helper routines for seeding the SSL PRNG */
1480static PyObject *
1481PySSL_RAND_add(PyObject *self, PyObject *args)
1482{
1483 char *buf;
1484 int len;
1485 double entropy;
1486
1487 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
1488 return NULL;
1489 RAND_add(buf, len, entropy);
1490 Py_INCREF(Py_None);
1491 return Py_None;
1492}
1493
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001494PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001495"RAND_add(string, entropy)\n\
1496\n\
1497Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001498bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001499
1500static PyObject *
1501PySSL_RAND_status(PyObject *self)
1502{
Christian Heimes217cfd12007-12-02 14:31:20 +00001503 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001504}
1505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001506PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001507"RAND_status() -> 0 or 1\n\
1508\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001509Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1510It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1511using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001512
1513static PyObject *
1514PySSL_RAND_egd(PyObject *self, PyObject *arg)
1515{
1516 int bytes;
1517
Bill Janssen6e027db2007-11-15 22:23:56 +00001518 if (!PyUnicode_Check(arg))
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001519 return PyErr_Format(PyExc_TypeError,
1520 "RAND_egd() expected string, found %s",
Christian Heimes90aa7642007-12-19 02:45:37 +00001521 Py_TYPE(arg)->tp_name);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001522 bytes = RAND_egd(_PyUnicode_AsString(arg));
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001523 if (bytes == -1) {
1524 PyErr_SetString(PySSLErrorObject,
1525 "EGD connection failed or EGD did not return "
1526 "enough data to seed the PRNG");
1527 return NULL;
1528 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001529 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001530}
1531
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001532PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001533"RAND_egd(path) -> bytes\n\
1534\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1536Returns number of bytes read. Raises SSLError if connection to EGD\n\
1537fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001538
1539#endif
1540
Bill Janssen40a0f662008-08-12 16:56:25 +00001541
1542
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001543/* List of functions exported by this module. */
1544
1545static PyMethodDef PySSL_methods[] = {
Thomas Woutersed03b412007-08-28 21:37:11 +00001546 {"sslwrap", PySSL_sslwrap,
1547 METH_VARARGS, ssl_doc},
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548 {"_test_decode_cert", PySSL_test_decode_certificate,
1549 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001550#ifdef HAVE_OPENSSL_RAND
Thomas Woutersed03b412007-08-28 21:37:11 +00001551 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001552 PySSL_RAND_add_doc},
1553 {"RAND_egd", PySSL_RAND_egd, METH_O,
1554 PySSL_RAND_egd_doc},
1555 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1556 PySSL_RAND_status_doc},
1557#endif
Thomas Woutersed03b412007-08-28 21:37:11 +00001558 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001559};
1560
1561
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001562#ifdef WITH_THREAD
1563
1564/* an implementation of OpenSSL threading operations in terms
1565 of the Python C thread library */
1566
1567static PyThread_type_lock *_ssl_locks = NULL;
1568
1569static unsigned long _ssl_thread_id_function (void) {
1570 return PyThread_get_thread_ident();
1571}
1572
Bill Janssen6e027db2007-11-15 22:23:56 +00001573static void _ssl_thread_locking_function
1574 (int mode, int n, const char *file, int line) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575 /* this function is needed to perform locking on shared data
1576 structures. (Note that OpenSSL uses a number of global data
Bill Janssen6e027db2007-11-15 22:23:56 +00001577 structures that will be implicitly shared whenever multiple
1578 threads use OpenSSL.) Multi-threaded applications will
1579 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001580
Bill Janssen6e027db2007-11-15 22:23:56 +00001581 locking_function() must be able to handle up to
1582 CRYPTO_num_locks() different mutex locks. It sets the n-th
1583 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584
1585 file and line are the file number of the function setting the
1586 lock. They can be useful for debugging.
1587 */
1588
1589 if ((_ssl_locks == NULL) ||
Christian Heimesba4af492008-03-28 00:55:15 +00001590 (n < 0) || ((unsigned)n >= _ssl_locks_count))
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591 return;
1592
1593 if (mode & CRYPTO_LOCK) {
1594 PyThread_acquire_lock(_ssl_locks[n], 1);
1595 } else {
1596 PyThread_release_lock(_ssl_locks[n]);
1597 }
1598}
1599
1600static int _setup_ssl_threads(void) {
1601
Christian Heimesba4af492008-03-28 00:55:15 +00001602 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001603
1604 if (_ssl_locks == NULL) {
1605 _ssl_locks_count = CRYPTO_num_locks();
1606 _ssl_locks = (PyThread_type_lock *)
1607 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1608 if (_ssl_locks == NULL)
1609 return 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001610 memset(_ssl_locks, 0,
1611 sizeof(PyThread_type_lock) * _ssl_locks_count);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001612 for (i = 0; i < _ssl_locks_count; i++) {
1613 _ssl_locks[i] = PyThread_allocate_lock();
1614 if (_ssl_locks[i] == NULL) {
Raymond Hettinger26dd7602009-01-26 16:53:29 +00001615 unsigned int j;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001616 for (j = 0; j < i; j++) {
1617 PyThread_free_lock(_ssl_locks[j]);
1618 }
1619 free(_ssl_locks);
1620 return 0;
1621 }
1622 }
1623 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1624 CRYPTO_set_id_callback(_ssl_thread_id_function);
1625 }
1626 return 1;
1627}
1628
1629#endif /* def HAVE_THREAD */
1630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001631PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001632"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001633for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001634
Martin v. Löwis1a214512008-06-11 05:26:20 +00001635
1636static struct PyModuleDef _sslmodule = {
1637 PyModuleDef_HEAD_INIT,
1638 "_ssl",
1639 module_doc,
1640 -1,
1641 PySSL_methods,
1642 NULL,
1643 NULL,
1644 NULL,
1645 NULL
1646};
1647
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001648PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001649PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001650{
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001651 PyObject *m, *d, *r;
1652 unsigned long libver;
1653 unsigned int major, minor, fix, patch, status;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001654 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001655
Amaury Forgeot d'Arce43d33a2008-07-02 20:50:16 +00001656 if (PyType_Ready(&PySSL_Type) < 0)
1657 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001658
Martin v. Löwis1a214512008-06-11 05:26:20 +00001659 m = PyModule_Create(&_sslmodule);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001660 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001661 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001662 d = PyModule_GetDict(m);
1663
1664 /* Load _socket module and its C API */
Benjamin Petersonb173f782009-05-05 22:31:58 +00001665 socket_api = PySocketModule_ImportModuleAndAPI();
1666 if (!socket_api)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001667 return NULL;
Benjamin Petersonb173f782009-05-05 22:31:58 +00001668 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001669
1670 /* Init OpenSSL */
1671 SSL_load_error_strings();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672#ifdef WITH_THREAD
1673 /* note that this will start threading if not already started */
1674 if (!_setup_ssl_threads()) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00001675 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676 }
1677#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001678 SSLeay_add_ssl_algorithms();
1679
1680 /* Add symbols to module dict */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001681 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
Thomas Woutersed03b412007-08-28 21:37:11 +00001682 PySocketModule.error,
1683 NULL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001684 if (PySSLErrorObject == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001685 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001687 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001688 if (PyDict_SetItemString(d, "SSLType",
1689 (PyObject *)&PySSL_Type) != 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001690 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001691 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001692 PY_SSL_ERROR_ZERO_RETURN);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001693 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001694 PY_SSL_ERROR_WANT_READ);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001695 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001696 PY_SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001697 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001698 PY_SSL_ERROR_WANT_X509_LOOKUP);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001699 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001700 PY_SSL_ERROR_SYSCALL);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001701 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001702 PY_SSL_ERROR_SSL);
1703 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
1704 PY_SSL_ERROR_WANT_CONNECT);
1705 /* non ssl.h errorcodes */
1706 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
1707 PY_SSL_ERROR_EOF);
1708 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
1709 PY_SSL_ERROR_INVALID_ERROR_CODE);
Thomas Woutersed03b412007-08-28 21:37:11 +00001710 /* cert requirements */
1711 PyModule_AddIntConstant(m, "CERT_NONE",
1712 PY_SSL_CERT_NONE);
1713 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
1714 PY_SSL_CERT_OPTIONAL);
1715 PyModule_AddIntConstant(m, "CERT_REQUIRED",
1716 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00001717
Thomas Woutersed03b412007-08-28 21:37:11 +00001718 /* protocol versions */
1719 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
1720 PY_SSL_VERSION_SSL2);
1721 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
1722 PY_SSL_VERSION_SSL3);
1723 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
1724 PY_SSL_VERSION_SSL23);
1725 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
1726 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00001727
1728 /* OpenSSL version */
1729 /* SSLeay() gives us the version of the library linked against,
1730 which could be different from the headers version.
1731 */
1732 libver = SSLeay();
1733 r = PyLong_FromUnsignedLong(libver);
1734 if (r == NULL)
1735 return NULL;
1736 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
1737 return NULL;
1738 status = libver & 0xF;
1739 libver >>= 4;
1740 patch = libver & 0xFF;
1741 libver >>= 8;
1742 fix = libver & 0xFF;
1743 libver >>= 8;
1744 minor = libver & 0xFF;
1745 libver >>= 8;
1746 major = libver & 0xFF;
1747 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
1748 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
1749 return NULL;
1750 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
1751 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
1752 return NULL;
1753
Martin v. Löwis1a214512008-06-11 05:26:20 +00001754 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001755}