blob: 3fa2d6ac36f2ec1d3ef26e12b72e0f3eb789a24e [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 */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100522 if (rdn != NULL) {
523 if (PyList_GET_SIZE(rdn) > 0) {
524 rdnt = PyList_AsTuple(rdn);
525 Py_DECREF(rdn);
526 if (rdnt == NULL)
527 goto fail0;
528 retcode = PyList_Append(dn, rdnt);
529 Py_DECREF(rdnt);
530 if (retcode < 0)
531 goto fail0;
532 }
533 else {
534 Py_DECREF(rdn);
535 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000536 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 /* convert list to tuple */
539 rdnt = PyList_AsTuple(dn);
540 Py_DECREF(dn);
541 if (rdnt == NULL)
542 return NULL;
543 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
545 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
548 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 Py_XDECREF(dn);
550 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551}
552
553static PyObject *
554_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 /* this code follows the procedure outlined in
557 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
558 function to extract the STACK_OF(GENERAL_NAME),
559 then iterates through the stack to add the
560 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 int i, j;
563 PyObject *peer_alt_names = Py_None;
564 PyObject *v, *t;
565 X509_EXTENSION *ext = NULL;
566 GENERAL_NAMES *names = NULL;
567 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000568 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 BIO *biobuf = NULL;
570 char buf[2048];
571 char *vptr;
572 int len;
573 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000574#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000576#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000578#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 if (certificate == NULL)
581 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 /* get a memory buffer */
584 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200586 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 while ((i = X509_get_ext_by_NID(
588 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 if (peer_alt_names == Py_None) {
591 peer_alt_names = PyList_New(0);
592 if (peer_alt_names == NULL)
593 goto fail;
594 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 /* now decode the altName */
597 ext = X509_get_ext(certificate, i);
598 if(!(method = X509V3_EXT_get(ext))) {
599 PyErr_SetString
600 (PySSLErrorObject,
601 ERRSTR("No method for internalizing subjectAltName!"));
602 goto fail;
603 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 p = ext->value->data;
606 if (method->it)
607 names = (GENERAL_NAMES*)
608 (ASN1_item_d2i(NULL,
609 &p,
610 ext->value->length,
611 ASN1_ITEM_ptr(method->it)));
612 else
613 names = (GENERAL_NAMES*)
614 (method->d2i(NULL,
615 &p,
616 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 name = sk_GENERAL_NAME_value(names, j);
623 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 /* we special-case DirName as a tuple of
626 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 t = PyTuple_New(2);
629 if (t == NULL) {
630 goto fail;
631 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 v = PyUnicode_FromString("DirName");
634 if (v == NULL) {
635 Py_DECREF(t);
636 goto fail;
637 }
638 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 v = _create_tuple_for_X509_NAME (name->d.dirn);
641 if (v == NULL) {
642 Py_DECREF(t);
643 goto fail;
644 }
645 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 (void) BIO_reset(biobuf);
652 GENERAL_NAME_print(biobuf, name);
653 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
654 if (len < 0) {
655 _setSSLError(NULL, 0, __FILE__, __LINE__);
656 goto fail;
657 }
658 vptr = strchr(buf, ':');
659 if (vptr == NULL)
660 goto fail;
661 t = PyTuple_New(2);
662 if (t == NULL)
663 goto fail;
664 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
665 if (v == NULL) {
666 Py_DECREF(t);
667 goto fail;
668 }
669 PyTuple_SET_ITEM(t, 0, v);
670 v = PyUnicode_FromStringAndSize((vptr + 1),
671 (len - (vptr - buf + 1)));
672 if (v == NULL) {
673 Py_DECREF(t);
674 goto fail;
675 }
676 PyTuple_SET_ITEM(t, 1, v);
677 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 if (PyList_Append(peer_alt_names, t) < 0) {
682 Py_DECREF(t);
683 goto fail;
684 }
685 Py_DECREF(t);
686 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100687 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000688 }
689 BIO_free(biobuf);
690 if (peer_alt_names != Py_None) {
691 v = PyList_AsTuple(peer_alt_names);
692 Py_DECREF(peer_alt_names);
693 return v;
694 } else {
695 return peer_alt_names;
696 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000697
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
699 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 if (biobuf != NULL)
701 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000703 if (peer_alt_names != Py_None) {
704 Py_XDECREF(peer_alt_names);
705 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708}
709
710static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000711_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 PyObject *retval = NULL;
714 BIO *biobuf = NULL;
715 PyObject *peer;
716 PyObject *peer_alt_names = NULL;
717 PyObject *issuer;
718 PyObject *version;
719 PyObject *sn_obj;
720 ASN1_INTEGER *serialNumber;
721 char buf[2048];
722 int len;
723 ASN1_TIME *notBefore, *notAfter;
724 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 retval = PyDict_New();
727 if (retval == NULL)
728 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 peer = _create_tuple_for_X509_NAME(
731 X509_get_subject_name(certificate));
732 if (peer == NULL)
733 goto fail0;
734 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
735 Py_DECREF(peer);
736 goto fail0;
737 }
738 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Antoine Pitroufb046912010-11-09 20:21:19 +0000740 issuer = _create_tuple_for_X509_NAME(
741 X509_get_issuer_name(certificate));
742 if (issuer == NULL)
743 goto fail0;
744 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000746 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000748 Py_DECREF(issuer);
749
750 version = PyLong_FromLong(X509_get_version(certificate) + 1);
751 if (PyDict_SetItemString(retval, "version", version) < 0) {
752 Py_DECREF(version);
753 goto fail0;
754 }
755 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 /* get a memory buffer */
758 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000759
Antoine Pitroufb046912010-11-09 20:21:19 +0000760 (void) BIO_reset(biobuf);
761 serialNumber = X509_get_serialNumber(certificate);
762 /* should not exceed 20 octets, 160 bits, so buf is big enough */
763 i2a_ASN1_INTEGER(biobuf, serialNumber);
764 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
765 if (len < 0) {
766 _setSSLError(NULL, 0, __FILE__, __LINE__);
767 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000769 sn_obj = PyUnicode_FromStringAndSize(buf, len);
770 if (sn_obj == NULL)
771 goto fail1;
772 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
773 Py_DECREF(sn_obj);
774 goto fail1;
775 }
776 Py_DECREF(sn_obj);
777
778 (void) BIO_reset(biobuf);
779 notBefore = X509_get_notBefore(certificate);
780 ASN1_TIME_print(biobuf, notBefore);
781 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
782 if (len < 0) {
783 _setSSLError(NULL, 0, __FILE__, __LINE__);
784 goto fail1;
785 }
786 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
787 if (pnotBefore == NULL)
788 goto fail1;
789 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
790 Py_DECREF(pnotBefore);
791 goto fail1;
792 }
793 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 (void) BIO_reset(biobuf);
796 notAfter = X509_get_notAfter(certificate);
797 ASN1_TIME_print(biobuf, notAfter);
798 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
799 if (len < 0) {
800 _setSSLError(NULL, 0, __FILE__, __LINE__);
801 goto fail1;
802 }
803 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
804 if (pnotAfter == NULL)
805 goto fail1;
806 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
807 Py_DECREF(pnotAfter);
808 goto fail1;
809 }
810 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 peer_alt_names = _get_peer_alt_names(certificate);
815 if (peer_alt_names == NULL)
816 goto fail1;
817 else if (peer_alt_names != Py_None) {
818 if (PyDict_SetItemString(retval, "subjectAltName",
819 peer_alt_names) < 0) {
820 Py_DECREF(peer_alt_names);
821 goto fail1;
822 }
823 Py_DECREF(peer_alt_names);
824 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 BIO_free(biobuf);
827 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000828
829 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 if (biobuf != NULL)
831 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000832 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 Py_XDECREF(retval);
834 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000835}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000836
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
838static PyObject *
839PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000842 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 X509 *x=NULL;
844 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845
Antoine Pitroufb046912010-11-09 20:21:19 +0000846 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
847 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 if ((cert=BIO_new(BIO_s_file())) == NULL) {
851 PyErr_SetString(PySSLErrorObject,
852 "Can't malloc memory to read file");
853 goto fail0;
854 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Victor Stinner3800e1e2010-05-16 21:23:48 +0000856 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 PyErr_SetString(PySSLErrorObject,
858 "Can't open file");
859 goto fail0;
860 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
863 if (x == NULL) {
864 PyErr_SetString(PySSLErrorObject,
865 "Error decoding PEM-encoded file");
866 goto fail0;
867 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868
Antoine Pitroufb046912010-11-09 20:21:19 +0000869 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000870 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
872 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000873 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000874 if (cert != NULL) BIO_free(cert);
875 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876}
877
878
879static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000880PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 PyObject *retval = NULL;
883 int len;
884 int verification;
885 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
888 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 if (!self->peer_cert)
891 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 if (PyObject_IsTrue(binary_mode)) {
894 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 bytes_buf = NULL;
899 len = i2d_X509(self->peer_cert, &bytes_buf);
900 if (len < 0) {
901 PySSL_SetError(self, len, __FILE__, __LINE__);
902 return NULL;
903 }
904 /* this is actually an immutable bytes sequence */
905 retval = PyBytes_FromStringAndSize
906 ((const char *) bytes_buf, len);
907 OPENSSL_free(bytes_buf);
908 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000911 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 if ((verification & SSL_VERIFY_PEER) == 0)
913 return PyDict_New();
914 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000915 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917}
918
919PyDoc_STRVAR(PySSL_peercert_doc,
920"peer_certificate([der=False]) -> certificate\n\
921\n\
922Returns the certificate for the peer. If no certificate was provided,\n\
923returns None. If a certificate was provided, but not validated, returns\n\
924an empty dictionary. Otherwise returns a dict containing information\n\
925about the peer certificate.\n\
926\n\
927If the optional argument is True, returns a DER-encoded copy of the\n\
928peer certificate, or None if no certificate was provided. This will\n\
929return the certificate even if it wasn't validated.");
930
Antoine Pitrou152efa22010-05-16 18:19:27 +0000931static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000934 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 char *cipher_name;
936 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000939 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 current = SSL_get_current_cipher(self->ssl);
941 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000942 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 retval = PyTuple_New(3);
945 if (retval == NULL)
946 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 cipher_name = (char *) SSL_CIPHER_get_name(current);
949 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000950 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 PyTuple_SET_ITEM(retval, 0, Py_None);
952 } else {
953 v = PyUnicode_FromString(cipher_name);
954 if (v == NULL)
955 goto fail0;
956 PyTuple_SET_ITEM(retval, 0, v);
957 }
958 cipher_protocol = SSL_CIPHER_get_version(current);
959 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000960 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PyTuple_SET_ITEM(retval, 1, Py_None);
962 } else {
963 v = PyUnicode_FromString(cipher_protocol);
964 if (v == NULL)
965 goto fail0;
966 PyTuple_SET_ITEM(retval, 1, v);
967 }
968 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
969 if (v == NULL)
970 goto fail0;
971 PyTuple_SET_ITEM(retval, 2, v);
972 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 Py_DECREF(retval);
976 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977}
978
Antoine Pitrou152efa22010-05-16 18:19:27 +0000979static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000980{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 if (self->peer_cert) /* Possible not to have one? */
982 X509_free (self->peer_cert);
983 if (self->ssl)
984 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 Py_XDECREF(self->Socket);
986 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000987}
988
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000990 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000991 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000992 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000993
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000994static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000995check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000996{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 fd_set fds;
998 struct timeval tv;
999 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1002 if (s->sock_timeout < 0.0)
1003 return SOCKET_IS_BLOCKING;
1004 else if (s->sock_timeout == 0.0)
1005 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* Guard against closed socket */
1008 if (s->sock_fd < 0)
1009 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 /* Prefer poll, if available, since you can poll() any fd
1012 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001013#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 {
1015 struct pollfd pollfd;
1016 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 pollfd.fd = s->sock_fd;
1019 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 /* s->sock_timeout is in seconds, timeout in ms */
1022 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1023 PySSL_BEGIN_ALLOW_THREADS
1024 rc = poll(&pollfd, 1, timeout);
1025 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 goto normal_return;
1028 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029#endif
1030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001032 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001034
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 /* Construct the arguments to select */
1036 tv.tv_sec = (int)s->sock_timeout;
1037 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1038 FD_ZERO(&fds);
1039 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001040
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 /* See if the socket is ready */
1042 PySSL_BEGIN_ALLOW_THREADS
1043 if (writing)
1044 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1045 else
1046 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1047 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001048
Bill Janssen6e027db2007-11-15 22:23:56 +00001049#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001050normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001051#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1053 (when we are able to write or when there's something to read) */
1054 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001055}
1056
Antoine Pitrou152efa22010-05-16 18:19:27 +00001057static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001058{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 Py_buffer buf;
1060 int len;
1061 int sockstate;
1062 int err;
1063 int nonblocking;
1064 PySocketSockObject *sock
1065 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 if (((PyObject*)sock) == Py_None) {
1068 _setSSLError("Underlying socket connection gone",
1069 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1070 return NULL;
1071 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001072 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001074 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1075 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001077 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078
1079 /* just in case the blocking state of the socket has been changed */
1080 nonblocking = (sock->sock_timeout >= 0.0);
1081 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1082 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1083
1084 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1085 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001086 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 "The write operation timed out");
1088 goto error;
1089 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1090 PyErr_SetString(PySSLErrorObject,
1091 "Underlying socket has been closed.");
1092 goto error;
1093 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1094 PyErr_SetString(PySSLErrorObject,
1095 "Underlying socket too large for select().");
1096 goto error;
1097 }
1098 do {
1099 err = 0;
1100 PySSL_BEGIN_ALLOW_THREADS
1101 len = SSL_write(self->ssl, buf.buf, buf.len);
1102 err = SSL_get_error(self->ssl, len);
1103 PySSL_END_ALLOW_THREADS
1104 if (PyErr_CheckSignals()) {
1105 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001106 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001108 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001110 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 } else {
1112 sockstate = SOCKET_OPERATION_OK;
1113 }
1114 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001115 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 "The write operation timed out");
1117 goto error;
1118 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1119 PyErr_SetString(PySSLErrorObject,
1120 "Underlying socket has been closed.");
1121 goto error;
1122 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1123 break;
1124 }
1125 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001126
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 PyBuffer_Release(&buf);
1129 if (len > 0)
1130 return PyLong_FromLong(len);
1131 else
1132 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001133
1134error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001135 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 PyBuffer_Release(&buf);
1137 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001138}
1139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001140PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001141"write(s) -> len\n\
1142\n\
1143Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001144of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001145
Antoine Pitrou152efa22010-05-16 18:19:27 +00001146static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001147{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 PySSL_BEGIN_ALLOW_THREADS
1151 count = SSL_pending(self->ssl);
1152 PySSL_END_ALLOW_THREADS
1153 if (count < 0)
1154 return PySSL_SetError(self, count, __FILE__, __LINE__);
1155 else
1156 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001157}
1158
1159PyDoc_STRVAR(PySSL_SSLpending_doc,
1160"pending() -> count\n\
1161\n\
1162Returns the number of already decrypted bytes available for read,\n\
1163pending on the connection.\n");
1164
Antoine Pitrou152efa22010-05-16 18:19:27 +00001165static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001166{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 PyObject *dest = NULL;
1168 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001170 int len, count;
1171 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 int sockstate;
1173 int err;
1174 int nonblocking;
1175 PySocketSockObject *sock
1176 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 if (((PyObject*)sock) == Py_None) {
1179 _setSSLError("Underlying socket connection gone",
1180 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1181 return NULL;
1182 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001183 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001185 buf.obj = NULL;
1186 buf.buf = NULL;
1187 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001188 goto error;
1189
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001190 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1191 dest = PyBytes_FromStringAndSize(NULL, len);
1192 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001193 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001194 mem = PyBytes_AS_STRING(dest);
1195 }
1196 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001198 mem = buf.buf;
1199 if (len <= 0 || len > buf.len) {
1200 len = (int) buf.len;
1201 if (buf.len != len) {
1202 PyErr_SetString(PyExc_OverflowError,
1203 "maximum length can't fit in a C 'int'");
1204 goto error;
1205 }
1206 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 }
1208
1209 /* just in case the blocking state of the socket has been changed */
1210 nonblocking = (sock->sock_timeout >= 0.0);
1211 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1212 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1213
1214 /* first check if there are bytes ready to be read */
1215 PySSL_BEGIN_ALLOW_THREADS
1216 count = SSL_pending(self->ssl);
1217 PySSL_END_ALLOW_THREADS
1218
1219 if (!count) {
1220 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1221 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001222 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 "The read operation timed out");
1224 goto error;
1225 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1226 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001227 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 goto error;
1229 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1230 count = 0;
1231 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001232 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 }
1234 do {
1235 err = 0;
1236 PySSL_BEGIN_ALLOW_THREADS
1237 count = SSL_read(self->ssl, mem, len);
1238 err = SSL_get_error(self->ssl, count);
1239 PySSL_END_ALLOW_THREADS
1240 if (PyErr_CheckSignals())
1241 goto error;
1242 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001243 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001245 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1247 (SSL_get_shutdown(self->ssl) ==
1248 SSL_RECEIVED_SHUTDOWN))
1249 {
1250 count = 0;
1251 goto done;
1252 } else {
1253 sockstate = SOCKET_OPERATION_OK;
1254 }
1255 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001256 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 "The read operation timed out");
1258 goto error;
1259 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1260 break;
1261 }
1262 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1263 if (count <= 0) {
1264 PySSL_SetError(self, count, __FILE__, __LINE__);
1265 goto error;
1266 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001267
1268done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001269 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001271 _PyBytes_Resize(&dest, count);
1272 return dest;
1273 }
1274 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 PyBuffer_Release(&buf);
1276 return PyLong_FromLong(count);
1277 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001278
1279error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001280 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001281 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001282 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001283 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001286}
1287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001288PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001289"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001290\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001291Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001292
Antoine Pitrou152efa22010-05-16 18:19:27 +00001293static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001294{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 int err, ssl_err, sockstate, nonblocking;
1296 int zeros = 0;
1297 PySocketSockObject *sock
1298 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 /* Guard against closed socket */
1301 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1302 _setSSLError("Underlying socket connection gone",
1303 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1304 return NULL;
1305 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001306 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307
1308 /* Just in case the blocking state of the socket has been changed */
1309 nonblocking = (sock->sock_timeout >= 0.0);
1310 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1311 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1312
1313 while (1) {
1314 PySSL_BEGIN_ALLOW_THREADS
1315 /* Disable read-ahead so that unwrap can work correctly.
1316 * Otherwise OpenSSL might read in too much data,
1317 * eating clear text data that happens to be
1318 * transmitted after the SSL shutdown.
1319 * Should be safe to call repeatedly everytime this
1320 * function is used and the shutdown_seen_zero != 0
1321 * condition is met.
1322 */
1323 if (self->shutdown_seen_zero)
1324 SSL_set_read_ahead(self->ssl, 0);
1325 err = SSL_shutdown(self->ssl);
1326 PySSL_END_ALLOW_THREADS
1327 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1328 if (err > 0)
1329 break;
1330 if (err == 0) {
1331 /* Don't loop endlessly; instead preserve legacy
1332 behaviour of trying SSL_shutdown() only twice.
1333 This looks necessary for OpenSSL < 0.9.8m */
1334 if (++zeros > 1)
1335 break;
1336 /* Shutdown was sent, now try receiving */
1337 self->shutdown_seen_zero = 1;
1338 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001339 }
1340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 /* Possibly retry shutdown until timeout or failure */
1342 ssl_err = SSL_get_error(self->ssl, err);
1343 if (ssl_err == SSL_ERROR_WANT_READ)
1344 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1345 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1346 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1347 else
1348 break;
1349 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1350 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001351 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 "The read operation timed out");
1353 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001354 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001356 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 }
1358 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1359 PyErr_SetString(PySSLErrorObject,
1360 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001361 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 }
1363 else if (sockstate != SOCKET_OPERATION_OK)
1364 /* Retain the SSL error code */
1365 break;
1366 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001367
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001368 if (err < 0) {
1369 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001372 else
1373 /* It's already INCREF'ed */
1374 return (PyObject *) sock;
1375
1376error:
1377 Py_DECREF(sock);
1378 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001379}
1380
1381PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1382"shutdown(s) -> socket\n\
1383\n\
1384Does the SSL shutdown handshake with the remote end, and returns\n\
1385the underlying socket object.");
1386
1387
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001388static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1390 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1391 PySSL_SSLwrite_doc},
1392 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1393 PySSL_SSLread_doc},
1394 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1395 PySSL_SSLpending_doc},
1396 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1397 PySSL_peercert_doc},
1398 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1399 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1400 PySSL_SSLshutdown_doc},
1401 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001402};
1403
Antoine Pitrou152efa22010-05-16 18:19:27 +00001404static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001406 "_ssl._SSLSocket", /*tp_name*/
1407 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 0, /*tp_itemsize*/
1409 /* methods */
1410 (destructor)PySSL_dealloc, /*tp_dealloc*/
1411 0, /*tp_print*/
1412 0, /*tp_getattr*/
1413 0, /*tp_setattr*/
1414 0, /*tp_reserved*/
1415 0, /*tp_repr*/
1416 0, /*tp_as_number*/
1417 0, /*tp_as_sequence*/
1418 0, /*tp_as_mapping*/
1419 0, /*tp_hash*/
1420 0, /*tp_call*/
1421 0, /*tp_str*/
1422 0, /*tp_getattro*/
1423 0, /*tp_setattro*/
1424 0, /*tp_as_buffer*/
1425 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1426 0, /*tp_doc*/
1427 0, /*tp_traverse*/
1428 0, /*tp_clear*/
1429 0, /*tp_richcompare*/
1430 0, /*tp_weaklistoffset*/
1431 0, /*tp_iter*/
1432 0, /*tp_iternext*/
1433 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001434};
1435
Antoine Pitrou152efa22010-05-16 18:19:27 +00001436
1437/*
1438 * _SSLContext objects
1439 */
1440
1441static PyObject *
1442context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1443{
1444 char *kwlist[] = {"protocol", NULL};
1445 PySSLContext *self;
1446 int proto_version = PY_SSL_VERSION_SSL23;
1447 SSL_CTX *ctx = NULL;
1448
1449 if (!PyArg_ParseTupleAndKeywords(
1450 args, kwds, "i:_SSLContext", kwlist,
1451 &proto_version))
1452 return NULL;
1453
1454 PySSL_BEGIN_ALLOW_THREADS
1455 if (proto_version == PY_SSL_VERSION_TLS1)
1456 ctx = SSL_CTX_new(TLSv1_method());
1457 else if (proto_version == PY_SSL_VERSION_SSL3)
1458 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001459#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001460 else if (proto_version == PY_SSL_VERSION_SSL2)
1461 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner17ca3232011-05-10 00:48:41 +02001462#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001463 else if (proto_version == PY_SSL_VERSION_SSL23)
1464 ctx = SSL_CTX_new(SSLv23_method());
1465 else
1466 proto_version = -1;
1467 PySSL_END_ALLOW_THREADS
1468
1469 if (proto_version == -1) {
1470 PyErr_SetString(PyExc_ValueError,
1471 "invalid protocol version");
1472 return NULL;
1473 }
1474 if (ctx == NULL) {
1475 PyErr_SetString(PySSLErrorObject,
1476 "failed to allocate SSL context");
1477 return NULL;
1478 }
1479
1480 assert(type != NULL && type->tp_alloc != NULL);
1481 self = (PySSLContext *) type->tp_alloc(type, 0);
1482 if (self == NULL) {
1483 SSL_CTX_free(ctx);
1484 return NULL;
1485 }
1486 self->ctx = ctx;
1487 /* Defaults */
1488 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001489 SSL_CTX_set_options(self->ctx,
1490 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001491
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001492#define SID_CTX "Python"
1493 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1494 sizeof(SID_CTX));
1495#undef SID_CTX
1496
Antoine Pitrou152efa22010-05-16 18:19:27 +00001497 return (PyObject *)self;
1498}
1499
1500static void
1501context_dealloc(PySSLContext *self)
1502{
1503 SSL_CTX_free(self->ctx);
1504 Py_TYPE(self)->tp_free(self);
1505}
1506
1507static PyObject *
1508set_ciphers(PySSLContext *self, PyObject *args)
1509{
1510 int ret;
1511 const char *cipherlist;
1512
1513 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1514 return NULL;
1515 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1516 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001517 /* Clearing the error queue is necessary on some OpenSSL versions,
1518 otherwise the error will be reported again when another SSL call
1519 is done. */
1520 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001521 PyErr_SetString(PySSLErrorObject,
1522 "No cipher can be selected.");
1523 return NULL;
1524 }
1525 Py_RETURN_NONE;
1526}
1527
1528static PyObject *
1529get_verify_mode(PySSLContext *self, void *c)
1530{
1531 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1532 case SSL_VERIFY_NONE:
1533 return PyLong_FromLong(PY_SSL_CERT_NONE);
1534 case SSL_VERIFY_PEER:
1535 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1536 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1537 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1538 }
1539 PyErr_SetString(PySSLErrorObject,
1540 "invalid return value from SSL_CTX_get_verify_mode");
1541 return NULL;
1542}
1543
1544static int
1545set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1546{
1547 int n, mode;
1548 if (!PyArg_Parse(arg, "i", &n))
1549 return -1;
1550 if (n == PY_SSL_CERT_NONE)
1551 mode = SSL_VERIFY_NONE;
1552 else if (n == PY_SSL_CERT_OPTIONAL)
1553 mode = SSL_VERIFY_PEER;
1554 else if (n == PY_SSL_CERT_REQUIRED)
1555 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1556 else {
1557 PyErr_SetString(PyExc_ValueError,
1558 "invalid value for verify_mode");
1559 return -1;
1560 }
1561 SSL_CTX_set_verify(self->ctx, mode, NULL);
1562 return 0;
1563}
1564
1565static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001566get_options(PySSLContext *self, void *c)
1567{
1568 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1569}
1570
1571static int
1572set_options(PySSLContext *self, PyObject *arg, void *c)
1573{
1574 long new_opts, opts, set, clear;
1575 if (!PyArg_Parse(arg, "l", &new_opts))
1576 return -1;
1577 opts = SSL_CTX_get_options(self->ctx);
1578 clear = opts & ~new_opts;
1579 set = ~opts & new_opts;
1580 if (clear) {
1581#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1582 SSL_CTX_clear_options(self->ctx, clear);
1583#else
1584 PyErr_SetString(PyExc_ValueError,
1585 "can't clear options before OpenSSL 0.9.8m");
1586 return -1;
1587#endif
1588 }
1589 if (set)
1590 SSL_CTX_set_options(self->ctx, set);
1591 return 0;
1592}
1593
1594static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001595load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1596{
1597 char *kwlist[] = {"certfile", "keyfile", NULL};
1598 PyObject *certfile, *keyfile = NULL;
1599 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1600 int r;
1601
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001602 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001603 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001604 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1605 "O|O:load_cert_chain", kwlist,
1606 &certfile, &keyfile))
1607 return NULL;
1608 if (keyfile == Py_None)
1609 keyfile = NULL;
1610 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1611 PyErr_SetString(PyExc_TypeError,
1612 "certfile should be a valid filesystem path");
1613 return NULL;
1614 }
1615 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1616 PyErr_SetString(PyExc_TypeError,
1617 "keyfile should be a valid filesystem path");
1618 goto error;
1619 }
1620 PySSL_BEGIN_ALLOW_THREADS
1621 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1622 PyBytes_AS_STRING(certfile_bytes));
1623 PySSL_END_ALLOW_THREADS
1624 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001625 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001626 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001627 PyErr_SetFromErrno(PyExc_IOError);
1628 }
1629 else {
1630 _setSSLError(NULL, 0, __FILE__, __LINE__);
1631 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001632 goto error;
1633 }
1634 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001635 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001636 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1637 SSL_FILETYPE_PEM);
1638 PySSL_END_ALLOW_THREADS
1639 Py_XDECREF(keyfile_bytes);
1640 Py_XDECREF(certfile_bytes);
1641 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001642 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001643 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001644 PyErr_SetFromErrno(PyExc_IOError);
1645 }
1646 else {
1647 _setSSLError(NULL, 0, __FILE__, __LINE__);
1648 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001649 return NULL;
1650 }
1651 PySSL_BEGIN_ALLOW_THREADS
1652 r = SSL_CTX_check_private_key(self->ctx);
1653 PySSL_END_ALLOW_THREADS
1654 if (r != 1) {
1655 _setSSLError(NULL, 0, __FILE__, __LINE__);
1656 return NULL;
1657 }
1658 Py_RETURN_NONE;
1659
1660error:
1661 Py_XDECREF(keyfile_bytes);
1662 Py_XDECREF(certfile_bytes);
1663 return NULL;
1664}
1665
1666static PyObject *
1667load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1668{
1669 char *kwlist[] = {"cafile", "capath", NULL};
1670 PyObject *cafile = NULL, *capath = NULL;
1671 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1672 const char *cafile_buf = NULL, *capath_buf = NULL;
1673 int r;
1674
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001675 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001676 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1677 "|OO:load_verify_locations", kwlist,
1678 &cafile, &capath))
1679 return NULL;
1680 if (cafile == Py_None)
1681 cafile = NULL;
1682 if (capath == Py_None)
1683 capath = NULL;
1684 if (cafile == NULL && capath == NULL) {
1685 PyErr_SetString(PyExc_TypeError,
1686 "cafile and capath cannot be both omitted");
1687 return NULL;
1688 }
1689 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1690 PyErr_SetString(PyExc_TypeError,
1691 "cafile should be a valid filesystem path");
1692 return NULL;
1693 }
1694 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001695 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001696 PyErr_SetString(PyExc_TypeError,
1697 "capath should be a valid filesystem path");
1698 return NULL;
1699 }
1700 if (cafile)
1701 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1702 if (capath)
1703 capath_buf = PyBytes_AS_STRING(capath_bytes);
1704 PySSL_BEGIN_ALLOW_THREADS
1705 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1706 PySSL_END_ALLOW_THREADS
1707 Py_XDECREF(cafile_bytes);
1708 Py_XDECREF(capath_bytes);
1709 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001710 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001711 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001712 PyErr_SetFromErrno(PyExc_IOError);
1713 }
1714 else {
1715 _setSSLError(NULL, 0, __FILE__, __LINE__);
1716 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001717 return NULL;
1718 }
1719 Py_RETURN_NONE;
1720}
1721
1722static PyObject *
1723context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1724{
Antoine Pitroud5323212010-10-22 18:19:07 +00001725 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001726 PySocketSockObject *sock;
1727 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001728 char *hostname = NULL;
1729 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001730
Antoine Pitroud5323212010-10-22 18:19:07 +00001731 /* server_hostname is either None (or absent), or to be encoded
1732 using the idna encoding. */
1733 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001734 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001735 &sock, &server_side,
1736 Py_TYPE(Py_None), &hostname_obj)) {
1737 PyErr_Clear();
1738 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1739 PySocketModule.Sock_Type,
1740 &sock, &server_side,
1741 "idna", &hostname))
1742 return NULL;
1743#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1744 PyMem_Free(hostname);
1745 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1746 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001747 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001748#endif
1749 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001750
Antoine Pitroud5323212010-10-22 18:19:07 +00001751 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1752 hostname);
1753 if (hostname != NULL)
1754 PyMem_Free(hostname);
1755 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001756}
1757
Antoine Pitroub0182c82010-10-12 20:09:02 +00001758static PyObject *
1759session_stats(PySSLContext *self, PyObject *unused)
1760{
1761 int r;
1762 PyObject *value, *stats = PyDict_New();
1763 if (!stats)
1764 return NULL;
1765
1766#define ADD_STATS(SSL_NAME, KEY_NAME) \
1767 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1768 if (value == NULL) \
1769 goto error; \
1770 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1771 Py_DECREF(value); \
1772 if (r < 0) \
1773 goto error;
1774
1775 ADD_STATS(number, "number");
1776 ADD_STATS(connect, "connect");
1777 ADD_STATS(connect_good, "connect_good");
1778 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1779 ADD_STATS(accept, "accept");
1780 ADD_STATS(accept_good, "accept_good");
1781 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1782 ADD_STATS(accept, "accept");
1783 ADD_STATS(hits, "hits");
1784 ADD_STATS(misses, "misses");
1785 ADD_STATS(timeouts, "timeouts");
1786 ADD_STATS(cache_full, "cache_full");
1787
1788#undef ADD_STATS
1789
1790 return stats;
1791
1792error:
1793 Py_DECREF(stats);
1794 return NULL;
1795}
1796
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001797static PyObject *
1798set_default_verify_paths(PySSLContext *self, PyObject *unused)
1799{
1800 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1801 _setSSLError(NULL, 0, __FILE__, __LINE__);
1802 return NULL;
1803 }
1804 Py_RETURN_NONE;
1805}
1806
Antoine Pitrou152efa22010-05-16 18:19:27 +00001807static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001808 {"options", (getter) get_options,
1809 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001810 {"verify_mode", (getter) get_verify_mode,
1811 (setter) set_verify_mode, NULL},
1812 {NULL}, /* sentinel */
1813};
1814
1815static struct PyMethodDef context_methods[] = {
1816 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1817 METH_VARARGS | METH_KEYWORDS, NULL},
1818 {"set_ciphers", (PyCFunction) set_ciphers,
1819 METH_VARARGS, NULL},
1820 {"load_cert_chain", (PyCFunction) load_cert_chain,
1821 METH_VARARGS | METH_KEYWORDS, NULL},
1822 {"load_verify_locations", (PyCFunction) load_verify_locations,
1823 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001824 {"session_stats", (PyCFunction) session_stats,
1825 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001826 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1827 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001828 {NULL, NULL} /* sentinel */
1829};
1830
1831static PyTypeObject PySSLContext_Type = {
1832 PyVarObject_HEAD_INIT(NULL, 0)
1833 "_ssl._SSLContext", /*tp_name*/
1834 sizeof(PySSLContext), /*tp_basicsize*/
1835 0, /*tp_itemsize*/
1836 (destructor)context_dealloc, /*tp_dealloc*/
1837 0, /*tp_print*/
1838 0, /*tp_getattr*/
1839 0, /*tp_setattr*/
1840 0, /*tp_reserved*/
1841 0, /*tp_repr*/
1842 0, /*tp_as_number*/
1843 0, /*tp_as_sequence*/
1844 0, /*tp_as_mapping*/
1845 0, /*tp_hash*/
1846 0, /*tp_call*/
1847 0, /*tp_str*/
1848 0, /*tp_getattro*/
1849 0, /*tp_setattro*/
1850 0, /*tp_as_buffer*/
1851 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1852 0, /*tp_doc*/
1853 0, /*tp_traverse*/
1854 0, /*tp_clear*/
1855 0, /*tp_richcompare*/
1856 0, /*tp_weaklistoffset*/
1857 0, /*tp_iter*/
1858 0, /*tp_iternext*/
1859 context_methods, /*tp_methods*/
1860 0, /*tp_members*/
1861 context_getsetlist, /*tp_getset*/
1862 0, /*tp_base*/
1863 0, /*tp_dict*/
1864 0, /*tp_descr_get*/
1865 0, /*tp_descr_set*/
1866 0, /*tp_dictoffset*/
1867 0, /*tp_init*/
1868 0, /*tp_alloc*/
1869 context_new, /*tp_new*/
1870};
1871
1872
1873
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001874#ifdef HAVE_OPENSSL_RAND
1875
1876/* helper routines for seeding the SSL PRNG */
1877static PyObject *
1878PySSL_RAND_add(PyObject *self, PyObject *args)
1879{
1880 char *buf;
1881 int len;
1882 double entropy;
1883
1884 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001885 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001886 RAND_add(buf, len, entropy);
1887 Py_INCREF(Py_None);
1888 return Py_None;
1889}
1890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001892"RAND_add(string, entropy)\n\
1893\n\
1894Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001895bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001896
1897static PyObject *
1898PySSL_RAND_status(PyObject *self)
1899{
Christian Heimes217cfd12007-12-02 14:31:20 +00001900 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001901}
1902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001903PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001904"RAND_status() -> 0 or 1\n\
1905\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001906Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1907It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1908using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001909
1910static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001911PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001912{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001913 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001914 int bytes;
1915
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001916 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1917 PyUnicode_FSConverter, &path))
1918 return NULL;
1919
1920 bytes = RAND_egd(PyBytes_AsString(path));
1921 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001922 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001923 PyErr_SetString(PySSLErrorObject,
1924 "EGD connection failed or EGD did not return "
1925 "enough data to seed the PRNG");
1926 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001927 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001928 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001929}
1930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001931PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001932"RAND_egd(path) -> bytes\n\
1933\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001934Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1935Returns number of bytes read. Raises SSLError if connection to EGD\n\
1936fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937
1938#endif
1939
Bill Janssen40a0f662008-08-12 16:56:25 +00001940
1941
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942/* List of functions exported by this module. */
1943
1944static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 {"_test_decode_cert", PySSL_test_decode_certificate,
1946 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001947#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1949 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001950 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 PySSL_RAND_egd_doc},
1952 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1953 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001956};
1957
1958
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001959#ifdef WITH_THREAD
1960
1961/* an implementation of OpenSSL threading operations in terms
1962 of the Python C thread library */
1963
1964static PyThread_type_lock *_ssl_locks = NULL;
1965
1966static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001968}
1969
Bill Janssen6e027db2007-11-15 22:23:56 +00001970static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 (int mode, int n, const char *file, int line) {
1972 /* this function is needed to perform locking on shared data
1973 structures. (Note that OpenSSL uses a number of global data
1974 structures that will be implicitly shared whenever multiple
1975 threads use OpenSSL.) Multi-threaded applications will
1976 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 locking_function() must be able to handle up to
1979 CRYPTO_num_locks() different mutex locks. It sets the n-th
1980 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 file and line are the file number of the function setting the
1983 lock. They can be useful for debugging.
1984 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 if ((_ssl_locks == NULL) ||
1987 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1988 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001989
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001990 if (mode & CRYPTO_LOCK) {
1991 PyThread_acquire_lock(_ssl_locks[n], 1);
1992 } else {
1993 PyThread_release_lock(_ssl_locks[n]);
1994 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001995}
1996
1997static int _setup_ssl_threads(void) {
1998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 if (_ssl_locks == NULL) {
2002 _ssl_locks_count = CRYPTO_num_locks();
2003 _ssl_locks = (PyThread_type_lock *)
2004 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2005 if (_ssl_locks == NULL)
2006 return 0;
2007 memset(_ssl_locks, 0,
2008 sizeof(PyThread_type_lock) * _ssl_locks_count);
2009 for (i = 0; i < _ssl_locks_count; i++) {
2010 _ssl_locks[i] = PyThread_allocate_lock();
2011 if (_ssl_locks[i] == NULL) {
2012 unsigned int j;
2013 for (j = 0; j < i; j++) {
2014 PyThread_free_lock(_ssl_locks[j]);
2015 }
2016 free(_ssl_locks);
2017 return 0;
2018 }
2019 }
2020 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2021 CRYPTO_set_id_callback(_ssl_thread_id_function);
2022 }
2023 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002024}
2025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002027
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002028PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002029"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002030for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002031
Martin v. Löwis1a214512008-06-11 05:26:20 +00002032
2033static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 PyModuleDef_HEAD_INIT,
2035 "_ssl",
2036 module_doc,
2037 -1,
2038 PySSL_methods,
2039 NULL,
2040 NULL,
2041 NULL,
2042 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002043};
2044
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002045
2046static void
2047parse_openssl_version(unsigned long libver,
2048 unsigned int *major, unsigned int *minor,
2049 unsigned int *fix, unsigned int *patch,
2050 unsigned int *status)
2051{
2052 *status = libver & 0xF;
2053 libver >>= 4;
2054 *patch = libver & 0xFF;
2055 libver >>= 8;
2056 *fix = libver & 0xFF;
2057 libver >>= 8;
2058 *minor = libver & 0xFF;
2059 libver >>= 8;
2060 *major = libver & 0xFF;
2061}
2062
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002063PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002064PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002065{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 PyObject *m, *d, *r;
2067 unsigned long libver;
2068 unsigned int major, minor, fix, patch, status;
2069 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002070
Antoine Pitrou152efa22010-05-16 18:19:27 +00002071 if (PyType_Ready(&PySSLContext_Type) < 0)
2072 return NULL;
2073 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002074 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 m = PyModule_Create(&_sslmodule);
2077 if (m == NULL)
2078 return NULL;
2079 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 /* Load _socket module and its C API */
2082 socket_api = PySocketModule_ImportModuleAndAPI();
2083 if (!socket_api)
2084 return NULL;
2085 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 /* Init OpenSSL */
2088 SSL_load_error_strings();
2089 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002090#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 /* note that this will start threading if not already started */
2092 if (!_setup_ssl_threads()) {
2093 return NULL;
2094 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002095#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002096 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 /* Add symbols to module dict */
2099 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2100 PySocketModule.error,
2101 NULL);
2102 if (PySSLErrorObject == NULL)
2103 return NULL;
2104 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2105 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002106 if (PyDict_SetItemString(d, "_SSLContext",
2107 (PyObject *)&PySSLContext_Type) != 0)
2108 return NULL;
2109 if (PyDict_SetItemString(d, "_SSLSocket",
2110 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 return NULL;
2112 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2113 PY_SSL_ERROR_ZERO_RETURN);
2114 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2115 PY_SSL_ERROR_WANT_READ);
2116 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2117 PY_SSL_ERROR_WANT_WRITE);
2118 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2119 PY_SSL_ERROR_WANT_X509_LOOKUP);
2120 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2121 PY_SSL_ERROR_SYSCALL);
2122 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2123 PY_SSL_ERROR_SSL);
2124 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2125 PY_SSL_ERROR_WANT_CONNECT);
2126 /* non ssl.h errorcodes */
2127 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2128 PY_SSL_ERROR_EOF);
2129 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2130 PY_SSL_ERROR_INVALID_ERROR_CODE);
2131 /* cert requirements */
2132 PyModule_AddIntConstant(m, "CERT_NONE",
2133 PY_SSL_CERT_NONE);
2134 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2135 PY_SSL_CERT_OPTIONAL);
2136 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2137 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 /* protocol versions */
Victor Stinneree18b6f2011-05-10 00:38:00 +02002140#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2142 PY_SSL_VERSION_SSL2);
Victor Stinneree18b6f2011-05-10 00:38:00 +02002143#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2145 PY_SSL_VERSION_SSL3);
2146 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2147 PY_SSL_VERSION_SSL23);
2148 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2149 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002150
Antoine Pitroub5218772010-05-21 09:56:06 +00002151 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002152 PyModule_AddIntConstant(m, "OP_ALL",
2153 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002154 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2155 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2156 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2157
Antoine Pitroud5323212010-10-22 18:19:07 +00002158#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2159 r = Py_True;
2160#else
2161 r = Py_False;
2162#endif
2163 Py_INCREF(r);
2164 PyModule_AddObject(m, "HAS_SNI", r);
2165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 /* OpenSSL version */
2167 /* SSLeay() gives us the version of the library linked against,
2168 which could be different from the headers version.
2169 */
2170 libver = SSLeay();
2171 r = PyLong_FromUnsignedLong(libver);
2172 if (r == NULL)
2173 return NULL;
2174 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2175 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002176 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2178 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2179 return NULL;
2180 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2181 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2182 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002183
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002184 libver = OPENSSL_VERSION_NUMBER;
2185 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2186 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2187 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2188 return NULL;
2189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002191}