blob: fd0ea43fe40b316ce55d13113f9597902dcbe93f [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000022 PyThreadState *_save = NULL; \
23 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000039 /* these mirror ssl.h */
40 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
42 PY_SSL_ERROR_WANT_READ,
43 PY_SSL_ERROR_WANT_WRITE,
44 PY_SSL_ERROR_WANT_X509_LOOKUP,
45 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN,
47 PY_SSL_ERROR_WANT_CONNECT,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
51 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000052};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
Antoine Pitroub5218772010-05-21 09:56:06 +0000116/* SSL_CTX_clear_options() and SSL_clear_options() were first added in OpenSSL 0.9.8m */
117#if OPENSSL_VERSION_NUMBER >= 0x009080dfL
118# define HAVE_SSL_CTX_CLEAR_OPTIONS
119#else
120# undef HAVE_SSL_CTX_CLEAR_OPTIONS
121#endif
122
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000123typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000124 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000125 SSL_CTX *ctx;
126} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127
Antoine Pitrou152efa22010-05-16 18:19:27 +0000128typedef struct {
129 PyObject_HEAD
130 PyObject *Socket; /* weakref to socket on which we're layered */
131 SSL *ssl;
132 X509 *peer_cert;
133 int shutdown_seen_zero;
134} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Antoine Pitrou152efa22010-05-16 18:19:27 +0000136static PyTypeObject PySSLContext_Type;
137static PyTypeObject PySSLSocket_Type;
138
139static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
140static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000141static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000142 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000143static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
144static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000145
Antoine Pitrou152efa22010-05-16 18:19:27 +0000146#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
147#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000149typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000150 SOCKET_IS_NONBLOCKING,
151 SOCKET_IS_BLOCKING,
152 SOCKET_HAS_TIMED_OUT,
153 SOCKET_HAS_BEEN_CLOSED,
154 SOCKET_TOO_LARGE_FOR_SELECT,
155 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000156} timeout_state;
157
Thomas Woutersed03b412007-08-28 21:37:11 +0000158/* Wrap error strings with filename and line # */
159#define STRINGIFY1(x) #x
160#define STRINGIFY2(x) STRINGIFY1(x)
161#define ERRSTR1(x,y,z) (x ":" y ": " z)
162#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
163
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000164/* XXX It might be helpful to augment the error message generated
165 below with the name of the SSL function that generated the error.
166 I expect it's obvious most of the time.
167*/
168
169static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000170PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000171{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000172 PyObject *v;
173 char buf[2048];
174 char *errstr;
175 int err;
176 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000178 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 if (obj->ssl != NULL) {
181 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000183 switch (err) {
184 case SSL_ERROR_ZERO_RETURN:
185 errstr = "TLS/SSL connection has been closed";
186 p = PY_SSL_ERROR_ZERO_RETURN;
187 break;
188 case SSL_ERROR_WANT_READ:
189 errstr = "The operation did not complete (read)";
190 p = PY_SSL_ERROR_WANT_READ;
191 break;
192 case SSL_ERROR_WANT_WRITE:
193 p = PY_SSL_ERROR_WANT_WRITE;
194 errstr = "The operation did not complete (write)";
195 break;
196 case SSL_ERROR_WANT_X509_LOOKUP:
197 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000198 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 break;
200 case SSL_ERROR_WANT_CONNECT:
201 p = PY_SSL_ERROR_WANT_CONNECT;
202 errstr = "The operation did not complete (connect)";
203 break;
204 case SSL_ERROR_SYSCALL:
205 {
206 unsigned long e = ERR_get_error();
207 if (e == 0) {
208 PySocketSockObject *s
209 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
210 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000211 p = PY_SSL_ERROR_EOF;
212 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000214 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000215 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000216 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000217 v = s->errorhandler();
218 Py_DECREF(s);
219 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000221 p = PY_SSL_ERROR_SYSCALL;
222 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000223 }
224 } else {
225 p = PY_SSL_ERROR_SYSCALL;
226 /* XXX Protected by global interpreter lock */
227 errstr = ERR_error_string(e, NULL);
228 }
229 break;
230 }
231 case SSL_ERROR_SSL:
232 {
233 unsigned long e = ERR_get_error();
234 p = PY_SSL_ERROR_SSL;
235 if (e != 0)
236 /* XXX Protected by global interpreter lock */
237 errstr = ERR_error_string(e, NULL);
238 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000239 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000240 }
241 break;
242 }
243 default:
244 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
245 errstr = "Invalid error code";
246 }
247 } else {
248 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
249 }
250 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000251 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000252 v = Py_BuildValue("(is)", p, buf);
253 if (v != NULL) {
254 PyErr_SetObject(PySSLErrorObject, v);
255 Py_DECREF(v);
256 }
257 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000258}
259
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000260static PyObject *
261_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000263 char buf[2048];
264 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 if (errstr == NULL) {
267 errcode = ERR_peek_last_error();
268 errstr = ERR_error_string(errcode, NULL);
269 }
270 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000271 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000272 v = Py_BuildValue("(is)", errcode, buf);
273 if (v != NULL) {
274 PyErr_SetObject(PySSLErrorObject, v);
275 Py_DECREF(v);
276 }
277 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000278}
279
Antoine Pitrou152efa22010-05-16 18:19:27 +0000280static PySSLSocket *
281newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
282 enum py_ssl_server_or_client socket_type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000283{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000284 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000285
Antoine Pitrou152efa22010-05-16 18:19:27 +0000286 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 if (self == NULL)
288 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 self->peer_cert = NULL;
291 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000294 /* Make sure the SSL error state is initialized */
295 (void) ERR_get_state();
296 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000300 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000302#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000304#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 /* If the socket is in non-blocking mode or timeout mode, set the BIO
307 * to non-blocking mode (blocking is the default)
308 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000309 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000310 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
311 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
312 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PySSL_BEGIN_ALLOW_THREADS
315 if (socket_type == PY_SSL_CLIENT)
316 SSL_set_connect_state(self->ssl);
317 else
318 SSL_set_accept_state(self->ssl);
319 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000320
Antoine Pitrou152efa22010-05-16 18:19:27 +0000321 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000323}
324
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000325/* SSL object methods */
326
Antoine Pitrou152efa22010-05-16 18:19:27 +0000327static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000328{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000329 int ret;
330 int err;
331 int sockstate, nonblocking;
332 PySocketSockObject *sock
333 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000335 if (((PyObject*)sock) == Py_None) {
336 _setSSLError("Underlying socket connection gone",
337 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
338 return NULL;
339 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000340 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 /* just in case the blocking state of the socket has been changed */
343 nonblocking = (sock->sock_timeout >= 0.0);
344 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
345 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 /* Actually negotiate SSL connection */
348 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
349 sockstate = 0;
350 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000351 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 ret = SSL_do_handshake(self->ssl);
353 err = SSL_get_error(self->ssl, ret);
354 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000355 if (PyErr_CheckSignals())
356 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 if (err == SSL_ERROR_WANT_READ) {
358 sockstate = check_socket_and_wait_for_timeout(sock, 0);
359 } else if (err == SSL_ERROR_WANT_WRITE) {
360 sockstate = check_socket_and_wait_for_timeout(sock, 1);
361 } else {
362 sockstate = SOCKET_OPERATION_OK;
363 }
364 if (sockstate == SOCKET_HAS_TIMED_OUT) {
365 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000366 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000367 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
369 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000370 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000371 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
373 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000374 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000375 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
377 break;
378 }
379 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000380 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 if (ret < 1)
382 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (self->peer_cert)
385 X509_free (self->peer_cert);
386 PySSL_BEGIN_ALLOW_THREADS
387 self->peer_cert = SSL_get_peer_certificate(self->ssl);
388 PySSL_END_ALLOW_THREADS
389
390 Py_INCREF(Py_None);
391 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000392
393error:
394 Py_DECREF(sock);
395 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000396}
397
Thomas Woutersed03b412007-08-28 21:37:11 +0000398static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 char namebuf[X509_NAME_MAXLEN];
402 int buflen;
403 PyObject *name_obj;
404 PyObject *value_obj;
405 PyObject *attr;
406 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
409 if (buflen < 0) {
410 _setSSLError(NULL, 0, __FILE__, __LINE__);
411 goto fail;
412 }
413 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
414 if (name_obj == NULL)
415 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
418 if (buflen < 0) {
419 _setSSLError(NULL, 0, __FILE__, __LINE__);
420 Py_DECREF(name_obj);
421 goto fail;
422 }
423 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000424 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 OPENSSL_free(valuebuf);
426 if (value_obj == NULL) {
427 Py_DECREF(name_obj);
428 goto fail;
429 }
430 attr = PyTuple_New(2);
431 if (attr == NULL) {
432 Py_DECREF(name_obj);
433 Py_DECREF(value_obj);
434 goto fail;
435 }
436 PyTuple_SET_ITEM(attr, 0, name_obj);
437 PyTuple_SET_ITEM(attr, 1, value_obj);
438 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000439
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000442}
443
444static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000446{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
448 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
449 PyObject *rdnt;
450 PyObject *attr = NULL; /* tuple to hold an attribute */
451 int entry_count = X509_NAME_entry_count(xname);
452 X509_NAME_ENTRY *entry;
453 ASN1_OBJECT *name;
454 ASN1_STRING *value;
455 int index_counter;
456 int rdn_level = -1;
457 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 dn = PyList_New(0);
460 if (dn == NULL)
461 return NULL;
462 /* now create another tuple to hold the top-level RDN */
463 rdn = PyList_New(0);
464 if (rdn == NULL)
465 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 for (index_counter = 0;
468 index_counter < entry_count;
469 index_counter++)
470 {
471 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000473 /* check to see if we've gotten to a new RDN */
474 if (rdn_level >= 0) {
475 if (rdn_level != entry->set) {
476 /* yes, new RDN */
477 /* add old RDN to DN */
478 rdnt = PyList_AsTuple(rdn);
479 Py_DECREF(rdn);
480 if (rdnt == NULL)
481 goto fail0;
482 retcode = PyList_Append(dn, rdnt);
483 Py_DECREF(rdnt);
484 if (retcode < 0)
485 goto fail0;
486 /* create new RDN */
487 rdn = PyList_New(0);
488 if (rdn == NULL)
489 goto fail0;
490 }
491 }
492 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 /* now add this attribute to the current RDN */
495 name = X509_NAME_ENTRY_get_object(entry);
496 value = X509_NAME_ENTRY_get_data(entry);
497 attr = _create_tuple_for_attribute(name, value);
498 /*
499 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
500 entry->set,
501 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
502 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
503 */
504 if (attr == NULL)
505 goto fail1;
506 retcode = PyList_Append(rdn, attr);
507 Py_DECREF(attr);
508 if (retcode < 0)
509 goto fail1;
510 }
511 /* now, there's typically a dangling RDN */
512 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
513 rdnt = PyList_AsTuple(rdn);
514 Py_DECREF(rdn);
515 if (rdnt == NULL)
516 goto fail0;
517 retcode = PyList_Append(dn, rdnt);
518 Py_DECREF(rdnt);
519 if (retcode < 0)
520 goto fail0;
521 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 /* convert list to tuple */
524 rdnt = PyList_AsTuple(dn);
525 Py_DECREF(dn);
526 if (rdnt == NULL)
527 return NULL;
528 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
533 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 Py_XDECREF(dn);
535 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536}
537
538static PyObject *
539_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 /* this code follows the procedure outlined in
542 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
543 function to extract the STACK_OF(GENERAL_NAME),
544 then iterates through the stack to add the
545 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 int i, j;
548 PyObject *peer_alt_names = Py_None;
549 PyObject *v, *t;
550 X509_EXTENSION *ext = NULL;
551 GENERAL_NAMES *names = NULL;
552 GENERAL_NAME *name;
553 X509V3_EXT_METHOD *method;
554 BIO *biobuf = NULL;
555 char buf[2048];
556 char *vptr;
557 int len;
558 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000559#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000561#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000563#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 if (certificate == NULL)
566 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 /* get a memory buffer */
569 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 i = 0;
572 while ((i = X509_get_ext_by_NID(
573 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 if (peer_alt_names == Py_None) {
576 peer_alt_names = PyList_New(0);
577 if (peer_alt_names == NULL)
578 goto fail;
579 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 /* now decode the altName */
582 ext = X509_get_ext(certificate, i);
583 if(!(method = X509V3_EXT_get(ext))) {
584 PyErr_SetString
585 (PySSLErrorObject,
586 ERRSTR("No method for internalizing subjectAltName!"));
587 goto fail;
588 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 p = ext->value->data;
591 if (method->it)
592 names = (GENERAL_NAMES*)
593 (ASN1_item_d2i(NULL,
594 &p,
595 ext->value->length,
596 ASN1_ITEM_ptr(method->it)));
597 else
598 names = (GENERAL_NAMES*)
599 (method->d2i(NULL,
600 &p,
601 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 name = sk_GENERAL_NAME_value(names, j);
608 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 /* we special-case DirName as a tuple of
611 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 t = PyTuple_New(2);
614 if (t == NULL) {
615 goto fail;
616 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 v = PyUnicode_FromString("DirName");
619 if (v == NULL) {
620 Py_DECREF(t);
621 goto fail;
622 }
623 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 v = _create_tuple_for_X509_NAME (name->d.dirn);
626 if (v == NULL) {
627 Py_DECREF(t);
628 goto fail;
629 }
630 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 (void) BIO_reset(biobuf);
637 GENERAL_NAME_print(biobuf, name);
638 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
639 if (len < 0) {
640 _setSSLError(NULL, 0, __FILE__, __LINE__);
641 goto fail;
642 }
643 vptr = strchr(buf, ':');
644 if (vptr == NULL)
645 goto fail;
646 t = PyTuple_New(2);
647 if (t == NULL)
648 goto fail;
649 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
650 if (v == NULL) {
651 Py_DECREF(t);
652 goto fail;
653 }
654 PyTuple_SET_ITEM(t, 0, v);
655 v = PyUnicode_FromStringAndSize((vptr + 1),
656 (len - (vptr - buf + 1)));
657 if (v == NULL) {
658 Py_DECREF(t);
659 goto fail;
660 }
661 PyTuple_SET_ITEM(t, 1, v);
662 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 if (PyList_Append(peer_alt_names, t) < 0) {
667 Py_DECREF(t);
668 goto fail;
669 }
670 Py_DECREF(t);
671 }
672 }
673 BIO_free(biobuf);
674 if (peer_alt_names != Py_None) {
675 v = PyList_AsTuple(peer_alt_names);
676 Py_DECREF(peer_alt_names);
677 return v;
678 } else {
679 return peer_alt_names;
680 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000681
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
683 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 if (biobuf != NULL)
685 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 if (peer_alt_names != Py_None) {
688 Py_XDECREF(peer_alt_names);
689 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692}
693
694static PyObject *
695_decode_certificate (X509 *certificate, int verbose) {
696
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 PyObject *retval = NULL;
698 BIO *biobuf = NULL;
699 PyObject *peer;
700 PyObject *peer_alt_names = NULL;
701 PyObject *issuer;
702 PyObject *version;
703 PyObject *sn_obj;
704 ASN1_INTEGER *serialNumber;
705 char buf[2048];
706 int len;
707 ASN1_TIME *notBefore, *notAfter;
708 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 retval = PyDict_New();
711 if (retval == NULL)
712 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 peer = _create_tuple_for_X509_NAME(
715 X509_get_subject_name(certificate));
716 if (peer == NULL)
717 goto fail0;
718 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
719 Py_DECREF(peer);
720 goto fail0;
721 }
722 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 if (verbose) {
725 issuer = _create_tuple_for_X509_NAME(
726 X509_get_issuer_name(certificate));
727 if (issuer == NULL)
728 goto fail0;
729 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
730 Py_DECREF(issuer);
731 goto fail0;
732 }
733 Py_DECREF(issuer);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 version = PyLong_FromLong(X509_get_version(certificate) + 1);
736 if (PyDict_SetItemString(retval, "version", version) < 0) {
737 Py_DECREF(version);
738 goto fail0;
739 }
740 Py_DECREF(version);
741 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 /* get a memory buffer */
744 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (verbose) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 (void) BIO_reset(biobuf);
749 serialNumber = X509_get_serialNumber(certificate);
750 /* should not exceed 20 octets, 160 bits, so buf is big enough */
751 i2a_ASN1_INTEGER(biobuf, serialNumber);
752 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
753 if (len < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto fail1;
756 }
757 sn_obj = PyUnicode_FromStringAndSize(buf, len);
758 if (sn_obj == NULL)
759 goto fail1;
760 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
761 Py_DECREF(sn_obj);
762 goto fail1;
763 }
764 Py_DECREF(sn_obj);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 (void) BIO_reset(biobuf);
767 notBefore = X509_get_notBefore(certificate);
768 ASN1_TIME_print(biobuf, notBefore);
769 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
770 if (len < 0) {
771 _setSSLError(NULL, 0, __FILE__, __LINE__);
772 goto fail1;
773 }
774 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
775 if (pnotBefore == NULL)
776 goto fail1;
777 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
778 Py_DECREF(pnotBefore);
779 goto fail1;
780 }
781 Py_DECREF(pnotBefore);
782 }
Thomas Woutersed03b412007-08-28 21:37:11 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 (void) BIO_reset(biobuf);
785 notAfter = X509_get_notAfter(certificate);
786 ASN1_TIME_print(biobuf, notAfter);
787 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
788 if (len < 0) {
789 _setSSLError(NULL, 0, __FILE__, __LINE__);
790 goto fail1;
791 }
792 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
793 if (pnotAfter == NULL)
794 goto fail1;
795 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
796 Py_DECREF(pnotAfter);
797 goto fail1;
798 }
799 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 peer_alt_names = _get_peer_alt_names(certificate);
804 if (peer_alt_names == NULL)
805 goto fail1;
806 else if (peer_alt_names != Py_None) {
807 if (PyDict_SetItemString(retval, "subjectAltName",
808 peer_alt_names) < 0) {
809 Py_DECREF(peer_alt_names);
810 goto fail1;
811 }
812 Py_DECREF(peer_alt_names);
813 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 BIO_free(biobuf);
816 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000817
818 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 if (biobuf != NULL)
820 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000821 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 Py_XDECREF(retval);
823 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000824}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000825
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
827static PyObject *
828PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000831 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 X509 *x=NULL;
833 BIO *cert;
834 int verbose = 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Victor Stinner3800e1e2010-05-16 21:23:48 +0000836 if (!PyArg_ParseTuple(args, "O&|i:test_decode_certificate",
837 PyUnicode_FSConverter, &filename, &verbose))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 if ((cert=BIO_new(BIO_s_file())) == NULL) {
841 PyErr_SetString(PySSLErrorObject,
842 "Can't malloc memory to read file");
843 goto fail0;
844 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845
Victor Stinner3800e1e2010-05-16 21:23:48 +0000846 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 PyErr_SetString(PySSLErrorObject,
848 "Can't open file");
849 goto fail0;
850 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
853 if (x == NULL) {
854 PyErr_SetString(PySSLErrorObject,
855 "Error decoding PEM-encoded file");
856 goto fail0;
857 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000858
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000859 retval = _decode_certificate(x, verbose);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000860 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
862 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000863 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 if (cert != NULL) BIO_free(cert);
865 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866}
867
868
869static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000870PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 PyObject *retval = NULL;
873 int len;
874 int verification;
875 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
878 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 if (!self->peer_cert)
881 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 if (PyObject_IsTrue(binary_mode)) {
884 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 bytes_buf = NULL;
889 len = i2d_X509(self->peer_cert, &bytes_buf);
890 if (len < 0) {
891 PySSL_SetError(self, len, __FILE__, __LINE__);
892 return NULL;
893 }
894 /* this is actually an immutable bytes sequence */
895 retval = PyBytes_FromStringAndSize
896 ((const char *) bytes_buf, len);
897 OPENSSL_free(bytes_buf);
898 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000901 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 if ((verification & SSL_VERIFY_PEER) == 0)
903 return PyDict_New();
904 else
905 return _decode_certificate (self->peer_cert, 0);
906 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907}
908
909PyDoc_STRVAR(PySSL_peercert_doc,
910"peer_certificate([der=False]) -> certificate\n\
911\n\
912Returns the certificate for the peer. If no certificate was provided,\n\
913returns None. If a certificate was provided, but not validated, returns\n\
914an empty dictionary. Otherwise returns a dict containing information\n\
915about the peer certificate.\n\
916\n\
917If the optional argument is True, returns a DER-encoded copy of the\n\
918peer certificate, or None if no certificate was provided. This will\n\
919return the certificate even if it wasn't validated.");
920
Antoine Pitrou152efa22010-05-16 18:19:27 +0000921static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 PyObject *retval, *v;
924 SSL_CIPHER *current;
925 char *cipher_name;
926 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 if (self->ssl == NULL)
929 return Py_None;
930 current = SSL_get_current_cipher(self->ssl);
931 if (current == NULL)
932 return Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 retval = PyTuple_New(3);
935 if (retval == NULL)
936 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 cipher_name = (char *) SSL_CIPHER_get_name(current);
939 if (cipher_name == NULL) {
940 PyTuple_SET_ITEM(retval, 0, Py_None);
941 } else {
942 v = PyUnicode_FromString(cipher_name);
943 if (v == NULL)
944 goto fail0;
945 PyTuple_SET_ITEM(retval, 0, v);
946 }
947 cipher_protocol = SSL_CIPHER_get_version(current);
948 if (cipher_protocol == NULL) {
949 PyTuple_SET_ITEM(retval, 1, Py_None);
950 } else {
951 v = PyUnicode_FromString(cipher_protocol);
952 if (v == NULL)
953 goto fail0;
954 PyTuple_SET_ITEM(retval, 1, v);
955 }
956 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
957 if (v == NULL)
958 goto fail0;
959 PyTuple_SET_ITEM(retval, 2, v);
960 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000961
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000962 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 Py_DECREF(retval);
964 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965}
966
Antoine Pitrou152efa22010-05-16 18:19:27 +0000967static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000968{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 if (self->peer_cert) /* Possible not to have one? */
970 X509_free (self->peer_cert);
971 if (self->ssl)
972 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 Py_XDECREF(self->Socket);
974 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000975}
976
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000977/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000978 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000979 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000980 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000981
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000982static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000983check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000984{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 fd_set fds;
986 struct timeval tv;
987 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 /* Nothing to do unless we're in timeout mode (not non-blocking) */
990 if (s->sock_timeout < 0.0)
991 return SOCKET_IS_BLOCKING;
992 else if (s->sock_timeout == 0.0)
993 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 /* Guard against closed socket */
996 if (s->sock_fd < 0)
997 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 /* Prefer poll, if available, since you can poll() any fd
1000 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001001#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 {
1003 struct pollfd pollfd;
1004 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 pollfd.fd = s->sock_fd;
1007 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 /* s->sock_timeout is in seconds, timeout in ms */
1010 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1011 PySSL_BEGIN_ALLOW_THREADS
1012 rc = poll(&pollfd, 1, timeout);
1013 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 goto normal_return;
1016 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017#endif
1018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001020#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 if (s->sock_fd >= FD_SETSIZE)
1022 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001023#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 /* Construct the arguments to select */
1026 tv.tv_sec = (int)s->sock_timeout;
1027 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1028 FD_ZERO(&fds);
1029 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 /* See if the socket is ready */
1032 PySSL_BEGIN_ALLOW_THREADS
1033 if (writing)
1034 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1035 else
1036 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1037 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001038
Bill Janssen6e027db2007-11-15 22:23:56 +00001039#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001040normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001041#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1043 (when we are able to write or when there's something to read) */
1044 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001045}
1046
Antoine Pitrou152efa22010-05-16 18:19:27 +00001047static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001048{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 Py_buffer buf;
1050 int len;
1051 int sockstate;
1052 int err;
1053 int nonblocking;
1054 PySocketSockObject *sock
1055 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 if (((PyObject*)sock) == Py_None) {
1058 _setSSLError("Underlying socket connection gone",
1059 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1060 return NULL;
1061 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001062 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001064 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1065 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001067 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068
1069 /* just in case the blocking state of the socket has been changed */
1070 nonblocking = (sock->sock_timeout >= 0.0);
1071 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1072 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1073
1074 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1075 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1076 PyErr_SetString(PySSLErrorObject,
1077 "The write operation timed out");
1078 goto error;
1079 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1080 PyErr_SetString(PySSLErrorObject,
1081 "Underlying socket has been closed.");
1082 goto error;
1083 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1084 PyErr_SetString(PySSLErrorObject,
1085 "Underlying socket too large for select().");
1086 goto error;
1087 }
1088 do {
1089 err = 0;
1090 PySSL_BEGIN_ALLOW_THREADS
1091 len = SSL_write(self->ssl, buf.buf, buf.len);
1092 err = SSL_get_error(self->ssl, len);
1093 PySSL_END_ALLOW_THREADS
1094 if (PyErr_CheckSignals()) {
1095 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001096 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001098 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001100 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else {
1102 sockstate = SOCKET_OPERATION_OK;
1103 }
1104 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1105 PyErr_SetString(PySSLErrorObject,
1106 "The write operation timed out");
1107 goto error;
1108 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1109 PyErr_SetString(PySSLErrorObject,
1110 "Underlying socket has been closed.");
1111 goto error;
1112 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1113 break;
1114 }
1115 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001116
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001117 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 PyBuffer_Release(&buf);
1119 if (len > 0)
1120 return PyLong_FromLong(len);
1121 else
1122 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001123
1124error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001125 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 PyBuffer_Release(&buf);
1127 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001128}
1129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001131"write(s) -> len\n\
1132\n\
1133Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001135
Antoine Pitrou152efa22010-05-16 18:19:27 +00001136static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001137{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 PySSL_BEGIN_ALLOW_THREADS
1141 count = SSL_pending(self->ssl);
1142 PySSL_END_ALLOW_THREADS
1143 if (count < 0)
1144 return PySSL_SetError(self, count, __FILE__, __LINE__);
1145 else
1146 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001147}
1148
1149PyDoc_STRVAR(PySSL_SSLpending_doc,
1150"pending() -> count\n\
1151\n\
1152Returns the number of already decrypted bytes available for read,\n\
1153pending on the connection.\n");
1154
Antoine Pitrou152efa22010-05-16 18:19:27 +00001155static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001156{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 PyObject *dest = NULL;
1158 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001160 int len, count;
1161 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 int sockstate;
1163 int err;
1164 int nonblocking;
1165 PySocketSockObject *sock
1166 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 if (((PyObject*)sock) == Py_None) {
1169 _setSSLError("Underlying socket connection gone",
1170 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1171 return NULL;
1172 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001173 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001175 buf.obj = NULL;
1176 buf.buf = NULL;
1177 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001178 goto error;
1179
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001180 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1181 dest = PyBytes_FromStringAndSize(NULL, len);
1182 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001183 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001184 mem = PyBytes_AS_STRING(dest);
1185 }
1186 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001188 mem = buf.buf;
1189 if (len <= 0 || len > buf.len) {
1190 len = (int) buf.len;
1191 if (buf.len != len) {
1192 PyErr_SetString(PyExc_OverflowError,
1193 "maximum length can't fit in a C 'int'");
1194 goto error;
1195 }
1196 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 }
1198
1199 /* just in case the blocking state of the socket has been changed */
1200 nonblocking = (sock->sock_timeout >= 0.0);
1201 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1202 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1203
1204 /* first check if there are bytes ready to be read */
1205 PySSL_BEGIN_ALLOW_THREADS
1206 count = SSL_pending(self->ssl);
1207 PySSL_END_ALLOW_THREADS
1208
1209 if (!count) {
1210 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1211 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1212 PyErr_SetString(PySSLErrorObject,
1213 "The read operation timed out");
1214 goto error;
1215 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1216 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001217 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 goto error;
1219 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1220 count = 0;
1221 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001222 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 }
1224 do {
1225 err = 0;
1226 PySSL_BEGIN_ALLOW_THREADS
1227 count = SSL_read(self->ssl, mem, len);
1228 err = SSL_get_error(self->ssl, count);
1229 PySSL_END_ALLOW_THREADS
1230 if (PyErr_CheckSignals())
1231 goto error;
1232 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001233 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001235 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1237 (SSL_get_shutdown(self->ssl) ==
1238 SSL_RECEIVED_SHUTDOWN))
1239 {
1240 count = 0;
1241 goto done;
1242 } else {
1243 sockstate = SOCKET_OPERATION_OK;
1244 }
1245 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1246 PyErr_SetString(PySSLErrorObject,
1247 "The read operation timed out");
1248 goto error;
1249 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1250 break;
1251 }
1252 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1253 if (count <= 0) {
1254 PySSL_SetError(self, count, __FILE__, __LINE__);
1255 goto error;
1256 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001257
1258done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001259 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001261 _PyBytes_Resize(&dest, count);
1262 return dest;
1263 }
1264 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 PyBuffer_Release(&buf);
1266 return PyLong_FromLong(count);
1267 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001268
1269error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001270 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001271 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001272 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001273 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001276}
1277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001278PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001279"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001280\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001281Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001282
Antoine Pitrou152efa22010-05-16 18:19:27 +00001283static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001284{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 int err, ssl_err, sockstate, nonblocking;
1286 int zeros = 0;
1287 PySocketSockObject *sock
1288 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 /* Guard against closed socket */
1291 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1292 _setSSLError("Underlying socket connection gone",
1293 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1294 return NULL;
1295 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001296 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297
1298 /* Just in case the blocking state of the socket has been changed */
1299 nonblocking = (sock->sock_timeout >= 0.0);
1300 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1301 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1302
1303 while (1) {
1304 PySSL_BEGIN_ALLOW_THREADS
1305 /* Disable read-ahead so that unwrap can work correctly.
1306 * Otherwise OpenSSL might read in too much data,
1307 * eating clear text data that happens to be
1308 * transmitted after the SSL shutdown.
1309 * Should be safe to call repeatedly everytime this
1310 * function is used and the shutdown_seen_zero != 0
1311 * condition is met.
1312 */
1313 if (self->shutdown_seen_zero)
1314 SSL_set_read_ahead(self->ssl, 0);
1315 err = SSL_shutdown(self->ssl);
1316 PySSL_END_ALLOW_THREADS
1317 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1318 if (err > 0)
1319 break;
1320 if (err == 0) {
1321 /* Don't loop endlessly; instead preserve legacy
1322 behaviour of trying SSL_shutdown() only twice.
1323 This looks necessary for OpenSSL < 0.9.8m */
1324 if (++zeros > 1)
1325 break;
1326 /* Shutdown was sent, now try receiving */
1327 self->shutdown_seen_zero = 1;
1328 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001329 }
1330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 /* Possibly retry shutdown until timeout or failure */
1332 ssl_err = SSL_get_error(self->ssl, err);
1333 if (ssl_err == SSL_ERROR_WANT_READ)
1334 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1335 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1336 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1337 else
1338 break;
1339 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1340 if (ssl_err == SSL_ERROR_WANT_READ)
1341 PyErr_SetString(PySSLErrorObject,
1342 "The read operation timed out");
1343 else
1344 PyErr_SetString(PySSLErrorObject,
1345 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001346 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 }
1348 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1349 PyErr_SetString(PySSLErrorObject,
1350 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001351 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 }
1353 else if (sockstate != SOCKET_OPERATION_OK)
1354 /* Retain the SSL error code */
1355 break;
1356 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001357
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001358 if (err < 0) {
1359 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001362 else
1363 /* It's already INCREF'ed */
1364 return (PyObject *) sock;
1365
1366error:
1367 Py_DECREF(sock);
1368 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001369}
1370
1371PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1372"shutdown(s) -> socket\n\
1373\n\
1374Does the SSL shutdown handshake with the remote end, and returns\n\
1375the underlying socket object.");
1376
1377
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001378static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1380 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1381 PySSL_SSLwrite_doc},
1382 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1383 PySSL_SSLread_doc},
1384 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1385 PySSL_SSLpending_doc},
1386 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1387 PySSL_peercert_doc},
1388 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1389 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1390 PySSL_SSLshutdown_doc},
1391 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001392};
1393
Antoine Pitrou152efa22010-05-16 18:19:27 +00001394static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396 "_ssl._SSLSocket", /*tp_name*/
1397 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 0, /*tp_itemsize*/
1399 /* methods */
1400 (destructor)PySSL_dealloc, /*tp_dealloc*/
1401 0, /*tp_print*/
1402 0, /*tp_getattr*/
1403 0, /*tp_setattr*/
1404 0, /*tp_reserved*/
1405 0, /*tp_repr*/
1406 0, /*tp_as_number*/
1407 0, /*tp_as_sequence*/
1408 0, /*tp_as_mapping*/
1409 0, /*tp_hash*/
1410 0, /*tp_call*/
1411 0, /*tp_str*/
1412 0, /*tp_getattro*/
1413 0, /*tp_setattro*/
1414 0, /*tp_as_buffer*/
1415 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1416 0, /*tp_doc*/
1417 0, /*tp_traverse*/
1418 0, /*tp_clear*/
1419 0, /*tp_richcompare*/
1420 0, /*tp_weaklistoffset*/
1421 0, /*tp_iter*/
1422 0, /*tp_iternext*/
1423 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001424};
1425
Antoine Pitrou152efa22010-05-16 18:19:27 +00001426
1427/*
1428 * _SSLContext objects
1429 */
1430
1431static PyObject *
1432context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1433{
1434 char *kwlist[] = {"protocol", NULL};
1435 PySSLContext *self;
1436 int proto_version = PY_SSL_VERSION_SSL23;
1437 SSL_CTX *ctx = NULL;
1438
1439 if (!PyArg_ParseTupleAndKeywords(
1440 args, kwds, "i:_SSLContext", kwlist,
1441 &proto_version))
1442 return NULL;
1443
1444 PySSL_BEGIN_ALLOW_THREADS
1445 if (proto_version == PY_SSL_VERSION_TLS1)
1446 ctx = SSL_CTX_new(TLSv1_method());
1447 else if (proto_version == PY_SSL_VERSION_SSL3)
1448 ctx = SSL_CTX_new(SSLv3_method());
1449 else if (proto_version == PY_SSL_VERSION_SSL2)
1450 ctx = SSL_CTX_new(SSLv2_method());
1451 else if (proto_version == PY_SSL_VERSION_SSL23)
1452 ctx = SSL_CTX_new(SSLv23_method());
1453 else
1454 proto_version = -1;
1455 PySSL_END_ALLOW_THREADS
1456
1457 if (proto_version == -1) {
1458 PyErr_SetString(PyExc_ValueError,
1459 "invalid protocol version");
1460 return NULL;
1461 }
1462 if (ctx == NULL) {
1463 PyErr_SetString(PySSLErrorObject,
1464 "failed to allocate SSL context");
1465 return NULL;
1466 }
1467
1468 assert(type != NULL && type->tp_alloc != NULL);
1469 self = (PySSLContext *) type->tp_alloc(type, 0);
1470 if (self == NULL) {
1471 SSL_CTX_free(ctx);
1472 return NULL;
1473 }
1474 self->ctx = ctx;
1475 /* Defaults */
1476 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1477 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1478
1479 return (PyObject *)self;
1480}
1481
1482static void
1483context_dealloc(PySSLContext *self)
1484{
1485 SSL_CTX_free(self->ctx);
1486 Py_TYPE(self)->tp_free(self);
1487}
1488
1489static PyObject *
1490set_ciphers(PySSLContext *self, PyObject *args)
1491{
1492 int ret;
1493 const char *cipherlist;
1494
1495 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1496 return NULL;
1497 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1498 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001499 /* Clearing the error queue is necessary on some OpenSSL versions,
1500 otherwise the error will be reported again when another SSL call
1501 is done. */
1502 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001503 PyErr_SetString(PySSLErrorObject,
1504 "No cipher can be selected.");
1505 return NULL;
1506 }
1507 Py_RETURN_NONE;
1508}
1509
1510static PyObject *
1511get_verify_mode(PySSLContext *self, void *c)
1512{
1513 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1514 case SSL_VERIFY_NONE:
1515 return PyLong_FromLong(PY_SSL_CERT_NONE);
1516 case SSL_VERIFY_PEER:
1517 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1518 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1519 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1520 }
1521 PyErr_SetString(PySSLErrorObject,
1522 "invalid return value from SSL_CTX_get_verify_mode");
1523 return NULL;
1524}
1525
1526static int
1527set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1528{
1529 int n, mode;
1530 if (!PyArg_Parse(arg, "i", &n))
1531 return -1;
1532 if (n == PY_SSL_CERT_NONE)
1533 mode = SSL_VERIFY_NONE;
1534 else if (n == PY_SSL_CERT_OPTIONAL)
1535 mode = SSL_VERIFY_PEER;
1536 else if (n == PY_SSL_CERT_REQUIRED)
1537 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1538 else {
1539 PyErr_SetString(PyExc_ValueError,
1540 "invalid value for verify_mode");
1541 return -1;
1542 }
1543 SSL_CTX_set_verify(self->ctx, mode, NULL);
1544 return 0;
1545}
1546
1547static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001548get_options(PySSLContext *self, void *c)
1549{
1550 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1551}
1552
1553static int
1554set_options(PySSLContext *self, PyObject *arg, void *c)
1555{
1556 long new_opts, opts, set, clear;
1557 if (!PyArg_Parse(arg, "l", &new_opts))
1558 return -1;
1559 opts = SSL_CTX_get_options(self->ctx);
1560 clear = opts & ~new_opts;
1561 set = ~opts & new_opts;
1562 if (clear) {
1563#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1564 SSL_CTX_clear_options(self->ctx, clear);
1565#else
1566 PyErr_SetString(PyExc_ValueError,
1567 "can't clear options before OpenSSL 0.9.8m");
1568 return -1;
1569#endif
1570 }
1571 if (set)
1572 SSL_CTX_set_options(self->ctx, set);
1573 return 0;
1574}
1575
1576static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001577load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1578{
1579 char *kwlist[] = {"certfile", "keyfile", NULL};
1580 PyObject *certfile, *keyfile = NULL;
1581 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1582 int r;
1583
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001584 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001585 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001586 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1587 "O|O:load_cert_chain", kwlist,
1588 &certfile, &keyfile))
1589 return NULL;
1590 if (keyfile == Py_None)
1591 keyfile = NULL;
1592 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1593 PyErr_SetString(PyExc_TypeError,
1594 "certfile should be a valid filesystem path");
1595 return NULL;
1596 }
1597 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1598 PyErr_SetString(PyExc_TypeError,
1599 "keyfile should be a valid filesystem path");
1600 goto error;
1601 }
1602 PySSL_BEGIN_ALLOW_THREADS
1603 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1604 PyBytes_AS_STRING(certfile_bytes));
1605 PySSL_END_ALLOW_THREADS
1606 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001607 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001608 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001609 PyErr_SetFromErrno(PyExc_IOError);
1610 }
1611 else {
1612 _setSSLError(NULL, 0, __FILE__, __LINE__);
1613 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001614 goto error;
1615 }
1616 PySSL_BEGIN_ALLOW_THREADS
1617 r = SSL_CTX_use_RSAPrivateKey_file(self->ctx,
1618 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1619 SSL_FILETYPE_PEM);
1620 PySSL_END_ALLOW_THREADS
1621 Py_XDECREF(keyfile_bytes);
1622 Py_XDECREF(certfile_bytes);
1623 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001624 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001625 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001626 PyErr_SetFromErrno(PyExc_IOError);
1627 }
1628 else {
1629 _setSSLError(NULL, 0, __FILE__, __LINE__);
1630 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001631 return NULL;
1632 }
1633 PySSL_BEGIN_ALLOW_THREADS
1634 r = SSL_CTX_check_private_key(self->ctx);
1635 PySSL_END_ALLOW_THREADS
1636 if (r != 1) {
1637 _setSSLError(NULL, 0, __FILE__, __LINE__);
1638 return NULL;
1639 }
1640 Py_RETURN_NONE;
1641
1642error:
1643 Py_XDECREF(keyfile_bytes);
1644 Py_XDECREF(certfile_bytes);
1645 return NULL;
1646}
1647
1648static PyObject *
1649load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1650{
1651 char *kwlist[] = {"cafile", "capath", NULL};
1652 PyObject *cafile = NULL, *capath = NULL;
1653 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1654 const char *cafile_buf = NULL, *capath_buf = NULL;
1655 int r;
1656
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001657 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001658 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1659 "|OO:load_verify_locations", kwlist,
1660 &cafile, &capath))
1661 return NULL;
1662 if (cafile == Py_None)
1663 cafile = NULL;
1664 if (capath == Py_None)
1665 capath = NULL;
1666 if (cafile == NULL && capath == NULL) {
1667 PyErr_SetString(PyExc_TypeError,
1668 "cafile and capath cannot be both omitted");
1669 return NULL;
1670 }
1671 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1672 PyErr_SetString(PyExc_TypeError,
1673 "cafile should be a valid filesystem path");
1674 return NULL;
1675 }
1676 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
1677 Py_DECREF(cafile_bytes);
1678 PyErr_SetString(PyExc_TypeError,
1679 "capath should be a valid filesystem path");
1680 return NULL;
1681 }
1682 if (cafile)
1683 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1684 if (capath)
1685 capath_buf = PyBytes_AS_STRING(capath_bytes);
1686 PySSL_BEGIN_ALLOW_THREADS
1687 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1688 PySSL_END_ALLOW_THREADS
1689 Py_XDECREF(cafile_bytes);
1690 Py_XDECREF(capath_bytes);
1691 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001692 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001693 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001694 PyErr_SetFromErrno(PyExc_IOError);
1695 }
1696 else {
1697 _setSSLError(NULL, 0, __FILE__, __LINE__);
1698 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001699 return NULL;
1700 }
1701 Py_RETURN_NONE;
1702}
1703
1704static PyObject *
1705context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1706{
1707 char *kwlist[] = {"sock", "server_side", NULL};
1708 PySocketSockObject *sock;
1709 int server_side = 0;
1710
1711 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i:_wrap_socket", kwlist,
1712 PySocketModule.Sock_Type,
1713 &sock, &server_side))
1714 return NULL;
1715
1716 return (PyObject *) newPySSLSocket(self->ctx, sock, server_side);
1717}
1718
1719static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001720 {"options", (getter) get_options,
1721 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001722 {"verify_mode", (getter) get_verify_mode,
1723 (setter) set_verify_mode, NULL},
1724 {NULL}, /* sentinel */
1725};
1726
1727static struct PyMethodDef context_methods[] = {
1728 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1729 METH_VARARGS | METH_KEYWORDS, NULL},
1730 {"set_ciphers", (PyCFunction) set_ciphers,
1731 METH_VARARGS, NULL},
1732 {"load_cert_chain", (PyCFunction) load_cert_chain,
1733 METH_VARARGS | METH_KEYWORDS, NULL},
1734 {"load_verify_locations", (PyCFunction) load_verify_locations,
1735 METH_VARARGS | METH_KEYWORDS, NULL},
1736 {NULL, NULL} /* sentinel */
1737};
1738
1739static PyTypeObject PySSLContext_Type = {
1740 PyVarObject_HEAD_INIT(NULL, 0)
1741 "_ssl._SSLContext", /*tp_name*/
1742 sizeof(PySSLContext), /*tp_basicsize*/
1743 0, /*tp_itemsize*/
1744 (destructor)context_dealloc, /*tp_dealloc*/
1745 0, /*tp_print*/
1746 0, /*tp_getattr*/
1747 0, /*tp_setattr*/
1748 0, /*tp_reserved*/
1749 0, /*tp_repr*/
1750 0, /*tp_as_number*/
1751 0, /*tp_as_sequence*/
1752 0, /*tp_as_mapping*/
1753 0, /*tp_hash*/
1754 0, /*tp_call*/
1755 0, /*tp_str*/
1756 0, /*tp_getattro*/
1757 0, /*tp_setattro*/
1758 0, /*tp_as_buffer*/
1759 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1760 0, /*tp_doc*/
1761 0, /*tp_traverse*/
1762 0, /*tp_clear*/
1763 0, /*tp_richcompare*/
1764 0, /*tp_weaklistoffset*/
1765 0, /*tp_iter*/
1766 0, /*tp_iternext*/
1767 context_methods, /*tp_methods*/
1768 0, /*tp_members*/
1769 context_getsetlist, /*tp_getset*/
1770 0, /*tp_base*/
1771 0, /*tp_dict*/
1772 0, /*tp_descr_get*/
1773 0, /*tp_descr_set*/
1774 0, /*tp_dictoffset*/
1775 0, /*tp_init*/
1776 0, /*tp_alloc*/
1777 context_new, /*tp_new*/
1778};
1779
1780
1781
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001782#ifdef HAVE_OPENSSL_RAND
1783
1784/* helper routines for seeding the SSL PRNG */
1785static PyObject *
1786PySSL_RAND_add(PyObject *self, PyObject *args)
1787{
1788 char *buf;
1789 int len;
1790 double entropy;
1791
1792 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001793 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794 RAND_add(buf, len, entropy);
1795 Py_INCREF(Py_None);
1796 return Py_None;
1797}
1798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001799PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001800"RAND_add(string, entropy)\n\
1801\n\
1802Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001804
1805static PyObject *
1806PySSL_RAND_status(PyObject *self)
1807{
Christian Heimes217cfd12007-12-02 14:31:20 +00001808 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001809}
1810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001811PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001812"RAND_status() -> 0 or 1\n\
1813\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001814Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1815It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1816using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001817
1818static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001819PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001820{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001821 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001822 int bytes;
1823
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001824 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1825 PyUnicode_FSConverter, &path))
1826 return NULL;
1827
1828 bytes = RAND_egd(PyBytes_AsString(path));
1829 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001830 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001831 PyErr_SetString(PySSLErrorObject,
1832 "EGD connection failed or EGD did not return "
1833 "enough data to seed the PRNG");
1834 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001835 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001836 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001837}
1838
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001839PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001840"RAND_egd(path) -> bytes\n\
1841\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001842Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1843Returns number of bytes read. Raises SSLError if connection to EGD\n\
1844fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001845
1846#endif
1847
Bill Janssen40a0f662008-08-12 16:56:25 +00001848
1849
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001850/* List of functions exported by this module. */
1851
1852static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 {"_test_decode_cert", PySSL_test_decode_certificate,
1854 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001855#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1857 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001858 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 PySSL_RAND_egd_doc},
1860 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1861 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001862#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001864};
1865
1866
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867#ifdef WITH_THREAD
1868
1869/* an implementation of OpenSSL threading operations in terms
1870 of the Python C thread library */
1871
1872static PyThread_type_lock *_ssl_locks = NULL;
1873
1874static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001876}
1877
Bill Janssen6e027db2007-11-15 22:23:56 +00001878static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 (int mode, int n, const char *file, int line) {
1880 /* this function is needed to perform locking on shared data
1881 structures. (Note that OpenSSL uses a number of global data
1882 structures that will be implicitly shared whenever multiple
1883 threads use OpenSSL.) Multi-threaded applications will
1884 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 locking_function() must be able to handle up to
1887 CRYPTO_num_locks() different mutex locks. It sets the n-th
1888 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 file and line are the file number of the function setting the
1891 lock. They can be useful for debugging.
1892 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 if ((_ssl_locks == NULL) ||
1895 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1896 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 if (mode & CRYPTO_LOCK) {
1899 PyThread_acquire_lock(_ssl_locks[n], 1);
1900 } else {
1901 PyThread_release_lock(_ssl_locks[n]);
1902 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001903}
1904
1905static int _setup_ssl_threads(void) {
1906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 if (_ssl_locks == NULL) {
1910 _ssl_locks_count = CRYPTO_num_locks();
1911 _ssl_locks = (PyThread_type_lock *)
1912 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1913 if (_ssl_locks == NULL)
1914 return 0;
1915 memset(_ssl_locks, 0,
1916 sizeof(PyThread_type_lock) * _ssl_locks_count);
1917 for (i = 0; i < _ssl_locks_count; i++) {
1918 _ssl_locks[i] = PyThread_allocate_lock();
1919 if (_ssl_locks[i] == NULL) {
1920 unsigned int j;
1921 for (j = 0; j < i; j++) {
1922 PyThread_free_lock(_ssl_locks[j]);
1923 }
1924 free(_ssl_locks);
1925 return 0;
1926 }
1927 }
1928 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
1929 CRYPTO_set_id_callback(_ssl_thread_id_function);
1930 }
1931 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001932}
1933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001936PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001939
Martin v. Löwis1a214512008-06-11 05:26:20 +00001940
1941static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 PyModuleDef_HEAD_INIT,
1943 "_ssl",
1944 module_doc,
1945 -1,
1946 PySSL_methods,
1947 NULL,
1948 NULL,
1949 NULL,
1950 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001951};
1952
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001953PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001954PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001955{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 PyObject *m, *d, *r;
1957 unsigned long libver;
1958 unsigned int major, minor, fix, patch, status;
1959 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001960
Antoine Pitrou152efa22010-05-16 18:19:27 +00001961 if (PyType_Ready(&PySSLContext_Type) < 0)
1962 return NULL;
1963 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 m = PyModule_Create(&_sslmodule);
1967 if (m == NULL)
1968 return NULL;
1969 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 /* Load _socket module and its C API */
1972 socket_api = PySocketModule_ImportModuleAndAPI();
1973 if (!socket_api)
1974 return NULL;
1975 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 /* Init OpenSSL */
1978 SSL_load_error_strings();
1979 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 /* note that this will start threading if not already started */
1982 if (!_setup_ssl_threads()) {
1983 return NULL;
1984 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001985#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 /* Add symbols to module dict */
1989 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
1990 PySocketModule.error,
1991 NULL);
1992 if (PySSLErrorObject == NULL)
1993 return NULL;
1994 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
1995 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001996 if (PyDict_SetItemString(d, "_SSLContext",
1997 (PyObject *)&PySSLContext_Type) != 0)
1998 return NULL;
1999 if (PyDict_SetItemString(d, "_SSLSocket",
2000 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 return NULL;
2002 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2003 PY_SSL_ERROR_ZERO_RETURN);
2004 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2005 PY_SSL_ERROR_WANT_READ);
2006 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2007 PY_SSL_ERROR_WANT_WRITE);
2008 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2009 PY_SSL_ERROR_WANT_X509_LOOKUP);
2010 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2011 PY_SSL_ERROR_SYSCALL);
2012 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2013 PY_SSL_ERROR_SSL);
2014 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2015 PY_SSL_ERROR_WANT_CONNECT);
2016 /* non ssl.h errorcodes */
2017 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2018 PY_SSL_ERROR_EOF);
2019 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2020 PY_SSL_ERROR_INVALID_ERROR_CODE);
2021 /* cert requirements */
2022 PyModule_AddIntConstant(m, "CERT_NONE",
2023 PY_SSL_CERT_NONE);
2024 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2025 PY_SSL_CERT_OPTIONAL);
2026 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2027 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 /* protocol versions */
2030 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2031 PY_SSL_VERSION_SSL2);
2032 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2033 PY_SSL_VERSION_SSL3);
2034 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2035 PY_SSL_VERSION_SSL23);
2036 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2037 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002038
Antoine Pitroub5218772010-05-21 09:56:06 +00002039 /* protocol options */
2040 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2041 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2042 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2043 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002045 /* OpenSSL version */
2046 /* SSLeay() gives us the version of the library linked against,
2047 which could be different from the headers version.
2048 */
2049 libver = SSLeay();
2050 r = PyLong_FromUnsignedLong(libver);
2051 if (r == NULL)
2052 return NULL;
2053 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2054 return NULL;
2055 status = libver & 0xF;
2056 libver >>= 4;
2057 patch = libver & 0xFF;
2058 libver >>= 8;
2059 fix = libver & 0xFF;
2060 libver >>= 8;
2061 minor = libver & 0xFF;
2062 libver >>= 8;
2063 major = libver & 0xFF;
2064 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2065 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2066 return NULL;
2067 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2068 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2069 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002072}