blob: 27dcdbc5730dcc46927c8c576ae043d268d1f923 [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 Pitroucbb82eb2010-05-05 15:57:33 +0000581 i = 0;
582 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 }
682 }
683 BIO_free(biobuf);
684 if (peer_alt_names != Py_None) {
685 v = PyList_AsTuple(peer_alt_names);
686 Py_DECREF(peer_alt_names);
687 return v;
688 } else {
689 return peer_alt_names;
690 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000691
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
693 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 if (biobuf != NULL)
695 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000696
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 if (peer_alt_names != Py_None) {
698 Py_XDECREF(peer_alt_names);
699 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702}
703
704static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000705_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 PyObject *retval = NULL;
708 BIO *biobuf = NULL;
709 PyObject *peer;
710 PyObject *peer_alt_names = NULL;
711 PyObject *issuer;
712 PyObject *version;
713 PyObject *sn_obj;
714 ASN1_INTEGER *serialNumber;
715 char buf[2048];
716 int len;
717 ASN1_TIME *notBefore, *notAfter;
718 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 retval = PyDict_New();
721 if (retval == NULL)
722 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 peer = _create_tuple_for_X509_NAME(
725 X509_get_subject_name(certificate));
726 if (peer == NULL)
727 goto fail0;
728 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
729 Py_DECREF(peer);
730 goto fail0;
731 }
732 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000733
Antoine Pitroufb046912010-11-09 20:21:19 +0000734 issuer = _create_tuple_for_X509_NAME(
735 X509_get_issuer_name(certificate));
736 if (issuer == NULL)
737 goto fail0;
738 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000740 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000742 Py_DECREF(issuer);
743
744 version = PyLong_FromLong(X509_get_version(certificate) + 1);
745 if (PyDict_SetItemString(retval, "version", version) < 0) {
746 Py_DECREF(version);
747 goto fail0;
748 }
749 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 /* get a memory buffer */
752 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000753
Antoine Pitroufb046912010-11-09 20:21:19 +0000754 (void) BIO_reset(biobuf);
755 serialNumber = X509_get_serialNumber(certificate);
756 /* should not exceed 20 octets, 160 bits, so buf is big enough */
757 i2a_ASN1_INTEGER(biobuf, serialNumber);
758 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
759 if (len < 0) {
760 _setSSLError(NULL, 0, __FILE__, __LINE__);
761 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000763 sn_obj = PyUnicode_FromStringAndSize(buf, len);
764 if (sn_obj == NULL)
765 goto fail1;
766 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
767 Py_DECREF(sn_obj);
768 goto fail1;
769 }
770 Py_DECREF(sn_obj);
771
772 (void) BIO_reset(biobuf);
773 notBefore = X509_get_notBefore(certificate);
774 ASN1_TIME_print(biobuf, notBefore);
775 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
776 if (len < 0) {
777 _setSSLError(NULL, 0, __FILE__, __LINE__);
778 goto fail1;
779 }
780 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
781 if (pnotBefore == NULL)
782 goto fail1;
783 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
784 Py_DECREF(pnotBefore);
785 goto fail1;
786 }
787 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 (void) BIO_reset(biobuf);
790 notAfter = X509_get_notAfter(certificate);
791 ASN1_TIME_print(biobuf, notAfter);
792 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
793 if (len < 0) {
794 _setSSLError(NULL, 0, __FILE__, __LINE__);
795 goto fail1;
796 }
797 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
798 if (pnotAfter == NULL)
799 goto fail1;
800 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
801 Py_DECREF(pnotAfter);
802 goto fail1;
803 }
804 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 peer_alt_names = _get_peer_alt_names(certificate);
809 if (peer_alt_names == NULL)
810 goto fail1;
811 else if (peer_alt_names != Py_None) {
812 if (PyDict_SetItemString(retval, "subjectAltName",
813 peer_alt_names) < 0) {
814 Py_DECREF(peer_alt_names);
815 goto fail1;
816 }
817 Py_DECREF(peer_alt_names);
818 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 BIO_free(biobuf);
821 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000822
823 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 if (biobuf != NULL)
825 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000826 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 Py_XDECREF(retval);
828 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000829}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000830
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
832static PyObject *
833PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000836 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 X509 *x=NULL;
838 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroufb046912010-11-09 20:21:19 +0000840 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
841 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 if ((cert=BIO_new(BIO_s_file())) == NULL) {
845 PyErr_SetString(PySSLErrorObject,
846 "Can't malloc memory to read file");
847 goto fail0;
848 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Victor Stinner3800e1e2010-05-16 21:23:48 +0000850 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 PyErr_SetString(PySSLErrorObject,
852 "Can't open file");
853 goto fail0;
854 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
857 if (x == NULL) {
858 PyErr_SetString(PySSLErrorObject,
859 "Error decoding PEM-encoded file");
860 goto fail0;
861 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862
Antoine Pitroufb046912010-11-09 20:21:19 +0000863 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000864 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865
866 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000867 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 if (cert != NULL) BIO_free(cert);
869 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870}
871
872
873static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000874PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 PyObject *retval = NULL;
877 int len;
878 int verification;
879 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
882 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 if (!self->peer_cert)
885 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 if (PyObject_IsTrue(binary_mode)) {
888 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 bytes_buf = NULL;
893 len = i2d_X509(self->peer_cert, &bytes_buf);
894 if (len < 0) {
895 PySSL_SetError(self, len, __FILE__, __LINE__);
896 return NULL;
897 }
898 /* this is actually an immutable bytes sequence */
899 retval = PyBytes_FromStringAndSize
900 ((const char *) bytes_buf, len);
901 OPENSSL_free(bytes_buf);
902 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000905 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 if ((verification & SSL_VERIFY_PEER) == 0)
907 return PyDict_New();
908 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000909 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911}
912
913PyDoc_STRVAR(PySSL_peercert_doc,
914"peer_certificate([der=False]) -> certificate\n\
915\n\
916Returns the certificate for the peer. If no certificate was provided,\n\
917returns None. If a certificate was provided, but not validated, returns\n\
918an empty dictionary. Otherwise returns a dict containing information\n\
919about the peer certificate.\n\
920\n\
921If the optional argument is True, returns a DER-encoded copy of the\n\
922peer certificate, or None if no certificate was provided. This will\n\
923return the certificate even if it wasn't validated.");
924
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000928 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 char *cipher_name;
930 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000933 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 current = SSL_get_current_cipher(self->ssl);
935 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000936 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 retval = PyTuple_New(3);
939 if (retval == NULL)
940 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 cipher_name = (char *) SSL_CIPHER_get_name(current);
943 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000944 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 PyTuple_SET_ITEM(retval, 0, Py_None);
946 } else {
947 v = PyUnicode_FromString(cipher_name);
948 if (v == NULL)
949 goto fail0;
950 PyTuple_SET_ITEM(retval, 0, v);
951 }
952 cipher_protocol = SSL_CIPHER_get_version(current);
953 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000954 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 PyTuple_SET_ITEM(retval, 1, Py_None);
956 } else {
957 v = PyUnicode_FromString(cipher_protocol);
958 if (v == NULL)
959 goto fail0;
960 PyTuple_SET_ITEM(retval, 1, v);
961 }
962 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
963 if (v == NULL)
964 goto fail0;
965 PyTuple_SET_ITEM(retval, 2, v);
966 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000967
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 Py_DECREF(retval);
970 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971}
972
Antoine Pitrou152efa22010-05-16 18:19:27 +0000973static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000974{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 if (self->peer_cert) /* Possible not to have one? */
976 X509_free (self->peer_cert);
977 if (self->ssl)
978 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 Py_XDECREF(self->Socket);
980 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000981}
982
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000983/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000984 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000985 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000986 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000987
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000988static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000989check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000990{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 fd_set fds;
992 struct timeval tv;
993 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 /* Nothing to do unless we're in timeout mode (not non-blocking) */
996 if (s->sock_timeout < 0.0)
997 return SOCKET_IS_BLOCKING;
998 else if (s->sock_timeout == 0.0)
999 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Guard against closed socket */
1002 if (s->sock_fd < 0)
1003 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 /* Prefer poll, if available, since you can poll() any fd
1006 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 {
1009 struct pollfd pollfd;
1010 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 pollfd.fd = s->sock_fd;
1013 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 /* s->sock_timeout is in seconds, timeout in ms */
1016 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1017 PySSL_BEGIN_ALLOW_THREADS
1018 rc = poll(&pollfd, 1, timeout);
1019 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 goto normal_return;
1022 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001023#endif
1024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001026#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 if (s->sock_fd >= FD_SETSIZE)
1028 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001029#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 /* Construct the arguments to select */
1032 tv.tv_sec = (int)s->sock_timeout;
1033 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1034 FD_ZERO(&fds);
1035 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 /* See if the socket is ready */
1038 PySSL_BEGIN_ALLOW_THREADS
1039 if (writing)
1040 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1041 else
1042 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1043 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001044
Bill Janssen6e027db2007-11-15 22:23:56 +00001045#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001046normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001047#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1049 (when we are able to write or when there's something to read) */
1050 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001051}
1052
Antoine Pitrou152efa22010-05-16 18:19:27 +00001053static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001054{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 Py_buffer buf;
1056 int len;
1057 int sockstate;
1058 int err;
1059 int nonblocking;
1060 PySocketSockObject *sock
1061 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 if (((PyObject*)sock) == Py_None) {
1064 _setSSLError("Underlying socket connection gone",
1065 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1066 return NULL;
1067 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001068 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001070 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1071 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001073 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074
1075 /* just in case the blocking state of the socket has been changed */
1076 nonblocking = (sock->sock_timeout >= 0.0);
1077 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1078 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1079
1080 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1081 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001082 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 "The write operation timed out");
1084 goto error;
1085 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1086 PyErr_SetString(PySSLErrorObject,
1087 "Underlying socket has been closed.");
1088 goto error;
1089 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1090 PyErr_SetString(PySSLErrorObject,
1091 "Underlying socket too large for select().");
1092 goto error;
1093 }
1094 do {
1095 err = 0;
1096 PySSL_BEGIN_ALLOW_THREADS
1097 len = SSL_write(self->ssl, buf.buf, buf.len);
1098 err = SSL_get_error(self->ssl, len);
1099 PySSL_END_ALLOW_THREADS
1100 if (PyErr_CheckSignals()) {
1101 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001102 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001104 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001106 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 } else {
1108 sockstate = SOCKET_OPERATION_OK;
1109 }
1110 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001111 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 "The write operation timed out");
1113 goto error;
1114 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1115 PyErr_SetString(PySSLErrorObject,
1116 "Underlying socket has been closed.");
1117 goto error;
1118 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1119 break;
1120 }
1121 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001122
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001123 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 PyBuffer_Release(&buf);
1125 if (len > 0)
1126 return PyLong_FromLong(len);
1127 else
1128 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001129
1130error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001131 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001132 PyBuffer_Release(&buf);
1133 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001134}
1135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001136PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001137"write(s) -> len\n\
1138\n\
1139Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001140of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001141
Antoine Pitrou152efa22010-05-16 18:19:27 +00001142static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001143{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001145
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 PySSL_BEGIN_ALLOW_THREADS
1147 count = SSL_pending(self->ssl);
1148 PySSL_END_ALLOW_THREADS
1149 if (count < 0)
1150 return PySSL_SetError(self, count, __FILE__, __LINE__);
1151 else
1152 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001153}
1154
1155PyDoc_STRVAR(PySSL_SSLpending_doc,
1156"pending() -> count\n\
1157\n\
1158Returns the number of already decrypted bytes available for read,\n\
1159pending on the connection.\n");
1160
Antoine Pitrou152efa22010-05-16 18:19:27 +00001161static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001162{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 PyObject *dest = NULL;
1164 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001166 int len, count;
1167 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 int sockstate;
1169 int err;
1170 int nonblocking;
1171 PySocketSockObject *sock
1172 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 if (((PyObject*)sock) == Py_None) {
1175 _setSSLError("Underlying socket connection gone",
1176 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1177 return NULL;
1178 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001179 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001181 buf.obj = NULL;
1182 buf.buf = NULL;
1183 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001184 goto error;
1185
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001186 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1187 dest = PyBytes_FromStringAndSize(NULL, len);
1188 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001189 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001190 mem = PyBytes_AS_STRING(dest);
1191 }
1192 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001194 mem = buf.buf;
1195 if (len <= 0 || len > buf.len) {
1196 len = (int) buf.len;
1197 if (buf.len != len) {
1198 PyErr_SetString(PyExc_OverflowError,
1199 "maximum length can't fit in a C 'int'");
1200 goto error;
1201 }
1202 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 }
1204
1205 /* just in case the blocking state of the socket has been changed */
1206 nonblocking = (sock->sock_timeout >= 0.0);
1207 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1208 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1209
1210 /* first check if there are bytes ready to be read */
1211 PySSL_BEGIN_ALLOW_THREADS
1212 count = SSL_pending(self->ssl);
1213 PySSL_END_ALLOW_THREADS
1214
1215 if (!count) {
1216 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1217 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001218 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 "The read operation timed out");
1220 goto error;
1221 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1222 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001223 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 goto error;
1225 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1226 count = 0;
1227 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001228 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 }
1230 do {
1231 err = 0;
1232 PySSL_BEGIN_ALLOW_THREADS
1233 count = SSL_read(self->ssl, mem, len);
1234 err = SSL_get_error(self->ssl, count);
1235 PySSL_END_ALLOW_THREADS
1236 if (PyErr_CheckSignals())
1237 goto error;
1238 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001239 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001241 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1243 (SSL_get_shutdown(self->ssl) ==
1244 SSL_RECEIVED_SHUTDOWN))
1245 {
1246 count = 0;
1247 goto done;
1248 } else {
1249 sockstate = SOCKET_OPERATION_OK;
1250 }
1251 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001252 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 "The read operation timed out");
1254 goto error;
1255 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1256 break;
1257 }
1258 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1259 if (count <= 0) {
1260 PySSL_SetError(self, count, __FILE__, __LINE__);
1261 goto error;
1262 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001263
1264done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001265 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001267 _PyBytes_Resize(&dest, count);
1268 return dest;
1269 }
1270 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 PyBuffer_Release(&buf);
1272 return PyLong_FromLong(count);
1273 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001274
1275error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001276 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001277 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001278 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001279 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001282}
1283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001284PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001285"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001286\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001287Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001288
Antoine Pitrou152efa22010-05-16 18:19:27 +00001289static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001290{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 int err, ssl_err, sockstate, nonblocking;
1292 int zeros = 0;
1293 PySocketSockObject *sock
1294 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 /* Guard against closed socket */
1297 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1298 _setSSLError("Underlying socket connection gone",
1299 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1300 return NULL;
1301 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001302 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303
1304 /* Just in case the blocking state of the socket has been changed */
1305 nonblocking = (sock->sock_timeout >= 0.0);
1306 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1307 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1308
1309 while (1) {
1310 PySSL_BEGIN_ALLOW_THREADS
1311 /* Disable read-ahead so that unwrap can work correctly.
1312 * Otherwise OpenSSL might read in too much data,
1313 * eating clear text data that happens to be
1314 * transmitted after the SSL shutdown.
1315 * Should be safe to call repeatedly everytime this
1316 * function is used and the shutdown_seen_zero != 0
1317 * condition is met.
1318 */
1319 if (self->shutdown_seen_zero)
1320 SSL_set_read_ahead(self->ssl, 0);
1321 err = SSL_shutdown(self->ssl);
1322 PySSL_END_ALLOW_THREADS
1323 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1324 if (err > 0)
1325 break;
1326 if (err == 0) {
1327 /* Don't loop endlessly; instead preserve legacy
1328 behaviour of trying SSL_shutdown() only twice.
1329 This looks necessary for OpenSSL < 0.9.8m */
1330 if (++zeros > 1)
1331 break;
1332 /* Shutdown was sent, now try receiving */
1333 self->shutdown_seen_zero = 1;
1334 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001335 }
1336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 /* Possibly retry shutdown until timeout or failure */
1338 ssl_err = SSL_get_error(self->ssl, err);
1339 if (ssl_err == SSL_ERROR_WANT_READ)
1340 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1341 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1342 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1343 else
1344 break;
1345 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1346 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001347 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 "The read operation timed out");
1349 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001350 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001352 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 }
1354 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1355 PyErr_SetString(PySSLErrorObject,
1356 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001357 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 }
1359 else if (sockstate != SOCKET_OPERATION_OK)
1360 /* Retain the SSL error code */
1361 break;
1362 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001363
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001364 if (err < 0) {
1365 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001368 else
1369 /* It's already INCREF'ed */
1370 return (PyObject *) sock;
1371
1372error:
1373 Py_DECREF(sock);
1374 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001375}
1376
1377PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1378"shutdown(s) -> socket\n\
1379\n\
1380Does the SSL shutdown handshake with the remote end, and returns\n\
1381the underlying socket object.");
1382
1383
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001384static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1386 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1387 PySSL_SSLwrite_doc},
1388 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1389 PySSL_SSLread_doc},
1390 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1391 PySSL_SSLpending_doc},
1392 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1393 PySSL_peercert_doc},
1394 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1395 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1396 PySSL_SSLshutdown_doc},
1397 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001398};
1399
Antoine Pitrou152efa22010-05-16 18:19:27 +00001400static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001402 "_ssl._SSLSocket", /*tp_name*/
1403 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 0, /*tp_itemsize*/
1405 /* methods */
1406 (destructor)PySSL_dealloc, /*tp_dealloc*/
1407 0, /*tp_print*/
1408 0, /*tp_getattr*/
1409 0, /*tp_setattr*/
1410 0, /*tp_reserved*/
1411 0, /*tp_repr*/
1412 0, /*tp_as_number*/
1413 0, /*tp_as_sequence*/
1414 0, /*tp_as_mapping*/
1415 0, /*tp_hash*/
1416 0, /*tp_call*/
1417 0, /*tp_str*/
1418 0, /*tp_getattro*/
1419 0, /*tp_setattro*/
1420 0, /*tp_as_buffer*/
1421 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1422 0, /*tp_doc*/
1423 0, /*tp_traverse*/
1424 0, /*tp_clear*/
1425 0, /*tp_richcompare*/
1426 0, /*tp_weaklistoffset*/
1427 0, /*tp_iter*/
1428 0, /*tp_iternext*/
1429 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430};
1431
Antoine Pitrou152efa22010-05-16 18:19:27 +00001432
1433/*
1434 * _SSLContext objects
1435 */
1436
1437static PyObject *
1438context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1439{
1440 char *kwlist[] = {"protocol", NULL};
1441 PySSLContext *self;
1442 int proto_version = PY_SSL_VERSION_SSL23;
1443 SSL_CTX *ctx = NULL;
1444
1445 if (!PyArg_ParseTupleAndKeywords(
1446 args, kwds, "i:_SSLContext", kwlist,
1447 &proto_version))
1448 return NULL;
1449
1450 PySSL_BEGIN_ALLOW_THREADS
1451 if (proto_version == PY_SSL_VERSION_TLS1)
1452 ctx = SSL_CTX_new(TLSv1_method());
1453 else if (proto_version == PY_SSL_VERSION_SSL3)
1454 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001455#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001456 else if (proto_version == PY_SSL_VERSION_SSL2)
1457 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001458#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001459 else if (proto_version == PY_SSL_VERSION_SSL23)
1460 ctx = SSL_CTX_new(SSLv23_method());
1461 else
1462 proto_version = -1;
1463 PySSL_END_ALLOW_THREADS
1464
1465 if (proto_version == -1) {
1466 PyErr_SetString(PyExc_ValueError,
1467 "invalid protocol version");
1468 return NULL;
1469 }
1470 if (ctx == NULL) {
1471 PyErr_SetString(PySSLErrorObject,
1472 "failed to allocate SSL context");
1473 return NULL;
1474 }
1475
1476 assert(type != NULL && type->tp_alloc != NULL);
1477 self = (PySSLContext *) type->tp_alloc(type, 0);
1478 if (self == NULL) {
1479 SSL_CTX_free(ctx);
1480 return NULL;
1481 }
1482 self->ctx = ctx;
1483 /* Defaults */
1484 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1485 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1486
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001487#define SID_CTX "Python"
1488 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1489 sizeof(SID_CTX));
1490#undef SID_CTX
1491
Antoine Pitrou152efa22010-05-16 18:19:27 +00001492 return (PyObject *)self;
1493}
1494
1495static void
1496context_dealloc(PySSLContext *self)
1497{
1498 SSL_CTX_free(self->ctx);
1499 Py_TYPE(self)->tp_free(self);
1500}
1501
1502static PyObject *
1503set_ciphers(PySSLContext *self, PyObject *args)
1504{
1505 int ret;
1506 const char *cipherlist;
1507
1508 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1509 return NULL;
1510 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1511 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001512 /* Clearing the error queue is necessary on some OpenSSL versions,
1513 otherwise the error will be reported again when another SSL call
1514 is done. */
1515 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001516 PyErr_SetString(PySSLErrorObject,
1517 "No cipher can be selected.");
1518 return NULL;
1519 }
1520 Py_RETURN_NONE;
1521}
1522
1523static PyObject *
1524get_verify_mode(PySSLContext *self, void *c)
1525{
1526 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1527 case SSL_VERIFY_NONE:
1528 return PyLong_FromLong(PY_SSL_CERT_NONE);
1529 case SSL_VERIFY_PEER:
1530 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1531 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1532 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1533 }
1534 PyErr_SetString(PySSLErrorObject,
1535 "invalid return value from SSL_CTX_get_verify_mode");
1536 return NULL;
1537}
1538
1539static int
1540set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1541{
1542 int n, mode;
1543 if (!PyArg_Parse(arg, "i", &n))
1544 return -1;
1545 if (n == PY_SSL_CERT_NONE)
1546 mode = SSL_VERIFY_NONE;
1547 else if (n == PY_SSL_CERT_OPTIONAL)
1548 mode = SSL_VERIFY_PEER;
1549 else if (n == PY_SSL_CERT_REQUIRED)
1550 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1551 else {
1552 PyErr_SetString(PyExc_ValueError,
1553 "invalid value for verify_mode");
1554 return -1;
1555 }
1556 SSL_CTX_set_verify(self->ctx, mode, NULL);
1557 return 0;
1558}
1559
1560static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001561get_options(PySSLContext *self, void *c)
1562{
1563 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1564}
1565
1566static int
1567set_options(PySSLContext *self, PyObject *arg, void *c)
1568{
1569 long new_opts, opts, set, clear;
1570 if (!PyArg_Parse(arg, "l", &new_opts))
1571 return -1;
1572 opts = SSL_CTX_get_options(self->ctx);
1573 clear = opts & ~new_opts;
1574 set = ~opts & new_opts;
1575 if (clear) {
1576#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1577 SSL_CTX_clear_options(self->ctx, clear);
1578#else
1579 PyErr_SetString(PyExc_ValueError,
1580 "can't clear options before OpenSSL 0.9.8m");
1581 return -1;
1582#endif
1583 }
1584 if (set)
1585 SSL_CTX_set_options(self->ctx, set);
1586 return 0;
1587}
1588
1589static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001590load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1591{
1592 char *kwlist[] = {"certfile", "keyfile", NULL};
1593 PyObject *certfile, *keyfile = NULL;
1594 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1595 int r;
1596
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001597 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001598 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001599 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1600 "O|O:load_cert_chain", kwlist,
1601 &certfile, &keyfile))
1602 return NULL;
1603 if (keyfile == Py_None)
1604 keyfile = NULL;
1605 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1606 PyErr_SetString(PyExc_TypeError,
1607 "certfile should be a valid filesystem path");
1608 return NULL;
1609 }
1610 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1611 PyErr_SetString(PyExc_TypeError,
1612 "keyfile should be a valid filesystem path");
1613 goto error;
1614 }
1615 PySSL_BEGIN_ALLOW_THREADS
1616 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1617 PyBytes_AS_STRING(certfile_bytes));
1618 PySSL_END_ALLOW_THREADS
1619 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001620 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001621 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001622 PyErr_SetFromErrno(PyExc_IOError);
1623 }
1624 else {
1625 _setSSLError(NULL, 0, __FILE__, __LINE__);
1626 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001627 goto error;
1628 }
1629 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001630 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001631 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1632 SSL_FILETYPE_PEM);
1633 PySSL_END_ALLOW_THREADS
1634 Py_XDECREF(keyfile_bytes);
1635 Py_XDECREF(certfile_bytes);
1636 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001637 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001638 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001639 PyErr_SetFromErrno(PyExc_IOError);
1640 }
1641 else {
1642 _setSSLError(NULL, 0, __FILE__, __LINE__);
1643 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001644 return NULL;
1645 }
1646 PySSL_BEGIN_ALLOW_THREADS
1647 r = SSL_CTX_check_private_key(self->ctx);
1648 PySSL_END_ALLOW_THREADS
1649 if (r != 1) {
1650 _setSSLError(NULL, 0, __FILE__, __LINE__);
1651 return NULL;
1652 }
1653 Py_RETURN_NONE;
1654
1655error:
1656 Py_XDECREF(keyfile_bytes);
1657 Py_XDECREF(certfile_bytes);
1658 return NULL;
1659}
1660
1661static PyObject *
1662load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1663{
1664 char *kwlist[] = {"cafile", "capath", NULL};
1665 PyObject *cafile = NULL, *capath = NULL;
1666 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1667 const char *cafile_buf = NULL, *capath_buf = NULL;
1668 int r;
1669
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001670 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001671 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1672 "|OO:load_verify_locations", kwlist,
1673 &cafile, &capath))
1674 return NULL;
1675 if (cafile == Py_None)
1676 cafile = NULL;
1677 if (capath == Py_None)
1678 capath = NULL;
1679 if (cafile == NULL && capath == NULL) {
1680 PyErr_SetString(PyExc_TypeError,
1681 "cafile and capath cannot be both omitted");
1682 return NULL;
1683 }
1684 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1685 PyErr_SetString(PyExc_TypeError,
1686 "cafile should be a valid filesystem path");
1687 return NULL;
1688 }
1689 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001690 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001691 PyErr_SetString(PyExc_TypeError,
1692 "capath should be a valid filesystem path");
1693 return NULL;
1694 }
1695 if (cafile)
1696 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1697 if (capath)
1698 capath_buf = PyBytes_AS_STRING(capath_bytes);
1699 PySSL_BEGIN_ALLOW_THREADS
1700 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1701 PySSL_END_ALLOW_THREADS
1702 Py_XDECREF(cafile_bytes);
1703 Py_XDECREF(capath_bytes);
1704 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001705 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001706 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001707 PyErr_SetFromErrno(PyExc_IOError);
1708 }
1709 else {
1710 _setSSLError(NULL, 0, __FILE__, __LINE__);
1711 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001712 return NULL;
1713 }
1714 Py_RETURN_NONE;
1715}
1716
1717static PyObject *
1718context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1719{
Antoine Pitroud5323212010-10-22 18:19:07 +00001720 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001721 PySocketSockObject *sock;
1722 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001723 char *hostname = NULL;
1724 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001725
Antoine Pitroud5323212010-10-22 18:19:07 +00001726 /* server_hostname is either None (or absent), or to be encoded
1727 using the idna encoding. */
1728 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001729 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001730 &sock, &server_side,
1731 Py_TYPE(Py_None), &hostname_obj)) {
1732 PyErr_Clear();
1733 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1734 PySocketModule.Sock_Type,
1735 &sock, &server_side,
1736 "idna", &hostname))
1737 return NULL;
1738#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1739 PyMem_Free(hostname);
1740 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1741 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001742 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001743#endif
1744 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001745
Antoine Pitroud5323212010-10-22 18:19:07 +00001746 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1747 hostname);
1748 if (hostname != NULL)
1749 PyMem_Free(hostname);
1750 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001751}
1752
Antoine Pitroub0182c82010-10-12 20:09:02 +00001753static PyObject *
1754session_stats(PySSLContext *self, PyObject *unused)
1755{
1756 int r;
1757 PyObject *value, *stats = PyDict_New();
1758 if (!stats)
1759 return NULL;
1760
1761#define ADD_STATS(SSL_NAME, KEY_NAME) \
1762 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1763 if (value == NULL) \
1764 goto error; \
1765 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1766 Py_DECREF(value); \
1767 if (r < 0) \
1768 goto error;
1769
1770 ADD_STATS(number, "number");
1771 ADD_STATS(connect, "connect");
1772 ADD_STATS(connect_good, "connect_good");
1773 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1774 ADD_STATS(accept, "accept");
1775 ADD_STATS(accept_good, "accept_good");
1776 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1777 ADD_STATS(accept, "accept");
1778 ADD_STATS(hits, "hits");
1779 ADD_STATS(misses, "misses");
1780 ADD_STATS(timeouts, "timeouts");
1781 ADD_STATS(cache_full, "cache_full");
1782
1783#undef ADD_STATS
1784
1785 return stats;
1786
1787error:
1788 Py_DECREF(stats);
1789 return NULL;
1790}
1791
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001792static PyObject *
1793set_default_verify_paths(PySSLContext *self, PyObject *unused)
1794{
1795 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1796 _setSSLError(NULL, 0, __FILE__, __LINE__);
1797 return NULL;
1798 }
1799 Py_RETURN_NONE;
1800}
1801
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001803 {"options", (getter) get_options,
1804 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001805 {"verify_mode", (getter) get_verify_mode,
1806 (setter) set_verify_mode, NULL},
1807 {NULL}, /* sentinel */
1808};
1809
1810static struct PyMethodDef context_methods[] = {
1811 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1812 METH_VARARGS | METH_KEYWORDS, NULL},
1813 {"set_ciphers", (PyCFunction) set_ciphers,
1814 METH_VARARGS, NULL},
1815 {"load_cert_chain", (PyCFunction) load_cert_chain,
1816 METH_VARARGS | METH_KEYWORDS, NULL},
1817 {"load_verify_locations", (PyCFunction) load_verify_locations,
1818 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001819 {"session_stats", (PyCFunction) session_stats,
1820 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001821 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1822 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001823 {NULL, NULL} /* sentinel */
1824};
1825
1826static PyTypeObject PySSLContext_Type = {
1827 PyVarObject_HEAD_INIT(NULL, 0)
1828 "_ssl._SSLContext", /*tp_name*/
1829 sizeof(PySSLContext), /*tp_basicsize*/
1830 0, /*tp_itemsize*/
1831 (destructor)context_dealloc, /*tp_dealloc*/
1832 0, /*tp_print*/
1833 0, /*tp_getattr*/
1834 0, /*tp_setattr*/
1835 0, /*tp_reserved*/
1836 0, /*tp_repr*/
1837 0, /*tp_as_number*/
1838 0, /*tp_as_sequence*/
1839 0, /*tp_as_mapping*/
1840 0, /*tp_hash*/
1841 0, /*tp_call*/
1842 0, /*tp_str*/
1843 0, /*tp_getattro*/
1844 0, /*tp_setattro*/
1845 0, /*tp_as_buffer*/
1846 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1847 0, /*tp_doc*/
1848 0, /*tp_traverse*/
1849 0, /*tp_clear*/
1850 0, /*tp_richcompare*/
1851 0, /*tp_weaklistoffset*/
1852 0, /*tp_iter*/
1853 0, /*tp_iternext*/
1854 context_methods, /*tp_methods*/
1855 0, /*tp_members*/
1856 context_getsetlist, /*tp_getset*/
1857 0, /*tp_base*/
1858 0, /*tp_dict*/
1859 0, /*tp_descr_get*/
1860 0, /*tp_descr_set*/
1861 0, /*tp_dictoffset*/
1862 0, /*tp_init*/
1863 0, /*tp_alloc*/
1864 context_new, /*tp_new*/
1865};
1866
1867
1868
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001869#ifdef HAVE_OPENSSL_RAND
1870
1871/* helper routines for seeding the SSL PRNG */
1872static PyObject *
1873PySSL_RAND_add(PyObject *self, PyObject *args)
1874{
1875 char *buf;
1876 int len;
1877 double entropy;
1878
1879 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001880 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001881 RAND_add(buf, len, entropy);
1882 Py_INCREF(Py_None);
1883 return Py_None;
1884}
1885
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001886PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001887"RAND_add(string, entropy)\n\
1888\n\
1889Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001891
1892static PyObject *
1893PySSL_RAND_status(PyObject *self)
1894{
Christian Heimes217cfd12007-12-02 14:31:20 +00001895 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001896}
1897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001898PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001899"RAND_status() -> 0 or 1\n\
1900\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001901Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1902It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1903using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001904
1905static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001906PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001907{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001908 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001909 int bytes;
1910
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001911 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1912 PyUnicode_FSConverter, &path))
1913 return NULL;
1914
1915 bytes = RAND_egd(PyBytes_AsString(path));
1916 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001917 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001918 PyErr_SetString(PySSLErrorObject,
1919 "EGD connection failed or EGD did not return "
1920 "enough data to seed the PRNG");
1921 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001922 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001923 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001924}
1925
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001926PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001927"RAND_egd(path) -> bytes\n\
1928\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001929Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1930Returns number of bytes read. Raises SSLError if connection to EGD\n\
1931fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001932
1933#endif
1934
Bill Janssen40a0f662008-08-12 16:56:25 +00001935
1936
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937/* List of functions exported by this module. */
1938
1939static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 {"_test_decode_cert", PySSL_test_decode_certificate,
1941 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1944 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001945 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 PySSL_RAND_egd_doc},
1947 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1948 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001949#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001951};
1952
1953
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001954#ifdef WITH_THREAD
1955
1956/* an implementation of OpenSSL threading operations in terms
1957 of the Python C thread library */
1958
1959static PyThread_type_lock *_ssl_locks = NULL;
1960
1961static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001963}
1964
Bill Janssen6e027db2007-11-15 22:23:56 +00001965static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 (int mode, int n, const char *file, int line) {
1967 /* this function is needed to perform locking on shared data
1968 structures. (Note that OpenSSL uses a number of global data
1969 structures that will be implicitly shared whenever multiple
1970 threads use OpenSSL.) Multi-threaded applications will
1971 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 locking_function() must be able to handle up to
1974 CRYPTO_num_locks() different mutex locks. It sets the n-th
1975 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 file and line are the file number of the function setting the
1978 lock. They can be useful for debugging.
1979 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 if ((_ssl_locks == NULL) ||
1982 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1983 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 if (mode & CRYPTO_LOCK) {
1986 PyThread_acquire_lock(_ssl_locks[n], 1);
1987 } else {
1988 PyThread_release_lock(_ssl_locks[n]);
1989 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001990}
1991
1992static int _setup_ssl_threads(void) {
1993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 if (_ssl_locks == NULL) {
1997 _ssl_locks_count = CRYPTO_num_locks();
1998 _ssl_locks = (PyThread_type_lock *)
1999 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2000 if (_ssl_locks == NULL)
2001 return 0;
2002 memset(_ssl_locks, 0,
2003 sizeof(PyThread_type_lock) * _ssl_locks_count);
2004 for (i = 0; i < _ssl_locks_count; i++) {
2005 _ssl_locks[i] = PyThread_allocate_lock();
2006 if (_ssl_locks[i] == NULL) {
2007 unsigned int j;
2008 for (j = 0; j < i; j++) {
2009 PyThread_free_lock(_ssl_locks[j]);
2010 }
2011 free(_ssl_locks);
2012 return 0;
2013 }
2014 }
2015 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2016 CRYPTO_set_id_callback(_ssl_thread_id_function);
2017 }
2018 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002019}
2020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002023PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002024"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002025for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002026
Martin v. Löwis1a214512008-06-11 05:26:20 +00002027
2028static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 PyModuleDef_HEAD_INIT,
2030 "_ssl",
2031 module_doc,
2032 -1,
2033 PySSL_methods,
2034 NULL,
2035 NULL,
2036 NULL,
2037 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002038};
2039
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002040
2041static void
2042parse_openssl_version(unsigned long libver,
2043 unsigned int *major, unsigned int *minor,
2044 unsigned int *fix, unsigned int *patch,
2045 unsigned int *status)
2046{
2047 *status = libver & 0xF;
2048 libver >>= 4;
2049 *patch = libver & 0xFF;
2050 libver >>= 8;
2051 *fix = libver & 0xFF;
2052 libver >>= 8;
2053 *minor = libver & 0xFF;
2054 libver >>= 8;
2055 *major = libver & 0xFF;
2056}
2057
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002058PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002059PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002060{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 PyObject *m, *d, *r;
2062 unsigned long libver;
2063 unsigned int major, minor, fix, patch, status;
2064 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002065
Antoine Pitrou152efa22010-05-16 18:19:27 +00002066 if (PyType_Ready(&PySSLContext_Type) < 0)
2067 return NULL;
2068 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002069 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 m = PyModule_Create(&_sslmodule);
2072 if (m == NULL)
2073 return NULL;
2074 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 /* Load _socket module and its C API */
2077 socket_api = PySocketModule_ImportModuleAndAPI();
2078 if (!socket_api)
2079 return NULL;
2080 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002081
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 /* Init OpenSSL */
2083 SSL_load_error_strings();
2084 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002085#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 /* note that this will start threading if not already started */
2087 if (!_setup_ssl_threads()) {
2088 return NULL;
2089 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002090#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 /* Add symbols to module dict */
2094 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2095 PySocketModule.error,
2096 NULL);
2097 if (PySSLErrorObject == NULL)
2098 return NULL;
2099 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2100 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002101 if (PyDict_SetItemString(d, "_SSLContext",
2102 (PyObject *)&PySSLContext_Type) != 0)
2103 return NULL;
2104 if (PyDict_SetItemString(d, "_SSLSocket",
2105 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 return NULL;
2107 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2108 PY_SSL_ERROR_ZERO_RETURN);
2109 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2110 PY_SSL_ERROR_WANT_READ);
2111 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2112 PY_SSL_ERROR_WANT_WRITE);
2113 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2114 PY_SSL_ERROR_WANT_X509_LOOKUP);
2115 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2116 PY_SSL_ERROR_SYSCALL);
2117 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2118 PY_SSL_ERROR_SSL);
2119 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2120 PY_SSL_ERROR_WANT_CONNECT);
2121 /* non ssl.h errorcodes */
2122 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2123 PY_SSL_ERROR_EOF);
2124 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2125 PY_SSL_ERROR_INVALID_ERROR_CODE);
2126 /* cert requirements */
2127 PyModule_AddIntConstant(m, "CERT_NONE",
2128 PY_SSL_CERT_NONE);
2129 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2130 PY_SSL_CERT_OPTIONAL);
2131 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2132 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002134 /* protocol versions */
Victor Stinneree18b6f2011-05-10 00:38:00 +02002135#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2137 PY_SSL_VERSION_SSL2);
Victor Stinneree18b6f2011-05-10 00:38:00 +02002138#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2140 PY_SSL_VERSION_SSL3);
2141 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2142 PY_SSL_VERSION_SSL23);
2143 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2144 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002145
Antoine Pitroub5218772010-05-21 09:56:06 +00002146 /* protocol options */
2147 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2148 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2149 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2150 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2151
Antoine Pitroud5323212010-10-22 18:19:07 +00002152#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2153 r = Py_True;
2154#else
2155 r = Py_False;
2156#endif
2157 Py_INCREF(r);
2158 PyModule_AddObject(m, "HAS_SNI", r);
2159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 /* OpenSSL version */
2161 /* SSLeay() gives us the version of the library linked against,
2162 which could be different from the headers version.
2163 */
2164 libver = SSLeay();
2165 r = PyLong_FromUnsignedLong(libver);
2166 if (r == NULL)
2167 return NULL;
2168 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2169 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002170 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2172 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2173 return NULL;
2174 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2175 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2176 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002177
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002178 libver = OPENSSL_VERSION_NUMBER;
2179 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2180 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2181 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2182 return NULL;
2183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002185}