blob: b203ce4262595908d9f44b8c1f987836c3987974 [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 Pitroucbb82eb2010-05-05 15:57:33 +0000598 i = 0;
599 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*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001043#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 if (s->sock_fd >= FD_SETSIZE)
1045 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001046#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 /* Construct the arguments to select */
1049 tv.tv_sec = (int)s->sock_timeout;
1050 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1051 FD_ZERO(&fds);
1052 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 /* See if the socket is ready */
1055 PySSL_BEGIN_ALLOW_THREADS
1056 if (writing)
1057 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1058 else
1059 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1060 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001061
Bill Janssen6e027db2007-11-15 22:23:56 +00001062#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001063normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001064#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1066 (when we are able to write or when there's something to read) */
1067 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001068}
1069
Antoine Pitrou152efa22010-05-16 18:19:27 +00001070static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001071{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 Py_buffer buf;
1073 int len;
1074 int sockstate;
1075 int err;
1076 int nonblocking;
1077 PySocketSockObject *sock
1078 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 if (((PyObject*)sock) == Py_None) {
1081 _setSSLError("Underlying socket connection gone",
1082 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1083 return NULL;
1084 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001085 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001087 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1088 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001090 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091
1092 /* just in case the blocking state of the socket has been changed */
1093 nonblocking = (sock->sock_timeout >= 0.0);
1094 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1095 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1096
1097 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1098 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001099 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 "The write operation timed out");
1101 goto error;
1102 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1103 PyErr_SetString(PySSLErrorObject,
1104 "Underlying socket has been closed.");
1105 goto error;
1106 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1107 PyErr_SetString(PySSLErrorObject,
1108 "Underlying socket too large for select().");
1109 goto error;
1110 }
1111 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 PySSL_BEGIN_ALLOW_THREADS
1113 len = SSL_write(self->ssl, buf.buf, buf.len);
1114 err = SSL_get_error(self->ssl, len);
1115 PySSL_END_ALLOW_THREADS
1116 if (PyErr_CheckSignals()) {
1117 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001118 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001120 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001122 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 } else {
1124 sockstate = SOCKET_OPERATION_OK;
1125 }
1126 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001127 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 "The write operation timed out");
1129 goto error;
1130 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1131 PyErr_SetString(PySSLErrorObject,
1132 "Underlying socket has been closed.");
1133 goto error;
1134 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1135 break;
1136 }
1137 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001138
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001139 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 PyBuffer_Release(&buf);
1141 if (len > 0)
1142 return PyLong_FromLong(len);
1143 else
1144 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001145
1146error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001147 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 PyBuffer_Release(&buf);
1149 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001150}
1151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001152PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001153"write(s) -> len\n\
1154\n\
1155Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001156of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001157
Antoine Pitrou152efa22010-05-16 18:19:27 +00001158static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001159{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 PySSL_BEGIN_ALLOW_THREADS
1163 count = SSL_pending(self->ssl);
1164 PySSL_END_ALLOW_THREADS
1165 if (count < 0)
1166 return PySSL_SetError(self, count, __FILE__, __LINE__);
1167 else
1168 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001169}
1170
1171PyDoc_STRVAR(PySSL_SSLpending_doc,
1172"pending() -> count\n\
1173\n\
1174Returns the number of already decrypted bytes available for read,\n\
1175pending on the connection.\n");
1176
Antoine Pitrou152efa22010-05-16 18:19:27 +00001177static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001178{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 PyObject *dest = NULL;
1180 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001182 int len, count;
1183 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 int sockstate;
1185 int err;
1186 int nonblocking;
1187 PySocketSockObject *sock
1188 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 if (((PyObject*)sock) == Py_None) {
1191 _setSSLError("Underlying socket connection gone",
1192 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1193 return NULL;
1194 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001195 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001197 buf.obj = NULL;
1198 buf.buf = NULL;
1199 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001200 goto error;
1201
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001202 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1203 dest = PyBytes_FromStringAndSize(NULL, len);
1204 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001205 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001206 mem = PyBytes_AS_STRING(dest);
1207 }
1208 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001210 mem = buf.buf;
1211 if (len <= 0 || len > buf.len) {
1212 len = (int) buf.len;
1213 if (buf.len != len) {
1214 PyErr_SetString(PyExc_OverflowError,
1215 "maximum length can't fit in a C 'int'");
1216 goto error;
1217 }
1218 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 }
1220
1221 /* just in case the blocking state of the socket has been changed */
1222 nonblocking = (sock->sock_timeout >= 0.0);
1223 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1224 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1225
1226 /* first check if there are bytes ready to be read */
1227 PySSL_BEGIN_ALLOW_THREADS
1228 count = SSL_pending(self->ssl);
1229 PySSL_END_ALLOW_THREADS
1230
1231 if (!count) {
1232 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1233 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001234 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 "The read operation timed out");
1236 goto error;
1237 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1238 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001239 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 goto error;
1241 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1242 count = 0;
1243 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001244 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 }
1246 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 PySSL_BEGIN_ALLOW_THREADS
1248 count = SSL_read(self->ssl, mem, len);
1249 err = SSL_get_error(self->ssl, count);
1250 PySSL_END_ALLOW_THREADS
1251 if (PyErr_CheckSignals())
1252 goto error;
1253 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001254 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001256 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1258 (SSL_get_shutdown(self->ssl) ==
1259 SSL_RECEIVED_SHUTDOWN))
1260 {
1261 count = 0;
1262 goto done;
1263 } else {
1264 sockstate = SOCKET_OPERATION_OK;
1265 }
1266 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001267 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 "The read operation timed out");
1269 goto error;
1270 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1271 break;
1272 }
1273 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1274 if (count <= 0) {
1275 PySSL_SetError(self, count, __FILE__, __LINE__);
1276 goto error;
1277 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001278
1279done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001280 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001282 _PyBytes_Resize(&dest, count);
1283 return dest;
1284 }
1285 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 PyBuffer_Release(&buf);
1287 return PyLong_FromLong(count);
1288 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001289
1290error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001291 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001292 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001293 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001294 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001297}
1298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001299PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001300"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001301\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001302Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001303
Antoine Pitrou152efa22010-05-16 18:19:27 +00001304static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001305{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001306 int err, ssl_err, sockstate, nonblocking;
1307 int zeros = 0;
1308 PySocketSockObject *sock
1309 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 /* Guard against closed socket */
1312 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1313 _setSSLError("Underlying socket connection gone",
1314 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1315 return NULL;
1316 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001317 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318
1319 /* Just in case the blocking state of the socket has been changed */
1320 nonblocking = (sock->sock_timeout >= 0.0);
1321 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1322 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1323
1324 while (1) {
1325 PySSL_BEGIN_ALLOW_THREADS
1326 /* Disable read-ahead so that unwrap can work correctly.
1327 * Otherwise OpenSSL might read in too much data,
1328 * eating clear text data that happens to be
1329 * transmitted after the SSL shutdown.
1330 * Should be safe to call repeatedly everytime this
1331 * function is used and the shutdown_seen_zero != 0
1332 * condition is met.
1333 */
1334 if (self->shutdown_seen_zero)
1335 SSL_set_read_ahead(self->ssl, 0);
1336 err = SSL_shutdown(self->ssl);
1337 PySSL_END_ALLOW_THREADS
1338 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1339 if (err > 0)
1340 break;
1341 if (err == 0) {
1342 /* Don't loop endlessly; instead preserve legacy
1343 behaviour of trying SSL_shutdown() only twice.
1344 This looks necessary for OpenSSL < 0.9.8m */
1345 if (++zeros > 1)
1346 break;
1347 /* Shutdown was sent, now try receiving */
1348 self->shutdown_seen_zero = 1;
1349 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001350 }
1351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 /* Possibly retry shutdown until timeout or failure */
1353 ssl_err = SSL_get_error(self->ssl, err);
1354 if (ssl_err == SSL_ERROR_WANT_READ)
1355 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1356 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1357 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1358 else
1359 break;
1360 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1361 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001362 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 "The read operation timed out");
1364 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001365 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001367 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 }
1369 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1370 PyErr_SetString(PySSLErrorObject,
1371 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001372 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 }
1374 else if (sockstate != SOCKET_OPERATION_OK)
1375 /* Retain the SSL error code */
1376 break;
1377 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001378
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001379 if (err < 0) {
1380 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001383 else
1384 /* It's already INCREF'ed */
1385 return (PyObject *) sock;
1386
1387error:
1388 Py_DECREF(sock);
1389 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001390}
1391
1392PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1393"shutdown(s) -> socket\n\
1394\n\
1395Does the SSL shutdown handshake with the remote end, and returns\n\
1396the underlying socket object.");
1397
Antoine Pitroud6494802011-07-21 01:11:30 +02001398#if HAVE_OPENSSL_FINISHED
1399static PyObject *
1400PySSL_tls_unique_cb(PySSLSocket *self)
1401{
1402 PyObject *retval = NULL;
1403 char buf[PySSL_CB_MAXLEN];
1404 int len;
1405
1406 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1407 /* if session is resumed XOR we are the client */
1408 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1409 }
1410 else {
1411 /* if a new session XOR we are the server */
1412 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1413 }
1414
1415 /* It cannot be negative in current OpenSSL version as of July 2011 */
1416 assert(len >= 0);
1417 if (len == 0)
1418 Py_RETURN_NONE;
1419
1420 retval = PyBytes_FromStringAndSize(buf, len);
1421
1422 return retval;
1423}
1424
1425PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1426"tls_unique_cb() -> bytes\n\
1427\n\
1428Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1429\n\
1430If the TLS handshake is not yet complete, None is returned");
1431
1432#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001433
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001434static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1436 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1437 PySSL_SSLwrite_doc},
1438 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1439 PySSL_SSLread_doc},
1440 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1441 PySSL_SSLpending_doc},
1442 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1443 PySSL_peercert_doc},
1444 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1445 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1446 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001447#if HAVE_OPENSSL_FINISHED
1448 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1449 PySSL_tls_unique_cb_doc},
1450#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001452};
1453
Antoine Pitrou152efa22010-05-16 18:19:27 +00001454static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001455 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001456 "_ssl._SSLSocket", /*tp_name*/
1457 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001458 0, /*tp_itemsize*/
1459 /* methods */
1460 (destructor)PySSL_dealloc, /*tp_dealloc*/
1461 0, /*tp_print*/
1462 0, /*tp_getattr*/
1463 0, /*tp_setattr*/
1464 0, /*tp_reserved*/
1465 0, /*tp_repr*/
1466 0, /*tp_as_number*/
1467 0, /*tp_as_sequence*/
1468 0, /*tp_as_mapping*/
1469 0, /*tp_hash*/
1470 0, /*tp_call*/
1471 0, /*tp_str*/
1472 0, /*tp_getattro*/
1473 0, /*tp_setattro*/
1474 0, /*tp_as_buffer*/
1475 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1476 0, /*tp_doc*/
1477 0, /*tp_traverse*/
1478 0, /*tp_clear*/
1479 0, /*tp_richcompare*/
1480 0, /*tp_weaklistoffset*/
1481 0, /*tp_iter*/
1482 0, /*tp_iternext*/
1483 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001484};
1485
Antoine Pitrou152efa22010-05-16 18:19:27 +00001486
1487/*
1488 * _SSLContext objects
1489 */
1490
1491static PyObject *
1492context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1493{
1494 char *kwlist[] = {"protocol", NULL};
1495 PySSLContext *self;
1496 int proto_version = PY_SSL_VERSION_SSL23;
1497 SSL_CTX *ctx = NULL;
1498
1499 if (!PyArg_ParseTupleAndKeywords(
1500 args, kwds, "i:_SSLContext", kwlist,
1501 &proto_version))
1502 return NULL;
1503
1504 PySSL_BEGIN_ALLOW_THREADS
1505 if (proto_version == PY_SSL_VERSION_TLS1)
1506 ctx = SSL_CTX_new(TLSv1_method());
1507 else if (proto_version == PY_SSL_VERSION_SSL3)
1508 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001509#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001510 else if (proto_version == PY_SSL_VERSION_SSL2)
1511 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001512#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001513 else if (proto_version == PY_SSL_VERSION_SSL23)
1514 ctx = SSL_CTX_new(SSLv23_method());
1515 else
1516 proto_version = -1;
1517 PySSL_END_ALLOW_THREADS
1518
1519 if (proto_version == -1) {
1520 PyErr_SetString(PyExc_ValueError,
1521 "invalid protocol version");
1522 return NULL;
1523 }
1524 if (ctx == NULL) {
1525 PyErr_SetString(PySSLErrorObject,
1526 "failed to allocate SSL context");
1527 return NULL;
1528 }
1529
1530 assert(type != NULL && type->tp_alloc != NULL);
1531 self = (PySSLContext *) type->tp_alloc(type, 0);
1532 if (self == NULL) {
1533 SSL_CTX_free(ctx);
1534 return NULL;
1535 }
1536 self->ctx = ctx;
1537 /* Defaults */
1538 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1539 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1540
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001541#define SID_CTX "Python"
1542 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1543 sizeof(SID_CTX));
1544#undef SID_CTX
1545
Antoine Pitrou152efa22010-05-16 18:19:27 +00001546 return (PyObject *)self;
1547}
1548
1549static void
1550context_dealloc(PySSLContext *self)
1551{
1552 SSL_CTX_free(self->ctx);
1553 Py_TYPE(self)->tp_free(self);
1554}
1555
1556static PyObject *
1557set_ciphers(PySSLContext *self, PyObject *args)
1558{
1559 int ret;
1560 const char *cipherlist;
1561
1562 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1563 return NULL;
1564 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1565 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001566 /* Clearing the error queue is necessary on some OpenSSL versions,
1567 otherwise the error will be reported again when another SSL call
1568 is done. */
1569 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001570 PyErr_SetString(PySSLErrorObject,
1571 "No cipher can be selected.");
1572 return NULL;
1573 }
1574 Py_RETURN_NONE;
1575}
1576
1577static PyObject *
1578get_verify_mode(PySSLContext *self, void *c)
1579{
1580 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1581 case SSL_VERIFY_NONE:
1582 return PyLong_FromLong(PY_SSL_CERT_NONE);
1583 case SSL_VERIFY_PEER:
1584 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1585 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1586 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1587 }
1588 PyErr_SetString(PySSLErrorObject,
1589 "invalid return value from SSL_CTX_get_verify_mode");
1590 return NULL;
1591}
1592
1593static int
1594set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1595{
1596 int n, mode;
1597 if (!PyArg_Parse(arg, "i", &n))
1598 return -1;
1599 if (n == PY_SSL_CERT_NONE)
1600 mode = SSL_VERIFY_NONE;
1601 else if (n == PY_SSL_CERT_OPTIONAL)
1602 mode = SSL_VERIFY_PEER;
1603 else if (n == PY_SSL_CERT_REQUIRED)
1604 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1605 else {
1606 PyErr_SetString(PyExc_ValueError,
1607 "invalid value for verify_mode");
1608 return -1;
1609 }
1610 SSL_CTX_set_verify(self->ctx, mode, NULL);
1611 return 0;
1612}
1613
1614static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001615get_options(PySSLContext *self, void *c)
1616{
1617 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1618}
1619
1620static int
1621set_options(PySSLContext *self, PyObject *arg, void *c)
1622{
1623 long new_opts, opts, set, clear;
1624 if (!PyArg_Parse(arg, "l", &new_opts))
1625 return -1;
1626 opts = SSL_CTX_get_options(self->ctx);
1627 clear = opts & ~new_opts;
1628 set = ~opts & new_opts;
1629 if (clear) {
1630#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1631 SSL_CTX_clear_options(self->ctx, clear);
1632#else
1633 PyErr_SetString(PyExc_ValueError,
1634 "can't clear options before OpenSSL 0.9.8m");
1635 return -1;
1636#endif
1637 }
1638 if (set)
1639 SSL_CTX_set_options(self->ctx, set);
1640 return 0;
1641}
1642
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001643typedef struct {
1644 PyThreadState *thread_state;
1645 PyObject *callable;
1646 char *password;
1647 Py_ssize_t size;
1648 int error;
1649} _PySSLPasswordInfo;
1650
1651static int
1652_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1653 const char *bad_type_error)
1654{
1655 /* Set the password and size fields of a _PySSLPasswordInfo struct
1656 from a unicode, bytes, or byte array object.
1657 The password field will be dynamically allocated and must be freed
1658 by the caller */
1659 PyObject *password_bytes = NULL;
1660 const char *data = NULL;
1661 Py_ssize_t size;
1662
1663 if (PyUnicode_Check(password)) {
1664 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1665 if (!password_bytes) {
1666 goto error;
1667 }
1668 data = PyBytes_AS_STRING(password_bytes);
1669 size = PyBytes_GET_SIZE(password_bytes);
1670 } else if (PyBytes_Check(password)) {
1671 data = PyBytes_AS_STRING(password);
1672 size = PyBytes_GET_SIZE(password);
1673 } else if (PyByteArray_Check(password)) {
1674 data = PyByteArray_AS_STRING(password);
1675 size = PyByteArray_GET_SIZE(password);
1676 } else {
1677 PyErr_SetString(PyExc_TypeError, bad_type_error);
1678 goto error;
1679 }
1680
1681 free(pw_info->password);
1682 pw_info->password = malloc(size);
1683 if (!pw_info->password) {
1684 PyErr_SetString(PyExc_MemoryError,
1685 "unable to allocate password buffer");
1686 goto error;
1687 }
1688 memcpy(pw_info->password, data, size);
1689 pw_info->size = size;
1690
1691 Py_XDECREF(password_bytes);
1692 return 1;
1693
1694error:
1695 Py_XDECREF(password_bytes);
1696 return 0;
1697}
1698
1699static int
1700_password_callback(char *buf, int size, int rwflag, void *userdata)
1701{
1702 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1703 PyObject *fn_ret = NULL;
1704
1705 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1706
1707 if (pw_info->callable) {
1708 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1709 if (!fn_ret) {
1710 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1711 core python API, so we could use it to add a frame here */
1712 goto error;
1713 }
1714
1715 if (!_pwinfo_set(pw_info, fn_ret,
1716 "password callback must return a string")) {
1717 goto error;
1718 }
1719 Py_CLEAR(fn_ret);
1720 }
1721
1722 if (pw_info->size > size) {
1723 PyErr_Format(PyExc_ValueError,
1724 "password cannot be longer than %d bytes", size);
1725 goto error;
1726 }
1727
1728 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1729 memcpy(buf, pw_info->password, pw_info->size);
1730 return pw_info->size;
1731
1732error:
1733 Py_XDECREF(fn_ret);
1734 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1735 pw_info->error = 1;
1736 return -1;
1737}
1738
Antoine Pitroub5218772010-05-21 09:56:06 +00001739static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001740load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1741{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001742 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1743 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001744 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001745 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1746 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1747 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001748 int r;
1749
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001750 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001751 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001752 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001753 "O|OO:load_cert_chain", kwlist,
1754 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001755 return NULL;
1756 if (keyfile == Py_None)
1757 keyfile = NULL;
1758 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1759 PyErr_SetString(PyExc_TypeError,
1760 "certfile should be a valid filesystem path");
1761 return NULL;
1762 }
1763 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1764 PyErr_SetString(PyExc_TypeError,
1765 "keyfile should be a valid filesystem path");
1766 goto error;
1767 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001768 if (password && password != Py_None) {
1769 if (PyCallable_Check(password)) {
1770 pw_info.callable = password;
1771 } else if (!_pwinfo_set(&pw_info, password,
1772 "password should be a string or callable")) {
1773 goto error;
1774 }
1775 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1776 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1777 }
1778 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001779 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1780 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001781 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001782 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001783 if (pw_info.error) {
1784 ERR_clear_error();
1785 /* the password callback has already set the error information */
1786 }
1787 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001788 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001789 PyErr_SetFromErrno(PyExc_IOError);
1790 }
1791 else {
1792 _setSSLError(NULL, 0, __FILE__, __LINE__);
1793 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794 goto error;
1795 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001796 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001797 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001798 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1799 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001800 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1801 Py_CLEAR(keyfile_bytes);
1802 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001803 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001804 if (pw_info.error) {
1805 ERR_clear_error();
1806 /* the password callback has already set the error information */
1807 }
1808 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001809 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001810 PyErr_SetFromErrno(PyExc_IOError);
1811 }
1812 else {
1813 _setSSLError(NULL, 0, __FILE__, __LINE__);
1814 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001815 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001816 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001817 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001818 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001819 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001820 if (r != 1) {
1821 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001822 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001823 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001824 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1825 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1826 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001827 Py_RETURN_NONE;
1828
1829error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001830 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1831 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1832 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001833 Py_XDECREF(keyfile_bytes);
1834 Py_XDECREF(certfile_bytes);
1835 return NULL;
1836}
1837
1838static PyObject *
1839load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1840{
1841 char *kwlist[] = {"cafile", "capath", NULL};
1842 PyObject *cafile = NULL, *capath = NULL;
1843 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1844 const char *cafile_buf = NULL, *capath_buf = NULL;
1845 int r;
1846
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001847 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001848 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1849 "|OO:load_verify_locations", kwlist,
1850 &cafile, &capath))
1851 return NULL;
1852 if (cafile == Py_None)
1853 cafile = NULL;
1854 if (capath == Py_None)
1855 capath = NULL;
1856 if (cafile == NULL && capath == NULL) {
1857 PyErr_SetString(PyExc_TypeError,
1858 "cafile and capath cannot be both omitted");
1859 return NULL;
1860 }
1861 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1862 PyErr_SetString(PyExc_TypeError,
1863 "cafile should be a valid filesystem path");
1864 return NULL;
1865 }
1866 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001867 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001868 PyErr_SetString(PyExc_TypeError,
1869 "capath should be a valid filesystem path");
1870 return NULL;
1871 }
1872 if (cafile)
1873 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1874 if (capath)
1875 capath_buf = PyBytes_AS_STRING(capath_bytes);
1876 PySSL_BEGIN_ALLOW_THREADS
1877 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1878 PySSL_END_ALLOW_THREADS
1879 Py_XDECREF(cafile_bytes);
1880 Py_XDECREF(capath_bytes);
1881 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001882 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001883 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001884 PyErr_SetFromErrno(PyExc_IOError);
1885 }
1886 else {
1887 _setSSLError(NULL, 0, __FILE__, __LINE__);
1888 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001889 return NULL;
1890 }
1891 Py_RETURN_NONE;
1892}
1893
1894static PyObject *
1895context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1896{
Antoine Pitroud5323212010-10-22 18:19:07 +00001897 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001898 PySocketSockObject *sock;
1899 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001900 char *hostname = NULL;
1901 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001902
Antoine Pitroud5323212010-10-22 18:19:07 +00001903 /* server_hostname is either None (or absent), or to be encoded
1904 using the idna encoding. */
1905 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001906 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001907 &sock, &server_side,
1908 Py_TYPE(Py_None), &hostname_obj)) {
1909 PyErr_Clear();
1910 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1911 PySocketModule.Sock_Type,
1912 &sock, &server_side,
1913 "idna", &hostname))
1914 return NULL;
1915#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1916 PyMem_Free(hostname);
1917 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1918 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001919 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001920#endif
1921 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001922
Antoine Pitroud5323212010-10-22 18:19:07 +00001923 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1924 hostname);
1925 if (hostname != NULL)
1926 PyMem_Free(hostname);
1927 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001928}
1929
Antoine Pitroub0182c82010-10-12 20:09:02 +00001930static PyObject *
1931session_stats(PySSLContext *self, PyObject *unused)
1932{
1933 int r;
1934 PyObject *value, *stats = PyDict_New();
1935 if (!stats)
1936 return NULL;
1937
1938#define ADD_STATS(SSL_NAME, KEY_NAME) \
1939 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1940 if (value == NULL) \
1941 goto error; \
1942 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1943 Py_DECREF(value); \
1944 if (r < 0) \
1945 goto error;
1946
1947 ADD_STATS(number, "number");
1948 ADD_STATS(connect, "connect");
1949 ADD_STATS(connect_good, "connect_good");
1950 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1951 ADD_STATS(accept, "accept");
1952 ADD_STATS(accept_good, "accept_good");
1953 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1954 ADD_STATS(accept, "accept");
1955 ADD_STATS(hits, "hits");
1956 ADD_STATS(misses, "misses");
1957 ADD_STATS(timeouts, "timeouts");
1958 ADD_STATS(cache_full, "cache_full");
1959
1960#undef ADD_STATS
1961
1962 return stats;
1963
1964error:
1965 Py_DECREF(stats);
1966 return NULL;
1967}
1968
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001969static PyObject *
1970set_default_verify_paths(PySSLContext *self, PyObject *unused)
1971{
1972 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1973 _setSSLError(NULL, 0, __FILE__, __LINE__);
1974 return NULL;
1975 }
1976 Py_RETURN_NONE;
1977}
1978
Antoine Pitrou152efa22010-05-16 18:19:27 +00001979static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001980 {"options", (getter) get_options,
1981 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001982 {"verify_mode", (getter) get_verify_mode,
1983 (setter) set_verify_mode, NULL},
1984 {NULL}, /* sentinel */
1985};
1986
1987static struct PyMethodDef context_methods[] = {
1988 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1989 METH_VARARGS | METH_KEYWORDS, NULL},
1990 {"set_ciphers", (PyCFunction) set_ciphers,
1991 METH_VARARGS, NULL},
1992 {"load_cert_chain", (PyCFunction) load_cert_chain,
1993 METH_VARARGS | METH_KEYWORDS, NULL},
1994 {"load_verify_locations", (PyCFunction) load_verify_locations,
1995 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001996 {"session_stats", (PyCFunction) session_stats,
1997 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001998 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1999 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002000 {NULL, NULL} /* sentinel */
2001};
2002
2003static PyTypeObject PySSLContext_Type = {
2004 PyVarObject_HEAD_INIT(NULL, 0)
2005 "_ssl._SSLContext", /*tp_name*/
2006 sizeof(PySSLContext), /*tp_basicsize*/
2007 0, /*tp_itemsize*/
2008 (destructor)context_dealloc, /*tp_dealloc*/
2009 0, /*tp_print*/
2010 0, /*tp_getattr*/
2011 0, /*tp_setattr*/
2012 0, /*tp_reserved*/
2013 0, /*tp_repr*/
2014 0, /*tp_as_number*/
2015 0, /*tp_as_sequence*/
2016 0, /*tp_as_mapping*/
2017 0, /*tp_hash*/
2018 0, /*tp_call*/
2019 0, /*tp_str*/
2020 0, /*tp_getattro*/
2021 0, /*tp_setattro*/
2022 0, /*tp_as_buffer*/
2023 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2024 0, /*tp_doc*/
2025 0, /*tp_traverse*/
2026 0, /*tp_clear*/
2027 0, /*tp_richcompare*/
2028 0, /*tp_weaklistoffset*/
2029 0, /*tp_iter*/
2030 0, /*tp_iternext*/
2031 context_methods, /*tp_methods*/
2032 0, /*tp_members*/
2033 context_getsetlist, /*tp_getset*/
2034 0, /*tp_base*/
2035 0, /*tp_dict*/
2036 0, /*tp_descr_get*/
2037 0, /*tp_descr_set*/
2038 0, /*tp_dictoffset*/
2039 0, /*tp_init*/
2040 0, /*tp_alloc*/
2041 context_new, /*tp_new*/
2042};
2043
2044
2045
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002046#ifdef HAVE_OPENSSL_RAND
2047
2048/* helper routines for seeding the SSL PRNG */
2049static PyObject *
2050PySSL_RAND_add(PyObject *self, PyObject *args)
2051{
2052 char *buf;
2053 int len;
2054 double entropy;
2055
2056 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002057 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002058 RAND_add(buf, len, entropy);
2059 Py_INCREF(Py_None);
2060 return Py_None;
2061}
2062
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002063PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002064"RAND_add(string, entropy)\n\
2065\n\
2066Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002067bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002068
2069static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002070PySSL_RAND(int len, int pseudo)
2071{
2072 int ok;
2073 PyObject *bytes;
2074 unsigned long err;
2075 const char *errstr;
2076 PyObject *v;
2077
2078 bytes = PyBytes_FromStringAndSize(NULL, len);
2079 if (bytes == NULL)
2080 return NULL;
2081 if (pseudo) {
2082 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2083 if (ok == 0 || ok == 1)
2084 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2085 }
2086 else {
2087 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2088 if (ok == 1)
2089 return bytes;
2090 }
2091 Py_DECREF(bytes);
2092
2093 err = ERR_get_error();
2094 errstr = ERR_reason_error_string(err);
2095 v = Py_BuildValue("(ks)", err, errstr);
2096 if (v != NULL) {
2097 PyErr_SetObject(PySSLErrorObject, v);
2098 Py_DECREF(v);
2099 }
2100 return NULL;
2101}
2102
2103static PyObject *
2104PySSL_RAND_bytes(PyObject *self, PyObject *args)
2105{
2106 int len;
2107 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2108 return NULL;
2109 return PySSL_RAND(len, 0);
2110}
2111
2112PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2113"RAND_bytes(n) -> bytes\n\
2114\n\
2115Generate n cryptographically strong pseudo-random bytes.");
2116
2117static PyObject *
2118PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2119{
2120 int len;
2121 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2122 return NULL;
2123 return PySSL_RAND(len, 1);
2124}
2125
2126PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2127"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2128\n\
2129Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2130generated are cryptographically strong.");
2131
2132static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002133PySSL_RAND_status(PyObject *self)
2134{
Christian Heimes217cfd12007-12-02 14:31:20 +00002135 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002136}
2137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002138PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002139"RAND_status() -> 0 or 1\n\
2140\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002141Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2142It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2143using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002144
2145static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002146PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002147{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002148 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002149 int bytes;
2150
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002151 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2152 PyUnicode_FSConverter, &path))
2153 return NULL;
2154
2155 bytes = RAND_egd(PyBytes_AsString(path));
2156 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002157 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002158 PyErr_SetString(PySSLErrorObject,
2159 "EGD connection failed or EGD did not return "
2160 "enough data to seed the PRNG");
2161 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002162 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002163 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002164}
2165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002166PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002167"RAND_egd(path) -> bytes\n\
2168\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002169Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2170Returns number of bytes read. Raises SSLError if connection to EGD\n\
2171fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002172
2173#endif
2174
Bill Janssen40a0f662008-08-12 16:56:25 +00002175
2176
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002177/* List of functions exported by this module. */
2178
2179static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 {"_test_decode_cert", PySSL_test_decode_certificate,
2181 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002182#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2184 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002185 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2186 PySSL_RAND_bytes_doc},
2187 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2188 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002189 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 PySSL_RAND_egd_doc},
2191 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2192 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002193#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002195};
2196
2197
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002198#ifdef WITH_THREAD
2199
2200/* an implementation of OpenSSL threading operations in terms
2201 of the Python C thread library */
2202
2203static PyThread_type_lock *_ssl_locks = NULL;
2204
2205static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002207}
2208
Bill Janssen6e027db2007-11-15 22:23:56 +00002209static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 (int mode, int n, const char *file, int line) {
2211 /* this function is needed to perform locking on shared data
2212 structures. (Note that OpenSSL uses a number of global data
2213 structures that will be implicitly shared whenever multiple
2214 threads use OpenSSL.) Multi-threaded applications will
2215 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002217 locking_function() must be able to handle up to
2218 CRYPTO_num_locks() different mutex locks. It sets the n-th
2219 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 file and line are the file number of the function setting the
2222 lock. They can be useful for debugging.
2223 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002224
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225 if ((_ssl_locks == NULL) ||
2226 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2227 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 if (mode & CRYPTO_LOCK) {
2230 PyThread_acquire_lock(_ssl_locks[n], 1);
2231 } else {
2232 PyThread_release_lock(_ssl_locks[n]);
2233 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002234}
2235
2236static int _setup_ssl_threads(void) {
2237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 if (_ssl_locks == NULL) {
2241 _ssl_locks_count = CRYPTO_num_locks();
2242 _ssl_locks = (PyThread_type_lock *)
2243 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2244 if (_ssl_locks == NULL)
2245 return 0;
2246 memset(_ssl_locks, 0,
2247 sizeof(PyThread_type_lock) * _ssl_locks_count);
2248 for (i = 0; i < _ssl_locks_count; i++) {
2249 _ssl_locks[i] = PyThread_allocate_lock();
2250 if (_ssl_locks[i] == NULL) {
2251 unsigned int j;
2252 for (j = 0; j < i; j++) {
2253 PyThread_free_lock(_ssl_locks[j]);
2254 }
2255 free(_ssl_locks);
2256 return 0;
2257 }
2258 }
2259 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2260 CRYPTO_set_id_callback(_ssl_thread_id_function);
2261 }
2262 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002263}
2264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002266
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002268"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002270
Martin v. Löwis1a214512008-06-11 05:26:20 +00002271
2272static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 PyModuleDef_HEAD_INIT,
2274 "_ssl",
2275 module_doc,
2276 -1,
2277 PySSL_methods,
2278 NULL,
2279 NULL,
2280 NULL,
2281 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002282};
2283
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002284
2285static void
2286parse_openssl_version(unsigned long libver,
2287 unsigned int *major, unsigned int *minor,
2288 unsigned int *fix, unsigned int *patch,
2289 unsigned int *status)
2290{
2291 *status = libver & 0xF;
2292 libver >>= 4;
2293 *patch = libver & 0xFF;
2294 libver >>= 8;
2295 *fix = libver & 0xFF;
2296 libver >>= 8;
2297 *minor = libver & 0xFF;
2298 libver >>= 8;
2299 *major = libver & 0xFF;
2300}
2301
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002302PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002303PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002304{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 PyObject *m, *d, *r;
2306 unsigned long libver;
2307 unsigned int major, minor, fix, patch, status;
2308 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002309
Antoine Pitrou152efa22010-05-16 18:19:27 +00002310 if (PyType_Ready(&PySSLContext_Type) < 0)
2311 return NULL;
2312 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 m = PyModule_Create(&_sslmodule);
2316 if (m == NULL)
2317 return NULL;
2318 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 /* Load _socket module and its C API */
2321 socket_api = PySocketModule_ImportModuleAndAPI();
2322 if (!socket_api)
2323 return NULL;
2324 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 /* Init OpenSSL */
2327 SSL_load_error_strings();
2328 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002329#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 /* note that this will start threading if not already started */
2331 if (!_setup_ssl_threads()) {
2332 return NULL;
2333 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002334#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 /* Add symbols to module dict */
2338 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2339 PySocketModule.error,
2340 NULL);
2341 if (PySSLErrorObject == NULL)
2342 return NULL;
2343 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2344 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002345 if (PyDict_SetItemString(d, "_SSLContext",
2346 (PyObject *)&PySSLContext_Type) != 0)
2347 return NULL;
2348 if (PyDict_SetItemString(d, "_SSLSocket",
2349 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 return NULL;
2351 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2352 PY_SSL_ERROR_ZERO_RETURN);
2353 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2354 PY_SSL_ERROR_WANT_READ);
2355 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2356 PY_SSL_ERROR_WANT_WRITE);
2357 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2358 PY_SSL_ERROR_WANT_X509_LOOKUP);
2359 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2360 PY_SSL_ERROR_SYSCALL);
2361 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2362 PY_SSL_ERROR_SSL);
2363 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2364 PY_SSL_ERROR_WANT_CONNECT);
2365 /* non ssl.h errorcodes */
2366 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2367 PY_SSL_ERROR_EOF);
2368 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2369 PY_SSL_ERROR_INVALID_ERROR_CODE);
2370 /* cert requirements */
2371 PyModule_AddIntConstant(m, "CERT_NONE",
2372 PY_SSL_CERT_NONE);
2373 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2374 PY_SSL_CERT_OPTIONAL);
2375 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2376 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002379#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2381 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002382#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2384 PY_SSL_VERSION_SSL3);
2385 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2386 PY_SSL_VERSION_SSL23);
2387 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2388 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002389
Antoine Pitroub5218772010-05-21 09:56:06 +00002390 /* protocol options */
2391 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2392 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2393 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2394 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2395
Antoine Pitroud5323212010-10-22 18:19:07 +00002396#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2397 r = Py_True;
2398#else
2399 r = Py_False;
2400#endif
2401 Py_INCREF(r);
2402 PyModule_AddObject(m, "HAS_SNI", r);
2403
Antoine Pitroud6494802011-07-21 01:11:30 +02002404#if HAVE_OPENSSL_FINISHED
2405 r = Py_True;
2406#else
2407 r = Py_False;
2408#endif
2409 Py_INCREF(r);
2410 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412 /* OpenSSL version */
2413 /* SSLeay() gives us the version of the library linked against,
2414 which could be different from the headers version.
2415 */
2416 libver = SSLeay();
2417 r = PyLong_FromUnsignedLong(libver);
2418 if (r == NULL)
2419 return NULL;
2420 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2421 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002422 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2424 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2425 return NULL;
2426 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2427 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2428 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002429
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002430 libver = OPENSSL_VERSION_NUMBER;
2431 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2432 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2433 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2434 return NULL;
2435
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002437}