blob: 5419059e299876536d93193a7a7afae1542ece1a [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 Stinneree18b6f2011-05-10 00:38:00 +020066#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000067 PY_SSL_VERSION_SSL2,
Victor Stinneree18b6f2011-05-10 00:38:00 +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. */
359 sockstate = 0;
360 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000361 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000362 ret = SSL_do_handshake(self->ssl);
363 err = SSL_get_error(self->ssl, ret);
364 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000365 if (PyErr_CheckSignals())
366 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000367 if (err == SSL_ERROR_WANT_READ) {
368 sockstate = check_socket_and_wait_for_timeout(sock, 0);
369 } else if (err == SSL_ERROR_WANT_WRITE) {
370 sockstate = check_socket_and_wait_for_timeout(sock, 1);
371 } else {
372 sockstate = SOCKET_OPERATION_OK;
373 }
374 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000375 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000376 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000377 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000378 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
379 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000380 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000381 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
383 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000384 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000385 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
387 break;
388 }
389 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000390 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 if (ret < 1)
392 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 if (self->peer_cert)
395 X509_free (self->peer_cert);
396 PySSL_BEGIN_ALLOW_THREADS
397 self->peer_cert = SSL_get_peer_certificate(self->ssl);
398 PySSL_END_ALLOW_THREADS
399
400 Py_INCREF(Py_None);
401 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000402
403error:
404 Py_DECREF(sock);
405 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406}
407
Thomas Woutersed03b412007-08-28 21:37:11 +0000408static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 char namebuf[X509_NAME_MAXLEN];
412 int buflen;
413 PyObject *name_obj;
414 PyObject *value_obj;
415 PyObject *attr;
416 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000417
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
419 if (buflen < 0) {
420 _setSSLError(NULL, 0, __FILE__, __LINE__);
421 goto fail;
422 }
423 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
424 if (name_obj == NULL)
425 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
428 if (buflen < 0) {
429 _setSSLError(NULL, 0, __FILE__, __LINE__);
430 Py_DECREF(name_obj);
431 goto fail;
432 }
433 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000434 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 OPENSSL_free(valuebuf);
436 if (value_obj == NULL) {
437 Py_DECREF(name_obj);
438 goto fail;
439 }
440 attr = PyTuple_New(2);
441 if (attr == NULL) {
442 Py_DECREF(name_obj);
443 Py_DECREF(value_obj);
444 goto fail;
445 }
446 PyTuple_SET_ITEM(attr, 0, name_obj);
447 PyTuple_SET_ITEM(attr, 1, value_obj);
448 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000449
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000452}
453
454static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000456{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
458 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
459 PyObject *rdnt;
460 PyObject *attr = NULL; /* tuple to hold an attribute */
461 int entry_count = X509_NAME_entry_count(xname);
462 X509_NAME_ENTRY *entry;
463 ASN1_OBJECT *name;
464 ASN1_STRING *value;
465 int index_counter;
466 int rdn_level = -1;
467 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 dn = PyList_New(0);
470 if (dn == NULL)
471 return NULL;
472 /* now create another tuple to hold the top-level RDN */
473 rdn = PyList_New(0);
474 if (rdn == NULL)
475 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000477 for (index_counter = 0;
478 index_counter < entry_count;
479 index_counter++)
480 {
481 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000482
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 /* check to see if we've gotten to a new RDN */
484 if (rdn_level >= 0) {
485 if (rdn_level != entry->set) {
486 /* yes, new RDN */
487 /* add old RDN to DN */
488 rdnt = PyList_AsTuple(rdn);
489 Py_DECREF(rdn);
490 if (rdnt == NULL)
491 goto fail0;
492 retcode = PyList_Append(dn, rdnt);
493 Py_DECREF(rdnt);
494 if (retcode < 0)
495 goto fail0;
496 /* create new RDN */
497 rdn = PyList_New(0);
498 if (rdn == NULL)
499 goto fail0;
500 }
501 }
502 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 /* now add this attribute to the current RDN */
505 name = X509_NAME_ENTRY_get_object(entry);
506 value = X509_NAME_ENTRY_get_data(entry);
507 attr = _create_tuple_for_attribute(name, value);
508 /*
509 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
510 entry->set,
511 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
512 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
513 */
514 if (attr == NULL)
515 goto fail1;
516 retcode = PyList_Append(rdn, attr);
517 Py_DECREF(attr);
518 if (retcode < 0)
519 goto fail1;
520 }
521 /* now, there's typically a dangling RDN */
522 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
523 rdnt = PyList_AsTuple(rdn);
524 Py_DECREF(rdn);
525 if (rdnt == NULL)
526 goto fail0;
527 retcode = PyList_Append(dn, rdnt);
528 Py_DECREF(rdnt);
529 if (retcode < 0)
530 goto fail0;
531 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 /* convert list to tuple */
534 rdnt = PyList_AsTuple(dn);
535 Py_DECREF(dn);
536 if (rdnt == NULL)
537 return NULL;
538 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
540 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
543 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 Py_XDECREF(dn);
545 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546}
547
548static PyObject *
549_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 /* this code follows the procedure outlined in
552 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
553 function to extract the STACK_OF(GENERAL_NAME),
554 then iterates through the stack to add the
555 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000557 int i, j;
558 PyObject *peer_alt_names = Py_None;
559 PyObject *v, *t;
560 X509_EXTENSION *ext = NULL;
561 GENERAL_NAMES *names = NULL;
562 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000563 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 BIO *biobuf = NULL;
565 char buf[2048];
566 char *vptr;
567 int len;
568 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000569#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000571#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000573#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 if (certificate == NULL)
576 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 /* get a memory buffer */
579 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200581 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 while ((i = X509_get_ext_by_NID(
583 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 if (peer_alt_names == Py_None) {
586 peer_alt_names = PyList_New(0);
587 if (peer_alt_names == NULL)
588 goto fail;
589 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 /* now decode the altName */
592 ext = X509_get_ext(certificate, i);
593 if(!(method = X509V3_EXT_get(ext))) {
594 PyErr_SetString
595 (PySSLErrorObject,
596 ERRSTR("No method for internalizing subjectAltName!"));
597 goto fail;
598 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 p = ext->value->data;
601 if (method->it)
602 names = (GENERAL_NAMES*)
603 (ASN1_item_d2i(NULL,
604 &p,
605 ext->value->length,
606 ASN1_ITEM_ptr(method->it)));
607 else
608 names = (GENERAL_NAMES*)
609 (method->d2i(NULL,
610 &p,
611 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 name = sk_GENERAL_NAME_value(names, j);
618 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 /* we special-case DirName as a tuple of
621 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 t = PyTuple_New(2);
624 if (t == NULL) {
625 goto fail;
626 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 v = PyUnicode_FromString("DirName");
629 if (v == NULL) {
630 Py_DECREF(t);
631 goto fail;
632 }
633 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 v = _create_tuple_for_X509_NAME (name->d.dirn);
636 if (v == NULL) {
637 Py_DECREF(t);
638 goto fail;
639 }
640 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000641
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 (void) BIO_reset(biobuf);
647 GENERAL_NAME_print(biobuf, name);
648 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
649 if (len < 0) {
650 _setSSLError(NULL, 0, __FILE__, __LINE__);
651 goto fail;
652 }
653 vptr = strchr(buf, ':');
654 if (vptr == NULL)
655 goto fail;
656 t = PyTuple_New(2);
657 if (t == NULL)
658 goto fail;
659 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
660 if (v == NULL) {
661 Py_DECREF(t);
662 goto fail;
663 }
664 PyTuple_SET_ITEM(t, 0, v);
665 v = PyUnicode_FromStringAndSize((vptr + 1),
666 (len - (vptr - buf + 1)));
667 if (v == NULL) {
668 Py_DECREF(t);
669 goto fail;
670 }
671 PyTuple_SET_ITEM(t, 1, v);
672 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 if (PyList_Append(peer_alt_names, t) < 0) {
677 Py_DECREF(t);
678 goto fail;
679 }
680 Py_DECREF(t);
681 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100682 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 }
684 BIO_free(biobuf);
685 if (peer_alt_names != Py_None) {
686 v = PyList_AsTuple(peer_alt_names);
687 Py_DECREF(peer_alt_names);
688 return v;
689 } else {
690 return peer_alt_names;
691 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000692
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
694 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000695 if (biobuf != NULL)
696 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 if (peer_alt_names != Py_None) {
699 Py_XDECREF(peer_alt_names);
700 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703}
704
705static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000706_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000708 PyObject *retval = NULL;
709 BIO *biobuf = NULL;
710 PyObject *peer;
711 PyObject *peer_alt_names = NULL;
712 PyObject *issuer;
713 PyObject *version;
714 PyObject *sn_obj;
715 ASN1_INTEGER *serialNumber;
716 char buf[2048];
717 int len;
718 ASN1_TIME *notBefore, *notAfter;
719 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 retval = PyDict_New();
722 if (retval == NULL)
723 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 peer = _create_tuple_for_X509_NAME(
726 X509_get_subject_name(certificate));
727 if (peer == NULL)
728 goto fail0;
729 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
730 Py_DECREF(peer);
731 goto fail0;
732 }
733 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000734
Antoine Pitroufb046912010-11-09 20:21:19 +0000735 issuer = _create_tuple_for_X509_NAME(
736 X509_get_issuer_name(certificate));
737 if (issuer == NULL)
738 goto fail0;
739 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000741 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000743 Py_DECREF(issuer);
744
745 version = PyLong_FromLong(X509_get_version(certificate) + 1);
746 if (PyDict_SetItemString(retval, "version", version) < 0) {
747 Py_DECREF(version);
748 goto fail0;
749 }
750 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 /* get a memory buffer */
753 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000754
Antoine Pitroufb046912010-11-09 20:21:19 +0000755 (void) BIO_reset(biobuf);
756 serialNumber = X509_get_serialNumber(certificate);
757 /* should not exceed 20 octets, 160 bits, so buf is big enough */
758 i2a_ASN1_INTEGER(biobuf, serialNumber);
759 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
760 if (len < 0) {
761 _setSSLError(NULL, 0, __FILE__, __LINE__);
762 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000764 sn_obj = PyUnicode_FromStringAndSize(buf, len);
765 if (sn_obj == NULL)
766 goto fail1;
767 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
768 Py_DECREF(sn_obj);
769 goto fail1;
770 }
771 Py_DECREF(sn_obj);
772
773 (void) BIO_reset(biobuf);
774 notBefore = X509_get_notBefore(certificate);
775 ASN1_TIME_print(biobuf, notBefore);
776 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
777 if (len < 0) {
778 _setSSLError(NULL, 0, __FILE__, __LINE__);
779 goto fail1;
780 }
781 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
782 if (pnotBefore == NULL)
783 goto fail1;
784 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
785 Py_DECREF(pnotBefore);
786 goto fail1;
787 }
788 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 (void) BIO_reset(biobuf);
791 notAfter = X509_get_notAfter(certificate);
792 ASN1_TIME_print(biobuf, notAfter);
793 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
794 if (len < 0) {
795 _setSSLError(NULL, 0, __FILE__, __LINE__);
796 goto fail1;
797 }
798 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
799 if (pnotAfter == NULL)
800 goto fail1;
801 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
802 Py_DECREF(pnotAfter);
803 goto fail1;
804 }
805 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 peer_alt_names = _get_peer_alt_names(certificate);
810 if (peer_alt_names == NULL)
811 goto fail1;
812 else if (peer_alt_names != Py_None) {
813 if (PyDict_SetItemString(retval, "subjectAltName",
814 peer_alt_names) < 0) {
815 Py_DECREF(peer_alt_names);
816 goto fail1;
817 }
818 Py_DECREF(peer_alt_names);
819 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 BIO_free(biobuf);
822 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000823
824 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 if (biobuf != NULL)
826 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000827 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 Py_XDECREF(retval);
829 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000830}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000831
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
833static PyObject *
834PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000837 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 X509 *x=NULL;
839 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
Antoine Pitroufb046912010-11-09 20:21:19 +0000841 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
842 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 if ((cert=BIO_new(BIO_s_file())) == NULL) {
846 PyErr_SetString(PySSLErrorObject,
847 "Can't malloc memory to read file");
848 goto fail0;
849 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000850
Victor Stinner3800e1e2010-05-16 21:23:48 +0000851 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 PyErr_SetString(PySSLErrorObject,
853 "Can't open file");
854 goto fail0;
855 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
858 if (x == NULL) {
859 PyErr_SetString(PySSLErrorObject,
860 "Error decoding PEM-encoded file");
861 goto fail0;
862 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863
Antoine Pitroufb046912010-11-09 20:21:19 +0000864 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000865 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
867 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000868 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 if (cert != NULL) BIO_free(cert);
870 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871}
872
873
874static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000875PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 PyObject *retval = NULL;
878 int len;
879 int verification;
880 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
883 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 if (!self->peer_cert)
886 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 if (PyObject_IsTrue(binary_mode)) {
889 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 bytes_buf = NULL;
894 len = i2d_X509(self->peer_cert, &bytes_buf);
895 if (len < 0) {
896 PySSL_SetError(self, len, __FILE__, __LINE__);
897 return NULL;
898 }
899 /* this is actually an immutable bytes sequence */
900 retval = PyBytes_FromStringAndSize
901 ((const char *) bytes_buf, len);
902 OPENSSL_free(bytes_buf);
903 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000906 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 if ((verification & SSL_VERIFY_PEER) == 0)
908 return PyDict_New();
909 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000910 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912}
913
914PyDoc_STRVAR(PySSL_peercert_doc,
915"peer_certificate([der=False]) -> certificate\n\
916\n\
917Returns the certificate for the peer. If no certificate was provided,\n\
918returns None. If a certificate was provided, but not validated, returns\n\
919an empty dictionary. Otherwise returns a dict containing information\n\
920about the peer certificate.\n\
921\n\
922If the optional argument is True, returns a DER-encoded copy of the\n\
923peer certificate, or None if no certificate was provided. This will\n\
924return the certificate even if it wasn't validated.");
925
Antoine Pitrou152efa22010-05-16 18:19:27 +0000926static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000929 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 char *cipher_name;
931 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000934 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 current = SSL_get_current_cipher(self->ssl);
936 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000937 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 retval = PyTuple_New(3);
940 if (retval == NULL)
941 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 cipher_name = (char *) SSL_CIPHER_get_name(current);
944 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000945 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PyTuple_SET_ITEM(retval, 0, Py_None);
947 } else {
948 v = PyUnicode_FromString(cipher_name);
949 if (v == NULL)
950 goto fail0;
951 PyTuple_SET_ITEM(retval, 0, v);
952 }
953 cipher_protocol = SSL_CIPHER_get_version(current);
954 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000955 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 PyTuple_SET_ITEM(retval, 1, Py_None);
957 } else {
958 v = PyUnicode_FromString(cipher_protocol);
959 if (v == NULL)
960 goto fail0;
961 PyTuple_SET_ITEM(retval, 1, v);
962 }
963 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
964 if (v == NULL)
965 goto fail0;
966 PyTuple_SET_ITEM(retval, 2, v);
967 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000968
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 Py_DECREF(retval);
971 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972}
973
Antoine Pitrou152efa22010-05-16 18:19:27 +0000974static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000975{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 if (self->peer_cert) /* Possible not to have one? */
977 X509_free (self->peer_cert);
978 if (self->ssl)
979 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 Py_XDECREF(self->Socket);
981 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000982}
983
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000985 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000986 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000987 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000988
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000989static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000990check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000991{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 fd_set fds;
993 struct timeval tv;
994 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 /* Nothing to do unless we're in timeout mode (not non-blocking) */
997 if (s->sock_timeout < 0.0)
998 return SOCKET_IS_BLOCKING;
999 else if (s->sock_timeout == 0.0)
1000 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 /* Guard against closed socket */
1003 if (s->sock_fd < 0)
1004 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 /* Prefer poll, if available, since you can poll() any fd
1007 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 {
1010 struct pollfd pollfd;
1011 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 pollfd.fd = s->sock_fd;
1014 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* s->sock_timeout is in seconds, timeout in ms */
1017 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1018 PySSL_BEGIN_ALLOW_THREADS
1019 rc = poll(&pollfd, 1, timeout);
1020 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 goto normal_return;
1023 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024#endif
1025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001027 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 return SOCKET_TOO_LARGE_FOR_SELECT;
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 {
1094 err = 0;
1095 PySSL_BEGIN_ALLOW_THREADS
1096 len = SSL_write(self->ssl, buf.buf, buf.len);
1097 err = SSL_get_error(self->ssl, len);
1098 PySSL_END_ALLOW_THREADS
1099 if (PyErr_CheckSignals()) {
1100 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001101 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001103 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001105 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 } else {
1107 sockstate = SOCKET_OPERATION_OK;
1108 }
1109 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001110 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 "The write operation timed out");
1112 goto error;
1113 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1114 PyErr_SetString(PySSLErrorObject,
1115 "Underlying socket has been closed.");
1116 goto error;
1117 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1118 break;
1119 }
1120 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001121
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001122 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 PyBuffer_Release(&buf);
1124 if (len > 0)
1125 return PyLong_FromLong(len);
1126 else
1127 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001128
1129error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001130 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 PyBuffer_Release(&buf);
1132 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001133}
1134
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001135PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001136"write(s) -> len\n\
1137\n\
1138Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001139of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001140
Antoine Pitrou152efa22010-05-16 18:19:27 +00001141static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001142{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 PySSL_BEGIN_ALLOW_THREADS
1146 count = SSL_pending(self->ssl);
1147 PySSL_END_ALLOW_THREADS
1148 if (count < 0)
1149 return PySSL_SetError(self, count, __FILE__, __LINE__);
1150 else
1151 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001152}
1153
1154PyDoc_STRVAR(PySSL_SSLpending_doc,
1155"pending() -> count\n\
1156\n\
1157Returns the number of already decrypted bytes available for read,\n\
1158pending on the connection.\n");
1159
Antoine Pitrou152efa22010-05-16 18:19:27 +00001160static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001161{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 PyObject *dest = NULL;
1163 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001165 int len, count;
1166 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 int sockstate;
1168 int err;
1169 int nonblocking;
1170 PySocketSockObject *sock
1171 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 if (((PyObject*)sock) == Py_None) {
1174 _setSSLError("Underlying socket connection gone",
1175 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1176 return NULL;
1177 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001178 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001180 buf.obj = NULL;
1181 buf.buf = NULL;
1182 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001183 goto error;
1184
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001185 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1186 dest = PyBytes_FromStringAndSize(NULL, len);
1187 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001188 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001189 mem = PyBytes_AS_STRING(dest);
1190 }
1191 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001193 mem = buf.buf;
1194 if (len <= 0 || len > buf.len) {
1195 len = (int) buf.len;
1196 if (buf.len != len) {
1197 PyErr_SetString(PyExc_OverflowError,
1198 "maximum length can't fit in a C 'int'");
1199 goto error;
1200 }
1201 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 }
1203
1204 /* just in case the blocking state of the socket has been changed */
1205 nonblocking = (sock->sock_timeout >= 0.0);
1206 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1207 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1208
1209 /* first check if there are bytes ready to be read */
1210 PySSL_BEGIN_ALLOW_THREADS
1211 count = SSL_pending(self->ssl);
1212 PySSL_END_ALLOW_THREADS
1213
1214 if (!count) {
1215 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1216 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001217 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 "The read operation timed out");
1219 goto error;
1220 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1221 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001222 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 goto error;
1224 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1225 count = 0;
1226 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001227 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 }
1229 do {
1230 err = 0;
1231 PySSL_BEGIN_ALLOW_THREADS
1232 count = SSL_read(self->ssl, mem, len);
1233 err = SSL_get_error(self->ssl, count);
1234 PySSL_END_ALLOW_THREADS
1235 if (PyErr_CheckSignals())
1236 goto error;
1237 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001238 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001240 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1242 (SSL_get_shutdown(self->ssl) ==
1243 SSL_RECEIVED_SHUTDOWN))
1244 {
1245 count = 0;
1246 goto done;
1247 } else {
1248 sockstate = SOCKET_OPERATION_OK;
1249 }
1250 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001251 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 "The read operation timed out");
1253 goto error;
1254 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1255 break;
1256 }
1257 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1258 if (count <= 0) {
1259 PySSL_SetError(self, count, __FILE__, __LINE__);
1260 goto error;
1261 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001262
1263done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001264 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001266 _PyBytes_Resize(&dest, count);
1267 return dest;
1268 }
1269 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 PyBuffer_Release(&buf);
1271 return PyLong_FromLong(count);
1272 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001273
1274error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001275 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001276 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001277 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001278 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001281}
1282
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001283PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001284"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001285\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001286Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001287
Antoine Pitrou152efa22010-05-16 18:19:27 +00001288static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001289{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 int err, ssl_err, sockstate, nonblocking;
1291 int zeros = 0;
1292 PySocketSockObject *sock
1293 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 /* Guard against closed socket */
1296 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1297 _setSSLError("Underlying socket connection gone",
1298 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1299 return NULL;
1300 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001301 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302
1303 /* Just in case the blocking state of the socket has been changed */
1304 nonblocking = (sock->sock_timeout >= 0.0);
1305 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1306 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1307
1308 while (1) {
1309 PySSL_BEGIN_ALLOW_THREADS
1310 /* Disable read-ahead so that unwrap can work correctly.
1311 * Otherwise OpenSSL might read in too much data,
1312 * eating clear text data that happens to be
1313 * transmitted after the SSL shutdown.
1314 * Should be safe to call repeatedly everytime this
1315 * function is used and the shutdown_seen_zero != 0
1316 * condition is met.
1317 */
1318 if (self->shutdown_seen_zero)
1319 SSL_set_read_ahead(self->ssl, 0);
1320 err = SSL_shutdown(self->ssl);
1321 PySSL_END_ALLOW_THREADS
1322 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1323 if (err > 0)
1324 break;
1325 if (err == 0) {
1326 /* Don't loop endlessly; instead preserve legacy
1327 behaviour of trying SSL_shutdown() only twice.
1328 This looks necessary for OpenSSL < 0.9.8m */
1329 if (++zeros > 1)
1330 break;
1331 /* Shutdown was sent, now try receiving */
1332 self->shutdown_seen_zero = 1;
1333 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001334 }
1335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 /* Possibly retry shutdown until timeout or failure */
1337 ssl_err = SSL_get_error(self->ssl, err);
1338 if (ssl_err == SSL_ERROR_WANT_READ)
1339 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1340 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1341 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1342 else
1343 break;
1344 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1345 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001346 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 "The read operation timed out");
1348 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001349 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001351 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 }
1353 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1354 PyErr_SetString(PySSLErrorObject,
1355 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001356 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 }
1358 else if (sockstate != SOCKET_OPERATION_OK)
1359 /* Retain the SSL error code */
1360 break;
1361 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001362
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001363 if (err < 0) {
1364 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001367 else
1368 /* It's already INCREF'ed */
1369 return (PyObject *) sock;
1370
1371error:
1372 Py_DECREF(sock);
1373 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001374}
1375
1376PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1377"shutdown(s) -> socket\n\
1378\n\
1379Does the SSL shutdown handshake with the remote end, and returns\n\
1380the underlying socket object.");
1381
1382
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001383static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1385 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1386 PySSL_SSLwrite_doc},
1387 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1388 PySSL_SSLread_doc},
1389 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1390 PySSL_SSLpending_doc},
1391 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1392 PySSL_peercert_doc},
1393 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1394 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1395 PySSL_SSLshutdown_doc},
1396 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397};
1398
Antoine Pitrou152efa22010-05-16 18:19:27 +00001399static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001401 "_ssl._SSLSocket", /*tp_name*/
1402 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 0, /*tp_itemsize*/
1404 /* methods */
1405 (destructor)PySSL_dealloc, /*tp_dealloc*/
1406 0, /*tp_print*/
1407 0, /*tp_getattr*/
1408 0, /*tp_setattr*/
1409 0, /*tp_reserved*/
1410 0, /*tp_repr*/
1411 0, /*tp_as_number*/
1412 0, /*tp_as_sequence*/
1413 0, /*tp_as_mapping*/
1414 0, /*tp_hash*/
1415 0, /*tp_call*/
1416 0, /*tp_str*/
1417 0, /*tp_getattro*/
1418 0, /*tp_setattro*/
1419 0, /*tp_as_buffer*/
1420 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1421 0, /*tp_doc*/
1422 0, /*tp_traverse*/
1423 0, /*tp_clear*/
1424 0, /*tp_richcompare*/
1425 0, /*tp_weaklistoffset*/
1426 0, /*tp_iter*/
1427 0, /*tp_iternext*/
1428 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001429};
1430
Antoine Pitrou152efa22010-05-16 18:19:27 +00001431
1432/*
1433 * _SSLContext objects
1434 */
1435
1436static PyObject *
1437context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1438{
1439 char *kwlist[] = {"protocol", NULL};
1440 PySSLContext *self;
1441 int proto_version = PY_SSL_VERSION_SSL23;
1442 SSL_CTX *ctx = NULL;
1443
1444 if (!PyArg_ParseTupleAndKeywords(
1445 args, kwds, "i:_SSLContext", kwlist,
1446 &proto_version))
1447 return NULL;
1448
1449 PySSL_BEGIN_ALLOW_THREADS
1450 if (proto_version == PY_SSL_VERSION_TLS1)
1451 ctx = SSL_CTX_new(TLSv1_method());
1452 else if (proto_version == PY_SSL_VERSION_SSL3)
1453 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001454#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001455 else if (proto_version == PY_SSL_VERSION_SSL2)
1456 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001457#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001458 else if (proto_version == PY_SSL_VERSION_SSL23)
1459 ctx = SSL_CTX_new(SSLv23_method());
1460 else
1461 proto_version = -1;
1462 PySSL_END_ALLOW_THREADS
1463
1464 if (proto_version == -1) {
1465 PyErr_SetString(PyExc_ValueError,
1466 "invalid protocol version");
1467 return NULL;
1468 }
1469 if (ctx == NULL) {
1470 PyErr_SetString(PySSLErrorObject,
1471 "failed to allocate SSL context");
1472 return NULL;
1473 }
1474
1475 assert(type != NULL && type->tp_alloc != NULL);
1476 self = (PySSLContext *) type->tp_alloc(type, 0);
1477 if (self == NULL) {
1478 SSL_CTX_free(ctx);
1479 return NULL;
1480 }
1481 self->ctx = ctx;
1482 /* Defaults */
1483 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1484 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1485
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001486#define SID_CTX "Python"
1487 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1488 sizeof(SID_CTX));
1489#undef SID_CTX
1490
Antoine Pitrou152efa22010-05-16 18:19:27 +00001491 return (PyObject *)self;
1492}
1493
1494static void
1495context_dealloc(PySSLContext *self)
1496{
1497 SSL_CTX_free(self->ctx);
1498 Py_TYPE(self)->tp_free(self);
1499}
1500
1501static PyObject *
1502set_ciphers(PySSLContext *self, PyObject *args)
1503{
1504 int ret;
1505 const char *cipherlist;
1506
1507 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1508 return NULL;
1509 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1510 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001511 /* Clearing the error queue is necessary on some OpenSSL versions,
1512 otherwise the error will be reported again when another SSL call
1513 is done. */
1514 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001515 PyErr_SetString(PySSLErrorObject,
1516 "No cipher can be selected.");
1517 return NULL;
1518 }
1519 Py_RETURN_NONE;
1520}
1521
1522static PyObject *
1523get_verify_mode(PySSLContext *self, void *c)
1524{
1525 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1526 case SSL_VERIFY_NONE:
1527 return PyLong_FromLong(PY_SSL_CERT_NONE);
1528 case SSL_VERIFY_PEER:
1529 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1530 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1531 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1532 }
1533 PyErr_SetString(PySSLErrorObject,
1534 "invalid return value from SSL_CTX_get_verify_mode");
1535 return NULL;
1536}
1537
1538static int
1539set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1540{
1541 int n, mode;
1542 if (!PyArg_Parse(arg, "i", &n))
1543 return -1;
1544 if (n == PY_SSL_CERT_NONE)
1545 mode = SSL_VERIFY_NONE;
1546 else if (n == PY_SSL_CERT_OPTIONAL)
1547 mode = SSL_VERIFY_PEER;
1548 else if (n == PY_SSL_CERT_REQUIRED)
1549 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1550 else {
1551 PyErr_SetString(PyExc_ValueError,
1552 "invalid value for verify_mode");
1553 return -1;
1554 }
1555 SSL_CTX_set_verify(self->ctx, mode, NULL);
1556 return 0;
1557}
1558
1559static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001560get_options(PySSLContext *self, void *c)
1561{
1562 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1563}
1564
1565static int
1566set_options(PySSLContext *self, PyObject *arg, void *c)
1567{
1568 long new_opts, opts, set, clear;
1569 if (!PyArg_Parse(arg, "l", &new_opts))
1570 return -1;
1571 opts = SSL_CTX_get_options(self->ctx);
1572 clear = opts & ~new_opts;
1573 set = ~opts & new_opts;
1574 if (clear) {
1575#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1576 SSL_CTX_clear_options(self->ctx, clear);
1577#else
1578 PyErr_SetString(PyExc_ValueError,
1579 "can't clear options before OpenSSL 0.9.8m");
1580 return -1;
1581#endif
1582 }
1583 if (set)
1584 SSL_CTX_set_options(self->ctx, set);
1585 return 0;
1586}
1587
1588static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001589load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1590{
1591 char *kwlist[] = {"certfile", "keyfile", NULL};
1592 PyObject *certfile, *keyfile = NULL;
1593 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1594 int r;
1595
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001596 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001597 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001598 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1599 "O|O:load_cert_chain", kwlist,
1600 &certfile, &keyfile))
1601 return NULL;
1602 if (keyfile == Py_None)
1603 keyfile = NULL;
1604 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1605 PyErr_SetString(PyExc_TypeError,
1606 "certfile should be a valid filesystem path");
1607 return NULL;
1608 }
1609 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1610 PyErr_SetString(PyExc_TypeError,
1611 "keyfile should be a valid filesystem path");
1612 goto error;
1613 }
1614 PySSL_BEGIN_ALLOW_THREADS
1615 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1616 PyBytes_AS_STRING(certfile_bytes));
1617 PySSL_END_ALLOW_THREADS
1618 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001619 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001620 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001621 PyErr_SetFromErrno(PyExc_IOError);
1622 }
1623 else {
1624 _setSSLError(NULL, 0, __FILE__, __LINE__);
1625 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001626 goto error;
1627 }
1628 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001629 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001630 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1631 SSL_FILETYPE_PEM);
1632 PySSL_END_ALLOW_THREADS
1633 Py_XDECREF(keyfile_bytes);
1634 Py_XDECREF(certfile_bytes);
1635 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001636 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001637 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001638 PyErr_SetFromErrno(PyExc_IOError);
1639 }
1640 else {
1641 _setSSLError(NULL, 0, __FILE__, __LINE__);
1642 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001643 return NULL;
1644 }
1645 PySSL_BEGIN_ALLOW_THREADS
1646 r = SSL_CTX_check_private_key(self->ctx);
1647 PySSL_END_ALLOW_THREADS
1648 if (r != 1) {
1649 _setSSLError(NULL, 0, __FILE__, __LINE__);
1650 return NULL;
1651 }
1652 Py_RETURN_NONE;
1653
1654error:
1655 Py_XDECREF(keyfile_bytes);
1656 Py_XDECREF(certfile_bytes);
1657 return NULL;
1658}
1659
1660static PyObject *
1661load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1662{
1663 char *kwlist[] = {"cafile", "capath", NULL};
1664 PyObject *cafile = NULL, *capath = NULL;
1665 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1666 const char *cafile_buf = NULL, *capath_buf = NULL;
1667 int r;
1668
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001669 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001670 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1671 "|OO:load_verify_locations", kwlist,
1672 &cafile, &capath))
1673 return NULL;
1674 if (cafile == Py_None)
1675 cafile = NULL;
1676 if (capath == Py_None)
1677 capath = NULL;
1678 if (cafile == NULL && capath == NULL) {
1679 PyErr_SetString(PyExc_TypeError,
1680 "cafile and capath cannot be both omitted");
1681 return NULL;
1682 }
1683 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1684 PyErr_SetString(PyExc_TypeError,
1685 "cafile should be a valid filesystem path");
1686 return NULL;
1687 }
1688 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001689 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001690 PyErr_SetString(PyExc_TypeError,
1691 "capath should be a valid filesystem path");
1692 return NULL;
1693 }
1694 if (cafile)
1695 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1696 if (capath)
1697 capath_buf = PyBytes_AS_STRING(capath_bytes);
1698 PySSL_BEGIN_ALLOW_THREADS
1699 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1700 PySSL_END_ALLOW_THREADS
1701 Py_XDECREF(cafile_bytes);
1702 Py_XDECREF(capath_bytes);
1703 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001704 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001705 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001706 PyErr_SetFromErrno(PyExc_IOError);
1707 }
1708 else {
1709 _setSSLError(NULL, 0, __FILE__, __LINE__);
1710 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001711 return NULL;
1712 }
1713 Py_RETURN_NONE;
1714}
1715
1716static PyObject *
1717context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1718{
Antoine Pitroud5323212010-10-22 18:19:07 +00001719 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001720 PySocketSockObject *sock;
1721 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001722 char *hostname = NULL;
1723 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001724
Antoine Pitroud5323212010-10-22 18:19:07 +00001725 /* server_hostname is either None (or absent), or to be encoded
1726 using the idna encoding. */
1727 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001728 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001729 &sock, &server_side,
1730 Py_TYPE(Py_None), &hostname_obj)) {
1731 PyErr_Clear();
1732 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1733 PySocketModule.Sock_Type,
1734 &sock, &server_side,
1735 "idna", &hostname))
1736 return NULL;
1737#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1738 PyMem_Free(hostname);
1739 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1740 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001741 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001742#endif
1743 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001744
Antoine Pitroud5323212010-10-22 18:19:07 +00001745 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1746 hostname);
1747 if (hostname != NULL)
1748 PyMem_Free(hostname);
1749 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001750}
1751
Antoine Pitroub0182c82010-10-12 20:09:02 +00001752static PyObject *
1753session_stats(PySSLContext *self, PyObject *unused)
1754{
1755 int r;
1756 PyObject *value, *stats = PyDict_New();
1757 if (!stats)
1758 return NULL;
1759
1760#define ADD_STATS(SSL_NAME, KEY_NAME) \
1761 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1762 if (value == NULL) \
1763 goto error; \
1764 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1765 Py_DECREF(value); \
1766 if (r < 0) \
1767 goto error;
1768
1769 ADD_STATS(number, "number");
1770 ADD_STATS(connect, "connect");
1771 ADD_STATS(connect_good, "connect_good");
1772 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1773 ADD_STATS(accept, "accept");
1774 ADD_STATS(accept_good, "accept_good");
1775 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1776 ADD_STATS(accept, "accept");
1777 ADD_STATS(hits, "hits");
1778 ADD_STATS(misses, "misses");
1779 ADD_STATS(timeouts, "timeouts");
1780 ADD_STATS(cache_full, "cache_full");
1781
1782#undef ADD_STATS
1783
1784 return stats;
1785
1786error:
1787 Py_DECREF(stats);
1788 return NULL;
1789}
1790
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001791static PyObject *
1792set_default_verify_paths(PySSLContext *self, PyObject *unused)
1793{
1794 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1795 _setSSLError(NULL, 0, __FILE__, __LINE__);
1796 return NULL;
1797 }
1798 Py_RETURN_NONE;
1799}
1800
Antoine Pitrou152efa22010-05-16 18:19:27 +00001801static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001802 {"options", (getter) get_options,
1803 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001804 {"verify_mode", (getter) get_verify_mode,
1805 (setter) set_verify_mode, NULL},
1806 {NULL}, /* sentinel */
1807};
1808
1809static struct PyMethodDef context_methods[] = {
1810 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1811 METH_VARARGS | METH_KEYWORDS, NULL},
1812 {"set_ciphers", (PyCFunction) set_ciphers,
1813 METH_VARARGS, NULL},
1814 {"load_cert_chain", (PyCFunction) load_cert_chain,
1815 METH_VARARGS | METH_KEYWORDS, NULL},
1816 {"load_verify_locations", (PyCFunction) load_verify_locations,
1817 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001818 {"session_stats", (PyCFunction) session_stats,
1819 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001820 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1821 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001822 {NULL, NULL} /* sentinel */
1823};
1824
1825static PyTypeObject PySSLContext_Type = {
1826 PyVarObject_HEAD_INIT(NULL, 0)
1827 "_ssl._SSLContext", /*tp_name*/
1828 sizeof(PySSLContext), /*tp_basicsize*/
1829 0, /*tp_itemsize*/
1830 (destructor)context_dealloc, /*tp_dealloc*/
1831 0, /*tp_print*/
1832 0, /*tp_getattr*/
1833 0, /*tp_setattr*/
1834 0, /*tp_reserved*/
1835 0, /*tp_repr*/
1836 0, /*tp_as_number*/
1837 0, /*tp_as_sequence*/
1838 0, /*tp_as_mapping*/
1839 0, /*tp_hash*/
1840 0, /*tp_call*/
1841 0, /*tp_str*/
1842 0, /*tp_getattro*/
1843 0, /*tp_setattro*/
1844 0, /*tp_as_buffer*/
1845 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1846 0, /*tp_doc*/
1847 0, /*tp_traverse*/
1848 0, /*tp_clear*/
1849 0, /*tp_richcompare*/
1850 0, /*tp_weaklistoffset*/
1851 0, /*tp_iter*/
1852 0, /*tp_iternext*/
1853 context_methods, /*tp_methods*/
1854 0, /*tp_members*/
1855 context_getsetlist, /*tp_getset*/
1856 0, /*tp_base*/
1857 0, /*tp_dict*/
1858 0, /*tp_descr_get*/
1859 0, /*tp_descr_set*/
1860 0, /*tp_dictoffset*/
1861 0, /*tp_init*/
1862 0, /*tp_alloc*/
1863 context_new, /*tp_new*/
1864};
1865
1866
1867
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001868#ifdef HAVE_OPENSSL_RAND
1869
1870/* helper routines for seeding the SSL PRNG */
1871static PyObject *
1872PySSL_RAND_add(PyObject *self, PyObject *args)
1873{
1874 char *buf;
1875 int len;
1876 double entropy;
1877
1878 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001879 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001880 RAND_add(buf, len, entropy);
1881 Py_INCREF(Py_None);
1882 return Py_None;
1883}
1884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001885PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001886"RAND_add(string, entropy)\n\
1887\n\
1888Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001889bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001890
1891static PyObject *
1892PySSL_RAND_status(PyObject *self)
1893{
Christian Heimes217cfd12007-12-02 14:31:20 +00001894 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001895}
1896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001897PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001898"RAND_status() -> 0 or 1\n\
1899\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001900Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1901It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1902using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001903
1904static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001905PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001906{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001907 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001908 int bytes;
1909
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001910 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1911 PyUnicode_FSConverter, &path))
1912 return NULL;
1913
1914 bytes = RAND_egd(PyBytes_AsString(path));
1915 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001916 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001917 PyErr_SetString(PySSLErrorObject,
1918 "EGD connection failed or EGD did not return "
1919 "enough data to seed the PRNG");
1920 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001921 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001922 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001923}
1924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001925PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001926"RAND_egd(path) -> bytes\n\
1927\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001928Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1929Returns number of bytes read. Raises SSLError if connection to EGD\n\
1930fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001931
1932#endif
1933
Bill Janssen40a0f662008-08-12 16:56:25 +00001934
1935
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001936/* List of functions exported by this module. */
1937
1938static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 {"_test_decode_cert", PySSL_test_decode_certificate,
1940 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001941#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1943 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001944 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 PySSL_RAND_egd_doc},
1946 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1947 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001948#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001950};
1951
1952
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001953#ifdef WITH_THREAD
1954
1955/* an implementation of OpenSSL threading operations in terms
1956 of the Python C thread library */
1957
1958static PyThread_type_lock *_ssl_locks = NULL;
1959
1960static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001962}
1963
Bill Janssen6e027db2007-11-15 22:23:56 +00001964static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 (int mode, int n, const char *file, int line) {
1966 /* this function is needed to perform locking on shared data
1967 structures. (Note that OpenSSL uses a number of global data
1968 structures that will be implicitly shared whenever multiple
1969 threads use OpenSSL.) Multi-threaded applications will
1970 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 locking_function() must be able to handle up to
1973 CRYPTO_num_locks() different mutex locks. It sets the n-th
1974 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001975
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 file and line are the file number of the function setting the
1977 lock. They can be useful for debugging.
1978 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001980 if ((_ssl_locks == NULL) ||
1981 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1982 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 if (mode & CRYPTO_LOCK) {
1985 PyThread_acquire_lock(_ssl_locks[n], 1);
1986 } else {
1987 PyThread_release_lock(_ssl_locks[n]);
1988 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001989}
1990
1991static int _setup_ssl_threads(void) {
1992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 if (_ssl_locks == NULL) {
1996 _ssl_locks_count = CRYPTO_num_locks();
1997 _ssl_locks = (PyThread_type_lock *)
1998 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1999 if (_ssl_locks == NULL)
2000 return 0;
2001 memset(_ssl_locks, 0,
2002 sizeof(PyThread_type_lock) * _ssl_locks_count);
2003 for (i = 0; i < _ssl_locks_count; i++) {
2004 _ssl_locks[i] = PyThread_allocate_lock();
2005 if (_ssl_locks[i] == NULL) {
2006 unsigned int j;
2007 for (j = 0; j < i; j++) {
2008 PyThread_free_lock(_ssl_locks[j]);
2009 }
2010 free(_ssl_locks);
2011 return 0;
2012 }
2013 }
2014 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2015 CRYPTO_set_id_callback(_ssl_thread_id_function);
2016 }
2017 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002018}
2019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002020#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002022PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002023"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002024for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002025
Martin v. Löwis1a214512008-06-11 05:26:20 +00002026
2027static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002028 PyModuleDef_HEAD_INIT,
2029 "_ssl",
2030 module_doc,
2031 -1,
2032 PySSL_methods,
2033 NULL,
2034 NULL,
2035 NULL,
2036 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002037};
2038
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002039
2040static void
2041parse_openssl_version(unsigned long libver,
2042 unsigned int *major, unsigned int *minor,
2043 unsigned int *fix, unsigned int *patch,
2044 unsigned int *status)
2045{
2046 *status = libver & 0xF;
2047 libver >>= 4;
2048 *patch = libver & 0xFF;
2049 libver >>= 8;
2050 *fix = libver & 0xFF;
2051 libver >>= 8;
2052 *minor = libver & 0xFF;
2053 libver >>= 8;
2054 *major = libver & 0xFF;
2055}
2056
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002057PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002058PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002059{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002060 PyObject *m, *d, *r;
2061 unsigned long libver;
2062 unsigned int major, minor, fix, patch, status;
2063 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002064
Antoine Pitrou152efa22010-05-16 18:19:27 +00002065 if (PyType_Ready(&PySSLContext_Type) < 0)
2066 return NULL;
2067 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002068 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002070 m = PyModule_Create(&_sslmodule);
2071 if (m == NULL)
2072 return NULL;
2073 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002074
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 /* Load _socket module and its C API */
2076 socket_api = PySocketModule_ImportModuleAndAPI();
2077 if (!socket_api)
2078 return NULL;
2079 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 /* Init OpenSSL */
2082 SSL_load_error_strings();
2083 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002084#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002085 /* note that this will start threading if not already started */
2086 if (!_setup_ssl_threads()) {
2087 return NULL;
2088 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002089#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002090 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002091
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002092 /* Add symbols to module dict */
2093 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2094 PySocketModule.error,
2095 NULL);
2096 if (PySSLErrorObject == NULL)
2097 return NULL;
2098 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2099 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002100 if (PyDict_SetItemString(d, "_SSLContext",
2101 (PyObject *)&PySSLContext_Type) != 0)
2102 return NULL;
2103 if (PyDict_SetItemString(d, "_SSLSocket",
2104 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 return NULL;
2106 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2107 PY_SSL_ERROR_ZERO_RETURN);
2108 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2109 PY_SSL_ERROR_WANT_READ);
2110 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2111 PY_SSL_ERROR_WANT_WRITE);
2112 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2113 PY_SSL_ERROR_WANT_X509_LOOKUP);
2114 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2115 PY_SSL_ERROR_SYSCALL);
2116 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2117 PY_SSL_ERROR_SSL);
2118 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2119 PY_SSL_ERROR_WANT_CONNECT);
2120 /* non ssl.h errorcodes */
2121 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2122 PY_SSL_ERROR_EOF);
2123 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2124 PY_SSL_ERROR_INVALID_ERROR_CODE);
2125 /* cert requirements */
2126 PyModule_AddIntConstant(m, "CERT_NONE",
2127 PY_SSL_CERT_NONE);
2128 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2129 PY_SSL_CERT_OPTIONAL);
2130 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2131 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 /* protocol versions */
Victor Stinneree18b6f2011-05-10 00:38:00 +02002134#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2136 PY_SSL_VERSION_SSL2);
Victor Stinneree18b6f2011-05-10 00:38:00 +02002137#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2139 PY_SSL_VERSION_SSL3);
2140 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2141 PY_SSL_VERSION_SSL23);
2142 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2143 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002144
Antoine Pitroub5218772010-05-21 09:56:06 +00002145 /* protocol options */
2146 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2147 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2148 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2149 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2150
Antoine Pitroud5323212010-10-22 18:19:07 +00002151#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2152 r = Py_True;
2153#else
2154 r = Py_False;
2155#endif
2156 Py_INCREF(r);
2157 PyModule_AddObject(m, "HAS_SNI", r);
2158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 /* OpenSSL version */
2160 /* SSLeay() gives us the version of the library linked against,
2161 which could be different from the headers version.
2162 */
2163 libver = SSLeay();
2164 r = PyLong_FromUnsignedLong(libver);
2165 if (r == NULL)
2166 return NULL;
2167 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2168 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002169 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2171 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2172 return NULL;
2173 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2174 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2175 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002176
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002177 libver = OPENSSL_VERSION_NUMBER;
2178 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2179 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2180 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2181 return NULL;
2182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002184}