blob: 3f631e31ac08f4656ad698b08dab6fdea61e2517 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
21#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000022 PyThreadState *_save = NULL; \
23 if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
24#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};
25#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
26#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
27 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030
31#define PySSL_BEGIN_ALLOW_THREADS
32#define PySSL_BLOCK_THREADS
33#define PySSL_UNBLOCK_THREADS
34#define PySSL_END_ALLOW_THREADS
35
36#endif
37
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000038enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000039 /* these mirror ssl.h */
40 PY_SSL_ERROR_NONE,
41 PY_SSL_ERROR_SSL,
42 PY_SSL_ERROR_WANT_READ,
43 PY_SSL_ERROR_WANT_WRITE,
44 PY_SSL_ERROR_WANT_X509_LOOKUP,
45 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
46 PY_SSL_ERROR_ZERO_RETURN,
47 PY_SSL_ERROR_WANT_CONNECT,
48 /* start of non ssl.h errorcodes */
49 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
50 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
51 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000052};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000053
Thomas Woutersed03b412007-08-28 21:37:11 +000054enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000055 PY_SSL_CLIENT,
56 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000057};
58
59enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CERT_NONE,
61 PY_SSL_CERT_OPTIONAL,
62 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000063};
64
65enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020066#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000067 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020068#endif
69 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000070 PY_SSL_VERSION_SSL23,
71 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000072};
73
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000074/* Include symbols from _socket module */
75#include "socketmodule.h"
76
Benjamin Petersonb173f782009-05-05 22:31:58 +000077static PySocketModule_APIObject PySocketModule;
78
Thomas Woutersed03b412007-08-28 21:37:11 +000079#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080#include <poll.h>
81#elif defined(HAVE_SYS_POLL_H)
82#include <sys/poll.h>
83#endif
84
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000085/* Include OpenSSL header files */
86#include "openssl/rsa.h"
87#include "openssl/crypto.h"
88#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000089#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090#include "openssl/pem.h"
91#include "openssl/ssl.h"
92#include "openssl/err.h"
93#include "openssl/rand.h"
94
95/* SSL error object */
96static PyObject *PySSLErrorObject;
97
Thomas Wouters1b7f8912007-09-19 03:06:30 +000098#ifdef WITH_THREAD
99
100/* serves as a flag to see whether we've initialized the SSL thread support. */
101/* 0 means no, greater than 0 means yes */
102
103static unsigned int _ssl_locks_count = 0;
104
105#endif /* def WITH_THREAD */
106
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107/* SSL socket object */
108
109#define X509_NAME_MAXLEN 256
110
111/* RAND_* APIs got added to OpenSSL in 0.9.5 */
112#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
113# define HAVE_OPENSSL_RAND 1
114#else
115# undef HAVE_OPENSSL_RAND
116#endif
117
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000118/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
119 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
120 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
121#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000122# define HAVE_SSL_CTX_CLEAR_OPTIONS
123#else
124# undef HAVE_SSL_CTX_CLEAR_OPTIONS
125#endif
126
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000127typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000128 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000129 SSL_CTX *ctx;
130} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Antoine Pitrou152efa22010-05-16 18:19:27 +0000132typedef struct {
133 PyObject_HEAD
134 PyObject *Socket; /* weakref to socket on which we're layered */
135 SSL *ssl;
136 X509 *peer_cert;
137 int shutdown_seen_zero;
138} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000139
Antoine Pitrou152efa22010-05-16 18:19:27 +0000140static PyTypeObject PySSLContext_Type;
141static PyTypeObject PySSLSocket_Type;
142
143static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
144static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000145static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000146 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000147static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
148static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000149
Antoine Pitrou152efa22010-05-16 18:19:27 +0000150#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
151#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000152
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000153typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000154 SOCKET_IS_NONBLOCKING,
155 SOCKET_IS_BLOCKING,
156 SOCKET_HAS_TIMED_OUT,
157 SOCKET_HAS_BEEN_CLOSED,
158 SOCKET_TOO_LARGE_FOR_SELECT,
159 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000160} timeout_state;
161
Thomas Woutersed03b412007-08-28 21:37:11 +0000162/* Wrap error strings with filename and line # */
163#define STRINGIFY1(x) #x
164#define STRINGIFY2(x) STRINGIFY1(x)
165#define ERRSTR1(x,y,z) (x ":" y ": " z)
166#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
167
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000168/* XXX It might be helpful to augment the error message generated
169 below with the name of the SSL function that generated the error.
170 I expect it's obvious most of the time.
171*/
172
173static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000174PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000175{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000176 PyObject *v;
177 char buf[2048];
178 char *errstr;
179 int err;
180 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000182 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000184 if (obj->ssl != NULL) {
185 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000187 switch (err) {
188 case SSL_ERROR_ZERO_RETURN:
189 errstr = "TLS/SSL connection has been closed";
190 p = PY_SSL_ERROR_ZERO_RETURN;
191 break;
192 case SSL_ERROR_WANT_READ:
193 errstr = "The operation did not complete (read)";
194 p = PY_SSL_ERROR_WANT_READ;
195 break;
196 case SSL_ERROR_WANT_WRITE:
197 p = PY_SSL_ERROR_WANT_WRITE;
198 errstr = "The operation did not complete (write)";
199 break;
200 case SSL_ERROR_WANT_X509_LOOKUP:
201 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000202 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000203 break;
204 case SSL_ERROR_WANT_CONNECT:
205 p = PY_SSL_ERROR_WANT_CONNECT;
206 errstr = "The operation did not complete (connect)";
207 break;
208 case SSL_ERROR_SYSCALL:
209 {
210 unsigned long e = ERR_get_error();
211 if (e == 0) {
212 PySocketSockObject *s
213 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
214 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000215 p = PY_SSL_ERROR_EOF;
216 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000217 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000218 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000219 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000220 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000221 v = s->errorhandler();
222 Py_DECREF(s);
223 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000224 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000225 p = PY_SSL_ERROR_SYSCALL;
226 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 }
228 } else {
229 p = PY_SSL_ERROR_SYSCALL;
230 /* XXX Protected by global interpreter lock */
231 errstr = ERR_error_string(e, NULL);
232 }
233 break;
234 }
235 case SSL_ERROR_SSL:
236 {
237 unsigned long e = ERR_get_error();
238 p = PY_SSL_ERROR_SSL;
239 if (e != 0)
240 /* XXX Protected by global interpreter lock */
241 errstr = ERR_error_string(e, NULL);
242 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000243 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 }
245 break;
246 }
247 default:
248 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
249 errstr = "Invalid error code";
250 }
251 } else {
252 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
253 }
254 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000255 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000256 v = Py_BuildValue("(is)", p, buf);
257 if (v != NULL) {
258 PyErr_SetObject(PySSLErrorObject, v);
259 Py_DECREF(v);
260 }
261 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000262}
263
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000264static PyObject *
265_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000267 char buf[2048];
268 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000270 if (errstr == NULL) {
271 errcode = ERR_peek_last_error();
272 errstr = ERR_error_string(errcode, NULL);
273 }
274 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000275 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000276 v = Py_BuildValue("(is)", errcode, buf);
277 if (v != NULL) {
278 PyErr_SetObject(PySSLErrorObject, v);
279 Py_DECREF(v);
280 }
281 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282}
283
Antoine Pitrou152efa22010-05-16 18:19:27 +0000284static PySSLSocket *
285newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000286 enum py_ssl_server_or_client socket_type,
287 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000288{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000290
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 if (self == NULL)
293 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 self->peer_cert = NULL;
296 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000299 /* Make sure the SSL error state is initialized */
300 (void) ERR_get_state();
301 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000304 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000305 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000306 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000307#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000308 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000309#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000310
Antoine Pitroud5323212010-10-22 18:19:07 +0000311#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
312 if (server_hostname != NULL)
313 SSL_set_tlsext_host_name(self->ssl, server_hostname);
314#endif
315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 /* If the socket is in non-blocking mode or timeout mode, set the BIO
317 * to non-blocking mode (blocking is the default)
318 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
321 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
322 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000324 PySSL_BEGIN_ALLOW_THREADS
325 if (socket_type == PY_SSL_CLIENT)
326 SSL_set_connect_state(self->ssl);
327 else
328 SSL_set_accept_state(self->ssl);
329 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000330
Antoine Pitrou152efa22010-05-16 18:19:27 +0000331 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000332 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000333}
334
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000335/* SSL object methods */
336
Antoine Pitrou152efa22010-05-16 18:19:27 +0000337static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000338{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000339 int ret;
340 int err;
341 int sockstate, nonblocking;
342 PySocketSockObject *sock
343 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000345 if (((PyObject*)sock) == Py_None) {
346 _setSSLError("Underlying socket connection gone",
347 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
348 return NULL;
349 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000350 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 /* just in case the blocking state of the socket has been changed */
353 nonblocking = (sock->sock_timeout >= 0.0);
354 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
355 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000356
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 /* Actually negotiate SSL connection */
358 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000360 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000361 ret = SSL_do_handshake(self->ssl);
362 err = SSL_get_error(self->ssl, ret);
363 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000364 if (PyErr_CheckSignals())
365 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000366 if (err == SSL_ERROR_WANT_READ) {
367 sockstate = check_socket_and_wait_for_timeout(sock, 0);
368 } else if (err == SSL_ERROR_WANT_WRITE) {
369 sockstate = check_socket_and_wait_for_timeout(sock, 1);
370 } else {
371 sockstate = SOCKET_OPERATION_OK;
372 }
373 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000374 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000375 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000376 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
378 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000379 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000380 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
382 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000383 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000384 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
386 break;
387 }
388 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000389 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 if (ret < 1)
391 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 if (self->peer_cert)
394 X509_free (self->peer_cert);
395 PySSL_BEGIN_ALLOW_THREADS
396 self->peer_cert = SSL_get_peer_certificate(self->ssl);
397 PySSL_END_ALLOW_THREADS
398
399 Py_INCREF(Py_None);
400 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000401
402error:
403 Py_DECREF(sock);
404 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000405}
406
Thomas Woutersed03b412007-08-28 21:37:11 +0000407static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 char namebuf[X509_NAME_MAXLEN];
411 int buflen;
412 PyObject *name_obj;
413 PyObject *value_obj;
414 PyObject *attr;
415 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
418 if (buflen < 0) {
419 _setSSLError(NULL, 0, __FILE__, __LINE__);
420 goto fail;
421 }
422 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
423 if (name_obj == NULL)
424 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000425
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
427 if (buflen < 0) {
428 _setSSLError(NULL, 0, __FILE__, __LINE__);
429 Py_DECREF(name_obj);
430 goto fail;
431 }
432 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000433 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 OPENSSL_free(valuebuf);
435 if (value_obj == NULL) {
436 Py_DECREF(name_obj);
437 goto fail;
438 }
439 attr = PyTuple_New(2);
440 if (attr == NULL) {
441 Py_DECREF(name_obj);
442 Py_DECREF(value_obj);
443 goto fail;
444 }
445 PyTuple_SET_ITEM(attr, 0, name_obj);
446 PyTuple_SET_ITEM(attr, 1, value_obj);
447 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000448
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000451}
452
453static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000455{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
457 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
458 PyObject *rdnt;
459 PyObject *attr = NULL; /* tuple to hold an attribute */
460 int entry_count = X509_NAME_entry_count(xname);
461 X509_NAME_ENTRY *entry;
462 ASN1_OBJECT *name;
463 ASN1_STRING *value;
464 int index_counter;
465 int rdn_level = -1;
466 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000468 dn = PyList_New(0);
469 if (dn == NULL)
470 return NULL;
471 /* now create another tuple to hold the top-level RDN */
472 rdn = PyList_New(0);
473 if (rdn == NULL)
474 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 for (index_counter = 0;
477 index_counter < entry_count;
478 index_counter++)
479 {
480 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 /* check to see if we've gotten to a new RDN */
483 if (rdn_level >= 0) {
484 if (rdn_level != entry->set) {
485 /* yes, new RDN */
486 /* add old RDN to DN */
487 rdnt = PyList_AsTuple(rdn);
488 Py_DECREF(rdn);
489 if (rdnt == NULL)
490 goto fail0;
491 retcode = PyList_Append(dn, rdnt);
492 Py_DECREF(rdnt);
493 if (retcode < 0)
494 goto fail0;
495 /* create new RDN */
496 rdn = PyList_New(0);
497 if (rdn == NULL)
498 goto fail0;
499 }
500 }
501 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 /* now add this attribute to the current RDN */
504 name = X509_NAME_ENTRY_get_object(entry);
505 value = X509_NAME_ENTRY_get_data(entry);
506 attr = _create_tuple_for_attribute(name, value);
507 /*
508 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
509 entry->set,
510 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
511 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
512 */
513 if (attr == NULL)
514 goto fail1;
515 retcode = PyList_Append(rdn, attr);
516 Py_DECREF(attr);
517 if (retcode < 0)
518 goto fail1;
519 }
520 /* now, there's typically a dangling RDN */
521 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
522 rdnt = PyList_AsTuple(rdn);
523 Py_DECREF(rdn);
524 if (rdnt == NULL)
525 goto fail0;
526 retcode = PyList_Append(dn, rdnt);
527 Py_DECREF(rdnt);
528 if (retcode < 0)
529 goto fail0;
530 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 /* convert list to tuple */
533 rdnt = PyList_AsTuple(dn);
534 Py_DECREF(dn);
535 if (rdnt == NULL)
536 return NULL;
537 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538
539 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
542 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 Py_XDECREF(dn);
544 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545}
546
547static PyObject *
548_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 /* this code follows the procedure outlined in
551 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
552 function to extract the STACK_OF(GENERAL_NAME),
553 then iterates through the stack to add the
554 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 int i, j;
557 PyObject *peer_alt_names = Py_None;
558 PyObject *v, *t;
559 X509_EXTENSION *ext = NULL;
560 GENERAL_NAMES *names = NULL;
561 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000562 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 BIO *biobuf = NULL;
564 char buf[2048];
565 char *vptr;
566 int len;
567 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000568#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000570#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000572#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 if (certificate == NULL)
575 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 /* get a memory buffer */
578 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 i = 0;
581 while ((i = X509_get_ext_by_NID(
582 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 if (peer_alt_names == Py_None) {
585 peer_alt_names = PyList_New(0);
586 if (peer_alt_names == NULL)
587 goto fail;
588 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 /* now decode the altName */
591 ext = X509_get_ext(certificate, i);
592 if(!(method = X509V3_EXT_get(ext))) {
593 PyErr_SetString
594 (PySSLErrorObject,
595 ERRSTR("No method for internalizing subjectAltName!"));
596 goto fail;
597 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 p = ext->value->data;
600 if (method->it)
601 names = (GENERAL_NAMES*)
602 (ASN1_item_d2i(NULL,
603 &p,
604 ext->value->length,
605 ASN1_ITEM_ptr(method->it)));
606 else
607 names = (GENERAL_NAMES*)
608 (method->d2i(NULL,
609 &p,
610 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 name = sk_GENERAL_NAME_value(names, j);
617 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 /* we special-case DirName as a tuple of
620 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 t = PyTuple_New(2);
623 if (t == NULL) {
624 goto fail;
625 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 v = PyUnicode_FromString("DirName");
628 if (v == NULL) {
629 Py_DECREF(t);
630 goto fail;
631 }
632 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 v = _create_tuple_for_X509_NAME (name->d.dirn);
635 if (v == NULL) {
636 Py_DECREF(t);
637 goto fail;
638 }
639 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 (void) BIO_reset(biobuf);
646 GENERAL_NAME_print(biobuf, name);
647 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
648 if (len < 0) {
649 _setSSLError(NULL, 0, __FILE__, __LINE__);
650 goto fail;
651 }
652 vptr = strchr(buf, ':');
653 if (vptr == NULL)
654 goto fail;
655 t = PyTuple_New(2);
656 if (t == NULL)
657 goto fail;
658 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
659 if (v == NULL) {
660 Py_DECREF(t);
661 goto fail;
662 }
663 PyTuple_SET_ITEM(t, 0, v);
664 v = PyUnicode_FromStringAndSize((vptr + 1),
665 (len - (vptr - buf + 1)));
666 if (v == NULL) {
667 Py_DECREF(t);
668 goto fail;
669 }
670 PyTuple_SET_ITEM(t, 1, v);
671 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 if (PyList_Append(peer_alt_names, t) < 0) {
676 Py_DECREF(t);
677 goto fail;
678 }
679 Py_DECREF(t);
680 }
681 }
682 BIO_free(biobuf);
683 if (peer_alt_names != Py_None) {
684 v = PyList_AsTuple(peer_alt_names);
685 Py_DECREF(peer_alt_names);
686 return v;
687 } else {
688 return peer_alt_names;
689 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000690
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000691
692 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 if (biobuf != NULL)
694 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 if (peer_alt_names != Py_None) {
697 Py_XDECREF(peer_alt_names);
698 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701}
702
703static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000704_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 PyObject *retval = NULL;
707 BIO *biobuf = NULL;
708 PyObject *peer;
709 PyObject *peer_alt_names = NULL;
710 PyObject *issuer;
711 PyObject *version;
712 PyObject *sn_obj;
713 ASN1_INTEGER *serialNumber;
714 char buf[2048];
715 int len;
716 ASN1_TIME *notBefore, *notAfter;
717 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 retval = PyDict_New();
720 if (retval == NULL)
721 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 peer = _create_tuple_for_X509_NAME(
724 X509_get_subject_name(certificate));
725 if (peer == NULL)
726 goto fail0;
727 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
728 Py_DECREF(peer);
729 goto fail0;
730 }
731 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000732
Antoine Pitroufb046912010-11-09 20:21:19 +0000733 issuer = _create_tuple_for_X509_NAME(
734 X509_get_issuer_name(certificate));
735 if (issuer == NULL)
736 goto fail0;
737 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000739 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000741 Py_DECREF(issuer);
742
743 version = PyLong_FromLong(X509_get_version(certificate) + 1);
744 if (PyDict_SetItemString(retval, "version", version) < 0) {
745 Py_DECREF(version);
746 goto fail0;
747 }
748 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 /* get a memory buffer */
751 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000752
Antoine Pitroufb046912010-11-09 20:21:19 +0000753 (void) BIO_reset(biobuf);
754 serialNumber = X509_get_serialNumber(certificate);
755 /* should not exceed 20 octets, 160 bits, so buf is big enough */
756 i2a_ASN1_INTEGER(biobuf, serialNumber);
757 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
758 if (len < 0) {
759 _setSSLError(NULL, 0, __FILE__, __LINE__);
760 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000762 sn_obj = PyUnicode_FromStringAndSize(buf, len);
763 if (sn_obj == NULL)
764 goto fail1;
765 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
766 Py_DECREF(sn_obj);
767 goto fail1;
768 }
769 Py_DECREF(sn_obj);
770
771 (void) BIO_reset(biobuf);
772 notBefore = X509_get_notBefore(certificate);
773 ASN1_TIME_print(biobuf, notBefore);
774 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
775 if (len < 0) {
776 _setSSLError(NULL, 0, __FILE__, __LINE__);
777 goto fail1;
778 }
779 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
780 if (pnotBefore == NULL)
781 goto fail1;
782 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
783 Py_DECREF(pnotBefore);
784 goto fail1;
785 }
786 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 (void) BIO_reset(biobuf);
789 notAfter = X509_get_notAfter(certificate);
790 ASN1_TIME_print(biobuf, notAfter);
791 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
792 if (len < 0) {
793 _setSSLError(NULL, 0, __FILE__, __LINE__);
794 goto fail1;
795 }
796 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
797 if (pnotAfter == NULL)
798 goto fail1;
799 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
800 Py_DECREF(pnotAfter);
801 goto fail1;
802 }
803 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 peer_alt_names = _get_peer_alt_names(certificate);
808 if (peer_alt_names == NULL)
809 goto fail1;
810 else if (peer_alt_names != Py_None) {
811 if (PyDict_SetItemString(retval, "subjectAltName",
812 peer_alt_names) < 0) {
813 Py_DECREF(peer_alt_names);
814 goto fail1;
815 }
816 Py_DECREF(peer_alt_names);
817 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 BIO_free(biobuf);
820 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000821
822 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 if (biobuf != NULL)
824 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000825 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 Py_XDECREF(retval);
827 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000828}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000829
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
831static PyObject *
832PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000835 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 X509 *x=NULL;
837 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroufb046912010-11-09 20:21:19 +0000839 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
840 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 if ((cert=BIO_new(BIO_s_file())) == NULL) {
844 PyErr_SetString(PySSLErrorObject,
845 "Can't malloc memory to read file");
846 goto fail0;
847 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Victor Stinner3800e1e2010-05-16 21:23:48 +0000849 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 PyErr_SetString(PySSLErrorObject,
851 "Can't open file");
852 goto fail0;
853 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
856 if (x == NULL) {
857 PyErr_SetString(PySSLErrorObject,
858 "Error decoding PEM-encoded file");
859 goto fail0;
860 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroufb046912010-11-09 20:21:19 +0000862 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000863 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
865 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000866 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 if (cert != NULL) BIO_free(cert);
868 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869}
870
871
872static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000873PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000874{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 PyObject *retval = NULL;
876 int len;
877 int verification;
878 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
881 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 if (!self->peer_cert)
884 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 if (PyObject_IsTrue(binary_mode)) {
887 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 bytes_buf = NULL;
892 len = i2d_X509(self->peer_cert, &bytes_buf);
893 if (len < 0) {
894 PySSL_SetError(self, len, __FILE__, __LINE__);
895 return NULL;
896 }
897 /* this is actually an immutable bytes sequence */
898 retval = PyBytes_FromStringAndSize
899 ((const char *) bytes_buf, len);
900 OPENSSL_free(bytes_buf);
901 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000904 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 if ((verification & SSL_VERIFY_PEER) == 0)
906 return PyDict_New();
907 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000908 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000910}
911
912PyDoc_STRVAR(PySSL_peercert_doc,
913"peer_certificate([der=False]) -> certificate\n\
914\n\
915Returns the certificate for the peer. If no certificate was provided,\n\
916returns None. If a certificate was provided, but not validated, returns\n\
917an empty dictionary. Otherwise returns a dict containing information\n\
918about the peer certificate.\n\
919\n\
920If the optional argument is True, returns a DER-encoded copy of the\n\
921peer certificate, or None if no certificate was provided. This will\n\
922return the certificate even if it wasn't validated.");
923
Antoine Pitrou152efa22010-05-16 18:19:27 +0000924static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000927 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 char *cipher_name;
929 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000932 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 current = SSL_get_current_cipher(self->ssl);
934 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000935 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 retval = PyTuple_New(3);
938 if (retval == NULL)
939 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 cipher_name = (char *) SSL_CIPHER_get_name(current);
942 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000943 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PyTuple_SET_ITEM(retval, 0, Py_None);
945 } else {
946 v = PyUnicode_FromString(cipher_name);
947 if (v == NULL)
948 goto fail0;
949 PyTuple_SET_ITEM(retval, 0, v);
950 }
951 cipher_protocol = SSL_CIPHER_get_version(current);
952 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000953 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 PyTuple_SET_ITEM(retval, 1, Py_None);
955 } else {
956 v = PyUnicode_FromString(cipher_protocol);
957 if (v == NULL)
958 goto fail0;
959 PyTuple_SET_ITEM(retval, 1, v);
960 }
961 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
962 if (v == NULL)
963 goto fail0;
964 PyTuple_SET_ITEM(retval, 2, v);
965 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000966
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 Py_DECREF(retval);
969 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970}
971
Antoine Pitrou152efa22010-05-16 18:19:27 +0000972static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000973{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 if (self->peer_cert) /* Possible not to have one? */
975 X509_free (self->peer_cert);
976 if (self->ssl)
977 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 Py_XDECREF(self->Socket);
979 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000980}
981
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000982/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000983 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000984 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000985 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000986
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000987static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000988check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000989{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 fd_set fds;
991 struct timeval tv;
992 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 /* Nothing to do unless we're in timeout mode (not non-blocking) */
995 if (s->sock_timeout < 0.0)
996 return SOCKET_IS_BLOCKING;
997 else if (s->sock_timeout == 0.0)
998 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 /* Guard against closed socket */
1001 if (s->sock_fd < 0)
1002 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 /* Prefer poll, if available, since you can poll() any fd
1005 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 {
1008 struct pollfd pollfd;
1009 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 pollfd.fd = s->sock_fd;
1012 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 /* s->sock_timeout is in seconds, timeout in ms */
1015 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1016 PySSL_BEGIN_ALLOW_THREADS
1017 rc = poll(&pollfd, 1, timeout);
1018 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 goto normal_return;
1021 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022#endif
1023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001025#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 if (s->sock_fd >= FD_SETSIZE)
1027 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001028#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 /* Construct the arguments to select */
1031 tv.tv_sec = (int)s->sock_timeout;
1032 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1033 FD_ZERO(&fds);
1034 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 /* See if the socket is ready */
1037 PySSL_BEGIN_ALLOW_THREADS
1038 if (writing)
1039 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1040 else
1041 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1042 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001043
Bill Janssen6e027db2007-11-15 22:23:56 +00001044#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001045normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001046#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1048 (when we are able to write or when there's something to read) */
1049 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001050}
1051
Antoine Pitrou152efa22010-05-16 18:19:27 +00001052static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001053{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 Py_buffer buf;
1055 int len;
1056 int sockstate;
1057 int err;
1058 int nonblocking;
1059 PySocketSockObject *sock
1060 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 if (((PyObject*)sock) == Py_None) {
1063 _setSSLError("Underlying socket connection gone",
1064 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1065 return NULL;
1066 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001067 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001069 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1070 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001072 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073
1074 /* just in case the blocking state of the socket has been changed */
1075 nonblocking = (sock->sock_timeout >= 0.0);
1076 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1077 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1078
1079 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1080 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001081 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 "The write operation timed out");
1083 goto error;
1084 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1085 PyErr_SetString(PySSLErrorObject,
1086 "Underlying socket has been closed.");
1087 goto error;
1088 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1089 PyErr_SetString(PySSLErrorObject,
1090 "Underlying socket too large for select().");
1091 goto error;
1092 }
1093 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 PySSL_BEGIN_ALLOW_THREADS
1095 len = SSL_write(self->ssl, buf.buf, buf.len);
1096 err = SSL_get_error(self->ssl, len);
1097 PySSL_END_ALLOW_THREADS
1098 if (PyErr_CheckSignals()) {
1099 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001100 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001102 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001104 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 } else {
1106 sockstate = SOCKET_OPERATION_OK;
1107 }
1108 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001109 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 "The write operation timed out");
1111 goto error;
1112 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1113 PyErr_SetString(PySSLErrorObject,
1114 "Underlying socket has been closed.");
1115 goto error;
1116 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1117 break;
1118 }
1119 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001120
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001121 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 PyBuffer_Release(&buf);
1123 if (len > 0)
1124 return PyLong_FromLong(len);
1125 else
1126 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001127
1128error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001129 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 PyBuffer_Release(&buf);
1131 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001132}
1133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001135"write(s) -> len\n\
1136\n\
1137Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001139
Antoine Pitrou152efa22010-05-16 18:19:27 +00001140static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001141{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 PySSL_BEGIN_ALLOW_THREADS
1145 count = SSL_pending(self->ssl);
1146 PySSL_END_ALLOW_THREADS
1147 if (count < 0)
1148 return PySSL_SetError(self, count, __FILE__, __LINE__);
1149 else
1150 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001151}
1152
1153PyDoc_STRVAR(PySSL_SSLpending_doc,
1154"pending() -> count\n\
1155\n\
1156Returns the number of already decrypted bytes available for read,\n\
1157pending on the connection.\n");
1158
Antoine Pitrou152efa22010-05-16 18:19:27 +00001159static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001160{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 PyObject *dest = NULL;
1162 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001164 int len, count;
1165 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 int sockstate;
1167 int err;
1168 int nonblocking;
1169 PySocketSockObject *sock
1170 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 if (((PyObject*)sock) == Py_None) {
1173 _setSSLError("Underlying socket connection gone",
1174 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1175 return NULL;
1176 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001177 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001179 buf.obj = NULL;
1180 buf.buf = NULL;
1181 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001182 goto error;
1183
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001184 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1185 dest = PyBytes_FromStringAndSize(NULL, len);
1186 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001187 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001188 mem = PyBytes_AS_STRING(dest);
1189 }
1190 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001192 mem = buf.buf;
1193 if (len <= 0 || len > buf.len) {
1194 len = (int) buf.len;
1195 if (buf.len != len) {
1196 PyErr_SetString(PyExc_OverflowError,
1197 "maximum length can't fit in a C 'int'");
1198 goto error;
1199 }
1200 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 }
1202
1203 /* just in case the blocking state of the socket has been changed */
1204 nonblocking = (sock->sock_timeout >= 0.0);
1205 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1206 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1207
1208 /* first check if there are bytes ready to be read */
1209 PySSL_BEGIN_ALLOW_THREADS
1210 count = SSL_pending(self->ssl);
1211 PySSL_END_ALLOW_THREADS
1212
1213 if (!count) {
1214 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1215 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001216 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 "The read operation timed out");
1218 goto error;
1219 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1220 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001221 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 goto error;
1223 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1224 count = 0;
1225 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001226 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 }
1228 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 PySSL_BEGIN_ALLOW_THREADS
1230 count = SSL_read(self->ssl, mem, len);
1231 err = SSL_get_error(self->ssl, count);
1232 PySSL_END_ALLOW_THREADS
1233 if (PyErr_CheckSignals())
1234 goto error;
1235 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001236 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001238 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1240 (SSL_get_shutdown(self->ssl) ==
1241 SSL_RECEIVED_SHUTDOWN))
1242 {
1243 count = 0;
1244 goto done;
1245 } else {
1246 sockstate = SOCKET_OPERATION_OK;
1247 }
1248 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001249 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 "The read operation timed out");
1251 goto error;
1252 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1253 break;
1254 }
1255 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1256 if (count <= 0) {
1257 PySSL_SetError(self, count, __FILE__, __LINE__);
1258 goto error;
1259 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001260
1261done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001262 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001264 _PyBytes_Resize(&dest, count);
1265 return dest;
1266 }
1267 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 PyBuffer_Release(&buf);
1269 return PyLong_FromLong(count);
1270 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001271
1272error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001273 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001274 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001275 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001276 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001279}
1280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001281PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001282"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001284Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001285
Antoine Pitrou152efa22010-05-16 18:19:27 +00001286static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001287{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 int err, ssl_err, sockstate, nonblocking;
1289 int zeros = 0;
1290 PySocketSockObject *sock
1291 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 /* Guard against closed socket */
1294 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1295 _setSSLError("Underlying socket connection gone",
1296 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1297 return NULL;
1298 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001299 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300
1301 /* Just in case the blocking state of the socket has been changed */
1302 nonblocking = (sock->sock_timeout >= 0.0);
1303 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1304 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1305
1306 while (1) {
1307 PySSL_BEGIN_ALLOW_THREADS
1308 /* Disable read-ahead so that unwrap can work correctly.
1309 * Otherwise OpenSSL might read in too much data,
1310 * eating clear text data that happens to be
1311 * transmitted after the SSL shutdown.
1312 * Should be safe to call repeatedly everytime this
1313 * function is used and the shutdown_seen_zero != 0
1314 * condition is met.
1315 */
1316 if (self->shutdown_seen_zero)
1317 SSL_set_read_ahead(self->ssl, 0);
1318 err = SSL_shutdown(self->ssl);
1319 PySSL_END_ALLOW_THREADS
1320 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1321 if (err > 0)
1322 break;
1323 if (err == 0) {
1324 /* Don't loop endlessly; instead preserve legacy
1325 behaviour of trying SSL_shutdown() only twice.
1326 This looks necessary for OpenSSL < 0.9.8m */
1327 if (++zeros > 1)
1328 break;
1329 /* Shutdown was sent, now try receiving */
1330 self->shutdown_seen_zero = 1;
1331 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001332 }
1333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 /* Possibly retry shutdown until timeout or failure */
1335 ssl_err = SSL_get_error(self->ssl, err);
1336 if (ssl_err == SSL_ERROR_WANT_READ)
1337 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1338 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1339 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1340 else
1341 break;
1342 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1343 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001344 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 "The read operation timed out");
1346 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001347 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001349 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 }
1351 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1352 PyErr_SetString(PySSLErrorObject,
1353 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001354 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 }
1356 else if (sockstate != SOCKET_OPERATION_OK)
1357 /* Retain the SSL error code */
1358 break;
1359 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001360
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001361 if (err < 0) {
1362 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001365 else
1366 /* It's already INCREF'ed */
1367 return (PyObject *) sock;
1368
1369error:
1370 Py_DECREF(sock);
1371 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001372}
1373
1374PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1375"shutdown(s) -> socket\n\
1376\n\
1377Does the SSL shutdown handshake with the remote end, and returns\n\
1378the underlying socket object.");
1379
1380
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001381static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1383 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1384 PySSL_SSLwrite_doc},
1385 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1386 PySSL_SSLread_doc},
1387 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1388 PySSL_SSLpending_doc},
1389 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1390 PySSL_peercert_doc},
1391 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1392 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1393 PySSL_SSLshutdown_doc},
1394 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395};
1396
Antoine Pitrou152efa22010-05-16 18:19:27 +00001397static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001399 "_ssl._SSLSocket", /*tp_name*/
1400 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 0, /*tp_itemsize*/
1402 /* methods */
1403 (destructor)PySSL_dealloc, /*tp_dealloc*/
1404 0, /*tp_print*/
1405 0, /*tp_getattr*/
1406 0, /*tp_setattr*/
1407 0, /*tp_reserved*/
1408 0, /*tp_repr*/
1409 0, /*tp_as_number*/
1410 0, /*tp_as_sequence*/
1411 0, /*tp_as_mapping*/
1412 0, /*tp_hash*/
1413 0, /*tp_call*/
1414 0, /*tp_str*/
1415 0, /*tp_getattro*/
1416 0, /*tp_setattro*/
1417 0, /*tp_as_buffer*/
1418 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1419 0, /*tp_doc*/
1420 0, /*tp_traverse*/
1421 0, /*tp_clear*/
1422 0, /*tp_richcompare*/
1423 0, /*tp_weaklistoffset*/
1424 0, /*tp_iter*/
1425 0, /*tp_iternext*/
1426 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001427};
1428
Antoine Pitrou152efa22010-05-16 18:19:27 +00001429
1430/*
1431 * _SSLContext objects
1432 */
1433
1434static PyObject *
1435context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1436{
1437 char *kwlist[] = {"protocol", NULL};
1438 PySSLContext *self;
1439 int proto_version = PY_SSL_VERSION_SSL23;
1440 SSL_CTX *ctx = NULL;
1441
1442 if (!PyArg_ParseTupleAndKeywords(
1443 args, kwds, "i:_SSLContext", kwlist,
1444 &proto_version))
1445 return NULL;
1446
1447 PySSL_BEGIN_ALLOW_THREADS
1448 if (proto_version == PY_SSL_VERSION_TLS1)
1449 ctx = SSL_CTX_new(TLSv1_method());
1450 else if (proto_version == PY_SSL_VERSION_SSL3)
1451 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001452#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001453 else if (proto_version == PY_SSL_VERSION_SSL2)
1454 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001455#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001456 else if (proto_version == PY_SSL_VERSION_SSL23)
1457 ctx = SSL_CTX_new(SSLv23_method());
1458 else
1459 proto_version = -1;
1460 PySSL_END_ALLOW_THREADS
1461
1462 if (proto_version == -1) {
1463 PyErr_SetString(PyExc_ValueError,
1464 "invalid protocol version");
1465 return NULL;
1466 }
1467 if (ctx == NULL) {
1468 PyErr_SetString(PySSLErrorObject,
1469 "failed to allocate SSL context");
1470 return NULL;
1471 }
1472
1473 assert(type != NULL && type->tp_alloc != NULL);
1474 self = (PySSLContext *) type->tp_alloc(type, 0);
1475 if (self == NULL) {
1476 SSL_CTX_free(ctx);
1477 return NULL;
1478 }
1479 self->ctx = ctx;
1480 /* Defaults */
1481 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1482 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1483
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001484#define SID_CTX "Python"
1485 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1486 sizeof(SID_CTX));
1487#undef SID_CTX
1488
Antoine Pitrou152efa22010-05-16 18:19:27 +00001489 return (PyObject *)self;
1490}
1491
1492static void
1493context_dealloc(PySSLContext *self)
1494{
1495 SSL_CTX_free(self->ctx);
1496 Py_TYPE(self)->tp_free(self);
1497}
1498
1499static PyObject *
1500set_ciphers(PySSLContext *self, PyObject *args)
1501{
1502 int ret;
1503 const char *cipherlist;
1504
1505 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1506 return NULL;
1507 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1508 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001509 /* Clearing the error queue is necessary on some OpenSSL versions,
1510 otherwise the error will be reported again when another SSL call
1511 is done. */
1512 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001513 PyErr_SetString(PySSLErrorObject,
1514 "No cipher can be selected.");
1515 return NULL;
1516 }
1517 Py_RETURN_NONE;
1518}
1519
1520static PyObject *
1521get_verify_mode(PySSLContext *self, void *c)
1522{
1523 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1524 case SSL_VERIFY_NONE:
1525 return PyLong_FromLong(PY_SSL_CERT_NONE);
1526 case SSL_VERIFY_PEER:
1527 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1528 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1529 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1530 }
1531 PyErr_SetString(PySSLErrorObject,
1532 "invalid return value from SSL_CTX_get_verify_mode");
1533 return NULL;
1534}
1535
1536static int
1537set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1538{
1539 int n, mode;
1540 if (!PyArg_Parse(arg, "i", &n))
1541 return -1;
1542 if (n == PY_SSL_CERT_NONE)
1543 mode = SSL_VERIFY_NONE;
1544 else if (n == PY_SSL_CERT_OPTIONAL)
1545 mode = SSL_VERIFY_PEER;
1546 else if (n == PY_SSL_CERT_REQUIRED)
1547 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1548 else {
1549 PyErr_SetString(PyExc_ValueError,
1550 "invalid value for verify_mode");
1551 return -1;
1552 }
1553 SSL_CTX_set_verify(self->ctx, mode, NULL);
1554 return 0;
1555}
1556
1557static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001558get_options(PySSLContext *self, void *c)
1559{
1560 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1561}
1562
1563static int
1564set_options(PySSLContext *self, PyObject *arg, void *c)
1565{
1566 long new_opts, opts, set, clear;
1567 if (!PyArg_Parse(arg, "l", &new_opts))
1568 return -1;
1569 opts = SSL_CTX_get_options(self->ctx);
1570 clear = opts & ~new_opts;
1571 set = ~opts & new_opts;
1572 if (clear) {
1573#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1574 SSL_CTX_clear_options(self->ctx, clear);
1575#else
1576 PyErr_SetString(PyExc_ValueError,
1577 "can't clear options before OpenSSL 0.9.8m");
1578 return -1;
1579#endif
1580 }
1581 if (set)
1582 SSL_CTX_set_options(self->ctx, set);
1583 return 0;
1584}
1585
1586static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001587load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1588{
1589 char *kwlist[] = {"certfile", "keyfile", NULL};
1590 PyObject *certfile, *keyfile = NULL;
1591 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1592 int r;
1593
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001594 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001595 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001596 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1597 "O|O:load_cert_chain", kwlist,
1598 &certfile, &keyfile))
1599 return NULL;
1600 if (keyfile == Py_None)
1601 keyfile = NULL;
1602 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1603 PyErr_SetString(PyExc_TypeError,
1604 "certfile should be a valid filesystem path");
1605 return NULL;
1606 }
1607 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1608 PyErr_SetString(PyExc_TypeError,
1609 "keyfile should be a valid filesystem path");
1610 goto error;
1611 }
1612 PySSL_BEGIN_ALLOW_THREADS
1613 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1614 PyBytes_AS_STRING(certfile_bytes));
1615 PySSL_END_ALLOW_THREADS
1616 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001617 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001618 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001619 PyErr_SetFromErrno(PyExc_IOError);
1620 }
1621 else {
1622 _setSSLError(NULL, 0, __FILE__, __LINE__);
1623 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001624 goto error;
1625 }
1626 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001627 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001628 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1629 SSL_FILETYPE_PEM);
1630 PySSL_END_ALLOW_THREADS
1631 Py_XDECREF(keyfile_bytes);
1632 Py_XDECREF(certfile_bytes);
1633 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001634 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001635 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001636 PyErr_SetFromErrno(PyExc_IOError);
1637 }
1638 else {
1639 _setSSLError(NULL, 0, __FILE__, __LINE__);
1640 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001641 return NULL;
1642 }
1643 PySSL_BEGIN_ALLOW_THREADS
1644 r = SSL_CTX_check_private_key(self->ctx);
1645 PySSL_END_ALLOW_THREADS
1646 if (r != 1) {
1647 _setSSLError(NULL, 0, __FILE__, __LINE__);
1648 return NULL;
1649 }
1650 Py_RETURN_NONE;
1651
1652error:
1653 Py_XDECREF(keyfile_bytes);
1654 Py_XDECREF(certfile_bytes);
1655 return NULL;
1656}
1657
1658static PyObject *
1659load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1660{
1661 char *kwlist[] = {"cafile", "capath", NULL};
1662 PyObject *cafile = NULL, *capath = NULL;
1663 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1664 const char *cafile_buf = NULL, *capath_buf = NULL;
1665 int r;
1666
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001667 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001668 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1669 "|OO:load_verify_locations", kwlist,
1670 &cafile, &capath))
1671 return NULL;
1672 if (cafile == Py_None)
1673 cafile = NULL;
1674 if (capath == Py_None)
1675 capath = NULL;
1676 if (cafile == NULL && capath == NULL) {
1677 PyErr_SetString(PyExc_TypeError,
1678 "cafile and capath cannot be both omitted");
1679 return NULL;
1680 }
1681 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1682 PyErr_SetString(PyExc_TypeError,
1683 "cafile should be a valid filesystem path");
1684 return NULL;
1685 }
1686 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001687 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001688 PyErr_SetString(PyExc_TypeError,
1689 "capath should be a valid filesystem path");
1690 return NULL;
1691 }
1692 if (cafile)
1693 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1694 if (capath)
1695 capath_buf = PyBytes_AS_STRING(capath_bytes);
1696 PySSL_BEGIN_ALLOW_THREADS
1697 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1698 PySSL_END_ALLOW_THREADS
1699 Py_XDECREF(cafile_bytes);
1700 Py_XDECREF(capath_bytes);
1701 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001702 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001703 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001704 PyErr_SetFromErrno(PyExc_IOError);
1705 }
1706 else {
1707 _setSSLError(NULL, 0, __FILE__, __LINE__);
1708 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001709 return NULL;
1710 }
1711 Py_RETURN_NONE;
1712}
1713
1714static PyObject *
1715context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1716{
Antoine Pitroud5323212010-10-22 18:19:07 +00001717 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001718 PySocketSockObject *sock;
1719 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001720 char *hostname = NULL;
1721 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001722
Antoine Pitroud5323212010-10-22 18:19:07 +00001723 /* server_hostname is either None (or absent), or to be encoded
1724 using the idna encoding. */
1725 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001726 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001727 &sock, &server_side,
1728 Py_TYPE(Py_None), &hostname_obj)) {
1729 PyErr_Clear();
1730 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1731 PySocketModule.Sock_Type,
1732 &sock, &server_side,
1733 "idna", &hostname))
1734 return NULL;
1735#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1736 PyMem_Free(hostname);
1737 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1738 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001739 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001740#endif
1741 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001742
Antoine Pitroud5323212010-10-22 18:19:07 +00001743 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1744 hostname);
1745 if (hostname != NULL)
1746 PyMem_Free(hostname);
1747 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001748}
1749
Antoine Pitroub0182c82010-10-12 20:09:02 +00001750static PyObject *
1751session_stats(PySSLContext *self, PyObject *unused)
1752{
1753 int r;
1754 PyObject *value, *stats = PyDict_New();
1755 if (!stats)
1756 return NULL;
1757
1758#define ADD_STATS(SSL_NAME, KEY_NAME) \
1759 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1760 if (value == NULL) \
1761 goto error; \
1762 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1763 Py_DECREF(value); \
1764 if (r < 0) \
1765 goto error;
1766
1767 ADD_STATS(number, "number");
1768 ADD_STATS(connect, "connect");
1769 ADD_STATS(connect_good, "connect_good");
1770 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1771 ADD_STATS(accept, "accept");
1772 ADD_STATS(accept_good, "accept_good");
1773 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1774 ADD_STATS(accept, "accept");
1775 ADD_STATS(hits, "hits");
1776 ADD_STATS(misses, "misses");
1777 ADD_STATS(timeouts, "timeouts");
1778 ADD_STATS(cache_full, "cache_full");
1779
1780#undef ADD_STATS
1781
1782 return stats;
1783
1784error:
1785 Py_DECREF(stats);
1786 return NULL;
1787}
1788
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001789static PyObject *
1790set_default_verify_paths(PySSLContext *self, PyObject *unused)
1791{
1792 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1793 _setSSLError(NULL, 0, __FILE__, __LINE__);
1794 return NULL;
1795 }
1796 Py_RETURN_NONE;
1797}
1798
Antoine Pitrou152efa22010-05-16 18:19:27 +00001799static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001800 {"options", (getter) get_options,
1801 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802 {"verify_mode", (getter) get_verify_mode,
1803 (setter) set_verify_mode, NULL},
1804 {NULL}, /* sentinel */
1805};
1806
1807static struct PyMethodDef context_methods[] = {
1808 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1809 METH_VARARGS | METH_KEYWORDS, NULL},
1810 {"set_ciphers", (PyCFunction) set_ciphers,
1811 METH_VARARGS, NULL},
1812 {"load_cert_chain", (PyCFunction) load_cert_chain,
1813 METH_VARARGS | METH_KEYWORDS, NULL},
1814 {"load_verify_locations", (PyCFunction) load_verify_locations,
1815 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001816 {"session_stats", (PyCFunction) session_stats,
1817 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001818 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1819 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001820 {NULL, NULL} /* sentinel */
1821};
1822
1823static PyTypeObject PySSLContext_Type = {
1824 PyVarObject_HEAD_INIT(NULL, 0)
1825 "_ssl._SSLContext", /*tp_name*/
1826 sizeof(PySSLContext), /*tp_basicsize*/
1827 0, /*tp_itemsize*/
1828 (destructor)context_dealloc, /*tp_dealloc*/
1829 0, /*tp_print*/
1830 0, /*tp_getattr*/
1831 0, /*tp_setattr*/
1832 0, /*tp_reserved*/
1833 0, /*tp_repr*/
1834 0, /*tp_as_number*/
1835 0, /*tp_as_sequence*/
1836 0, /*tp_as_mapping*/
1837 0, /*tp_hash*/
1838 0, /*tp_call*/
1839 0, /*tp_str*/
1840 0, /*tp_getattro*/
1841 0, /*tp_setattro*/
1842 0, /*tp_as_buffer*/
1843 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1844 0, /*tp_doc*/
1845 0, /*tp_traverse*/
1846 0, /*tp_clear*/
1847 0, /*tp_richcompare*/
1848 0, /*tp_weaklistoffset*/
1849 0, /*tp_iter*/
1850 0, /*tp_iternext*/
1851 context_methods, /*tp_methods*/
1852 0, /*tp_members*/
1853 context_getsetlist, /*tp_getset*/
1854 0, /*tp_base*/
1855 0, /*tp_dict*/
1856 0, /*tp_descr_get*/
1857 0, /*tp_descr_set*/
1858 0, /*tp_dictoffset*/
1859 0, /*tp_init*/
1860 0, /*tp_alloc*/
1861 context_new, /*tp_new*/
1862};
1863
1864
1865
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001866#ifdef HAVE_OPENSSL_RAND
1867
1868/* helper routines for seeding the SSL PRNG */
1869static PyObject *
1870PySSL_RAND_add(PyObject *self, PyObject *args)
1871{
1872 char *buf;
1873 int len;
1874 double entropy;
1875
1876 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001877 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001878 RAND_add(buf, len, entropy);
1879 Py_INCREF(Py_None);
1880 return Py_None;
1881}
1882
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001883PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001884"RAND_add(string, entropy)\n\
1885\n\
1886Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001888
1889static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02001890PySSL_RAND(int len, int pseudo)
1891{
1892 int ok;
1893 PyObject *bytes;
1894 unsigned long err;
1895 const char *errstr;
1896 PyObject *v;
1897
1898 bytes = PyBytes_FromStringAndSize(NULL, len);
1899 if (bytes == NULL)
1900 return NULL;
1901 if (pseudo) {
1902 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
1903 if (ok == 0 || ok == 1)
1904 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
1905 }
1906 else {
1907 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
1908 if (ok == 1)
1909 return bytes;
1910 }
1911 Py_DECREF(bytes);
1912
1913 err = ERR_get_error();
1914 errstr = ERR_reason_error_string(err);
1915 v = Py_BuildValue("(ks)", err, errstr);
1916 if (v != NULL) {
1917 PyErr_SetObject(PySSLErrorObject, v);
1918 Py_DECREF(v);
1919 }
1920 return NULL;
1921}
1922
1923static PyObject *
1924PySSL_RAND_bytes(PyObject *self, PyObject *args)
1925{
1926 int len;
1927 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
1928 return NULL;
1929 return PySSL_RAND(len, 0);
1930}
1931
1932PyDoc_STRVAR(PySSL_RAND_bytes_doc,
1933"RAND_bytes(n) -> bytes\n\
1934\n\
1935Generate n cryptographically strong pseudo-random bytes.");
1936
1937static PyObject *
1938PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
1939{
1940 int len;
1941 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
1942 return NULL;
1943 return PySSL_RAND(len, 1);
1944}
1945
1946PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
1947"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
1948\n\
1949Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
1950generated are cryptographically strong.");
1951
1952static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001953PySSL_RAND_status(PyObject *self)
1954{
Christian Heimes217cfd12007-12-02 14:31:20 +00001955 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001956}
1957
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001958PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001959"RAND_status() -> 0 or 1\n\
1960\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001961Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1962It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1963using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001964
1965static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001966PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001967{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001968 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001969 int bytes;
1970
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001971 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1972 PyUnicode_FSConverter, &path))
1973 return NULL;
1974
1975 bytes = RAND_egd(PyBytes_AsString(path));
1976 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001977 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001978 PyErr_SetString(PySSLErrorObject,
1979 "EGD connection failed or EGD did not return "
1980 "enough data to seed the PRNG");
1981 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001982 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001983 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001984}
1985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001986PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001987"RAND_egd(path) -> bytes\n\
1988\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001989Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1990Returns number of bytes read. Raises SSLError if connection to EGD\n\
1991fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001992
1993#endif
1994
Bill Janssen40a0f662008-08-12 16:56:25 +00001995
1996
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001997/* List of functions exported by this module. */
1998
1999static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 {"_test_decode_cert", PySSL_test_decode_certificate,
2001 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002002#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2004 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002005 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2006 PySSL_RAND_bytes_doc},
2007 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2008 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002009 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 PySSL_RAND_egd_doc},
2011 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2012 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002013#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002015};
2016
2017
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002018#ifdef WITH_THREAD
2019
2020/* an implementation of OpenSSL threading operations in terms
2021 of the Python C thread library */
2022
2023static PyThread_type_lock *_ssl_locks = NULL;
2024
2025static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002027}
2028
Bill Janssen6e027db2007-11-15 22:23:56 +00002029static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002030 (int mode, int n, const char *file, int line) {
2031 /* this function is needed to perform locking on shared data
2032 structures. (Note that OpenSSL uses a number of global data
2033 structures that will be implicitly shared whenever multiple
2034 threads use OpenSSL.) Multi-threaded applications will
2035 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002037 locking_function() must be able to handle up to
2038 CRYPTO_num_locks() different mutex locks. It sets the n-th
2039 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002040
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 file and line are the file number of the function setting the
2042 lock. They can be useful for debugging.
2043 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002045 if ((_ssl_locks == NULL) ||
2046 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2047 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 if (mode & CRYPTO_LOCK) {
2050 PyThread_acquire_lock(_ssl_locks[n], 1);
2051 } else {
2052 PyThread_release_lock(_ssl_locks[n]);
2053 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002054}
2055
2056static int _setup_ssl_threads(void) {
2057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002058 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002060 if (_ssl_locks == NULL) {
2061 _ssl_locks_count = CRYPTO_num_locks();
2062 _ssl_locks = (PyThread_type_lock *)
2063 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2064 if (_ssl_locks == NULL)
2065 return 0;
2066 memset(_ssl_locks, 0,
2067 sizeof(PyThread_type_lock) * _ssl_locks_count);
2068 for (i = 0; i < _ssl_locks_count; i++) {
2069 _ssl_locks[i] = PyThread_allocate_lock();
2070 if (_ssl_locks[i] == NULL) {
2071 unsigned int j;
2072 for (j = 0; j < i; j++) {
2073 PyThread_free_lock(_ssl_locks[j]);
2074 }
2075 free(_ssl_locks);
2076 return 0;
2077 }
2078 }
2079 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2080 CRYPTO_set_id_callback(_ssl_thread_id_function);
2081 }
2082 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002083}
2084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002085#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002088"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002089for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002090
Martin v. Löwis1a214512008-06-11 05:26:20 +00002091
2092static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 PyModuleDef_HEAD_INIT,
2094 "_ssl",
2095 module_doc,
2096 -1,
2097 PySSL_methods,
2098 NULL,
2099 NULL,
2100 NULL,
2101 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002102};
2103
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002104PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002105PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002106{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002107 PyObject *m, *d, *r;
2108 unsigned long libver;
2109 unsigned int major, minor, fix, patch, status;
2110 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002111
Antoine Pitrou152efa22010-05-16 18:19:27 +00002112 if (PyType_Ready(&PySSLContext_Type) < 0)
2113 return NULL;
2114 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002117 m = PyModule_Create(&_sslmodule);
2118 if (m == NULL)
2119 return NULL;
2120 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122 /* Load _socket module and its C API */
2123 socket_api = PySocketModule_ImportModuleAndAPI();
2124 if (!socket_api)
2125 return NULL;
2126 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002127
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 /* Init OpenSSL */
2129 SSL_load_error_strings();
2130 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002131#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002132 /* note that this will start threading if not already started */
2133 if (!_setup_ssl_threads()) {
2134 return NULL;
2135 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002136#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 /* Add symbols to module dict */
2140 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2141 PySocketModule.error,
2142 NULL);
2143 if (PySSLErrorObject == NULL)
2144 return NULL;
2145 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2146 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002147 if (PyDict_SetItemString(d, "_SSLContext",
2148 (PyObject *)&PySSLContext_Type) != 0)
2149 return NULL;
2150 if (PyDict_SetItemString(d, "_SSLSocket",
2151 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002152 return NULL;
2153 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2154 PY_SSL_ERROR_ZERO_RETURN);
2155 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2156 PY_SSL_ERROR_WANT_READ);
2157 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2158 PY_SSL_ERROR_WANT_WRITE);
2159 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2160 PY_SSL_ERROR_WANT_X509_LOOKUP);
2161 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2162 PY_SSL_ERROR_SYSCALL);
2163 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2164 PY_SSL_ERROR_SSL);
2165 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2166 PY_SSL_ERROR_WANT_CONNECT);
2167 /* non ssl.h errorcodes */
2168 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2169 PY_SSL_ERROR_EOF);
2170 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2171 PY_SSL_ERROR_INVALID_ERROR_CODE);
2172 /* cert requirements */
2173 PyModule_AddIntConstant(m, "CERT_NONE",
2174 PY_SSL_CERT_NONE);
2175 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2176 PY_SSL_CERT_OPTIONAL);
2177 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2178 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002181#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2183 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002184#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2186 PY_SSL_VERSION_SSL3);
2187 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2188 PY_SSL_VERSION_SSL23);
2189 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2190 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002191
Antoine Pitroub5218772010-05-21 09:56:06 +00002192 /* protocol options */
2193 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2194 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2195 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2196 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2197
Antoine Pitroud5323212010-10-22 18:19:07 +00002198#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2199 r = Py_True;
2200#else
2201 r = Py_False;
2202#endif
2203 Py_INCREF(r);
2204 PyModule_AddObject(m, "HAS_SNI", r);
2205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 /* OpenSSL version */
2207 /* SSLeay() gives us the version of the library linked against,
2208 which could be different from the headers version.
2209 */
2210 libver = SSLeay();
2211 r = PyLong_FromUnsignedLong(libver);
2212 if (r == NULL)
2213 return NULL;
2214 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2215 return NULL;
2216 status = libver & 0xF;
2217 libver >>= 4;
2218 patch = libver & 0xFF;
2219 libver >>= 8;
2220 fix = libver & 0xFF;
2221 libver >>= 8;
2222 minor = libver & 0xFF;
2223 libver >>= 8;
2224 major = libver & 0xFF;
2225 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2226 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2227 return NULL;
2228 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2229 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2230 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002233}