blob: 7fee74cd5343f6028a1fd94eb638f4287a7b2c0c [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"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000079/* Include symbols from _socket module */
80#include "socketmodule.h"
81
Benjamin Petersonb173f782009-05-05 22:31:58 +000082static PySocketModule_APIObject PySocketModule;
83
Thomas Woutersed03b412007-08-28 21:37:11 +000084#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085#include <poll.h>
86#elif defined(HAVE_SYS_POLL_H)
87#include <sys/poll.h>
88#endif
89
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090/* Include OpenSSL header files */
91#include "openssl/rsa.h"
92#include "openssl/crypto.h"
93#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000095#include "openssl/pem.h"
96#include "openssl/ssl.h"
97#include "openssl/err.h"
98#include "openssl/rand.h"
99
100/* SSL error object */
101static PyObject *PySSLErrorObject;
102
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000103#ifdef WITH_THREAD
104
105/* serves as a flag to see whether we've initialized the SSL thread support. */
106/* 0 means no, greater than 0 means yes */
107
108static unsigned int _ssl_locks_count = 0;
109
110#endif /* def WITH_THREAD */
111
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000112/* SSL socket object */
113
114#define X509_NAME_MAXLEN 256
115
116/* RAND_* APIs got added to OpenSSL in 0.9.5 */
117#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
118# define HAVE_OPENSSL_RAND 1
119#else
120# undef HAVE_OPENSSL_RAND
121#endif
122
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000123/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
124 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
125 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
126#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000127# define HAVE_SSL_CTX_CLEAR_OPTIONS
128#else
129# undef HAVE_SSL_CTX_CLEAR_OPTIONS
130#endif
131
Antoine Pitroud6494802011-07-21 01:11:30 +0200132/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
133 * older SSL, but let's be safe */
134#define PySSL_CB_MAXLEN 128
135
136/* SSL_get_finished got added to OpenSSL in 0.9.5 */
137#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
138# define HAVE_OPENSSL_FINISHED 1
139#else
140# define HAVE_OPENSSL_FINISHED 0
141#endif
142
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000143typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000145 SSL_CTX *ctx;
146} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147
Antoine Pitrou152efa22010-05-16 18:19:27 +0000148typedef struct {
149 PyObject_HEAD
150 PyObject *Socket; /* weakref to socket on which we're layered */
151 SSL *ssl;
152 X509 *peer_cert;
153 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200154 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000155} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000156
Antoine Pitrou152efa22010-05-16 18:19:27 +0000157static PyTypeObject PySSLContext_Type;
158static PyTypeObject PySSLSocket_Type;
159
160static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
161static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000162static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000163 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000164static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
165static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166
Antoine Pitrou152efa22010-05-16 18:19:27 +0000167#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
168#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000169
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000170typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000171 SOCKET_IS_NONBLOCKING,
172 SOCKET_IS_BLOCKING,
173 SOCKET_HAS_TIMED_OUT,
174 SOCKET_HAS_BEEN_CLOSED,
175 SOCKET_TOO_LARGE_FOR_SELECT,
176 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000177} timeout_state;
178
Thomas Woutersed03b412007-08-28 21:37:11 +0000179/* Wrap error strings with filename and line # */
180#define STRINGIFY1(x) #x
181#define STRINGIFY2(x) STRINGIFY1(x)
182#define ERRSTR1(x,y,z) (x ":" y ": " z)
183#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
184
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000185/* XXX It might be helpful to augment the error message generated
186 below with the name of the SSL function that generated the error.
187 I expect it's obvious most of the time.
188*/
189
190static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000191PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000192{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000193 PyObject *v;
194 char buf[2048];
195 char *errstr;
196 int err;
197 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 if (obj->ssl != NULL) {
202 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000204 switch (err) {
205 case SSL_ERROR_ZERO_RETURN:
206 errstr = "TLS/SSL connection has been closed";
207 p = PY_SSL_ERROR_ZERO_RETURN;
208 break;
209 case SSL_ERROR_WANT_READ:
210 errstr = "The operation did not complete (read)";
211 p = PY_SSL_ERROR_WANT_READ;
212 break;
213 case SSL_ERROR_WANT_WRITE:
214 p = PY_SSL_ERROR_WANT_WRITE;
215 errstr = "The operation did not complete (write)";
216 break;
217 case SSL_ERROR_WANT_X509_LOOKUP:
218 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000219 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 break;
221 case SSL_ERROR_WANT_CONNECT:
222 p = PY_SSL_ERROR_WANT_CONNECT;
223 errstr = "The operation did not complete (connect)";
224 break;
225 case SSL_ERROR_SYSCALL:
226 {
227 unsigned long e = ERR_get_error();
228 if (e == 0) {
229 PySocketSockObject *s
230 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
231 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000232 p = PY_SSL_ERROR_EOF;
233 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000235 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000236 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000237 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000238 v = s->errorhandler();
239 Py_DECREF(s);
240 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000241 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000242 p = PY_SSL_ERROR_SYSCALL;
243 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 }
245 } else {
246 p = PY_SSL_ERROR_SYSCALL;
247 /* XXX Protected by global interpreter lock */
248 errstr = ERR_error_string(e, NULL);
249 }
250 break;
251 }
252 case SSL_ERROR_SSL:
253 {
254 unsigned long e = ERR_get_error();
255 p = PY_SSL_ERROR_SSL;
256 if (e != 0)
257 /* XXX Protected by global interpreter lock */
258 errstr = ERR_error_string(e, NULL);
259 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000260 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000261 }
262 break;
263 }
264 default:
265 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
266 errstr = "Invalid error code";
267 }
268 } else {
269 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
270 }
271 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000272 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000273 v = Py_BuildValue("(is)", p, buf);
274 if (v != NULL) {
275 PyErr_SetObject(PySSLErrorObject, v);
276 Py_DECREF(v);
277 }
278 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279}
280
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000281static PyObject *
282_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 char buf[2048];
285 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 if (errstr == NULL) {
288 errcode = ERR_peek_last_error();
289 errstr = ERR_error_string(errcode, NULL);
290 }
291 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000292 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 v = Py_BuildValue("(is)", errcode, buf);
294 if (v != NULL) {
295 PyErr_SetObject(PySSLErrorObject, v);
296 Py_DECREF(v);
297 }
298 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000299}
300
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301static PySSLSocket *
302newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000303 enum py_ssl_server_or_client socket_type,
304 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000305{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307
Antoine Pitrou152efa22010-05-16 18:19:27 +0000308 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 if (self == NULL)
310 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000312 self->peer_cert = NULL;
313 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 /* Make sure the SSL error state is initialized */
317 (void) ERR_get_state();
318 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000321 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000324#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000325 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000326#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000327
Antoine Pitroud5323212010-10-22 18:19:07 +0000328#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
329 if (server_hostname != NULL)
330 SSL_set_tlsext_host_name(self->ssl, server_hostname);
331#endif
332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000333 /* If the socket is in non-blocking mode or timeout mode, set the BIO
334 * to non-blocking mode (blocking is the default)
335 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000336 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000337 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
338 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
339 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000341 PySSL_BEGIN_ALLOW_THREADS
342 if (socket_type == PY_SSL_CLIENT)
343 SSL_set_connect_state(self->ssl);
344 else
345 SSL_set_accept_state(self->ssl);
346 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000347
Antoine Pitroud6494802011-07-21 01:11:30 +0200348 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000349 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000350 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000351}
352
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353/* SSL object methods */
354
Antoine Pitrou152efa22010-05-16 18:19:27 +0000355static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000356{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 int ret;
358 int err;
359 int sockstate, nonblocking;
360 PySocketSockObject *sock
361 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000363 if (((PyObject*)sock) == Py_None) {
364 _setSSLError("Underlying socket connection gone",
365 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
366 return NULL;
367 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000368 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000370 /* just in case the blocking state of the socket has been changed */
371 nonblocking = (sock->sock_timeout >= 0.0);
372 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
373 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000375 /* Actually negotiate SSL connection */
376 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000378 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 ret = SSL_do_handshake(self->ssl);
380 err = SSL_get_error(self->ssl, ret);
381 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000382 if (PyErr_CheckSignals())
383 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (err == SSL_ERROR_WANT_READ) {
385 sockstate = check_socket_and_wait_for_timeout(sock, 0);
386 } else if (err == SSL_ERROR_WANT_WRITE) {
387 sockstate = check_socket_and_wait_for_timeout(sock, 1);
388 } else {
389 sockstate = SOCKET_OPERATION_OK;
390 }
391 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000392 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000393 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000394 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
396 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000397 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000398 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
400 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000401 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000402 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
404 break;
405 }
406 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000407 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 if (ret < 1)
409 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 if (self->peer_cert)
412 X509_free (self->peer_cert);
413 PySSL_BEGIN_ALLOW_THREADS
414 self->peer_cert = SSL_get_peer_certificate(self->ssl);
415 PySSL_END_ALLOW_THREADS
416
417 Py_INCREF(Py_None);
418 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000419
420error:
421 Py_DECREF(sock);
422 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423}
424
Thomas Woutersed03b412007-08-28 21:37:11 +0000425static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000426_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 char namebuf[X509_NAME_MAXLEN];
429 int buflen;
430 PyObject *name_obj;
431 PyObject *value_obj;
432 PyObject *attr;
433 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000434
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
436 if (buflen < 0) {
437 _setSSLError(NULL, 0, __FILE__, __LINE__);
438 goto fail;
439 }
440 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
441 if (name_obj == NULL)
442 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000443
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000444 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
445 if (buflen < 0) {
446 _setSSLError(NULL, 0, __FILE__, __LINE__);
447 Py_DECREF(name_obj);
448 goto fail;
449 }
450 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000451 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 OPENSSL_free(valuebuf);
453 if (value_obj == NULL) {
454 Py_DECREF(name_obj);
455 goto fail;
456 }
457 attr = PyTuple_New(2);
458 if (attr == NULL) {
459 Py_DECREF(name_obj);
460 Py_DECREF(value_obj);
461 goto fail;
462 }
463 PyTuple_SET_ITEM(attr, 0, name_obj);
464 PyTuple_SET_ITEM(attr, 1, value_obj);
465 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000466
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000469}
470
471static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000473{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000474 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
475 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
476 PyObject *rdnt;
477 PyObject *attr = NULL; /* tuple to hold an attribute */
478 int entry_count = X509_NAME_entry_count(xname);
479 X509_NAME_ENTRY *entry;
480 ASN1_OBJECT *name;
481 ASN1_STRING *value;
482 int index_counter;
483 int rdn_level = -1;
484 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 dn = PyList_New(0);
487 if (dn == NULL)
488 return NULL;
489 /* now create another tuple to hold the top-level RDN */
490 rdn = PyList_New(0);
491 if (rdn == NULL)
492 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 for (index_counter = 0;
495 index_counter < entry_count;
496 index_counter++)
497 {
498 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 /* check to see if we've gotten to a new RDN */
501 if (rdn_level >= 0) {
502 if (rdn_level != entry->set) {
503 /* yes, new RDN */
504 /* add old RDN to DN */
505 rdnt = PyList_AsTuple(rdn);
506 Py_DECREF(rdn);
507 if (rdnt == NULL)
508 goto fail0;
509 retcode = PyList_Append(dn, rdnt);
510 Py_DECREF(rdnt);
511 if (retcode < 0)
512 goto fail0;
513 /* create new RDN */
514 rdn = PyList_New(0);
515 if (rdn == NULL)
516 goto fail0;
517 }
518 }
519 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 /* now add this attribute to the current RDN */
522 name = X509_NAME_ENTRY_get_object(entry);
523 value = X509_NAME_ENTRY_get_data(entry);
524 attr = _create_tuple_for_attribute(name, value);
525 /*
526 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
527 entry->set,
528 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
529 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
530 */
531 if (attr == NULL)
532 goto fail1;
533 retcode = PyList_Append(rdn, attr);
534 Py_DECREF(attr);
535 if (retcode < 0)
536 goto fail1;
537 }
538 /* now, there's typically a dangling RDN */
539 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
540 rdnt = PyList_AsTuple(rdn);
541 Py_DECREF(rdn);
542 if (rdnt == NULL)
543 goto fail0;
544 retcode = PyList_Append(dn, rdnt);
545 Py_DECREF(rdnt);
546 if (retcode < 0)
547 goto fail0;
548 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 /* convert list to tuple */
551 rdnt = PyList_AsTuple(dn);
552 Py_DECREF(dn);
553 if (rdnt == NULL)
554 return NULL;
555 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
557 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
560 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 Py_XDECREF(dn);
562 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563}
564
565static PyObject *
566_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 /* this code follows the procedure outlined in
569 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
570 function to extract the STACK_OF(GENERAL_NAME),
571 then iterates through the stack to add the
572 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 int i, j;
575 PyObject *peer_alt_names = Py_None;
576 PyObject *v, *t;
577 X509_EXTENSION *ext = NULL;
578 GENERAL_NAMES *names = NULL;
579 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000580 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 BIO *biobuf = NULL;
582 char buf[2048];
583 char *vptr;
584 int len;
585 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000586#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000588#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000590#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 if (certificate == NULL)
593 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 /* get a memory buffer */
596 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200598 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 while ((i = X509_get_ext_by_NID(
600 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 if (peer_alt_names == Py_None) {
603 peer_alt_names = PyList_New(0);
604 if (peer_alt_names == NULL)
605 goto fail;
606 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 /* now decode the altName */
609 ext = X509_get_ext(certificate, i);
610 if(!(method = X509V3_EXT_get(ext))) {
611 PyErr_SetString
612 (PySSLErrorObject,
613 ERRSTR("No method for internalizing subjectAltName!"));
614 goto fail;
615 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 p = ext->value->data;
618 if (method->it)
619 names = (GENERAL_NAMES*)
620 (ASN1_item_d2i(NULL,
621 &p,
622 ext->value->length,
623 ASN1_ITEM_ptr(method->it)));
624 else
625 names = (GENERAL_NAMES*)
626 (method->d2i(NULL,
627 &p,
628 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 name = sk_GENERAL_NAME_value(names, j);
635 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 /* we special-case DirName as a tuple of
638 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 t = PyTuple_New(2);
641 if (t == NULL) {
642 goto fail;
643 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 v = PyUnicode_FromString("DirName");
646 if (v == NULL) {
647 Py_DECREF(t);
648 goto fail;
649 }
650 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 v = _create_tuple_for_X509_NAME (name->d.dirn);
653 if (v == NULL) {
654 Py_DECREF(t);
655 goto fail;
656 }
657 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 (void) BIO_reset(biobuf);
664 GENERAL_NAME_print(biobuf, name);
665 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
666 if (len < 0) {
667 _setSSLError(NULL, 0, __FILE__, __LINE__);
668 goto fail;
669 }
670 vptr = strchr(buf, ':');
671 if (vptr == NULL)
672 goto fail;
673 t = PyTuple_New(2);
674 if (t == NULL)
675 goto fail;
676 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
677 if (v == NULL) {
678 Py_DECREF(t);
679 goto fail;
680 }
681 PyTuple_SET_ITEM(t, 0, v);
682 v = PyUnicode_FromStringAndSize((vptr + 1),
683 (len - (vptr - buf + 1)));
684 if (v == NULL) {
685 Py_DECREF(t);
686 goto fail;
687 }
688 PyTuple_SET_ITEM(t, 1, v);
689 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 if (PyList_Append(peer_alt_names, t) < 0) {
694 Py_DECREF(t);
695 goto fail;
696 }
697 Py_DECREF(t);
698 }
699 }
700 BIO_free(biobuf);
701 if (peer_alt_names != Py_None) {
702 v = PyList_AsTuple(peer_alt_names);
703 Py_DECREF(peer_alt_names);
704 return v;
705 } else {
706 return peer_alt_names;
707 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000708
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
710 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 if (biobuf != NULL)
712 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 if (peer_alt_names != Py_None) {
715 Py_XDECREF(peer_alt_names);
716 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719}
720
721static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000722_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 PyObject *retval = NULL;
725 BIO *biobuf = NULL;
726 PyObject *peer;
727 PyObject *peer_alt_names = NULL;
728 PyObject *issuer;
729 PyObject *version;
730 PyObject *sn_obj;
731 ASN1_INTEGER *serialNumber;
732 char buf[2048];
733 int len;
734 ASN1_TIME *notBefore, *notAfter;
735 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 retval = PyDict_New();
738 if (retval == NULL)
739 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 peer = _create_tuple_for_X509_NAME(
742 X509_get_subject_name(certificate));
743 if (peer == NULL)
744 goto fail0;
745 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
746 Py_DECREF(peer);
747 goto fail0;
748 }
749 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000750
Antoine Pitroufb046912010-11-09 20:21:19 +0000751 issuer = _create_tuple_for_X509_NAME(
752 X509_get_issuer_name(certificate));
753 if (issuer == NULL)
754 goto fail0;
755 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000757 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000759 Py_DECREF(issuer);
760
761 version = PyLong_FromLong(X509_get_version(certificate) + 1);
762 if (PyDict_SetItemString(retval, "version", version) < 0) {
763 Py_DECREF(version);
764 goto fail0;
765 }
766 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 /* get a memory buffer */
769 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000770
Antoine Pitroufb046912010-11-09 20:21:19 +0000771 (void) BIO_reset(biobuf);
772 serialNumber = X509_get_serialNumber(certificate);
773 /* should not exceed 20 octets, 160 bits, so buf is big enough */
774 i2a_ASN1_INTEGER(biobuf, serialNumber);
775 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
776 if (len < 0) {
777 _setSSLError(NULL, 0, __FILE__, __LINE__);
778 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000780 sn_obj = PyUnicode_FromStringAndSize(buf, len);
781 if (sn_obj == NULL)
782 goto fail1;
783 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
784 Py_DECREF(sn_obj);
785 goto fail1;
786 }
787 Py_DECREF(sn_obj);
788
789 (void) BIO_reset(biobuf);
790 notBefore = X509_get_notBefore(certificate);
791 ASN1_TIME_print(biobuf, notBefore);
792 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
793 if (len < 0) {
794 _setSSLError(NULL, 0, __FILE__, __LINE__);
795 goto fail1;
796 }
797 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
798 if (pnotBefore == NULL)
799 goto fail1;
800 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
801 Py_DECREF(pnotBefore);
802 goto fail1;
803 }
804 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 (void) BIO_reset(biobuf);
807 notAfter = X509_get_notAfter(certificate);
808 ASN1_TIME_print(biobuf, notAfter);
809 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
810 if (len < 0) {
811 _setSSLError(NULL, 0, __FILE__, __LINE__);
812 goto fail1;
813 }
814 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
815 if (pnotAfter == NULL)
816 goto fail1;
817 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
818 Py_DECREF(pnotAfter);
819 goto fail1;
820 }
821 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 peer_alt_names = _get_peer_alt_names(certificate);
826 if (peer_alt_names == NULL)
827 goto fail1;
828 else if (peer_alt_names != Py_None) {
829 if (PyDict_SetItemString(retval, "subjectAltName",
830 peer_alt_names) < 0) {
831 Py_DECREF(peer_alt_names);
832 goto fail1;
833 }
834 Py_DECREF(peer_alt_names);
835 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 BIO_free(biobuf);
838 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000839
840 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 if (biobuf != NULL)
842 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000843 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 Py_XDECREF(retval);
845 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000846}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000847
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
849static PyObject *
850PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000853 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 X509 *x=NULL;
855 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856
Antoine Pitroufb046912010-11-09 20:21:19 +0000857 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
858 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000859 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 if ((cert=BIO_new(BIO_s_file())) == NULL) {
862 PyErr_SetString(PySSLErrorObject,
863 "Can't malloc memory to read file");
864 goto fail0;
865 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Victor Stinner3800e1e2010-05-16 21:23:48 +0000867 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 PyErr_SetString(PySSLErrorObject,
869 "Can't open file");
870 goto fail0;
871 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
874 if (x == NULL) {
875 PyErr_SetString(PySSLErrorObject,
876 "Error decoding PEM-encoded file");
877 goto fail0;
878 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroufb046912010-11-09 20:21:19 +0000880 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000881 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
883 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000884 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 if (cert != NULL) BIO_free(cert);
886 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887}
888
889
890static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000891PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 PyObject *retval = NULL;
894 int len;
895 int verification;
896 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
899 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 if (!self->peer_cert)
902 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 if (PyObject_IsTrue(binary_mode)) {
905 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 bytes_buf = NULL;
910 len = i2d_X509(self->peer_cert, &bytes_buf);
911 if (len < 0) {
912 PySSL_SetError(self, len, __FILE__, __LINE__);
913 return NULL;
914 }
915 /* this is actually an immutable bytes sequence */
916 retval = PyBytes_FromStringAndSize
917 ((const char *) bytes_buf, len);
918 OPENSSL_free(bytes_buf);
919 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000922 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 if ((verification & SSL_VERIFY_PEER) == 0)
924 return PyDict_New();
925 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000926 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928}
929
930PyDoc_STRVAR(PySSL_peercert_doc,
931"peer_certificate([der=False]) -> certificate\n\
932\n\
933Returns the certificate for the peer. If no certificate was provided,\n\
934returns None. If a certificate was provided, but not validated, returns\n\
935an empty dictionary. Otherwise returns a dict containing information\n\
936about the peer certificate.\n\
937\n\
938If the optional argument is True, returns a DER-encoded copy of the\n\
939peer certificate, or None if no certificate was provided. This will\n\
940return the certificate even if it wasn't validated.");
941
Antoine Pitrou152efa22010-05-16 18:19:27 +0000942static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000945 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 char *cipher_name;
947 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000950 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 current = SSL_get_current_cipher(self->ssl);
952 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000953 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 retval = PyTuple_New(3);
956 if (retval == NULL)
957 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 cipher_name = (char *) SSL_CIPHER_get_name(current);
960 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000961 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 PyTuple_SET_ITEM(retval, 0, Py_None);
963 } else {
964 v = PyUnicode_FromString(cipher_name);
965 if (v == NULL)
966 goto fail0;
967 PyTuple_SET_ITEM(retval, 0, v);
968 }
969 cipher_protocol = SSL_CIPHER_get_version(current);
970 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000971 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 PyTuple_SET_ITEM(retval, 1, Py_None);
973 } else {
974 v = PyUnicode_FromString(cipher_protocol);
975 if (v == NULL)
976 goto fail0;
977 PyTuple_SET_ITEM(retval, 1, v);
978 }
979 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
980 if (v == NULL)
981 goto fail0;
982 PyTuple_SET_ITEM(retval, 2, v);
983 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000984
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 Py_DECREF(retval);
987 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000988}
989
Antoine Pitrou152efa22010-05-16 18:19:27 +0000990static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000991{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 if (self->peer_cert) /* Possible not to have one? */
993 X509_free (self->peer_cert);
994 if (self->ssl)
995 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 Py_XDECREF(self->Socket);
997 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000998}
999
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001000/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001001 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001002 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001003 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001004
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001005static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001006check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001007{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 fd_set fds;
1009 struct timeval tv;
1010 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1013 if (s->sock_timeout < 0.0)
1014 return SOCKET_IS_BLOCKING;
1015 else if (s->sock_timeout == 0.0)
1016 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 /* Guard against closed socket */
1019 if (s->sock_fd < 0)
1020 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 /* Prefer poll, if available, since you can poll() any fd
1023 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 {
1026 struct pollfd pollfd;
1027 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 pollfd.fd = s->sock_fd;
1030 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 /* s->sock_timeout is in seconds, timeout in ms */
1033 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1034 PySSL_BEGIN_ALLOW_THREADS
1035 rc = poll(&pollfd, 1, timeout);
1036 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001037
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 goto normal_return;
1039 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001040#endif
1041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001043 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 /* Construct the arguments to select */
1047 tv.tv_sec = (int)s->sock_timeout;
1048 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1049 FD_ZERO(&fds);
1050 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 /* See if the socket is ready */
1053 PySSL_BEGIN_ALLOW_THREADS
1054 if (writing)
1055 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1056 else
1057 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1058 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001059
Bill Janssen6e027db2007-11-15 22:23:56 +00001060#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001061normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001062#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1064 (when we are able to write or when there's something to read) */
1065 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001066}
1067
Antoine Pitrou152efa22010-05-16 18:19:27 +00001068static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001069{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 Py_buffer buf;
1071 int len;
1072 int sockstate;
1073 int err;
1074 int nonblocking;
1075 PySocketSockObject *sock
1076 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 if (((PyObject*)sock) == Py_None) {
1079 _setSSLError("Underlying socket connection gone",
1080 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1081 return NULL;
1082 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001083 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001085 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1086 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001088 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089
1090 /* just in case the blocking state of the socket has been changed */
1091 nonblocking = (sock->sock_timeout >= 0.0);
1092 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1093 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1094
1095 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1096 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001097 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 "The write operation timed out");
1099 goto error;
1100 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1101 PyErr_SetString(PySSLErrorObject,
1102 "Underlying socket has been closed.");
1103 goto error;
1104 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1105 PyErr_SetString(PySSLErrorObject,
1106 "Underlying socket too large for select().");
1107 goto error;
1108 }
1109 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 PySSL_BEGIN_ALLOW_THREADS
1111 len = SSL_write(self->ssl, buf.buf, buf.len);
1112 err = SSL_get_error(self->ssl, len);
1113 PySSL_END_ALLOW_THREADS
1114 if (PyErr_CheckSignals()) {
1115 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001116 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001118 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001120 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 } else {
1122 sockstate = SOCKET_OPERATION_OK;
1123 }
1124 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001125 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 "The write operation timed out");
1127 goto error;
1128 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1129 PyErr_SetString(PySSLErrorObject,
1130 "Underlying socket has been closed.");
1131 goto error;
1132 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1133 break;
1134 }
1135 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001136
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001137 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 PyBuffer_Release(&buf);
1139 if (len > 0)
1140 return PyLong_FromLong(len);
1141 else
1142 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001143
1144error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001145 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 PyBuffer_Release(&buf);
1147 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001148}
1149
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001150PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001151"write(s) -> len\n\
1152\n\
1153Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001154of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001155
Antoine Pitrou152efa22010-05-16 18:19:27 +00001156static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001157{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 PySSL_BEGIN_ALLOW_THREADS
1161 count = SSL_pending(self->ssl);
1162 PySSL_END_ALLOW_THREADS
1163 if (count < 0)
1164 return PySSL_SetError(self, count, __FILE__, __LINE__);
1165 else
1166 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001167}
1168
1169PyDoc_STRVAR(PySSL_SSLpending_doc,
1170"pending() -> count\n\
1171\n\
1172Returns the number of already decrypted bytes available for read,\n\
1173pending on the connection.\n");
1174
Antoine Pitrou152efa22010-05-16 18:19:27 +00001175static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001176{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 PyObject *dest = NULL;
1178 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001180 int len, count;
1181 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 int sockstate;
1183 int err;
1184 int nonblocking;
1185 PySocketSockObject *sock
1186 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001187
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 if (((PyObject*)sock) == Py_None) {
1189 _setSSLError("Underlying socket connection gone",
1190 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1191 return NULL;
1192 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001193 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001195 buf.obj = NULL;
1196 buf.buf = NULL;
1197 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001198 goto error;
1199
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001200 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1201 dest = PyBytes_FromStringAndSize(NULL, len);
1202 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001203 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001204 mem = PyBytes_AS_STRING(dest);
1205 }
1206 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001208 mem = buf.buf;
1209 if (len <= 0 || len > buf.len) {
1210 len = (int) buf.len;
1211 if (buf.len != len) {
1212 PyErr_SetString(PyExc_OverflowError,
1213 "maximum length can't fit in a C 'int'");
1214 goto error;
1215 }
1216 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 }
1218
1219 /* just in case the blocking state of the socket has been changed */
1220 nonblocking = (sock->sock_timeout >= 0.0);
1221 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1222 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1223
1224 /* first check if there are bytes ready to be read */
1225 PySSL_BEGIN_ALLOW_THREADS
1226 count = SSL_pending(self->ssl);
1227 PySSL_END_ALLOW_THREADS
1228
1229 if (!count) {
1230 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1231 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001232 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 "The read operation timed out");
1234 goto error;
1235 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1236 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001237 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 goto error;
1239 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1240 count = 0;
1241 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001242 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 }
1244 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 PySSL_BEGIN_ALLOW_THREADS
1246 count = SSL_read(self->ssl, mem, len);
1247 err = SSL_get_error(self->ssl, count);
1248 PySSL_END_ALLOW_THREADS
1249 if (PyErr_CheckSignals())
1250 goto error;
1251 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001252 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001254 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1256 (SSL_get_shutdown(self->ssl) ==
1257 SSL_RECEIVED_SHUTDOWN))
1258 {
1259 count = 0;
1260 goto done;
1261 } else {
1262 sockstate = SOCKET_OPERATION_OK;
1263 }
1264 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001265 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 "The read operation timed out");
1267 goto error;
1268 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1269 break;
1270 }
1271 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1272 if (count <= 0) {
1273 PySSL_SetError(self, count, __FILE__, __LINE__);
1274 goto error;
1275 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001276
1277done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001278 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001280 _PyBytes_Resize(&dest, count);
1281 return dest;
1282 }
1283 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 PyBuffer_Release(&buf);
1285 return PyLong_FromLong(count);
1286 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001287
1288error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001289 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001290 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001291 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001292 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001295}
1296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001297PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001298"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001299\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001300Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001301
Antoine Pitrou152efa22010-05-16 18:19:27 +00001302static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001303{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 int err, ssl_err, sockstate, nonblocking;
1305 int zeros = 0;
1306 PySocketSockObject *sock
1307 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 /* Guard against closed socket */
1310 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1311 _setSSLError("Underlying socket connection gone",
1312 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1313 return NULL;
1314 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001315 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316
1317 /* Just in case the blocking state of the socket has been changed */
1318 nonblocking = (sock->sock_timeout >= 0.0);
1319 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1320 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1321
1322 while (1) {
1323 PySSL_BEGIN_ALLOW_THREADS
1324 /* Disable read-ahead so that unwrap can work correctly.
1325 * Otherwise OpenSSL might read in too much data,
1326 * eating clear text data that happens to be
1327 * transmitted after the SSL shutdown.
1328 * Should be safe to call repeatedly everytime this
1329 * function is used and the shutdown_seen_zero != 0
1330 * condition is met.
1331 */
1332 if (self->shutdown_seen_zero)
1333 SSL_set_read_ahead(self->ssl, 0);
1334 err = SSL_shutdown(self->ssl);
1335 PySSL_END_ALLOW_THREADS
1336 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1337 if (err > 0)
1338 break;
1339 if (err == 0) {
1340 /* Don't loop endlessly; instead preserve legacy
1341 behaviour of trying SSL_shutdown() only twice.
1342 This looks necessary for OpenSSL < 0.9.8m */
1343 if (++zeros > 1)
1344 break;
1345 /* Shutdown was sent, now try receiving */
1346 self->shutdown_seen_zero = 1;
1347 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001348 }
1349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 /* Possibly retry shutdown until timeout or failure */
1351 ssl_err = SSL_get_error(self->ssl, err);
1352 if (ssl_err == SSL_ERROR_WANT_READ)
1353 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1354 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1355 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1356 else
1357 break;
1358 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1359 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001360 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 "The read operation timed out");
1362 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001363 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001365 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 }
1367 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1368 PyErr_SetString(PySSLErrorObject,
1369 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001370 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 }
1372 else if (sockstate != SOCKET_OPERATION_OK)
1373 /* Retain the SSL error code */
1374 break;
1375 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001376
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001377 if (err < 0) {
1378 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001381 else
1382 /* It's already INCREF'ed */
1383 return (PyObject *) sock;
1384
1385error:
1386 Py_DECREF(sock);
1387 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001388}
1389
1390PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1391"shutdown(s) -> socket\n\
1392\n\
1393Does the SSL shutdown handshake with the remote end, and returns\n\
1394the underlying socket object.");
1395
Antoine Pitroud6494802011-07-21 01:11:30 +02001396#if HAVE_OPENSSL_FINISHED
1397static PyObject *
1398PySSL_tls_unique_cb(PySSLSocket *self)
1399{
1400 PyObject *retval = NULL;
1401 char buf[PySSL_CB_MAXLEN];
1402 int len;
1403
1404 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1405 /* if session is resumed XOR we are the client */
1406 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1407 }
1408 else {
1409 /* if a new session XOR we are the server */
1410 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1411 }
1412
1413 /* It cannot be negative in current OpenSSL version as of July 2011 */
1414 assert(len >= 0);
1415 if (len == 0)
1416 Py_RETURN_NONE;
1417
1418 retval = PyBytes_FromStringAndSize(buf, len);
1419
1420 return retval;
1421}
1422
1423PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1424"tls_unique_cb() -> bytes\n\
1425\n\
1426Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1427\n\
1428If the TLS handshake is not yet complete, None is returned");
1429
1430#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001431
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001432static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1434 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1435 PySSL_SSLwrite_doc},
1436 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1437 PySSL_SSLread_doc},
1438 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1439 PySSL_SSLpending_doc},
1440 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1441 PySSL_peercert_doc},
1442 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1443 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1444 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001445#if HAVE_OPENSSL_FINISHED
1446 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1447 PySSL_tls_unique_cb_doc},
1448#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001450};
1451
Antoine Pitrou152efa22010-05-16 18:19:27 +00001452static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001454 "_ssl._SSLSocket", /*tp_name*/
1455 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 0, /*tp_itemsize*/
1457 /* methods */
1458 (destructor)PySSL_dealloc, /*tp_dealloc*/
1459 0, /*tp_print*/
1460 0, /*tp_getattr*/
1461 0, /*tp_setattr*/
1462 0, /*tp_reserved*/
1463 0, /*tp_repr*/
1464 0, /*tp_as_number*/
1465 0, /*tp_as_sequence*/
1466 0, /*tp_as_mapping*/
1467 0, /*tp_hash*/
1468 0, /*tp_call*/
1469 0, /*tp_str*/
1470 0, /*tp_getattro*/
1471 0, /*tp_setattro*/
1472 0, /*tp_as_buffer*/
1473 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1474 0, /*tp_doc*/
1475 0, /*tp_traverse*/
1476 0, /*tp_clear*/
1477 0, /*tp_richcompare*/
1478 0, /*tp_weaklistoffset*/
1479 0, /*tp_iter*/
1480 0, /*tp_iternext*/
1481 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482};
1483
Antoine Pitrou152efa22010-05-16 18:19:27 +00001484
1485/*
1486 * _SSLContext objects
1487 */
1488
1489static PyObject *
1490context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1491{
1492 char *kwlist[] = {"protocol", NULL};
1493 PySSLContext *self;
1494 int proto_version = PY_SSL_VERSION_SSL23;
1495 SSL_CTX *ctx = NULL;
1496
1497 if (!PyArg_ParseTupleAndKeywords(
1498 args, kwds, "i:_SSLContext", kwlist,
1499 &proto_version))
1500 return NULL;
1501
1502 PySSL_BEGIN_ALLOW_THREADS
1503 if (proto_version == PY_SSL_VERSION_TLS1)
1504 ctx = SSL_CTX_new(TLSv1_method());
1505 else if (proto_version == PY_SSL_VERSION_SSL3)
1506 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001507#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001508 else if (proto_version == PY_SSL_VERSION_SSL2)
1509 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001510#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001511 else if (proto_version == PY_SSL_VERSION_SSL23)
1512 ctx = SSL_CTX_new(SSLv23_method());
1513 else
1514 proto_version = -1;
1515 PySSL_END_ALLOW_THREADS
1516
1517 if (proto_version == -1) {
1518 PyErr_SetString(PyExc_ValueError,
1519 "invalid protocol version");
1520 return NULL;
1521 }
1522 if (ctx == NULL) {
1523 PyErr_SetString(PySSLErrorObject,
1524 "failed to allocate SSL context");
1525 return NULL;
1526 }
1527
1528 assert(type != NULL && type->tp_alloc != NULL);
1529 self = (PySSLContext *) type->tp_alloc(type, 0);
1530 if (self == NULL) {
1531 SSL_CTX_free(ctx);
1532 return NULL;
1533 }
1534 self->ctx = ctx;
1535 /* Defaults */
1536 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1537 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1538
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001539#define SID_CTX "Python"
1540 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1541 sizeof(SID_CTX));
1542#undef SID_CTX
1543
Antoine Pitrou152efa22010-05-16 18:19:27 +00001544 return (PyObject *)self;
1545}
1546
1547static void
1548context_dealloc(PySSLContext *self)
1549{
1550 SSL_CTX_free(self->ctx);
1551 Py_TYPE(self)->tp_free(self);
1552}
1553
1554static PyObject *
1555set_ciphers(PySSLContext *self, PyObject *args)
1556{
1557 int ret;
1558 const char *cipherlist;
1559
1560 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1561 return NULL;
1562 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1563 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001564 /* Clearing the error queue is necessary on some OpenSSL versions,
1565 otherwise the error will be reported again when another SSL call
1566 is done. */
1567 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001568 PyErr_SetString(PySSLErrorObject,
1569 "No cipher can be selected.");
1570 return NULL;
1571 }
1572 Py_RETURN_NONE;
1573}
1574
1575static PyObject *
1576get_verify_mode(PySSLContext *self, void *c)
1577{
1578 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1579 case SSL_VERIFY_NONE:
1580 return PyLong_FromLong(PY_SSL_CERT_NONE);
1581 case SSL_VERIFY_PEER:
1582 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1583 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1584 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1585 }
1586 PyErr_SetString(PySSLErrorObject,
1587 "invalid return value from SSL_CTX_get_verify_mode");
1588 return NULL;
1589}
1590
1591static int
1592set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1593{
1594 int n, mode;
1595 if (!PyArg_Parse(arg, "i", &n))
1596 return -1;
1597 if (n == PY_SSL_CERT_NONE)
1598 mode = SSL_VERIFY_NONE;
1599 else if (n == PY_SSL_CERT_OPTIONAL)
1600 mode = SSL_VERIFY_PEER;
1601 else if (n == PY_SSL_CERT_REQUIRED)
1602 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1603 else {
1604 PyErr_SetString(PyExc_ValueError,
1605 "invalid value for verify_mode");
1606 return -1;
1607 }
1608 SSL_CTX_set_verify(self->ctx, mode, NULL);
1609 return 0;
1610}
1611
1612static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001613get_options(PySSLContext *self, void *c)
1614{
1615 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1616}
1617
1618static int
1619set_options(PySSLContext *self, PyObject *arg, void *c)
1620{
1621 long new_opts, opts, set, clear;
1622 if (!PyArg_Parse(arg, "l", &new_opts))
1623 return -1;
1624 opts = SSL_CTX_get_options(self->ctx);
1625 clear = opts & ~new_opts;
1626 set = ~opts & new_opts;
1627 if (clear) {
1628#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1629 SSL_CTX_clear_options(self->ctx, clear);
1630#else
1631 PyErr_SetString(PyExc_ValueError,
1632 "can't clear options before OpenSSL 0.9.8m");
1633 return -1;
1634#endif
1635 }
1636 if (set)
1637 SSL_CTX_set_options(self->ctx, set);
1638 return 0;
1639}
1640
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001641typedef struct {
1642 PyThreadState *thread_state;
1643 PyObject *callable;
1644 char *password;
1645 Py_ssize_t size;
1646 int error;
1647} _PySSLPasswordInfo;
1648
1649static int
1650_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1651 const char *bad_type_error)
1652{
1653 /* Set the password and size fields of a _PySSLPasswordInfo struct
1654 from a unicode, bytes, or byte array object.
1655 The password field will be dynamically allocated and must be freed
1656 by the caller */
1657 PyObject *password_bytes = NULL;
1658 const char *data = NULL;
1659 Py_ssize_t size;
1660
1661 if (PyUnicode_Check(password)) {
1662 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1663 if (!password_bytes) {
1664 goto error;
1665 }
1666 data = PyBytes_AS_STRING(password_bytes);
1667 size = PyBytes_GET_SIZE(password_bytes);
1668 } else if (PyBytes_Check(password)) {
1669 data = PyBytes_AS_STRING(password);
1670 size = PyBytes_GET_SIZE(password);
1671 } else if (PyByteArray_Check(password)) {
1672 data = PyByteArray_AS_STRING(password);
1673 size = PyByteArray_GET_SIZE(password);
1674 } else {
1675 PyErr_SetString(PyExc_TypeError, bad_type_error);
1676 goto error;
1677 }
1678
1679 free(pw_info->password);
1680 pw_info->password = malloc(size);
1681 if (!pw_info->password) {
1682 PyErr_SetString(PyExc_MemoryError,
1683 "unable to allocate password buffer");
1684 goto error;
1685 }
1686 memcpy(pw_info->password, data, size);
1687 pw_info->size = size;
1688
1689 Py_XDECREF(password_bytes);
1690 return 1;
1691
1692error:
1693 Py_XDECREF(password_bytes);
1694 return 0;
1695}
1696
1697static int
1698_password_callback(char *buf, int size, int rwflag, void *userdata)
1699{
1700 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1701 PyObject *fn_ret = NULL;
1702
1703 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1704
1705 if (pw_info->callable) {
1706 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1707 if (!fn_ret) {
1708 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1709 core python API, so we could use it to add a frame here */
1710 goto error;
1711 }
1712
1713 if (!_pwinfo_set(pw_info, fn_ret,
1714 "password callback must return a string")) {
1715 goto error;
1716 }
1717 Py_CLEAR(fn_ret);
1718 }
1719
1720 if (pw_info->size > size) {
1721 PyErr_Format(PyExc_ValueError,
1722 "password cannot be longer than %d bytes", size);
1723 goto error;
1724 }
1725
1726 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1727 memcpy(buf, pw_info->password, pw_info->size);
1728 return pw_info->size;
1729
1730error:
1731 Py_XDECREF(fn_ret);
1732 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1733 pw_info->error = 1;
1734 return -1;
1735}
1736
Antoine Pitroub5218772010-05-21 09:56:06 +00001737static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001738load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1739{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001740 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1741 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001742 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001743 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1744 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1745 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001746 int r;
1747
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001748 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001749 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001750 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001751 "O|OO:load_cert_chain", kwlist,
1752 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001753 return NULL;
1754 if (keyfile == Py_None)
1755 keyfile = NULL;
1756 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1757 PyErr_SetString(PyExc_TypeError,
1758 "certfile should be a valid filesystem path");
1759 return NULL;
1760 }
1761 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1762 PyErr_SetString(PyExc_TypeError,
1763 "keyfile should be a valid filesystem path");
1764 goto error;
1765 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001766 if (password && password != Py_None) {
1767 if (PyCallable_Check(password)) {
1768 pw_info.callable = password;
1769 } else if (!_pwinfo_set(&pw_info, password,
1770 "password should be a string or callable")) {
1771 goto error;
1772 }
1773 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1774 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1775 }
1776 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001777 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1778 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001779 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001780 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001781 if (pw_info.error) {
1782 ERR_clear_error();
1783 /* the password callback has already set the error information */
1784 }
1785 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001786 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001787 PyErr_SetFromErrno(PyExc_IOError);
1788 }
1789 else {
1790 _setSSLError(NULL, 0, __FILE__, __LINE__);
1791 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001792 goto error;
1793 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001794 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001795 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1797 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001798 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1799 Py_CLEAR(keyfile_bytes);
1800 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001801 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001802 if (pw_info.error) {
1803 ERR_clear_error();
1804 /* the password callback has already set the error information */
1805 }
1806 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001807 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001808 PyErr_SetFromErrno(PyExc_IOError);
1809 }
1810 else {
1811 _setSSLError(NULL, 0, __FILE__, __LINE__);
1812 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001813 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001814 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001815 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001816 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001817 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001818 if (r != 1) {
1819 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001820 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001822 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1823 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1824 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001825 Py_RETURN_NONE;
1826
1827error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001828 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1829 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1830 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001831 Py_XDECREF(keyfile_bytes);
1832 Py_XDECREF(certfile_bytes);
1833 return NULL;
1834}
1835
1836static PyObject *
1837load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1838{
1839 char *kwlist[] = {"cafile", "capath", NULL};
1840 PyObject *cafile = NULL, *capath = NULL;
1841 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1842 const char *cafile_buf = NULL, *capath_buf = NULL;
1843 int r;
1844
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001845 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001846 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1847 "|OO:load_verify_locations", kwlist,
1848 &cafile, &capath))
1849 return NULL;
1850 if (cafile == Py_None)
1851 cafile = NULL;
1852 if (capath == Py_None)
1853 capath = NULL;
1854 if (cafile == NULL && capath == NULL) {
1855 PyErr_SetString(PyExc_TypeError,
1856 "cafile and capath cannot be both omitted");
1857 return NULL;
1858 }
1859 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1860 PyErr_SetString(PyExc_TypeError,
1861 "cafile should be a valid filesystem path");
1862 return NULL;
1863 }
1864 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001865 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001866 PyErr_SetString(PyExc_TypeError,
1867 "capath should be a valid filesystem path");
1868 return NULL;
1869 }
1870 if (cafile)
1871 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1872 if (capath)
1873 capath_buf = PyBytes_AS_STRING(capath_bytes);
1874 PySSL_BEGIN_ALLOW_THREADS
1875 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1876 PySSL_END_ALLOW_THREADS
1877 Py_XDECREF(cafile_bytes);
1878 Py_XDECREF(capath_bytes);
1879 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001880 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001881 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001882 PyErr_SetFromErrno(PyExc_IOError);
1883 }
1884 else {
1885 _setSSLError(NULL, 0, __FILE__, __LINE__);
1886 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001887 return NULL;
1888 }
1889 Py_RETURN_NONE;
1890}
1891
1892static PyObject *
1893context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1894{
Antoine Pitroud5323212010-10-22 18:19:07 +00001895 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001896 PySocketSockObject *sock;
1897 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001898 char *hostname = NULL;
1899 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001900
Antoine Pitroud5323212010-10-22 18:19:07 +00001901 /* server_hostname is either None (or absent), or to be encoded
1902 using the idna encoding. */
1903 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001904 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001905 &sock, &server_side,
1906 Py_TYPE(Py_None), &hostname_obj)) {
1907 PyErr_Clear();
1908 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1909 PySocketModule.Sock_Type,
1910 &sock, &server_side,
1911 "idna", &hostname))
1912 return NULL;
1913#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1914 PyMem_Free(hostname);
1915 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1916 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001917 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001918#endif
1919 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001920
Antoine Pitroud5323212010-10-22 18:19:07 +00001921 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1922 hostname);
1923 if (hostname != NULL)
1924 PyMem_Free(hostname);
1925 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001926}
1927
Antoine Pitroub0182c82010-10-12 20:09:02 +00001928static PyObject *
1929session_stats(PySSLContext *self, PyObject *unused)
1930{
1931 int r;
1932 PyObject *value, *stats = PyDict_New();
1933 if (!stats)
1934 return NULL;
1935
1936#define ADD_STATS(SSL_NAME, KEY_NAME) \
1937 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1938 if (value == NULL) \
1939 goto error; \
1940 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1941 Py_DECREF(value); \
1942 if (r < 0) \
1943 goto error;
1944
1945 ADD_STATS(number, "number");
1946 ADD_STATS(connect, "connect");
1947 ADD_STATS(connect_good, "connect_good");
1948 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1949 ADD_STATS(accept, "accept");
1950 ADD_STATS(accept_good, "accept_good");
1951 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1952 ADD_STATS(accept, "accept");
1953 ADD_STATS(hits, "hits");
1954 ADD_STATS(misses, "misses");
1955 ADD_STATS(timeouts, "timeouts");
1956 ADD_STATS(cache_full, "cache_full");
1957
1958#undef ADD_STATS
1959
1960 return stats;
1961
1962error:
1963 Py_DECREF(stats);
1964 return NULL;
1965}
1966
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001967static PyObject *
1968set_default_verify_paths(PySSLContext *self, PyObject *unused)
1969{
1970 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1971 _setSSLError(NULL, 0, __FILE__, __LINE__);
1972 return NULL;
1973 }
1974 Py_RETURN_NONE;
1975}
1976
Antoine Pitrou152efa22010-05-16 18:19:27 +00001977static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001978 {"options", (getter) get_options,
1979 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001980 {"verify_mode", (getter) get_verify_mode,
1981 (setter) set_verify_mode, NULL},
1982 {NULL}, /* sentinel */
1983};
1984
1985static struct PyMethodDef context_methods[] = {
1986 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1987 METH_VARARGS | METH_KEYWORDS, NULL},
1988 {"set_ciphers", (PyCFunction) set_ciphers,
1989 METH_VARARGS, NULL},
1990 {"load_cert_chain", (PyCFunction) load_cert_chain,
1991 METH_VARARGS | METH_KEYWORDS, NULL},
1992 {"load_verify_locations", (PyCFunction) load_verify_locations,
1993 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001994 {"session_stats", (PyCFunction) session_stats,
1995 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001996 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1997 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001998 {NULL, NULL} /* sentinel */
1999};
2000
2001static PyTypeObject PySSLContext_Type = {
2002 PyVarObject_HEAD_INIT(NULL, 0)
2003 "_ssl._SSLContext", /*tp_name*/
2004 sizeof(PySSLContext), /*tp_basicsize*/
2005 0, /*tp_itemsize*/
2006 (destructor)context_dealloc, /*tp_dealloc*/
2007 0, /*tp_print*/
2008 0, /*tp_getattr*/
2009 0, /*tp_setattr*/
2010 0, /*tp_reserved*/
2011 0, /*tp_repr*/
2012 0, /*tp_as_number*/
2013 0, /*tp_as_sequence*/
2014 0, /*tp_as_mapping*/
2015 0, /*tp_hash*/
2016 0, /*tp_call*/
2017 0, /*tp_str*/
2018 0, /*tp_getattro*/
2019 0, /*tp_setattro*/
2020 0, /*tp_as_buffer*/
2021 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2022 0, /*tp_doc*/
2023 0, /*tp_traverse*/
2024 0, /*tp_clear*/
2025 0, /*tp_richcompare*/
2026 0, /*tp_weaklistoffset*/
2027 0, /*tp_iter*/
2028 0, /*tp_iternext*/
2029 context_methods, /*tp_methods*/
2030 0, /*tp_members*/
2031 context_getsetlist, /*tp_getset*/
2032 0, /*tp_base*/
2033 0, /*tp_dict*/
2034 0, /*tp_descr_get*/
2035 0, /*tp_descr_set*/
2036 0, /*tp_dictoffset*/
2037 0, /*tp_init*/
2038 0, /*tp_alloc*/
2039 context_new, /*tp_new*/
2040};
2041
2042
2043
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002044#ifdef HAVE_OPENSSL_RAND
2045
2046/* helper routines for seeding the SSL PRNG */
2047static PyObject *
2048PySSL_RAND_add(PyObject *self, PyObject *args)
2049{
2050 char *buf;
2051 int len;
2052 double entropy;
2053
2054 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002055 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002056 RAND_add(buf, len, entropy);
2057 Py_INCREF(Py_None);
2058 return Py_None;
2059}
2060
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002061PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002062"RAND_add(string, entropy)\n\
2063\n\
2064Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002065bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002066
2067static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002068PySSL_RAND(int len, int pseudo)
2069{
2070 int ok;
2071 PyObject *bytes;
2072 unsigned long err;
2073 const char *errstr;
2074 PyObject *v;
2075
2076 bytes = PyBytes_FromStringAndSize(NULL, len);
2077 if (bytes == NULL)
2078 return NULL;
2079 if (pseudo) {
2080 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2081 if (ok == 0 || ok == 1)
2082 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2083 }
2084 else {
2085 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2086 if (ok == 1)
2087 return bytes;
2088 }
2089 Py_DECREF(bytes);
2090
2091 err = ERR_get_error();
2092 errstr = ERR_reason_error_string(err);
2093 v = Py_BuildValue("(ks)", err, errstr);
2094 if (v != NULL) {
2095 PyErr_SetObject(PySSLErrorObject, v);
2096 Py_DECREF(v);
2097 }
2098 return NULL;
2099}
2100
2101static PyObject *
2102PySSL_RAND_bytes(PyObject *self, PyObject *args)
2103{
2104 int len;
2105 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2106 return NULL;
2107 return PySSL_RAND(len, 0);
2108}
2109
2110PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2111"RAND_bytes(n) -> bytes\n\
2112\n\
2113Generate n cryptographically strong pseudo-random bytes.");
2114
2115static PyObject *
2116PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2117{
2118 int len;
2119 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2120 return NULL;
2121 return PySSL_RAND(len, 1);
2122}
2123
2124PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2125"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2126\n\
2127Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2128generated are cryptographically strong.");
2129
2130static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002131PySSL_RAND_status(PyObject *self)
2132{
Christian Heimes217cfd12007-12-02 14:31:20 +00002133 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002134}
2135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002136PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002137"RAND_status() -> 0 or 1\n\
2138\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002139Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2140It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2141using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002142
2143static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002144PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002145{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002146 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002147 int bytes;
2148
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002149 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2150 PyUnicode_FSConverter, &path))
2151 return NULL;
2152
2153 bytes = RAND_egd(PyBytes_AsString(path));
2154 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002155 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002156 PyErr_SetString(PySSLErrorObject,
2157 "EGD connection failed or EGD did not return "
2158 "enough data to seed the PRNG");
2159 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002160 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002161 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002162}
2163
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002164PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002165"RAND_egd(path) -> bytes\n\
2166\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002167Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2168Returns number of bytes read. Raises SSLError if connection to EGD\n\
2169fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002170
2171#endif
2172
Bill Janssen40a0f662008-08-12 16:56:25 +00002173
2174
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002175/* List of functions exported by this module. */
2176
2177static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 {"_test_decode_cert", PySSL_test_decode_certificate,
2179 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002180#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2182 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002183 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2184 PySSL_RAND_bytes_doc},
2185 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2186 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002187 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 PySSL_RAND_egd_doc},
2189 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2190 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002191#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002193};
2194
2195
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002196#ifdef WITH_THREAD
2197
2198/* an implementation of OpenSSL threading operations in terms
2199 of the Python C thread library */
2200
2201static PyThread_type_lock *_ssl_locks = NULL;
2202
2203static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002205}
2206
Bill Janssen6e027db2007-11-15 22:23:56 +00002207static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 (int mode, int n, const char *file, int line) {
2209 /* this function is needed to perform locking on shared data
2210 structures. (Note that OpenSSL uses a number of global data
2211 structures that will be implicitly shared whenever multiple
2212 threads use OpenSSL.) Multi-threaded applications will
2213 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 locking_function() must be able to handle up to
2216 CRYPTO_num_locks() different mutex locks. It sets the n-th
2217 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 file and line are the file number of the function setting the
2220 lock. They can be useful for debugging.
2221 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 if ((_ssl_locks == NULL) ||
2224 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2225 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 if (mode & CRYPTO_LOCK) {
2228 PyThread_acquire_lock(_ssl_locks[n], 1);
2229 } else {
2230 PyThread_release_lock(_ssl_locks[n]);
2231 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002232}
2233
2234static int _setup_ssl_threads(void) {
2235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 if (_ssl_locks == NULL) {
2239 _ssl_locks_count = CRYPTO_num_locks();
2240 _ssl_locks = (PyThread_type_lock *)
2241 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2242 if (_ssl_locks == NULL)
2243 return 0;
2244 memset(_ssl_locks, 0,
2245 sizeof(PyThread_type_lock) * _ssl_locks_count);
2246 for (i = 0; i < _ssl_locks_count; i++) {
2247 _ssl_locks[i] = PyThread_allocate_lock();
2248 if (_ssl_locks[i] == NULL) {
2249 unsigned int j;
2250 for (j = 0; j < i; j++) {
2251 PyThread_free_lock(_ssl_locks[j]);
2252 }
2253 free(_ssl_locks);
2254 return 0;
2255 }
2256 }
2257 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2258 CRYPTO_set_id_callback(_ssl_thread_id_function);
2259 }
2260 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002261}
2262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002265PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002266"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002268
Martin v. Löwis1a214512008-06-11 05:26:20 +00002269
2270static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 PyModuleDef_HEAD_INIT,
2272 "_ssl",
2273 module_doc,
2274 -1,
2275 PySSL_methods,
2276 NULL,
2277 NULL,
2278 NULL,
2279 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002280};
2281
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002282
2283static void
2284parse_openssl_version(unsigned long libver,
2285 unsigned int *major, unsigned int *minor,
2286 unsigned int *fix, unsigned int *patch,
2287 unsigned int *status)
2288{
2289 *status = libver & 0xF;
2290 libver >>= 4;
2291 *patch = libver & 0xFF;
2292 libver >>= 8;
2293 *fix = libver & 0xFF;
2294 libver >>= 8;
2295 *minor = libver & 0xFF;
2296 libver >>= 8;
2297 *major = libver & 0xFF;
2298}
2299
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002300PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002301PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 PyObject *m, *d, *r;
2304 unsigned long libver;
2305 unsigned int major, minor, fix, patch, status;
2306 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002307
Antoine Pitrou152efa22010-05-16 18:19:27 +00002308 if (PyType_Ready(&PySSLContext_Type) < 0)
2309 return NULL;
2310 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002311 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 m = PyModule_Create(&_sslmodule);
2314 if (m == NULL)
2315 return NULL;
2316 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 /* Load _socket module and its C API */
2319 socket_api = PySocketModule_ImportModuleAndAPI();
2320 if (!socket_api)
2321 return NULL;
2322 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 /* Init OpenSSL */
2325 SSL_load_error_strings();
2326 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 /* note that this will start threading if not already started */
2329 if (!_setup_ssl_threads()) {
2330 return NULL;
2331 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002332#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 /* Add symbols to module dict */
2336 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2337 PySocketModule.error,
2338 NULL);
2339 if (PySSLErrorObject == NULL)
2340 return NULL;
2341 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2342 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002343 if (PyDict_SetItemString(d, "_SSLContext",
2344 (PyObject *)&PySSLContext_Type) != 0)
2345 return NULL;
2346 if (PyDict_SetItemString(d, "_SSLSocket",
2347 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 return NULL;
2349 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2350 PY_SSL_ERROR_ZERO_RETURN);
2351 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2352 PY_SSL_ERROR_WANT_READ);
2353 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2354 PY_SSL_ERROR_WANT_WRITE);
2355 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2356 PY_SSL_ERROR_WANT_X509_LOOKUP);
2357 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2358 PY_SSL_ERROR_SYSCALL);
2359 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2360 PY_SSL_ERROR_SSL);
2361 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2362 PY_SSL_ERROR_WANT_CONNECT);
2363 /* non ssl.h errorcodes */
2364 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2365 PY_SSL_ERROR_EOF);
2366 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2367 PY_SSL_ERROR_INVALID_ERROR_CODE);
2368 /* cert requirements */
2369 PyModule_AddIntConstant(m, "CERT_NONE",
2370 PY_SSL_CERT_NONE);
2371 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2372 PY_SSL_CERT_OPTIONAL);
2373 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2374 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002377#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2379 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002380#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002381 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2382 PY_SSL_VERSION_SSL3);
2383 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2384 PY_SSL_VERSION_SSL23);
2385 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2386 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002387
Antoine Pitroub5218772010-05-21 09:56:06 +00002388 /* protocol options */
2389 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2390 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2391 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2392 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2393
Antoine Pitroud5323212010-10-22 18:19:07 +00002394#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2395 r = Py_True;
2396#else
2397 r = Py_False;
2398#endif
2399 Py_INCREF(r);
2400 PyModule_AddObject(m, "HAS_SNI", r);
2401
Antoine Pitroud6494802011-07-21 01:11:30 +02002402#if HAVE_OPENSSL_FINISHED
2403 r = Py_True;
2404#else
2405 r = Py_False;
2406#endif
2407 Py_INCREF(r);
2408 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 /* OpenSSL version */
2411 /* SSLeay() gives us the version of the library linked against,
2412 which could be different from the headers version.
2413 */
2414 libver = SSLeay();
2415 r = PyLong_FromUnsignedLong(libver);
2416 if (r == NULL)
2417 return NULL;
2418 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2419 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002420 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2422 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2423 return NULL;
2424 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2425 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2426 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002427
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002428 libver = OPENSSL_VERSION_NUMBER;
2429 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2430 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2431 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2432 return NULL;
2433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002435}