blob: 0ae02a146d8be5fd7d0e5f5aa0869229d6e76d2d [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 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000066 PY_SSL_VERSION_SSL2,
67 PY_SSL_VERSION_SSL3,
68 PY_SSL_VERSION_SSL23,
69 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000072/* Include symbols from _socket module */
73#include "socketmodule.h"
74
Benjamin Petersonb173f782009-05-05 22:31:58 +000075static PySocketModule_APIObject PySocketModule;
76
Thomas Woutersed03b412007-08-28 21:37:11 +000077#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#include <poll.h>
79#elif defined(HAVE_SYS_POLL_H)
80#include <sys/poll.h>
81#endif
82
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000083/* Include OpenSSL header files */
84#include "openssl/rsa.h"
85#include "openssl/crypto.h"
86#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000088#include "openssl/pem.h"
89#include "openssl/ssl.h"
90#include "openssl/err.h"
91#include "openssl/rand.h"
92
93/* SSL error object */
94static PyObject *PySSLErrorObject;
95
Thomas Wouters1b7f8912007-09-19 03:06:30 +000096#ifdef WITH_THREAD
97
98/* serves as a flag to see whether we've initialized the SSL thread support. */
99/* 0 means no, greater than 0 means yes */
100
101static unsigned int _ssl_locks_count = 0;
102
103#endif /* def WITH_THREAD */
104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105/* SSL socket object */
106
107#define X509_NAME_MAXLEN 256
108
109/* RAND_* APIs got added to OpenSSL in 0.9.5 */
110#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
111# define HAVE_OPENSSL_RAND 1
112#else
113# undef HAVE_OPENSSL_RAND
114#endif
115
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000116/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
117 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
118 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
119#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000120# define HAVE_SSL_CTX_CLEAR_OPTIONS
121#else
122# undef HAVE_SSL_CTX_CLEAR_OPTIONS
123#endif
124
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000125typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000127 SSL_CTX *ctx;
128} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000129
Antoine Pitrou152efa22010-05-16 18:19:27 +0000130typedef struct {
131 PyObject_HEAD
132 PyObject *Socket; /* weakref to socket on which we're layered */
133 SSL *ssl;
134 X509 *peer_cert;
135 int shutdown_seen_zero;
136} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000137
Antoine Pitrou152efa22010-05-16 18:19:27 +0000138static PyTypeObject PySSLContext_Type;
139static PyTypeObject PySSLSocket_Type;
140
141static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
142static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000143static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000145static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
146static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000147
Antoine Pitrou152efa22010-05-16 18:19:27 +0000148#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
149#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000150
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000151typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000152 SOCKET_IS_NONBLOCKING,
153 SOCKET_IS_BLOCKING,
154 SOCKET_HAS_TIMED_OUT,
155 SOCKET_HAS_BEEN_CLOSED,
156 SOCKET_TOO_LARGE_FOR_SELECT,
157 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000158} timeout_state;
159
Thomas Woutersed03b412007-08-28 21:37:11 +0000160/* Wrap error strings with filename and line # */
161#define STRINGIFY1(x) #x
162#define STRINGIFY2(x) STRINGIFY1(x)
163#define ERRSTR1(x,y,z) (x ":" y ": " z)
164#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
165
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166/* XXX It might be helpful to augment the error message generated
167 below with the name of the SSL function that generated the error.
168 I expect it's obvious most of the time.
169*/
170
171static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000172PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000173{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000174 PyObject *v;
175 char buf[2048];
176 char *errstr;
177 int err;
178 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000182 if (obj->ssl != NULL) {
183 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 switch (err) {
186 case SSL_ERROR_ZERO_RETURN:
187 errstr = "TLS/SSL connection has been closed";
188 p = PY_SSL_ERROR_ZERO_RETURN;
189 break;
190 case SSL_ERROR_WANT_READ:
191 errstr = "The operation did not complete (read)";
192 p = PY_SSL_ERROR_WANT_READ;
193 break;
194 case SSL_ERROR_WANT_WRITE:
195 p = PY_SSL_ERROR_WANT_WRITE;
196 errstr = "The operation did not complete (write)";
197 break;
198 case SSL_ERROR_WANT_X509_LOOKUP:
199 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000200 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 break;
202 case SSL_ERROR_WANT_CONNECT:
203 p = PY_SSL_ERROR_WANT_CONNECT;
204 errstr = "The operation did not complete (connect)";
205 break;
206 case SSL_ERROR_SYSCALL:
207 {
208 unsigned long e = ERR_get_error();
209 if (e == 0) {
210 PySocketSockObject *s
211 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
212 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000213 p = PY_SSL_ERROR_EOF;
214 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000216 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000217 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000218 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000219 v = s->errorhandler();
220 Py_DECREF(s);
221 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000222 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000223 p = PY_SSL_ERROR_SYSCALL;
224 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 }
226 } else {
227 p = PY_SSL_ERROR_SYSCALL;
228 /* XXX Protected by global interpreter lock */
229 errstr = ERR_error_string(e, NULL);
230 }
231 break;
232 }
233 case SSL_ERROR_SSL:
234 {
235 unsigned long e = ERR_get_error();
236 p = PY_SSL_ERROR_SSL;
237 if (e != 0)
238 /* XXX Protected by global interpreter lock */
239 errstr = ERR_error_string(e, NULL);
240 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000241 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000242 }
243 break;
244 }
245 default:
246 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
247 errstr = "Invalid error code";
248 }
249 } else {
250 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
251 }
252 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000253 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000254 v = Py_BuildValue("(is)", p, buf);
255 if (v != NULL) {
256 PyErr_SetObject(PySSLErrorObject, v);
257 Py_DECREF(v);
258 }
259 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000260}
261
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000262static PyObject *
263_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000265 char buf[2048];
266 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 if (errstr == NULL) {
269 errcode = ERR_peek_last_error();
270 errstr = ERR_error_string(errcode, NULL);
271 }
272 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000273 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 v = Py_BuildValue("(is)", errcode, buf);
275 if (v != NULL) {
276 PyErr_SetObject(PySSLErrorObject, v);
277 Py_DECREF(v);
278 }
279 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000280}
281
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282static PySSLSocket *
283newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000284 enum py_ssl_server_or_client socket_type,
285 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000286{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000287 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000288
Antoine Pitrou152efa22010-05-16 18:19:27 +0000289 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 if (self == NULL)
291 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 self->peer_cert = NULL;
294 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 /* Make sure the SSL error state is initialized */
298 (void) ERR_get_state();
299 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000301 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000302 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000304 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000305#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000307#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000308
Antoine Pitroud5323212010-10-22 18:19:07 +0000309#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
310 if (server_hostname != NULL)
311 SSL_set_tlsext_host_name(self->ssl, server_hostname);
312#endif
313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 /* If the socket is in non-blocking mode or timeout mode, set the BIO
315 * to non-blocking mode (blocking is the default)
316 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000318 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
319 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
320 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 PySSL_BEGIN_ALLOW_THREADS
323 if (socket_type == PY_SSL_CLIENT)
324 SSL_set_connect_state(self->ssl);
325 else
326 SSL_set_accept_state(self->ssl);
327 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000328
Antoine Pitrou152efa22010-05-16 18:19:27 +0000329 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000330 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000331}
332
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000333/* SSL object methods */
334
Antoine Pitrou152efa22010-05-16 18:19:27 +0000335static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000336{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000337 int ret;
338 int err;
339 int sockstate, nonblocking;
340 PySocketSockObject *sock
341 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000343 if (((PyObject*)sock) == Py_None) {
344 _setSSLError("Underlying socket connection gone",
345 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
346 return NULL;
347 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000348 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000350 /* just in case the blocking state of the socket has been changed */
351 nonblocking = (sock->sock_timeout >= 0.0);
352 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
353 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000355 /* Actually negotiate SSL connection */
356 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000357 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000358 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 ret = SSL_do_handshake(self->ssl);
360 err = SSL_get_error(self->ssl, ret);
361 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000362 if (PyErr_CheckSignals())
363 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000364 if (err == SSL_ERROR_WANT_READ) {
365 sockstate = check_socket_and_wait_for_timeout(sock, 0);
366 } else if (err == SSL_ERROR_WANT_WRITE) {
367 sockstate = check_socket_and_wait_for_timeout(sock, 1);
368 } else {
369 sockstate = SOCKET_OPERATION_OK;
370 }
371 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000372 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000373 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000374 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000375 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
376 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000377 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000378 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
380 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000381 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000382 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
384 break;
385 }
386 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000387 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 if (ret < 1)
389 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 if (self->peer_cert)
392 X509_free (self->peer_cert);
393 PySSL_BEGIN_ALLOW_THREADS
394 self->peer_cert = SSL_get_peer_certificate(self->ssl);
395 PySSL_END_ALLOW_THREADS
396
397 Py_INCREF(Py_None);
398 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000399
400error:
401 Py_DECREF(sock);
402 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403}
404
Thomas Woutersed03b412007-08-28 21:37:11 +0000405static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000406_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 char namebuf[X509_NAME_MAXLEN];
409 int buflen;
410 PyObject *name_obj;
411 PyObject *value_obj;
412 PyObject *attr;
413 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
416 if (buflen < 0) {
417 _setSSLError(NULL, 0, __FILE__, __LINE__);
418 goto fail;
419 }
420 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
421 if (name_obj == NULL)
422 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
425 if (buflen < 0) {
426 _setSSLError(NULL, 0, __FILE__, __LINE__);
427 Py_DECREF(name_obj);
428 goto fail;
429 }
430 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000431 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000432 OPENSSL_free(valuebuf);
433 if (value_obj == NULL) {
434 Py_DECREF(name_obj);
435 goto fail;
436 }
437 attr = PyTuple_New(2);
438 if (attr == NULL) {
439 Py_DECREF(name_obj);
440 Py_DECREF(value_obj);
441 goto fail;
442 }
443 PyTuple_SET_ITEM(attr, 0, name_obj);
444 PyTuple_SET_ITEM(attr, 1, value_obj);
445 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000446
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000447 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000448 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000449}
450
451static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000453{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
455 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
456 PyObject *rdnt;
457 PyObject *attr = NULL; /* tuple to hold an attribute */
458 int entry_count = X509_NAME_entry_count(xname);
459 X509_NAME_ENTRY *entry;
460 ASN1_OBJECT *name;
461 ASN1_STRING *value;
462 int index_counter;
463 int rdn_level = -1;
464 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 dn = PyList_New(0);
467 if (dn == NULL)
468 return NULL;
469 /* now create another tuple to hold the top-level RDN */
470 rdn = PyList_New(0);
471 if (rdn == NULL)
472 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000474 for (index_counter = 0;
475 index_counter < entry_count;
476 index_counter++)
477 {
478 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000480 /* check to see if we've gotten to a new RDN */
481 if (rdn_level >= 0) {
482 if (rdn_level != entry->set) {
483 /* yes, new RDN */
484 /* add old RDN to DN */
485 rdnt = PyList_AsTuple(rdn);
486 Py_DECREF(rdn);
487 if (rdnt == NULL)
488 goto fail0;
489 retcode = PyList_Append(dn, rdnt);
490 Py_DECREF(rdnt);
491 if (retcode < 0)
492 goto fail0;
493 /* create new RDN */
494 rdn = PyList_New(0);
495 if (rdn == NULL)
496 goto fail0;
497 }
498 }
499 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000501 /* now add this attribute to the current RDN */
502 name = X509_NAME_ENTRY_get_object(entry);
503 value = X509_NAME_ENTRY_get_data(entry);
504 attr = _create_tuple_for_attribute(name, value);
505 /*
506 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
507 entry->set,
508 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
509 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
510 */
511 if (attr == NULL)
512 goto fail1;
513 retcode = PyList_Append(rdn, attr);
514 Py_DECREF(attr);
515 if (retcode < 0)
516 goto fail1;
517 }
518 /* now, there's typically a dangling RDN */
519 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
520 rdnt = PyList_AsTuple(rdn);
521 Py_DECREF(rdn);
522 if (rdnt == NULL)
523 goto fail0;
524 retcode = PyList_Append(dn, rdnt);
525 Py_DECREF(rdnt);
526 if (retcode < 0)
527 goto fail0;
528 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000530 /* convert list to tuple */
531 rdnt = PyList_AsTuple(dn);
532 Py_DECREF(dn);
533 if (rdnt == NULL)
534 return NULL;
535 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536
537 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
540 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 Py_XDECREF(dn);
542 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543}
544
545static PyObject *
546_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 /* this code follows the procedure outlined in
549 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
550 function to extract the STACK_OF(GENERAL_NAME),
551 then iterates through the stack to add the
552 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 int i, j;
555 PyObject *peer_alt_names = Py_None;
556 PyObject *v, *t;
557 X509_EXTENSION *ext = NULL;
558 GENERAL_NAMES *names = NULL;
559 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000560 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 BIO *biobuf = NULL;
562 char buf[2048];
563 char *vptr;
564 int len;
565 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000566#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000568#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000570#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 if (certificate == NULL)
573 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 /* get a memory buffer */
576 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 i = 0;
579 while ((i = X509_get_ext_by_NID(
580 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 if (peer_alt_names == Py_None) {
583 peer_alt_names = PyList_New(0);
584 if (peer_alt_names == NULL)
585 goto fail;
586 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 /* now decode the altName */
589 ext = X509_get_ext(certificate, i);
590 if(!(method = X509V3_EXT_get(ext))) {
591 PyErr_SetString
592 (PySSLErrorObject,
593 ERRSTR("No method for internalizing subjectAltName!"));
594 goto fail;
595 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 p = ext->value->data;
598 if (method->it)
599 names = (GENERAL_NAMES*)
600 (ASN1_item_d2i(NULL,
601 &p,
602 ext->value->length,
603 ASN1_ITEM_ptr(method->it)));
604 else
605 names = (GENERAL_NAMES*)
606 (method->d2i(NULL,
607 &p,
608 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 name = sk_GENERAL_NAME_value(names, j);
615 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 /* we special-case DirName as a tuple of
618 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 t = PyTuple_New(2);
621 if (t == NULL) {
622 goto fail;
623 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 v = PyUnicode_FromString("DirName");
626 if (v == NULL) {
627 Py_DECREF(t);
628 goto fail;
629 }
630 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 v = _create_tuple_for_X509_NAME (name->d.dirn);
633 if (v == NULL) {
634 Py_DECREF(t);
635 goto fail;
636 }
637 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 (void) BIO_reset(biobuf);
644 GENERAL_NAME_print(biobuf, name);
645 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
646 if (len < 0) {
647 _setSSLError(NULL, 0, __FILE__, __LINE__);
648 goto fail;
649 }
650 vptr = strchr(buf, ':');
651 if (vptr == NULL)
652 goto fail;
653 t = PyTuple_New(2);
654 if (t == NULL)
655 goto fail;
656 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
657 if (v == NULL) {
658 Py_DECREF(t);
659 goto fail;
660 }
661 PyTuple_SET_ITEM(t, 0, v);
662 v = PyUnicode_FromStringAndSize((vptr + 1),
663 (len - (vptr - buf + 1)));
664 if (v == NULL) {
665 Py_DECREF(t);
666 goto fail;
667 }
668 PyTuple_SET_ITEM(t, 1, v);
669 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000671 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 if (PyList_Append(peer_alt_names, t) < 0) {
674 Py_DECREF(t);
675 goto fail;
676 }
677 Py_DECREF(t);
678 }
679 }
680 BIO_free(biobuf);
681 if (peer_alt_names != Py_None) {
682 v = PyList_AsTuple(peer_alt_names);
683 Py_DECREF(peer_alt_names);
684 return v;
685 } else {
686 return peer_alt_names;
687 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000688
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
690 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 if (biobuf != NULL)
692 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 if (peer_alt_names != Py_None) {
695 Py_XDECREF(peer_alt_names);
696 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699}
700
701static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000702_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 PyObject *retval = NULL;
705 BIO *biobuf = NULL;
706 PyObject *peer;
707 PyObject *peer_alt_names = NULL;
708 PyObject *issuer;
709 PyObject *version;
710 PyObject *sn_obj;
711 ASN1_INTEGER *serialNumber;
712 char buf[2048];
713 int len;
714 ASN1_TIME *notBefore, *notAfter;
715 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 retval = PyDict_New();
718 if (retval == NULL)
719 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 peer = _create_tuple_for_X509_NAME(
722 X509_get_subject_name(certificate));
723 if (peer == NULL)
724 goto fail0;
725 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
726 Py_DECREF(peer);
727 goto fail0;
728 }
729 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000730
Antoine Pitroufb046912010-11-09 20:21:19 +0000731 issuer = _create_tuple_for_X509_NAME(
732 X509_get_issuer_name(certificate));
733 if (issuer == NULL)
734 goto fail0;
735 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000737 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000739 Py_DECREF(issuer);
740
741 version = PyLong_FromLong(X509_get_version(certificate) + 1);
742 if (PyDict_SetItemString(retval, "version", version) < 0) {
743 Py_DECREF(version);
744 goto fail0;
745 }
746 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 /* get a memory buffer */
749 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000750
Antoine Pitroufb046912010-11-09 20:21:19 +0000751 (void) BIO_reset(biobuf);
752 serialNumber = X509_get_serialNumber(certificate);
753 /* should not exceed 20 octets, 160 bits, so buf is big enough */
754 i2a_ASN1_INTEGER(biobuf, serialNumber);
755 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
756 if (len < 0) {
757 _setSSLError(NULL, 0, __FILE__, __LINE__);
758 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000760 sn_obj = PyUnicode_FromStringAndSize(buf, len);
761 if (sn_obj == NULL)
762 goto fail1;
763 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
764 Py_DECREF(sn_obj);
765 goto fail1;
766 }
767 Py_DECREF(sn_obj);
768
769 (void) BIO_reset(biobuf);
770 notBefore = X509_get_notBefore(certificate);
771 ASN1_TIME_print(biobuf, notBefore);
772 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
773 if (len < 0) {
774 _setSSLError(NULL, 0, __FILE__, __LINE__);
775 goto fail1;
776 }
777 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
778 if (pnotBefore == NULL)
779 goto fail1;
780 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
781 Py_DECREF(pnotBefore);
782 goto fail1;
783 }
784 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 (void) BIO_reset(biobuf);
787 notAfter = X509_get_notAfter(certificate);
788 ASN1_TIME_print(biobuf, notAfter);
789 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
790 if (len < 0) {
791 _setSSLError(NULL, 0, __FILE__, __LINE__);
792 goto fail1;
793 }
794 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
795 if (pnotAfter == NULL)
796 goto fail1;
797 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
798 Py_DECREF(pnotAfter);
799 goto fail1;
800 }
801 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 peer_alt_names = _get_peer_alt_names(certificate);
806 if (peer_alt_names == NULL)
807 goto fail1;
808 else if (peer_alt_names != Py_None) {
809 if (PyDict_SetItemString(retval, "subjectAltName",
810 peer_alt_names) < 0) {
811 Py_DECREF(peer_alt_names);
812 goto fail1;
813 }
814 Py_DECREF(peer_alt_names);
815 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 BIO_free(biobuf);
818 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000819
820 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 if (biobuf != NULL)
822 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000823 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 Py_XDECREF(retval);
825 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000826}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000827
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
829static PyObject *
830PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000833 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 X509 *x=NULL;
835 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroufb046912010-11-09 20:21:19 +0000837 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
838 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 if ((cert=BIO_new(BIO_s_file())) == NULL) {
842 PyErr_SetString(PySSLErrorObject,
843 "Can't malloc memory to read file");
844 goto fail0;
845 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846
Victor Stinner3800e1e2010-05-16 21:23:48 +0000847 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 PyErr_SetString(PySSLErrorObject,
849 "Can't open file");
850 goto fail0;
851 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000852
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
854 if (x == NULL) {
855 PyErr_SetString(PySSLErrorObject,
856 "Error decoding PEM-encoded file");
857 goto fail0;
858 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859
Antoine Pitroufb046912010-11-09 20:21:19 +0000860 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000861 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862
863 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000864 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 if (cert != NULL) BIO_free(cert);
866 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867}
868
869
870static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000871PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 PyObject *retval = NULL;
874 int len;
875 int verification;
876 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
879 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 if (!self->peer_cert)
882 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 if (PyObject_IsTrue(binary_mode)) {
885 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 bytes_buf = NULL;
890 len = i2d_X509(self->peer_cert, &bytes_buf);
891 if (len < 0) {
892 PySSL_SetError(self, len, __FILE__, __LINE__);
893 return NULL;
894 }
895 /* this is actually an immutable bytes sequence */
896 retval = PyBytes_FromStringAndSize
897 ((const char *) bytes_buf, len);
898 OPENSSL_free(bytes_buf);
899 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000902 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 if ((verification & SSL_VERIFY_PEER) == 0)
904 return PyDict_New();
905 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000906 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908}
909
910PyDoc_STRVAR(PySSL_peercert_doc,
911"peer_certificate([der=False]) -> certificate\n\
912\n\
913Returns the certificate for the peer. If no certificate was provided,\n\
914returns None. If a certificate was provided, but not validated, returns\n\
915an empty dictionary. Otherwise returns a dict containing information\n\
916about the peer certificate.\n\
917\n\
918If the optional argument is True, returns a DER-encoded copy of the\n\
919peer certificate, or None if no certificate was provided. This will\n\
920return the certificate even if it wasn't validated.");
921
Antoine Pitrou152efa22010-05-16 18:19:27 +0000922static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000925 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 char *cipher_name;
927 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000930 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 current = SSL_get_current_cipher(self->ssl);
932 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000933 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 retval = PyTuple_New(3);
936 if (retval == NULL)
937 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 cipher_name = (char *) SSL_CIPHER_get_name(current);
940 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000941 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 PyTuple_SET_ITEM(retval, 0, Py_None);
943 } else {
944 v = PyUnicode_FromString(cipher_name);
945 if (v == NULL)
946 goto fail0;
947 PyTuple_SET_ITEM(retval, 0, v);
948 }
949 cipher_protocol = SSL_CIPHER_get_version(current);
950 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000951 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 PyTuple_SET_ITEM(retval, 1, Py_None);
953 } else {
954 v = PyUnicode_FromString(cipher_protocol);
955 if (v == NULL)
956 goto fail0;
957 PyTuple_SET_ITEM(retval, 1, v);
958 }
959 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
960 if (v == NULL)
961 goto fail0;
962 PyTuple_SET_ITEM(retval, 2, v);
963 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000964
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 Py_DECREF(retval);
967 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968}
969
Antoine Pitrou152efa22010-05-16 18:19:27 +0000970static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000971{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 if (self->peer_cert) /* Possible not to have one? */
973 X509_free (self->peer_cert);
974 if (self->ssl)
975 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 Py_XDECREF(self->Socket);
977 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000978}
979
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000980/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000981 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000982 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000983 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000984
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000985static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000986check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000987{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 fd_set fds;
989 struct timeval tv;
990 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000991
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 /* Nothing to do unless we're in timeout mode (not non-blocking) */
993 if (s->sock_timeout < 0.0)
994 return SOCKET_IS_BLOCKING;
995 else if (s->sock_timeout == 0.0)
996 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +0000997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 /* Guard against closed socket */
999 if (s->sock_fd < 0)
1000 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 /* Prefer poll, if available, since you can poll() any fd
1003 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001004#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 {
1006 struct pollfd pollfd;
1007 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 pollfd.fd = s->sock_fd;
1010 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 /* s->sock_timeout is in seconds, timeout in ms */
1013 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1014 PySSL_BEGIN_ALLOW_THREADS
1015 rc = poll(&pollfd, 1, timeout);
1016 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 goto normal_return;
1019 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020#endif
1021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 /* Guard against socket too large for select*/
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001023#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 if (s->sock_fd >= FD_SETSIZE)
1025 return SOCKET_TOO_LARGE_FOR_SELECT;
Martin v. Löwisf84d1b92006-02-11 09:27:05 +00001026#endif
Neal Norwitz082b2df2006-02-07 07:04:46 +00001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 /* Construct the arguments to select */
1029 tv.tv_sec = (int)s->sock_timeout;
1030 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1031 FD_ZERO(&fds);
1032 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 /* See if the socket is ready */
1035 PySSL_BEGIN_ALLOW_THREADS
1036 if (writing)
1037 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1038 else
1039 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1040 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001041
Bill Janssen6e027db2007-11-15 22:23:56 +00001042#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001043normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001044#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1046 (when we are able to write or when there's something to read) */
1047 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001048}
1049
Antoine Pitrou152efa22010-05-16 18:19:27 +00001050static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001051{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 Py_buffer buf;
1053 int len;
1054 int sockstate;
1055 int err;
1056 int nonblocking;
1057 PySocketSockObject *sock
1058 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 if (((PyObject*)sock) == Py_None) {
1061 _setSSLError("Underlying socket connection gone",
1062 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1063 return NULL;
1064 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001065 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001067 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1068 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001070 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071
1072 /* just in case the blocking state of the socket has been changed */
1073 nonblocking = (sock->sock_timeout >= 0.0);
1074 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1075 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1076
1077 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1078 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001079 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 "The write operation timed out");
1081 goto error;
1082 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1083 PyErr_SetString(PySSLErrorObject,
1084 "Underlying socket has been closed.");
1085 goto error;
1086 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1087 PyErr_SetString(PySSLErrorObject,
1088 "Underlying socket too large for select().");
1089 goto error;
1090 }
1091 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 PySSL_BEGIN_ALLOW_THREADS
1093 len = SSL_write(self->ssl, buf.buf, buf.len);
1094 err = SSL_get_error(self->ssl, len);
1095 PySSL_END_ALLOW_THREADS
1096 if (PyErr_CheckSignals()) {
1097 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001098 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001100 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001102 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 } else {
1104 sockstate = SOCKET_OPERATION_OK;
1105 }
1106 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001107 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 "The write operation timed out");
1109 goto error;
1110 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1111 PyErr_SetString(PySSLErrorObject,
1112 "Underlying socket has been closed.");
1113 goto error;
1114 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1115 break;
1116 }
1117 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001118
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001119 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 PyBuffer_Release(&buf);
1121 if (len > 0)
1122 return PyLong_FromLong(len);
1123 else
1124 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001125
1126error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 PyBuffer_Release(&buf);
1129 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001130}
1131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001132PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001133"write(s) -> len\n\
1134\n\
1135Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001136of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001137
Antoine Pitrou152efa22010-05-16 18:19:27 +00001138static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001139{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 PySSL_BEGIN_ALLOW_THREADS
1143 count = SSL_pending(self->ssl);
1144 PySSL_END_ALLOW_THREADS
1145 if (count < 0)
1146 return PySSL_SetError(self, count, __FILE__, __LINE__);
1147 else
1148 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001149}
1150
1151PyDoc_STRVAR(PySSL_SSLpending_doc,
1152"pending() -> count\n\
1153\n\
1154Returns the number of already decrypted bytes available for read,\n\
1155pending on the connection.\n");
1156
Antoine Pitrou152efa22010-05-16 18:19:27 +00001157static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 PyObject *dest = NULL;
1160 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001162 int len, count;
1163 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 int sockstate;
1165 int err;
1166 int nonblocking;
1167 PySocketSockObject *sock
1168 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if (((PyObject*)sock) == Py_None) {
1171 _setSSLError("Underlying socket connection gone",
1172 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1173 return NULL;
1174 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001175 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001177 buf.obj = NULL;
1178 buf.buf = NULL;
1179 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001180 goto error;
1181
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001182 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1183 dest = PyBytes_FromStringAndSize(NULL, len);
1184 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001185 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001186 mem = PyBytes_AS_STRING(dest);
1187 }
1188 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001190 mem = buf.buf;
1191 if (len <= 0 || len > buf.len) {
1192 len = (int) buf.len;
1193 if (buf.len != len) {
1194 PyErr_SetString(PyExc_OverflowError,
1195 "maximum length can't fit in a C 'int'");
1196 goto error;
1197 }
1198 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 }
1200
1201 /* just in case the blocking state of the socket has been changed */
1202 nonblocking = (sock->sock_timeout >= 0.0);
1203 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1204 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1205
1206 /* first check if there are bytes ready to be read */
1207 PySSL_BEGIN_ALLOW_THREADS
1208 count = SSL_pending(self->ssl);
1209 PySSL_END_ALLOW_THREADS
1210
1211 if (!count) {
1212 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1213 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001214 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 "The read operation timed out");
1216 goto error;
1217 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1218 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001219 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 goto error;
1221 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1222 count = 0;
1223 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001224 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 }
1226 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 PySSL_BEGIN_ALLOW_THREADS
1228 count = SSL_read(self->ssl, mem, len);
1229 err = SSL_get_error(self->ssl, count);
1230 PySSL_END_ALLOW_THREADS
1231 if (PyErr_CheckSignals())
1232 goto error;
1233 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001234 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001236 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1238 (SSL_get_shutdown(self->ssl) ==
1239 SSL_RECEIVED_SHUTDOWN))
1240 {
1241 count = 0;
1242 goto done;
1243 } else {
1244 sockstate = SOCKET_OPERATION_OK;
1245 }
1246 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001247 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 "The read operation timed out");
1249 goto error;
1250 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1251 break;
1252 }
1253 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1254 if (count <= 0) {
1255 PySSL_SetError(self, count, __FILE__, __LINE__);
1256 goto error;
1257 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001258
1259done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001260 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001262 _PyBytes_Resize(&dest, count);
1263 return dest;
1264 }
1265 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 PyBuffer_Release(&buf);
1267 return PyLong_FromLong(count);
1268 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001269
1270error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001271 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001272 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001273 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001274 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001277}
1278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001280"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001281\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001282Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001283
Antoine Pitrou152efa22010-05-16 18:19:27 +00001284static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001285{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 int err, ssl_err, sockstate, nonblocking;
1287 int zeros = 0;
1288 PySocketSockObject *sock
1289 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 /* Guard against closed socket */
1292 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1293 _setSSLError("Underlying socket connection gone",
1294 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1295 return NULL;
1296 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001297 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298
1299 /* Just in case the blocking state of the socket has been changed */
1300 nonblocking = (sock->sock_timeout >= 0.0);
1301 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1302 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1303
1304 while (1) {
1305 PySSL_BEGIN_ALLOW_THREADS
1306 /* Disable read-ahead so that unwrap can work correctly.
1307 * Otherwise OpenSSL might read in too much data,
1308 * eating clear text data that happens to be
1309 * transmitted after the SSL shutdown.
1310 * Should be safe to call repeatedly everytime this
1311 * function is used and the shutdown_seen_zero != 0
1312 * condition is met.
1313 */
1314 if (self->shutdown_seen_zero)
1315 SSL_set_read_ahead(self->ssl, 0);
1316 err = SSL_shutdown(self->ssl);
1317 PySSL_END_ALLOW_THREADS
1318 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1319 if (err > 0)
1320 break;
1321 if (err == 0) {
1322 /* Don't loop endlessly; instead preserve legacy
1323 behaviour of trying SSL_shutdown() only twice.
1324 This looks necessary for OpenSSL < 0.9.8m */
1325 if (++zeros > 1)
1326 break;
1327 /* Shutdown was sent, now try receiving */
1328 self->shutdown_seen_zero = 1;
1329 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001330 }
1331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 /* Possibly retry shutdown until timeout or failure */
1333 ssl_err = SSL_get_error(self->ssl, err);
1334 if (ssl_err == SSL_ERROR_WANT_READ)
1335 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1336 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1337 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1338 else
1339 break;
1340 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1341 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001342 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 "The read operation timed out");
1344 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001345 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001347 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 }
1349 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1350 PyErr_SetString(PySSLErrorObject,
1351 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001352 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 }
1354 else if (sockstate != SOCKET_OPERATION_OK)
1355 /* Retain the SSL error code */
1356 break;
1357 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001358
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001359 if (err < 0) {
1360 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001363 else
1364 /* It's already INCREF'ed */
1365 return (PyObject *) sock;
1366
1367error:
1368 Py_DECREF(sock);
1369 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001370}
1371
1372PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1373"shutdown(s) -> socket\n\
1374\n\
1375Does the SSL shutdown handshake with the remote end, and returns\n\
1376the underlying socket object.");
1377
1378
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001379static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1381 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1382 PySSL_SSLwrite_doc},
1383 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1384 PySSL_SSLread_doc},
1385 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1386 PySSL_SSLpending_doc},
1387 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1388 PySSL_peercert_doc},
1389 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
1390 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1391 PySSL_SSLshutdown_doc},
1392 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001393};
1394
Antoine Pitrou152efa22010-05-16 18:19:27 +00001395static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001397 "_ssl._SSLSocket", /*tp_name*/
1398 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 0, /*tp_itemsize*/
1400 /* methods */
1401 (destructor)PySSL_dealloc, /*tp_dealloc*/
1402 0, /*tp_print*/
1403 0, /*tp_getattr*/
1404 0, /*tp_setattr*/
1405 0, /*tp_reserved*/
1406 0, /*tp_repr*/
1407 0, /*tp_as_number*/
1408 0, /*tp_as_sequence*/
1409 0, /*tp_as_mapping*/
1410 0, /*tp_hash*/
1411 0, /*tp_call*/
1412 0, /*tp_str*/
1413 0, /*tp_getattro*/
1414 0, /*tp_setattro*/
1415 0, /*tp_as_buffer*/
1416 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1417 0, /*tp_doc*/
1418 0, /*tp_traverse*/
1419 0, /*tp_clear*/
1420 0, /*tp_richcompare*/
1421 0, /*tp_weaklistoffset*/
1422 0, /*tp_iter*/
1423 0, /*tp_iternext*/
1424 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425};
1426
Antoine Pitrou152efa22010-05-16 18:19:27 +00001427
1428/*
1429 * _SSLContext objects
1430 */
1431
1432static PyObject *
1433context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1434{
1435 char *kwlist[] = {"protocol", NULL};
1436 PySSLContext *self;
1437 int proto_version = PY_SSL_VERSION_SSL23;
1438 SSL_CTX *ctx = NULL;
1439
1440 if (!PyArg_ParseTupleAndKeywords(
1441 args, kwds, "i:_SSLContext", kwlist,
1442 &proto_version))
1443 return NULL;
1444
1445 PySSL_BEGIN_ALLOW_THREADS
1446 if (proto_version == PY_SSL_VERSION_TLS1)
1447 ctx = SSL_CTX_new(TLSv1_method());
1448 else if (proto_version == PY_SSL_VERSION_SSL3)
1449 ctx = SSL_CTX_new(SSLv3_method());
1450 else if (proto_version == PY_SSL_VERSION_SSL2)
1451 ctx = SSL_CTX_new(SSLv2_method());
1452 else if (proto_version == PY_SSL_VERSION_SSL23)
1453 ctx = SSL_CTX_new(SSLv23_method());
1454 else
1455 proto_version = -1;
1456 PySSL_END_ALLOW_THREADS
1457
1458 if (proto_version == -1) {
1459 PyErr_SetString(PyExc_ValueError,
1460 "invalid protocol version");
1461 return NULL;
1462 }
1463 if (ctx == NULL) {
1464 PyErr_SetString(PySSLErrorObject,
1465 "failed to allocate SSL context");
1466 return NULL;
1467 }
1468
1469 assert(type != NULL && type->tp_alloc != NULL);
1470 self = (PySSLContext *) type->tp_alloc(type, 0);
1471 if (self == NULL) {
1472 SSL_CTX_free(ctx);
1473 return NULL;
1474 }
1475 self->ctx = ctx;
1476 /* Defaults */
1477 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
1478 SSL_CTX_set_options(self->ctx, SSL_OP_ALL);
1479
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001480#define SID_CTX "Python"
1481 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1482 sizeof(SID_CTX));
1483#undef SID_CTX
1484
Antoine Pitrou152efa22010-05-16 18:19:27 +00001485 return (PyObject *)self;
1486}
1487
1488static void
1489context_dealloc(PySSLContext *self)
1490{
1491 SSL_CTX_free(self->ctx);
1492 Py_TYPE(self)->tp_free(self);
1493}
1494
1495static PyObject *
1496set_ciphers(PySSLContext *self, PyObject *args)
1497{
1498 int ret;
1499 const char *cipherlist;
1500
1501 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1502 return NULL;
1503 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1504 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001505 /* Clearing the error queue is necessary on some OpenSSL versions,
1506 otherwise the error will be reported again when another SSL call
1507 is done. */
1508 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001509 PyErr_SetString(PySSLErrorObject,
1510 "No cipher can be selected.");
1511 return NULL;
1512 }
1513 Py_RETURN_NONE;
1514}
1515
1516static PyObject *
1517get_verify_mode(PySSLContext *self, void *c)
1518{
1519 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1520 case SSL_VERIFY_NONE:
1521 return PyLong_FromLong(PY_SSL_CERT_NONE);
1522 case SSL_VERIFY_PEER:
1523 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1524 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1525 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1526 }
1527 PyErr_SetString(PySSLErrorObject,
1528 "invalid return value from SSL_CTX_get_verify_mode");
1529 return NULL;
1530}
1531
1532static int
1533set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1534{
1535 int n, mode;
1536 if (!PyArg_Parse(arg, "i", &n))
1537 return -1;
1538 if (n == PY_SSL_CERT_NONE)
1539 mode = SSL_VERIFY_NONE;
1540 else if (n == PY_SSL_CERT_OPTIONAL)
1541 mode = SSL_VERIFY_PEER;
1542 else if (n == PY_SSL_CERT_REQUIRED)
1543 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1544 else {
1545 PyErr_SetString(PyExc_ValueError,
1546 "invalid value for verify_mode");
1547 return -1;
1548 }
1549 SSL_CTX_set_verify(self->ctx, mode, NULL);
1550 return 0;
1551}
1552
1553static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001554get_options(PySSLContext *self, void *c)
1555{
1556 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1557}
1558
1559static int
1560set_options(PySSLContext *self, PyObject *arg, void *c)
1561{
1562 long new_opts, opts, set, clear;
1563 if (!PyArg_Parse(arg, "l", &new_opts))
1564 return -1;
1565 opts = SSL_CTX_get_options(self->ctx);
1566 clear = opts & ~new_opts;
1567 set = ~opts & new_opts;
1568 if (clear) {
1569#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1570 SSL_CTX_clear_options(self->ctx, clear);
1571#else
1572 PyErr_SetString(PyExc_ValueError,
1573 "can't clear options before OpenSSL 0.9.8m");
1574 return -1;
1575#endif
1576 }
1577 if (set)
1578 SSL_CTX_set_options(self->ctx, set);
1579 return 0;
1580}
1581
1582static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001583load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1584{
1585 char *kwlist[] = {"certfile", "keyfile", NULL};
1586 PyObject *certfile, *keyfile = NULL;
1587 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
1588 int r;
1589
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001590 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001591 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001592 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1593 "O|O:load_cert_chain", kwlist,
1594 &certfile, &keyfile))
1595 return NULL;
1596 if (keyfile == Py_None)
1597 keyfile = NULL;
1598 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1599 PyErr_SetString(PyExc_TypeError,
1600 "certfile should be a valid filesystem path");
1601 return NULL;
1602 }
1603 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1604 PyErr_SetString(PyExc_TypeError,
1605 "keyfile should be a valid filesystem path");
1606 goto error;
1607 }
1608 PySSL_BEGIN_ALLOW_THREADS
1609 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1610 PyBytes_AS_STRING(certfile_bytes));
1611 PySSL_END_ALLOW_THREADS
1612 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001613 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001614 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001615 PyErr_SetFromErrno(PyExc_IOError);
1616 }
1617 else {
1618 _setSSLError(NULL, 0, __FILE__, __LINE__);
1619 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001620 goto error;
1621 }
1622 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou9c254862011-04-03 18:15:34 +02001623 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001624 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1625 SSL_FILETYPE_PEM);
1626 PySSL_END_ALLOW_THREADS
1627 Py_XDECREF(keyfile_bytes);
1628 Py_XDECREF(certfile_bytes);
1629 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001630 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001631 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001632 PyErr_SetFromErrno(PyExc_IOError);
1633 }
1634 else {
1635 _setSSLError(NULL, 0, __FILE__, __LINE__);
1636 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001637 return NULL;
1638 }
1639 PySSL_BEGIN_ALLOW_THREADS
1640 r = SSL_CTX_check_private_key(self->ctx);
1641 PySSL_END_ALLOW_THREADS
1642 if (r != 1) {
1643 _setSSLError(NULL, 0, __FILE__, __LINE__);
1644 return NULL;
1645 }
1646 Py_RETURN_NONE;
1647
1648error:
1649 Py_XDECREF(keyfile_bytes);
1650 Py_XDECREF(certfile_bytes);
1651 return NULL;
1652}
1653
1654static PyObject *
1655load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1656{
1657 char *kwlist[] = {"cafile", "capath", NULL};
1658 PyObject *cafile = NULL, *capath = NULL;
1659 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1660 const char *cafile_buf = NULL, *capath_buf = NULL;
1661 int r;
1662
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001663 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001664 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1665 "|OO:load_verify_locations", kwlist,
1666 &cafile, &capath))
1667 return NULL;
1668 if (cafile == Py_None)
1669 cafile = NULL;
1670 if (capath == Py_None)
1671 capath = NULL;
1672 if (cafile == NULL && capath == NULL) {
1673 PyErr_SetString(PyExc_TypeError,
1674 "cafile and capath cannot be both omitted");
1675 return NULL;
1676 }
1677 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1678 PyErr_SetString(PyExc_TypeError,
1679 "cafile should be a valid filesystem path");
1680 return NULL;
1681 }
1682 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001683 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001684 PyErr_SetString(PyExc_TypeError,
1685 "capath should be a valid filesystem path");
1686 return NULL;
1687 }
1688 if (cafile)
1689 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1690 if (capath)
1691 capath_buf = PyBytes_AS_STRING(capath_bytes);
1692 PySSL_BEGIN_ALLOW_THREADS
1693 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1694 PySSL_END_ALLOW_THREADS
1695 Py_XDECREF(cafile_bytes);
1696 Py_XDECREF(capath_bytes);
1697 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001698 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001699 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001700 PyErr_SetFromErrno(PyExc_IOError);
1701 }
1702 else {
1703 _setSSLError(NULL, 0, __FILE__, __LINE__);
1704 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001705 return NULL;
1706 }
1707 Py_RETURN_NONE;
1708}
1709
1710static PyObject *
1711context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1712{
Antoine Pitroud5323212010-10-22 18:19:07 +00001713 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001714 PySocketSockObject *sock;
1715 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001716 char *hostname = NULL;
1717 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001718
Antoine Pitroud5323212010-10-22 18:19:07 +00001719 /* server_hostname is either None (or absent), or to be encoded
1720 using the idna encoding. */
1721 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001722 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001723 &sock, &server_side,
1724 Py_TYPE(Py_None), &hostname_obj)) {
1725 PyErr_Clear();
1726 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1727 PySocketModule.Sock_Type,
1728 &sock, &server_side,
1729 "idna", &hostname))
1730 return NULL;
1731#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1732 PyMem_Free(hostname);
1733 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1734 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001735 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001736#endif
1737 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001738
Antoine Pitroud5323212010-10-22 18:19:07 +00001739 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1740 hostname);
1741 if (hostname != NULL)
1742 PyMem_Free(hostname);
1743 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001744}
1745
Antoine Pitroub0182c82010-10-12 20:09:02 +00001746static PyObject *
1747session_stats(PySSLContext *self, PyObject *unused)
1748{
1749 int r;
1750 PyObject *value, *stats = PyDict_New();
1751 if (!stats)
1752 return NULL;
1753
1754#define ADD_STATS(SSL_NAME, KEY_NAME) \
1755 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
1756 if (value == NULL) \
1757 goto error; \
1758 r = PyDict_SetItemString(stats, KEY_NAME, value); \
1759 Py_DECREF(value); \
1760 if (r < 0) \
1761 goto error;
1762
1763 ADD_STATS(number, "number");
1764 ADD_STATS(connect, "connect");
1765 ADD_STATS(connect_good, "connect_good");
1766 ADD_STATS(connect_renegotiate, "connect_renegotiate");
1767 ADD_STATS(accept, "accept");
1768 ADD_STATS(accept_good, "accept_good");
1769 ADD_STATS(accept_renegotiate, "accept_renegotiate");
1770 ADD_STATS(accept, "accept");
1771 ADD_STATS(hits, "hits");
1772 ADD_STATS(misses, "misses");
1773 ADD_STATS(timeouts, "timeouts");
1774 ADD_STATS(cache_full, "cache_full");
1775
1776#undef ADD_STATS
1777
1778 return stats;
1779
1780error:
1781 Py_DECREF(stats);
1782 return NULL;
1783}
1784
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001785static PyObject *
1786set_default_verify_paths(PySSLContext *self, PyObject *unused)
1787{
1788 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
1789 _setSSLError(NULL, 0, __FILE__, __LINE__);
1790 return NULL;
1791 }
1792 Py_RETURN_NONE;
1793}
1794
Antoine Pitrou152efa22010-05-16 18:19:27 +00001795static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00001796 {"options", (getter) get_options,
1797 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001798 {"verify_mode", (getter) get_verify_mode,
1799 (setter) set_verify_mode, NULL},
1800 {NULL}, /* sentinel */
1801};
1802
1803static struct PyMethodDef context_methods[] = {
1804 {"_wrap_socket", (PyCFunction) context_wrap_socket,
1805 METH_VARARGS | METH_KEYWORDS, NULL},
1806 {"set_ciphers", (PyCFunction) set_ciphers,
1807 METH_VARARGS, NULL},
1808 {"load_cert_chain", (PyCFunction) load_cert_chain,
1809 METH_VARARGS | METH_KEYWORDS, NULL},
1810 {"load_verify_locations", (PyCFunction) load_verify_locations,
1811 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00001812 {"session_stats", (PyCFunction) session_stats,
1813 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00001814 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
1815 METH_NOARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00001816 {NULL, NULL} /* sentinel */
1817};
1818
1819static PyTypeObject PySSLContext_Type = {
1820 PyVarObject_HEAD_INIT(NULL, 0)
1821 "_ssl._SSLContext", /*tp_name*/
1822 sizeof(PySSLContext), /*tp_basicsize*/
1823 0, /*tp_itemsize*/
1824 (destructor)context_dealloc, /*tp_dealloc*/
1825 0, /*tp_print*/
1826 0, /*tp_getattr*/
1827 0, /*tp_setattr*/
1828 0, /*tp_reserved*/
1829 0, /*tp_repr*/
1830 0, /*tp_as_number*/
1831 0, /*tp_as_sequence*/
1832 0, /*tp_as_mapping*/
1833 0, /*tp_hash*/
1834 0, /*tp_call*/
1835 0, /*tp_str*/
1836 0, /*tp_getattro*/
1837 0, /*tp_setattro*/
1838 0, /*tp_as_buffer*/
1839 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
1840 0, /*tp_doc*/
1841 0, /*tp_traverse*/
1842 0, /*tp_clear*/
1843 0, /*tp_richcompare*/
1844 0, /*tp_weaklistoffset*/
1845 0, /*tp_iter*/
1846 0, /*tp_iternext*/
1847 context_methods, /*tp_methods*/
1848 0, /*tp_members*/
1849 context_getsetlist, /*tp_getset*/
1850 0, /*tp_base*/
1851 0, /*tp_dict*/
1852 0, /*tp_descr_get*/
1853 0, /*tp_descr_set*/
1854 0, /*tp_dictoffset*/
1855 0, /*tp_init*/
1856 0, /*tp_alloc*/
1857 context_new, /*tp_new*/
1858};
1859
1860
1861
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001862#ifdef HAVE_OPENSSL_RAND
1863
1864/* helper routines for seeding the SSL PRNG */
1865static PyObject *
1866PySSL_RAND_add(PyObject *self, PyObject *args)
1867{
1868 char *buf;
1869 int len;
1870 double entropy;
1871
1872 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00001873 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001874 RAND_add(buf, len, entropy);
1875 Py_INCREF(Py_None);
1876 return Py_None;
1877}
1878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001879PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001880"RAND_add(string, entropy)\n\
1881\n\
1882Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001883bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001884
1885static PyObject *
1886PySSL_RAND_status(PyObject *self)
1887{
Christian Heimes217cfd12007-12-02 14:31:20 +00001888 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001889}
1890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001891PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001892"RAND_status() -> 0 or 1\n\
1893\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00001894Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
1895It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
1896using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001897
1898static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001899PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001900{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001901 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001902 int bytes;
1903
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001904 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
1905 PyUnicode_FSConverter, &path))
1906 return NULL;
1907
1908 bytes = RAND_egd(PyBytes_AsString(path));
1909 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001910 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001911 PyErr_SetString(PySSLErrorObject,
1912 "EGD connection failed or EGD did not return "
1913 "enough data to seed the PRNG");
1914 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001915 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001916 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001917}
1918
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001919PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001920"RAND_egd(path) -> bytes\n\
1921\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001922Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
1923Returns number of bytes read. Raises SSLError if connection to EGD\n\
1924fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001925
1926#endif
1927
Bill Janssen40a0f662008-08-12 16:56:25 +00001928
1929
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001930/* List of functions exported by this module. */
1931
1932static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 {"_test_decode_cert", PySSL_test_decode_certificate,
1934 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001935#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
1937 PySSL_RAND_add_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00001938 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 PySSL_RAND_egd_doc},
1940 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
1941 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001944};
1945
1946
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001947#ifdef WITH_THREAD
1948
1949/* an implementation of OpenSSL threading operations in terms
1950 of the Python C thread library */
1951
1952static PyThread_type_lock *_ssl_locks = NULL;
1953
1954static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001956}
1957
Bill Janssen6e027db2007-11-15 22:23:56 +00001958static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 (int mode, int n, const char *file, int line) {
1960 /* this function is needed to perform locking on shared data
1961 structures. (Note that OpenSSL uses a number of global data
1962 structures that will be implicitly shared whenever multiple
1963 threads use OpenSSL.) Multi-threaded applications will
1964 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 locking_function() must be able to handle up to
1967 CRYPTO_num_locks() different mutex locks. It sets the n-th
1968 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 file and line are the file number of the function setting the
1971 lock. They can be useful for debugging.
1972 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 if ((_ssl_locks == NULL) ||
1975 (n < 0) || ((unsigned)n >= _ssl_locks_count))
1976 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 if (mode & CRYPTO_LOCK) {
1979 PyThread_acquire_lock(_ssl_locks[n], 1);
1980 } else {
1981 PyThread_release_lock(_ssl_locks[n]);
1982 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001983}
1984
1985static int _setup_ssl_threads(void) {
1986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 if (_ssl_locks == NULL) {
1990 _ssl_locks_count = CRYPTO_num_locks();
1991 _ssl_locks = (PyThread_type_lock *)
1992 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
1993 if (_ssl_locks == NULL)
1994 return 0;
1995 memset(_ssl_locks, 0,
1996 sizeof(PyThread_type_lock) * _ssl_locks_count);
1997 for (i = 0; i < _ssl_locks_count; i++) {
1998 _ssl_locks[i] = PyThread_allocate_lock();
1999 if (_ssl_locks[i] == NULL) {
2000 unsigned int j;
2001 for (j = 0; j < i; j++) {
2002 PyThread_free_lock(_ssl_locks[j]);
2003 }
2004 free(_ssl_locks);
2005 return 0;
2006 }
2007 }
2008 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2009 CRYPTO_set_id_callback(_ssl_thread_id_function);
2010 }
2011 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002012}
2013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002015
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002016PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002017"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002018for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002019
Martin v. Löwis1a214512008-06-11 05:26:20 +00002020
2021static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 PyModuleDef_HEAD_INIT,
2023 "_ssl",
2024 module_doc,
2025 -1,
2026 PySSL_methods,
2027 NULL,
2028 NULL,
2029 NULL,
2030 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002031};
2032
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002033PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002034PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002035{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 PyObject *m, *d, *r;
2037 unsigned long libver;
2038 unsigned int major, minor, fix, patch, status;
2039 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002040
Antoine Pitrou152efa22010-05-16 18:19:27 +00002041 if (PyType_Ready(&PySSLContext_Type) < 0)
2042 return NULL;
2043 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002044 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002046 m = PyModule_Create(&_sslmodule);
2047 if (m == NULL)
2048 return NULL;
2049 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002051 /* Load _socket module and its C API */
2052 socket_api = PySocketModule_ImportModuleAndAPI();
2053 if (!socket_api)
2054 return NULL;
2055 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002057 /* Init OpenSSL */
2058 SSL_load_error_strings();
2059 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002060#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 /* note that this will start threading if not already started */
2062 if (!_setup_ssl_threads()) {
2063 return NULL;
2064 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002065#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002068 /* Add symbols to module dict */
2069 PySSLErrorObject = PyErr_NewException("ssl.SSLError",
2070 PySocketModule.error,
2071 NULL);
2072 if (PySSLErrorObject == NULL)
2073 return NULL;
2074 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)
2075 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002076 if (PyDict_SetItemString(d, "_SSLContext",
2077 (PyObject *)&PySSLContext_Type) != 0)
2078 return NULL;
2079 if (PyDict_SetItemString(d, "_SSLSocket",
2080 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 return NULL;
2082 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2083 PY_SSL_ERROR_ZERO_RETURN);
2084 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2085 PY_SSL_ERROR_WANT_READ);
2086 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2087 PY_SSL_ERROR_WANT_WRITE);
2088 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2089 PY_SSL_ERROR_WANT_X509_LOOKUP);
2090 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2091 PY_SSL_ERROR_SYSCALL);
2092 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2093 PY_SSL_ERROR_SSL);
2094 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2095 PY_SSL_ERROR_WANT_CONNECT);
2096 /* non ssl.h errorcodes */
2097 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2098 PY_SSL_ERROR_EOF);
2099 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2100 PY_SSL_ERROR_INVALID_ERROR_CODE);
2101 /* cert requirements */
2102 PyModule_AddIntConstant(m, "CERT_NONE",
2103 PY_SSL_CERT_NONE);
2104 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2105 PY_SSL_CERT_OPTIONAL);
2106 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2107 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 /* protocol versions */
2110 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2111 PY_SSL_VERSION_SSL2);
2112 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2113 PY_SSL_VERSION_SSL3);
2114 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2115 PY_SSL_VERSION_SSL23);
2116 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2117 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002118
Antoine Pitroub5218772010-05-21 09:56:06 +00002119 /* protocol options */
2120 PyModule_AddIntConstant(m, "OP_ALL", SSL_OP_ALL);
2121 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2122 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2123 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
2124
Antoine Pitroud5323212010-10-22 18:19:07 +00002125#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2126 r = Py_True;
2127#else
2128 r = Py_False;
2129#endif
2130 Py_INCREF(r);
2131 PyModule_AddObject(m, "HAS_SNI", r);
2132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 /* OpenSSL version */
2134 /* SSLeay() gives us the version of the library linked against,
2135 which could be different from the headers version.
2136 */
2137 libver = SSLeay();
2138 r = PyLong_FromUnsignedLong(libver);
2139 if (r == NULL)
2140 return NULL;
2141 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2142 return NULL;
2143 status = libver & 0xF;
2144 libver >>= 4;
2145 patch = libver & 0xFF;
2146 libver >>= 8;
2147 fix = libver & 0xFF;
2148 libver >>= 8;
2149 minor = libver & 0xFF;
2150 libver >>= 8;
2151 major = libver & 0xFF;
2152 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2153 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2154 return NULL;
2155 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2156 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2157 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002160}