blob: 3e2e264fedbbdc87f2fe994d8601e88f773a0546 [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"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000079/* Include symbols from _socket module */
80#include "socketmodule.h"
81
Benjamin Petersonb173f782009-05-05 22:31:58 +000082static PySocketModule_APIObject PySocketModule;
83
Thomas Woutersed03b412007-08-28 21:37:11 +000084#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000085#include <poll.h>
86#elif defined(HAVE_SYS_POLL_H)
87#include <sys/poll.h>
88#endif
89
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000090/* Include OpenSSL header files */
91#include "openssl/rsa.h"
92#include "openssl/crypto.h"
93#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000095#include "openssl/pem.h"
96#include "openssl/ssl.h"
97#include "openssl/err.h"
98#include "openssl/rand.h"
99
100/* SSL error object */
101static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200102static PyObject *PySSLZeroReturnErrorObject;
103static PyObject *PySSLWantReadErrorObject;
104static PyObject *PySSLWantWriteErrorObject;
105static PyObject *PySSLSyscallErrorObject;
106static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108#ifdef WITH_THREAD
109
110/* serves as a flag to see whether we've initialized the SSL thread support. */
111/* 0 means no, greater than 0 means yes */
112
113static unsigned int _ssl_locks_count = 0;
114
115#endif /* def WITH_THREAD */
116
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000117/* SSL socket object */
118
119#define X509_NAME_MAXLEN 256
120
121/* RAND_* APIs got added to OpenSSL in 0.9.5 */
122#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
123# define HAVE_OPENSSL_RAND 1
124#else
125# undef HAVE_OPENSSL_RAND
126#endif
127
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000128/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
129 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
130 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
131#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000132# define HAVE_SSL_CTX_CLEAR_OPTIONS
133#else
134# undef HAVE_SSL_CTX_CLEAR_OPTIONS
135#endif
136
Antoine Pitroud6494802011-07-21 01:11:30 +0200137/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
138 * older SSL, but let's be safe */
139#define PySSL_CB_MAXLEN 128
140
141/* SSL_get_finished got added to OpenSSL in 0.9.5 */
142#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
143# define HAVE_OPENSSL_FINISHED 1
144#else
145# define HAVE_OPENSSL_FINISHED 0
146#endif
147
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000148typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000149 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000150 SSL_CTX *ctx;
151} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000152
Antoine Pitrou152efa22010-05-16 18:19:27 +0000153typedef struct {
154 PyObject_HEAD
155 PyObject *Socket; /* weakref to socket on which we're layered */
156 SSL *ssl;
157 X509 *peer_cert;
158 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200159 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000160} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000161
Antoine Pitrou152efa22010-05-16 18:19:27 +0000162static PyTypeObject PySSLContext_Type;
163static PyTypeObject PySSLSocket_Type;
164
165static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
166static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000167static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000168 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000169static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
170static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000171
Antoine Pitrou152efa22010-05-16 18:19:27 +0000172#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
173#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000174
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000175typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000176 SOCKET_IS_NONBLOCKING,
177 SOCKET_IS_BLOCKING,
178 SOCKET_HAS_TIMED_OUT,
179 SOCKET_HAS_BEEN_CLOSED,
180 SOCKET_TOO_LARGE_FOR_SELECT,
181 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000182} timeout_state;
183
Thomas Woutersed03b412007-08-28 21:37:11 +0000184/* Wrap error strings with filename and line # */
185#define STRINGIFY1(x) #x
186#define STRINGIFY2(x) STRINGIFY1(x)
187#define ERRSTR1(x,y,z) (x ":" y ": " z)
188#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
189
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000190/* XXX It might be helpful to augment the error message generated
191 below with the name of the SSL function that generated the error.
192 I expect it's obvious most of the time.
193*/
194
195static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000196PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000197{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000198 PyObject *v;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200199 PyObject *type = PySSLErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000200 char buf[2048];
201 char *errstr;
202 int err;
203 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000205 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000207 if (obj->ssl != NULL) {
208 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000210 switch (err) {
211 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200212 errstr = "TLS/SSL connection has been closed (EOF)";
213 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000214 p = PY_SSL_ERROR_ZERO_RETURN;
215 break;
216 case SSL_ERROR_WANT_READ:
217 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200218 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000219 p = PY_SSL_ERROR_WANT_READ;
220 break;
221 case SSL_ERROR_WANT_WRITE:
222 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200223 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000224 errstr = "The operation did not complete (write)";
225 break;
226 case SSL_ERROR_WANT_X509_LOOKUP:
227 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000228 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000229 break;
230 case SSL_ERROR_WANT_CONNECT:
231 p = PY_SSL_ERROR_WANT_CONNECT;
232 errstr = "The operation did not complete (connect)";
233 break;
234 case SSL_ERROR_SYSCALL:
235 {
236 unsigned long e = ERR_get_error();
237 if (e == 0) {
238 PySocketSockObject *s
239 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
240 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000241 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200242 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000243 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000245 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000246 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000247 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000248 v = s->errorhandler();
249 Py_DECREF(s);
250 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000251 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000252 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200253 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000254 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000255 }
256 } else {
257 p = PY_SSL_ERROR_SYSCALL;
258 /* XXX Protected by global interpreter lock */
259 errstr = ERR_error_string(e, NULL);
260 }
261 break;
262 }
263 case SSL_ERROR_SSL:
264 {
265 unsigned long e = ERR_get_error();
266 p = PY_SSL_ERROR_SSL;
267 if (e != 0)
268 /* XXX Protected by global interpreter lock */
269 errstr = ERR_error_string(e, NULL);
270 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000271 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000272 }
273 break;
274 }
275 default:
276 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
277 errstr = "Invalid error code";
278 }
279 } else {
280 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
281 }
282 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000283 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000284 v = Py_BuildValue("(is)", p, buf);
285 if (v != NULL) {
Antoine Pitrou41032a62011-10-27 23:56:55 +0200286 PyErr_SetObject(type, v);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000287 Py_DECREF(v);
288 }
289 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000290}
291
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000292static PyObject *
293_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 char buf[2048];
296 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 if (errstr == NULL) {
299 errcode = ERR_peek_last_error();
300 errstr = ERR_error_string(errcode, NULL);
301 }
302 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000303 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 v = Py_BuildValue("(is)", errcode, buf);
305 if (v != NULL) {
306 PyErr_SetObject(PySSLErrorObject, v);
307 Py_DECREF(v);
308 }
309 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000310}
311
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312static PySSLSocket *
313newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000314 enum py_ssl_server_or_client socket_type,
315 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000316{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000318
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 if (self == NULL)
321 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000323 self->peer_cert = NULL;
324 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000325 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000327 /* Make sure the SSL error state is initialized */
328 (void) ERR_get_state();
329 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000332 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000333 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000334 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000335#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000336 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000337#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000338
Antoine Pitroud5323212010-10-22 18:19:07 +0000339#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
340 if (server_hostname != NULL)
341 SSL_set_tlsext_host_name(self->ssl, server_hostname);
342#endif
343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 /* If the socket is in non-blocking mode or timeout mode, set the BIO
345 * to non-blocking mode (blocking is the default)
346 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000348 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
349 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
350 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 PySSL_BEGIN_ALLOW_THREADS
353 if (socket_type == PY_SSL_CLIENT)
354 SSL_set_connect_state(self->ssl);
355 else
356 SSL_set_accept_state(self->ssl);
357 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000358
Antoine Pitroud6494802011-07-21 01:11:30 +0200359 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000360 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000361 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362}
363
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000364/* SSL object methods */
365
Antoine Pitrou152efa22010-05-16 18:19:27 +0000366static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000367{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 int ret;
369 int err;
370 int sockstate, nonblocking;
371 PySocketSockObject *sock
372 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 if (((PyObject*)sock) == Py_None) {
375 _setSSLError("Underlying socket connection gone",
376 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
377 return NULL;
378 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000379 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 /* just in case the blocking state of the socket has been changed */
382 nonblocking = (sock->sock_timeout >= 0.0);
383 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
384 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 /* Actually negotiate SSL connection */
387 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000389 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 ret = SSL_do_handshake(self->ssl);
391 err = SSL_get_error(self->ssl, ret);
392 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000393 if (PyErr_CheckSignals())
394 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 if (err == SSL_ERROR_WANT_READ) {
396 sockstate = check_socket_and_wait_for_timeout(sock, 0);
397 } else if (err == SSL_ERROR_WANT_WRITE) {
398 sockstate = check_socket_and_wait_for_timeout(sock, 1);
399 } else {
400 sockstate = SOCKET_OPERATION_OK;
401 }
402 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000403 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000404 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000405 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
407 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000408 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000409 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
411 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000413 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
415 break;
416 }
417 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000418 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000419 if (ret < 1)
420 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 if (self->peer_cert)
423 X509_free (self->peer_cert);
424 PySSL_BEGIN_ALLOW_THREADS
425 self->peer_cert = SSL_get_peer_certificate(self->ssl);
426 PySSL_END_ALLOW_THREADS
427
428 Py_INCREF(Py_None);
429 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000430
431error:
432 Py_DECREF(sock);
433 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000434}
435
Thomas Woutersed03b412007-08-28 21:37:11 +0000436static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 char namebuf[X509_NAME_MAXLEN];
440 int buflen;
441 PyObject *name_obj;
442 PyObject *value_obj;
443 PyObject *attr;
444 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
447 if (buflen < 0) {
448 _setSSLError(NULL, 0, __FILE__, __LINE__);
449 goto fail;
450 }
451 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
452 if (name_obj == NULL)
453 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
456 if (buflen < 0) {
457 _setSSLError(NULL, 0, __FILE__, __LINE__);
458 Py_DECREF(name_obj);
459 goto fail;
460 }
461 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000462 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 OPENSSL_free(valuebuf);
464 if (value_obj == NULL) {
465 Py_DECREF(name_obj);
466 goto fail;
467 }
468 attr = PyTuple_New(2);
469 if (attr == NULL) {
470 Py_DECREF(name_obj);
471 Py_DECREF(value_obj);
472 goto fail;
473 }
474 PyTuple_SET_ITEM(attr, 0, name_obj);
475 PyTuple_SET_ITEM(attr, 1, value_obj);
476 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000477
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000480}
481
482static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000483_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000484{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
486 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
487 PyObject *rdnt;
488 PyObject *attr = NULL; /* tuple to hold an attribute */
489 int entry_count = X509_NAME_entry_count(xname);
490 X509_NAME_ENTRY *entry;
491 ASN1_OBJECT *name;
492 ASN1_STRING *value;
493 int index_counter;
494 int rdn_level = -1;
495 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000497 dn = PyList_New(0);
498 if (dn == NULL)
499 return NULL;
500 /* now create another tuple to hold the top-level RDN */
501 rdn = PyList_New(0);
502 if (rdn == NULL)
503 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 for (index_counter = 0;
506 index_counter < entry_count;
507 index_counter++)
508 {
509 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 /* check to see if we've gotten to a new RDN */
512 if (rdn_level >= 0) {
513 if (rdn_level != entry->set) {
514 /* yes, new RDN */
515 /* add old RDN to DN */
516 rdnt = PyList_AsTuple(rdn);
517 Py_DECREF(rdn);
518 if (rdnt == NULL)
519 goto fail0;
520 retcode = PyList_Append(dn, rdnt);
521 Py_DECREF(rdnt);
522 if (retcode < 0)
523 goto fail0;
524 /* create new RDN */
525 rdn = PyList_New(0);
526 if (rdn == NULL)
527 goto fail0;
528 }
529 }
530 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 /* now add this attribute to the current RDN */
533 name = X509_NAME_ENTRY_get_object(entry);
534 value = X509_NAME_ENTRY_get_data(entry);
535 attr = _create_tuple_for_attribute(name, value);
536 /*
537 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
538 entry->set,
539 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
540 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
541 */
542 if (attr == NULL)
543 goto fail1;
544 retcode = PyList_Append(rdn, attr);
545 Py_DECREF(attr);
546 if (retcode < 0)
547 goto fail1;
548 }
549 /* now, there's typically a dangling RDN */
550 if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {
551 rdnt = PyList_AsTuple(rdn);
552 Py_DECREF(rdn);
553 if (rdnt == NULL)
554 goto fail0;
555 retcode = PyList_Append(dn, rdnt);
556 Py_DECREF(rdnt);
557 if (retcode < 0)
558 goto fail0;
559 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 /* convert list to tuple */
562 rdnt = PyList_AsTuple(dn);
563 Py_DECREF(dn);
564 if (rdnt == NULL)
565 return NULL;
566 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
568 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
571 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 Py_XDECREF(dn);
573 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574}
575
576static PyObject *
577_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 /* this code follows the procedure outlined in
580 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
581 function to extract the STACK_OF(GENERAL_NAME),
582 then iterates through the stack to add the
583 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 int i, j;
586 PyObject *peer_alt_names = Py_None;
587 PyObject *v, *t;
588 X509_EXTENSION *ext = NULL;
589 GENERAL_NAMES *names = NULL;
590 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000591 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 BIO *biobuf = NULL;
593 char buf[2048];
594 char *vptr;
595 int len;
596 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000597#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000599#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000601#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 if (certificate == NULL)
604 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 /* get a memory buffer */
607 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200609 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 while ((i = X509_get_ext_by_NID(
611 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 if (peer_alt_names == Py_None) {
614 peer_alt_names = PyList_New(0);
615 if (peer_alt_names == NULL)
616 goto fail;
617 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 /* now decode the altName */
620 ext = X509_get_ext(certificate, i);
621 if(!(method = X509V3_EXT_get(ext))) {
622 PyErr_SetString
623 (PySSLErrorObject,
624 ERRSTR("No method for internalizing subjectAltName!"));
625 goto fail;
626 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 p = ext->value->data;
629 if (method->it)
630 names = (GENERAL_NAMES*)
631 (ASN1_item_d2i(NULL,
632 &p,
633 ext->value->length,
634 ASN1_ITEM_ptr(method->it)));
635 else
636 names = (GENERAL_NAMES*)
637 (method->d2i(NULL,
638 &p,
639 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 name = sk_GENERAL_NAME_value(names, j);
646 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 /* we special-case DirName as a tuple of
649 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 t = PyTuple_New(2);
652 if (t == NULL) {
653 goto fail;
654 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 v = PyUnicode_FromString("DirName");
657 if (v == NULL) {
658 Py_DECREF(t);
659 goto fail;
660 }
661 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 v = _create_tuple_for_X509_NAME (name->d.dirn);
664 if (v == NULL) {
665 Py_DECREF(t);
666 goto fail;
667 }
668 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 (void) BIO_reset(biobuf);
675 GENERAL_NAME_print(biobuf, name);
676 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
677 if (len < 0) {
678 _setSSLError(NULL, 0, __FILE__, __LINE__);
679 goto fail;
680 }
681 vptr = strchr(buf, ':');
682 if (vptr == NULL)
683 goto fail;
684 t = PyTuple_New(2);
685 if (t == NULL)
686 goto fail;
687 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
688 if (v == NULL) {
689 Py_DECREF(t);
690 goto fail;
691 }
692 PyTuple_SET_ITEM(t, 0, v);
693 v = PyUnicode_FromStringAndSize((vptr + 1),
694 (len - (vptr - buf + 1)));
695 if (v == NULL) {
696 Py_DECREF(t);
697 goto fail;
698 }
699 PyTuple_SET_ITEM(t, 1, v);
700 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 if (PyList_Append(peer_alt_names, t) < 0) {
705 Py_DECREF(t);
706 goto fail;
707 }
708 Py_DECREF(t);
709 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100710 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 }
712 BIO_free(biobuf);
713 if (peer_alt_names != Py_None) {
714 v = PyList_AsTuple(peer_alt_names);
715 Py_DECREF(peer_alt_names);
716 return v;
717 } else {
718 return peer_alt_names;
719 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000720
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721
722 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 if (biobuf != NULL)
724 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 if (peer_alt_names != Py_None) {
727 Py_XDECREF(peer_alt_names);
728 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731}
732
733static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000734_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 PyObject *retval = NULL;
737 BIO *biobuf = NULL;
738 PyObject *peer;
739 PyObject *peer_alt_names = NULL;
740 PyObject *issuer;
741 PyObject *version;
742 PyObject *sn_obj;
743 ASN1_INTEGER *serialNumber;
744 char buf[2048];
745 int len;
746 ASN1_TIME *notBefore, *notAfter;
747 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 retval = PyDict_New();
750 if (retval == NULL)
751 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 peer = _create_tuple_for_X509_NAME(
754 X509_get_subject_name(certificate));
755 if (peer == NULL)
756 goto fail0;
757 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
758 Py_DECREF(peer);
759 goto fail0;
760 }
761 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000762
Antoine Pitroufb046912010-11-09 20:21:19 +0000763 issuer = _create_tuple_for_X509_NAME(
764 X509_get_issuer_name(certificate));
765 if (issuer == NULL)
766 goto fail0;
767 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000769 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000771 Py_DECREF(issuer);
772
773 version = PyLong_FromLong(X509_get_version(certificate) + 1);
774 if (PyDict_SetItemString(retval, "version", version) < 0) {
775 Py_DECREF(version);
776 goto fail0;
777 }
778 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 /* get a memory buffer */
781 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000782
Antoine Pitroufb046912010-11-09 20:21:19 +0000783 (void) BIO_reset(biobuf);
784 serialNumber = X509_get_serialNumber(certificate);
785 /* should not exceed 20 octets, 160 bits, so buf is big enough */
786 i2a_ASN1_INTEGER(biobuf, serialNumber);
787 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
788 if (len < 0) {
789 _setSSLError(NULL, 0, __FILE__, __LINE__);
790 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000792 sn_obj = PyUnicode_FromStringAndSize(buf, len);
793 if (sn_obj == NULL)
794 goto fail1;
795 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
796 Py_DECREF(sn_obj);
797 goto fail1;
798 }
799 Py_DECREF(sn_obj);
800
801 (void) BIO_reset(biobuf);
802 notBefore = X509_get_notBefore(certificate);
803 ASN1_TIME_print(biobuf, notBefore);
804 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
805 if (len < 0) {
806 _setSSLError(NULL, 0, __FILE__, __LINE__);
807 goto fail1;
808 }
809 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
810 if (pnotBefore == NULL)
811 goto fail1;
812 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
813 Py_DECREF(pnotBefore);
814 goto fail1;
815 }
816 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 (void) BIO_reset(biobuf);
819 notAfter = X509_get_notAfter(certificate);
820 ASN1_TIME_print(biobuf, notAfter);
821 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
822 if (len < 0) {
823 _setSSLError(NULL, 0, __FILE__, __LINE__);
824 goto fail1;
825 }
826 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
827 if (pnotAfter == NULL)
828 goto fail1;
829 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
830 Py_DECREF(pnotAfter);
831 goto fail1;
832 }
833 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 peer_alt_names = _get_peer_alt_names(certificate);
838 if (peer_alt_names == NULL)
839 goto fail1;
840 else if (peer_alt_names != Py_None) {
841 if (PyDict_SetItemString(retval, "subjectAltName",
842 peer_alt_names) < 0) {
843 Py_DECREF(peer_alt_names);
844 goto fail1;
845 }
846 Py_DECREF(peer_alt_names);
847 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 BIO_free(biobuf);
850 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000851
852 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 if (biobuf != NULL)
854 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000855 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 Py_XDECREF(retval);
857 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000858}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000859
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
861static PyObject *
862PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000865 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 X509 *x=NULL;
867 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868
Antoine Pitroufb046912010-11-09 20:21:19 +0000869 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
870 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 if ((cert=BIO_new(BIO_s_file())) == NULL) {
874 PyErr_SetString(PySSLErrorObject,
875 "Can't malloc memory to read file");
876 goto fail0;
877 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Victor Stinner3800e1e2010-05-16 21:23:48 +0000879 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 PyErr_SetString(PySSLErrorObject,
881 "Can't open file");
882 goto fail0;
883 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
886 if (x == NULL) {
887 PyErr_SetString(PySSLErrorObject,
888 "Error decoding PEM-encoded file");
889 goto fail0;
890 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroufb046912010-11-09 20:21:19 +0000892 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000893 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
895 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000896 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000897 if (cert != NULL) BIO_free(cert);
898 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899}
900
901
902static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000903PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 PyObject *retval = NULL;
906 int len;
907 int verification;
908 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
911 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 if (!self->peer_cert)
914 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 if (PyObject_IsTrue(binary_mode)) {
917 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 bytes_buf = NULL;
922 len = i2d_X509(self->peer_cert, &bytes_buf);
923 if (len < 0) {
924 PySSL_SetError(self, len, __FILE__, __LINE__);
925 return NULL;
926 }
927 /* this is actually an immutable bytes sequence */
928 retval = PyBytes_FromStringAndSize
929 ((const char *) bytes_buf, len);
930 OPENSSL_free(bytes_buf);
931 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000934 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 if ((verification & SSL_VERIFY_PEER) == 0)
936 return PyDict_New();
937 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000938 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940}
941
942PyDoc_STRVAR(PySSL_peercert_doc,
943"peer_certificate([der=False]) -> certificate\n\
944\n\
945Returns the certificate for the peer. If no certificate was provided,\n\
946returns None. If a certificate was provided, but not validated, returns\n\
947an empty dictionary. Otherwise returns a dict containing information\n\
948about the peer certificate.\n\
949\n\
950If the optional argument is True, returns a DER-encoded copy of the\n\
951peer certificate, or None if no certificate was provided. This will\n\
952return the certificate even if it wasn't validated.");
953
Antoine Pitrou152efa22010-05-16 18:19:27 +0000954static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000957 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 char *cipher_name;
959 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000962 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 current = SSL_get_current_cipher(self->ssl);
964 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000965 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 retval = PyTuple_New(3);
968 if (retval == NULL)
969 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 cipher_name = (char *) SSL_CIPHER_get_name(current);
972 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000973 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 PyTuple_SET_ITEM(retval, 0, Py_None);
975 } else {
976 v = PyUnicode_FromString(cipher_name);
977 if (v == NULL)
978 goto fail0;
979 PyTuple_SET_ITEM(retval, 0, v);
980 }
981 cipher_protocol = SSL_CIPHER_get_version(current);
982 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000983 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 PyTuple_SET_ITEM(retval, 1, Py_None);
985 } else {
986 v = PyUnicode_FromString(cipher_protocol);
987 if (v == NULL)
988 goto fail0;
989 PyTuple_SET_ITEM(retval, 1, v);
990 }
991 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
992 if (v == NULL)
993 goto fail0;
994 PyTuple_SET_ITEM(retval, 2, v);
995 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000996
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000997 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 Py_DECREF(retval);
999 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000}
1001
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001002static PyObject *PySSL_compression(PySSLSocket *self) {
1003#ifdef OPENSSL_NO_COMP
1004 Py_RETURN_NONE;
1005#else
1006 const COMP_METHOD *comp_method;
1007 const char *short_name;
1008
1009 if (self->ssl == NULL)
1010 Py_RETURN_NONE;
1011 comp_method = SSL_get_current_compression(self->ssl);
1012 if (comp_method == NULL || comp_method->type == NID_undef)
1013 Py_RETURN_NONE;
1014 short_name = OBJ_nid2sn(comp_method->type);
1015 if (short_name == NULL)
1016 Py_RETURN_NONE;
1017 return PyUnicode_DecodeFSDefault(short_name);
1018#endif
1019}
1020
Antoine Pitrou152efa22010-05-16 18:19:27 +00001021static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001022{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 if (self->peer_cert) /* Possible not to have one? */
1024 X509_free (self->peer_cert);
1025 if (self->ssl)
1026 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 Py_XDECREF(self->Socket);
1028 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001029}
1030
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001031/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001032 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001033 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001034 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001035
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001036static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001037check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001038{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 fd_set fds;
1040 struct timeval tv;
1041 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1044 if (s->sock_timeout < 0.0)
1045 return SOCKET_IS_BLOCKING;
1046 else if (s->sock_timeout == 0.0)
1047 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 /* Guard against closed socket */
1050 if (s->sock_fd < 0)
1051 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 /* Prefer poll, if available, since you can poll() any fd
1054 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001055#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 {
1057 struct pollfd pollfd;
1058 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 pollfd.fd = s->sock_fd;
1061 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* s->sock_timeout is in seconds, timeout in ms */
1064 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1065 PySSL_BEGIN_ALLOW_THREADS
1066 rc = poll(&pollfd, 1, timeout);
1067 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 goto normal_return;
1070 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001071#endif
1072
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001074 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 /* Construct the arguments to select */
1078 tv.tv_sec = (int)s->sock_timeout;
1079 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1080 FD_ZERO(&fds);
1081 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001082
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 /* See if the socket is ready */
1084 PySSL_BEGIN_ALLOW_THREADS
1085 if (writing)
1086 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1087 else
1088 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1089 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001090
Bill Janssen6e027db2007-11-15 22:23:56 +00001091#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001092normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001093#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1095 (when we are able to write or when there's something to read) */
1096 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001097}
1098
Antoine Pitrou152efa22010-05-16 18:19:27 +00001099static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001100{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 Py_buffer buf;
1102 int len;
1103 int sockstate;
1104 int err;
1105 int nonblocking;
1106 PySocketSockObject *sock
1107 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 if (((PyObject*)sock) == Py_None) {
1110 _setSSLError("Underlying socket connection gone",
1111 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1112 return NULL;
1113 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001114 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001116 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1117 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001119 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120
1121 /* just in case the blocking state of the socket has been changed */
1122 nonblocking = (sock->sock_timeout >= 0.0);
1123 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1124 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1125
1126 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1127 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001128 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 "The write operation timed out");
1130 goto error;
1131 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1132 PyErr_SetString(PySSLErrorObject,
1133 "Underlying socket has been closed.");
1134 goto error;
1135 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1136 PyErr_SetString(PySSLErrorObject,
1137 "Underlying socket too large for select().");
1138 goto error;
1139 }
1140 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 PySSL_BEGIN_ALLOW_THREADS
1142 len = SSL_write(self->ssl, buf.buf, buf.len);
1143 err = SSL_get_error(self->ssl, len);
1144 PySSL_END_ALLOW_THREADS
1145 if (PyErr_CheckSignals()) {
1146 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001147 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001149 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001151 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 } else {
1153 sockstate = SOCKET_OPERATION_OK;
1154 }
1155 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001156 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 "The write operation timed out");
1158 goto error;
1159 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1160 PyErr_SetString(PySSLErrorObject,
1161 "Underlying socket has been closed.");
1162 goto error;
1163 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1164 break;
1165 }
1166 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001167
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001168 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 PyBuffer_Release(&buf);
1170 if (len > 0)
1171 return PyLong_FromLong(len);
1172 else
1173 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001174
1175error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001176 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 PyBuffer_Release(&buf);
1178 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001179}
1180
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001181PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001182"write(s) -> len\n\
1183\n\
1184Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001185of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001186
Antoine Pitrou152efa22010-05-16 18:19:27 +00001187static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001188{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 PySSL_BEGIN_ALLOW_THREADS
1192 count = SSL_pending(self->ssl);
1193 PySSL_END_ALLOW_THREADS
1194 if (count < 0)
1195 return PySSL_SetError(self, count, __FILE__, __LINE__);
1196 else
1197 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001198}
1199
1200PyDoc_STRVAR(PySSL_SSLpending_doc,
1201"pending() -> count\n\
1202\n\
1203Returns the number of already decrypted bytes available for read,\n\
1204pending on the connection.\n");
1205
Antoine Pitrou152efa22010-05-16 18:19:27 +00001206static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001207{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 PyObject *dest = NULL;
1209 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001211 int len, count;
1212 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 int sockstate;
1214 int err;
1215 int nonblocking;
1216 PySocketSockObject *sock
1217 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 if (((PyObject*)sock) == Py_None) {
1220 _setSSLError("Underlying socket connection gone",
1221 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1222 return NULL;
1223 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001224 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001226 buf.obj = NULL;
1227 buf.buf = NULL;
1228 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001229 goto error;
1230
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001231 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1232 dest = PyBytes_FromStringAndSize(NULL, len);
1233 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001234 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001235 mem = PyBytes_AS_STRING(dest);
1236 }
1237 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001239 mem = buf.buf;
1240 if (len <= 0 || len > buf.len) {
1241 len = (int) buf.len;
1242 if (buf.len != len) {
1243 PyErr_SetString(PyExc_OverflowError,
1244 "maximum length can't fit in a C 'int'");
1245 goto error;
1246 }
1247 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 }
1249
1250 /* just in case the blocking state of the socket has been changed */
1251 nonblocking = (sock->sock_timeout >= 0.0);
1252 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1253 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1254
1255 /* first check if there are bytes ready to be read */
1256 PySSL_BEGIN_ALLOW_THREADS
1257 count = SSL_pending(self->ssl);
1258 PySSL_END_ALLOW_THREADS
1259
1260 if (!count) {
1261 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1262 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001263 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 "The read operation timed out");
1265 goto error;
1266 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1267 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001268 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 goto error;
1270 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1271 count = 0;
1272 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001273 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 }
1275 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 PySSL_BEGIN_ALLOW_THREADS
1277 count = SSL_read(self->ssl, mem, len);
1278 err = SSL_get_error(self->ssl, count);
1279 PySSL_END_ALLOW_THREADS
1280 if (PyErr_CheckSignals())
1281 goto error;
1282 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001283 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001285 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1287 (SSL_get_shutdown(self->ssl) ==
1288 SSL_RECEIVED_SHUTDOWN))
1289 {
1290 count = 0;
1291 goto done;
1292 } else {
1293 sockstate = SOCKET_OPERATION_OK;
1294 }
1295 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001296 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 "The read operation timed out");
1298 goto error;
1299 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1300 break;
1301 }
1302 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1303 if (count <= 0) {
1304 PySSL_SetError(self, count, __FILE__, __LINE__);
1305 goto error;
1306 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001307
1308done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001309 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001311 _PyBytes_Resize(&dest, count);
1312 return dest;
1313 }
1314 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 PyBuffer_Release(&buf);
1316 return PyLong_FromLong(count);
1317 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001318
1319error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001320 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001321 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001322 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001323 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001326}
1327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001328PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001329"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001330\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001332
Antoine Pitrou152efa22010-05-16 18:19:27 +00001333static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001334{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 int err, ssl_err, sockstate, nonblocking;
1336 int zeros = 0;
1337 PySocketSockObject *sock
1338 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* Guard against closed socket */
1341 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1342 _setSSLError("Underlying socket connection gone",
1343 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1344 return NULL;
1345 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001346 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347
1348 /* Just in case the blocking state of the socket has been changed */
1349 nonblocking = (sock->sock_timeout >= 0.0);
1350 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1351 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1352
1353 while (1) {
1354 PySSL_BEGIN_ALLOW_THREADS
1355 /* Disable read-ahead so that unwrap can work correctly.
1356 * Otherwise OpenSSL might read in too much data,
1357 * eating clear text data that happens to be
1358 * transmitted after the SSL shutdown.
1359 * Should be safe to call repeatedly everytime this
1360 * function is used and the shutdown_seen_zero != 0
1361 * condition is met.
1362 */
1363 if (self->shutdown_seen_zero)
1364 SSL_set_read_ahead(self->ssl, 0);
1365 err = SSL_shutdown(self->ssl);
1366 PySSL_END_ALLOW_THREADS
1367 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1368 if (err > 0)
1369 break;
1370 if (err == 0) {
1371 /* Don't loop endlessly; instead preserve legacy
1372 behaviour of trying SSL_shutdown() only twice.
1373 This looks necessary for OpenSSL < 0.9.8m */
1374 if (++zeros > 1)
1375 break;
1376 /* Shutdown was sent, now try receiving */
1377 self->shutdown_seen_zero = 1;
1378 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001379 }
1380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 /* Possibly retry shutdown until timeout or failure */
1382 ssl_err = SSL_get_error(self->ssl, err);
1383 if (ssl_err == SSL_ERROR_WANT_READ)
1384 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1385 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1386 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1387 else
1388 break;
1389 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1390 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001391 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 "The read operation timed out");
1393 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001394 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001396 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 }
1398 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1399 PyErr_SetString(PySSLErrorObject,
1400 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001401 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 }
1403 else if (sockstate != SOCKET_OPERATION_OK)
1404 /* Retain the SSL error code */
1405 break;
1406 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001407
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001408 if (err < 0) {
1409 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001412 else
1413 /* It's already INCREF'ed */
1414 return (PyObject *) sock;
1415
1416error:
1417 Py_DECREF(sock);
1418 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001419}
1420
1421PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1422"shutdown(s) -> socket\n\
1423\n\
1424Does the SSL shutdown handshake with the remote end, and returns\n\
1425the underlying socket object.");
1426
Antoine Pitroud6494802011-07-21 01:11:30 +02001427#if HAVE_OPENSSL_FINISHED
1428static PyObject *
1429PySSL_tls_unique_cb(PySSLSocket *self)
1430{
1431 PyObject *retval = NULL;
1432 char buf[PySSL_CB_MAXLEN];
1433 int len;
1434
1435 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1436 /* if session is resumed XOR we are the client */
1437 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1438 }
1439 else {
1440 /* if a new session XOR we are the server */
1441 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1442 }
1443
1444 /* It cannot be negative in current OpenSSL version as of July 2011 */
1445 assert(len >= 0);
1446 if (len == 0)
1447 Py_RETURN_NONE;
1448
1449 retval = PyBytes_FromStringAndSize(buf, len);
1450
1451 return retval;
1452}
1453
1454PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1455"tls_unique_cb() -> bytes\n\
1456\n\
1457Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1458\n\
1459If the TLS handshake is not yet complete, None is returned");
1460
1461#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001462
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001463static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1465 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1466 PySSL_SSLwrite_doc},
1467 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1468 PySSL_SSLread_doc},
1469 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1470 PySSL_SSLpending_doc},
1471 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1472 PySSL_peercert_doc},
1473 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001474 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001475 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1476 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001477#if HAVE_OPENSSL_FINISHED
1478 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1479 PySSL_tls_unique_cb_doc},
1480#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482};
1483
Antoine Pitrou152efa22010-05-16 18:19:27 +00001484static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001486 "_ssl._SSLSocket", /*tp_name*/
1487 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 0, /*tp_itemsize*/
1489 /* methods */
1490 (destructor)PySSL_dealloc, /*tp_dealloc*/
1491 0, /*tp_print*/
1492 0, /*tp_getattr*/
1493 0, /*tp_setattr*/
1494 0, /*tp_reserved*/
1495 0, /*tp_repr*/
1496 0, /*tp_as_number*/
1497 0, /*tp_as_sequence*/
1498 0, /*tp_as_mapping*/
1499 0, /*tp_hash*/
1500 0, /*tp_call*/
1501 0, /*tp_str*/
1502 0, /*tp_getattro*/
1503 0, /*tp_setattro*/
1504 0, /*tp_as_buffer*/
1505 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1506 0, /*tp_doc*/
1507 0, /*tp_traverse*/
1508 0, /*tp_clear*/
1509 0, /*tp_richcompare*/
1510 0, /*tp_weaklistoffset*/
1511 0, /*tp_iter*/
1512 0, /*tp_iternext*/
1513 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001514};
1515
Antoine Pitrou152efa22010-05-16 18:19:27 +00001516
1517/*
1518 * _SSLContext objects
1519 */
1520
1521static PyObject *
1522context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1523{
1524 char *kwlist[] = {"protocol", NULL};
1525 PySSLContext *self;
1526 int proto_version = PY_SSL_VERSION_SSL23;
1527 SSL_CTX *ctx = NULL;
1528
1529 if (!PyArg_ParseTupleAndKeywords(
1530 args, kwds, "i:_SSLContext", kwlist,
1531 &proto_version))
1532 return NULL;
1533
1534 PySSL_BEGIN_ALLOW_THREADS
1535 if (proto_version == PY_SSL_VERSION_TLS1)
1536 ctx = SSL_CTX_new(TLSv1_method());
1537 else if (proto_version == PY_SSL_VERSION_SSL3)
1538 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001539#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001540 else if (proto_version == PY_SSL_VERSION_SSL2)
1541 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001542#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001543 else if (proto_version == PY_SSL_VERSION_SSL23)
1544 ctx = SSL_CTX_new(SSLv23_method());
1545 else
1546 proto_version = -1;
1547 PySSL_END_ALLOW_THREADS
1548
1549 if (proto_version == -1) {
1550 PyErr_SetString(PyExc_ValueError,
1551 "invalid protocol version");
1552 return NULL;
1553 }
1554 if (ctx == NULL) {
1555 PyErr_SetString(PySSLErrorObject,
1556 "failed to allocate SSL context");
1557 return NULL;
1558 }
1559
1560 assert(type != NULL && type->tp_alloc != NULL);
1561 self = (PySSLContext *) type->tp_alloc(type, 0);
1562 if (self == NULL) {
1563 SSL_CTX_free(ctx);
1564 return NULL;
1565 }
1566 self->ctx = ctx;
1567 /* Defaults */
1568 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001569 SSL_CTX_set_options(self->ctx,
1570 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001571
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001572#define SID_CTX "Python"
1573 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1574 sizeof(SID_CTX));
1575#undef SID_CTX
1576
Antoine Pitrou152efa22010-05-16 18:19:27 +00001577 return (PyObject *)self;
1578}
1579
1580static void
1581context_dealloc(PySSLContext *self)
1582{
1583 SSL_CTX_free(self->ctx);
1584 Py_TYPE(self)->tp_free(self);
1585}
1586
1587static PyObject *
1588set_ciphers(PySSLContext *self, PyObject *args)
1589{
1590 int ret;
1591 const char *cipherlist;
1592
1593 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1594 return NULL;
1595 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1596 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001597 /* Clearing the error queue is necessary on some OpenSSL versions,
1598 otherwise the error will be reported again when another SSL call
1599 is done. */
1600 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001601 PyErr_SetString(PySSLErrorObject,
1602 "No cipher can be selected.");
1603 return NULL;
1604 }
1605 Py_RETURN_NONE;
1606}
1607
1608static PyObject *
1609get_verify_mode(PySSLContext *self, void *c)
1610{
1611 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1612 case SSL_VERIFY_NONE:
1613 return PyLong_FromLong(PY_SSL_CERT_NONE);
1614 case SSL_VERIFY_PEER:
1615 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1616 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1617 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1618 }
1619 PyErr_SetString(PySSLErrorObject,
1620 "invalid return value from SSL_CTX_get_verify_mode");
1621 return NULL;
1622}
1623
1624static int
1625set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1626{
1627 int n, mode;
1628 if (!PyArg_Parse(arg, "i", &n))
1629 return -1;
1630 if (n == PY_SSL_CERT_NONE)
1631 mode = SSL_VERIFY_NONE;
1632 else if (n == PY_SSL_CERT_OPTIONAL)
1633 mode = SSL_VERIFY_PEER;
1634 else if (n == PY_SSL_CERT_REQUIRED)
1635 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1636 else {
1637 PyErr_SetString(PyExc_ValueError,
1638 "invalid value for verify_mode");
1639 return -1;
1640 }
1641 SSL_CTX_set_verify(self->ctx, mode, NULL);
1642 return 0;
1643}
1644
1645static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001646get_options(PySSLContext *self, void *c)
1647{
1648 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1649}
1650
1651static int
1652set_options(PySSLContext *self, PyObject *arg, void *c)
1653{
1654 long new_opts, opts, set, clear;
1655 if (!PyArg_Parse(arg, "l", &new_opts))
1656 return -1;
1657 opts = SSL_CTX_get_options(self->ctx);
1658 clear = opts & ~new_opts;
1659 set = ~opts & new_opts;
1660 if (clear) {
1661#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1662 SSL_CTX_clear_options(self->ctx, clear);
1663#else
1664 PyErr_SetString(PyExc_ValueError,
1665 "can't clear options before OpenSSL 0.9.8m");
1666 return -1;
1667#endif
1668 }
1669 if (set)
1670 SSL_CTX_set_options(self->ctx, set);
1671 return 0;
1672}
1673
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001674typedef struct {
1675 PyThreadState *thread_state;
1676 PyObject *callable;
1677 char *password;
1678 Py_ssize_t size;
1679 int error;
1680} _PySSLPasswordInfo;
1681
1682static int
1683_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1684 const char *bad_type_error)
1685{
1686 /* Set the password and size fields of a _PySSLPasswordInfo struct
1687 from a unicode, bytes, or byte array object.
1688 The password field will be dynamically allocated and must be freed
1689 by the caller */
1690 PyObject *password_bytes = NULL;
1691 const char *data = NULL;
1692 Py_ssize_t size;
1693
1694 if (PyUnicode_Check(password)) {
1695 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1696 if (!password_bytes) {
1697 goto error;
1698 }
1699 data = PyBytes_AS_STRING(password_bytes);
1700 size = PyBytes_GET_SIZE(password_bytes);
1701 } else if (PyBytes_Check(password)) {
1702 data = PyBytes_AS_STRING(password);
1703 size = PyBytes_GET_SIZE(password);
1704 } else if (PyByteArray_Check(password)) {
1705 data = PyByteArray_AS_STRING(password);
1706 size = PyByteArray_GET_SIZE(password);
1707 } else {
1708 PyErr_SetString(PyExc_TypeError, bad_type_error);
1709 goto error;
1710 }
1711
1712 free(pw_info->password);
1713 pw_info->password = malloc(size);
1714 if (!pw_info->password) {
1715 PyErr_SetString(PyExc_MemoryError,
1716 "unable to allocate password buffer");
1717 goto error;
1718 }
1719 memcpy(pw_info->password, data, size);
1720 pw_info->size = size;
1721
1722 Py_XDECREF(password_bytes);
1723 return 1;
1724
1725error:
1726 Py_XDECREF(password_bytes);
1727 return 0;
1728}
1729
1730static int
1731_password_callback(char *buf, int size, int rwflag, void *userdata)
1732{
1733 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1734 PyObject *fn_ret = NULL;
1735
1736 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1737
1738 if (pw_info->callable) {
1739 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1740 if (!fn_ret) {
1741 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1742 core python API, so we could use it to add a frame here */
1743 goto error;
1744 }
1745
1746 if (!_pwinfo_set(pw_info, fn_ret,
1747 "password callback must return a string")) {
1748 goto error;
1749 }
1750 Py_CLEAR(fn_ret);
1751 }
1752
1753 if (pw_info->size > size) {
1754 PyErr_Format(PyExc_ValueError,
1755 "password cannot be longer than %d bytes", size);
1756 goto error;
1757 }
1758
1759 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1760 memcpy(buf, pw_info->password, pw_info->size);
1761 return pw_info->size;
1762
1763error:
1764 Py_XDECREF(fn_ret);
1765 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1766 pw_info->error = 1;
1767 return -1;
1768}
1769
Antoine Pitroub5218772010-05-21 09:56:06 +00001770static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001771load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1772{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001773 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1774 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001775 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001776 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1777 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1778 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001779 int r;
1780
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001781 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001782 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001783 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001784 "O|OO:load_cert_chain", kwlist,
1785 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001786 return NULL;
1787 if (keyfile == Py_None)
1788 keyfile = NULL;
1789 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1790 PyErr_SetString(PyExc_TypeError,
1791 "certfile should be a valid filesystem path");
1792 return NULL;
1793 }
1794 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1795 PyErr_SetString(PyExc_TypeError,
1796 "keyfile should be a valid filesystem path");
1797 goto error;
1798 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001799 if (password && password != Py_None) {
1800 if (PyCallable_Check(password)) {
1801 pw_info.callable = password;
1802 } else if (!_pwinfo_set(&pw_info, password,
1803 "password should be a string or callable")) {
1804 goto error;
1805 }
1806 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1807 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1808 }
1809 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001810 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1811 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001812 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001813 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001814 if (pw_info.error) {
1815 ERR_clear_error();
1816 /* the password callback has already set the error information */
1817 }
1818 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001819 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001820 PyErr_SetFromErrno(PyExc_IOError);
1821 }
1822 else {
1823 _setSSLError(NULL, 0, __FILE__, __LINE__);
1824 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001825 goto error;
1826 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001827 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001828 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001829 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1830 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001831 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1832 Py_CLEAR(keyfile_bytes);
1833 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001834 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001835 if (pw_info.error) {
1836 ERR_clear_error();
1837 /* the password callback has already set the error information */
1838 }
1839 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001840 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001841 PyErr_SetFromErrno(PyExc_IOError);
1842 }
1843 else {
1844 _setSSLError(NULL, 0, __FILE__, __LINE__);
1845 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001846 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001847 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001848 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001849 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001850 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001851 if (r != 1) {
1852 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001853 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001854 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001855 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1856 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1857 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001858 Py_RETURN_NONE;
1859
1860error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001861 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1862 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1863 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001864 Py_XDECREF(keyfile_bytes);
1865 Py_XDECREF(certfile_bytes);
1866 return NULL;
1867}
1868
1869static PyObject *
1870load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1871{
1872 char *kwlist[] = {"cafile", "capath", NULL};
1873 PyObject *cafile = NULL, *capath = NULL;
1874 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1875 const char *cafile_buf = NULL, *capath_buf = NULL;
1876 int r;
1877
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001878 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001879 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1880 "|OO:load_verify_locations", kwlist,
1881 &cafile, &capath))
1882 return NULL;
1883 if (cafile == Py_None)
1884 cafile = NULL;
1885 if (capath == Py_None)
1886 capath = NULL;
1887 if (cafile == NULL && capath == NULL) {
1888 PyErr_SetString(PyExc_TypeError,
1889 "cafile and capath cannot be both omitted");
1890 return NULL;
1891 }
1892 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1893 PyErr_SetString(PyExc_TypeError,
1894 "cafile should be a valid filesystem path");
1895 return NULL;
1896 }
1897 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001898 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001899 PyErr_SetString(PyExc_TypeError,
1900 "capath should be a valid filesystem path");
1901 return NULL;
1902 }
1903 if (cafile)
1904 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1905 if (capath)
1906 capath_buf = PyBytes_AS_STRING(capath_bytes);
1907 PySSL_BEGIN_ALLOW_THREADS
1908 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1909 PySSL_END_ALLOW_THREADS
1910 Py_XDECREF(cafile_bytes);
1911 Py_XDECREF(capath_bytes);
1912 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001913 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001914 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001915 PyErr_SetFromErrno(PyExc_IOError);
1916 }
1917 else {
1918 _setSSLError(NULL, 0, __FILE__, __LINE__);
1919 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001920 return NULL;
1921 }
1922 Py_RETURN_NONE;
1923}
1924
1925static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001926load_dh_params(PySSLContext *self, PyObject *filepath)
1927{
1928 FILE *f;
1929 DH *dh;
1930
1931 f = _Py_fopen(filepath, "rb");
1932 if (f == NULL) {
1933 if (!PyErr_Occurred())
1934 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1935 return NULL;
1936 }
1937 errno = 0;
1938 PySSL_BEGIN_ALLOW_THREADS
1939 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
1940 PySSL_END_ALLOW_THREADS
1941 if (dh == NULL) {
1942 if (errno != 0) {
1943 ERR_clear_error();
1944 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1945 }
1946 else {
1947 _setSSLError(NULL, 0, __FILE__, __LINE__);
1948 }
1949 return NULL;
1950 }
1951 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
1952 _setSSLError(NULL, 0, __FILE__, __LINE__);
1953 DH_free(dh);
1954 Py_RETURN_NONE;
1955}
1956
1957static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001958context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1959{
Antoine Pitroud5323212010-10-22 18:19:07 +00001960 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001961 PySocketSockObject *sock;
1962 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001963 char *hostname = NULL;
1964 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001965
Antoine Pitroud5323212010-10-22 18:19:07 +00001966 /* server_hostname is either None (or absent), or to be encoded
1967 using the idna encoding. */
1968 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001969 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001970 &sock, &server_side,
1971 Py_TYPE(Py_None), &hostname_obj)) {
1972 PyErr_Clear();
1973 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1974 PySocketModule.Sock_Type,
1975 &sock, &server_side,
1976 "idna", &hostname))
1977 return NULL;
1978#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1979 PyMem_Free(hostname);
1980 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1981 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001982 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001983#endif
1984 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001985
Antoine Pitroud5323212010-10-22 18:19:07 +00001986 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1987 hostname);
1988 if (hostname != NULL)
1989 PyMem_Free(hostname);
1990 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001991}
1992
Antoine Pitroub0182c82010-10-12 20:09:02 +00001993static PyObject *
1994session_stats(PySSLContext *self, PyObject *unused)
1995{
1996 int r;
1997 PyObject *value, *stats = PyDict_New();
1998 if (!stats)
1999 return NULL;
2000
2001#define ADD_STATS(SSL_NAME, KEY_NAME) \
2002 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2003 if (value == NULL) \
2004 goto error; \
2005 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2006 Py_DECREF(value); \
2007 if (r < 0) \
2008 goto error;
2009
2010 ADD_STATS(number, "number");
2011 ADD_STATS(connect, "connect");
2012 ADD_STATS(connect_good, "connect_good");
2013 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2014 ADD_STATS(accept, "accept");
2015 ADD_STATS(accept_good, "accept_good");
2016 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2017 ADD_STATS(accept, "accept");
2018 ADD_STATS(hits, "hits");
2019 ADD_STATS(misses, "misses");
2020 ADD_STATS(timeouts, "timeouts");
2021 ADD_STATS(cache_full, "cache_full");
2022
2023#undef ADD_STATS
2024
2025 return stats;
2026
2027error:
2028 Py_DECREF(stats);
2029 return NULL;
2030}
2031
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002032static PyObject *
2033set_default_verify_paths(PySSLContext *self, PyObject *unused)
2034{
2035 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2036 _setSSLError(NULL, 0, __FILE__, __LINE__);
2037 return NULL;
2038 }
2039 Py_RETURN_NONE;
2040}
2041
Antoine Pitrou501da612011-12-21 09:27:41 +01002042#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002043static PyObject *
2044set_ecdh_curve(PySSLContext *self, PyObject *name)
2045{
2046 PyObject *name_bytes;
2047 int nid;
2048 EC_KEY *key;
2049
2050 if (!PyUnicode_FSConverter(name, &name_bytes))
2051 return NULL;
2052 assert(PyBytes_Check(name_bytes));
2053 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2054 Py_DECREF(name_bytes);
2055 if (nid == 0) {
2056 PyErr_Format(PyExc_ValueError,
2057 "unknown elliptic curve name %R", name);
2058 return NULL;
2059 }
2060 key = EC_KEY_new_by_curve_name(nid);
2061 if (key == NULL) {
2062 _setSSLError(NULL, 0, __FILE__, __LINE__);
2063 return NULL;
2064 }
2065 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2066 EC_KEY_free(key);
2067 Py_RETURN_NONE;
2068}
Antoine Pitrou501da612011-12-21 09:27:41 +01002069#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002070
Antoine Pitrou152efa22010-05-16 18:19:27 +00002071static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002072 {"options", (getter) get_options,
2073 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002074 {"verify_mode", (getter) get_verify_mode,
2075 (setter) set_verify_mode, NULL},
2076 {NULL}, /* sentinel */
2077};
2078
2079static struct PyMethodDef context_methods[] = {
2080 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2081 METH_VARARGS | METH_KEYWORDS, NULL},
2082 {"set_ciphers", (PyCFunction) set_ciphers,
2083 METH_VARARGS, NULL},
2084 {"load_cert_chain", (PyCFunction) load_cert_chain,
2085 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002086 {"load_dh_params", (PyCFunction) load_dh_params,
2087 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002088 {"load_verify_locations", (PyCFunction) load_verify_locations,
2089 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002090 {"session_stats", (PyCFunction) session_stats,
2091 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002092 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2093 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002094#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002095 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2096 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002097#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002098 {NULL, NULL} /* sentinel */
2099};
2100
2101static PyTypeObject PySSLContext_Type = {
2102 PyVarObject_HEAD_INIT(NULL, 0)
2103 "_ssl._SSLContext", /*tp_name*/
2104 sizeof(PySSLContext), /*tp_basicsize*/
2105 0, /*tp_itemsize*/
2106 (destructor)context_dealloc, /*tp_dealloc*/
2107 0, /*tp_print*/
2108 0, /*tp_getattr*/
2109 0, /*tp_setattr*/
2110 0, /*tp_reserved*/
2111 0, /*tp_repr*/
2112 0, /*tp_as_number*/
2113 0, /*tp_as_sequence*/
2114 0, /*tp_as_mapping*/
2115 0, /*tp_hash*/
2116 0, /*tp_call*/
2117 0, /*tp_str*/
2118 0, /*tp_getattro*/
2119 0, /*tp_setattro*/
2120 0, /*tp_as_buffer*/
2121 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2122 0, /*tp_doc*/
2123 0, /*tp_traverse*/
2124 0, /*tp_clear*/
2125 0, /*tp_richcompare*/
2126 0, /*tp_weaklistoffset*/
2127 0, /*tp_iter*/
2128 0, /*tp_iternext*/
2129 context_methods, /*tp_methods*/
2130 0, /*tp_members*/
2131 context_getsetlist, /*tp_getset*/
2132 0, /*tp_base*/
2133 0, /*tp_dict*/
2134 0, /*tp_descr_get*/
2135 0, /*tp_descr_set*/
2136 0, /*tp_dictoffset*/
2137 0, /*tp_init*/
2138 0, /*tp_alloc*/
2139 context_new, /*tp_new*/
2140};
2141
2142
2143
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002144#ifdef HAVE_OPENSSL_RAND
2145
2146/* helper routines for seeding the SSL PRNG */
2147static PyObject *
2148PySSL_RAND_add(PyObject *self, PyObject *args)
2149{
2150 char *buf;
2151 int len;
2152 double entropy;
2153
2154 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002155 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156 RAND_add(buf, len, entropy);
2157 Py_INCREF(Py_None);
2158 return Py_None;
2159}
2160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002161PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002162"RAND_add(string, entropy)\n\
2163\n\
2164Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002165bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002166
2167static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002168PySSL_RAND(int len, int pseudo)
2169{
2170 int ok;
2171 PyObject *bytes;
2172 unsigned long err;
2173 const char *errstr;
2174 PyObject *v;
2175
2176 bytes = PyBytes_FromStringAndSize(NULL, len);
2177 if (bytes == NULL)
2178 return NULL;
2179 if (pseudo) {
2180 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2181 if (ok == 0 || ok == 1)
2182 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2183 }
2184 else {
2185 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2186 if (ok == 1)
2187 return bytes;
2188 }
2189 Py_DECREF(bytes);
2190
2191 err = ERR_get_error();
2192 errstr = ERR_reason_error_string(err);
2193 v = Py_BuildValue("(ks)", err, errstr);
2194 if (v != NULL) {
2195 PyErr_SetObject(PySSLErrorObject, v);
2196 Py_DECREF(v);
2197 }
2198 return NULL;
2199}
2200
2201static PyObject *
2202PySSL_RAND_bytes(PyObject *self, PyObject *args)
2203{
2204 int len;
2205 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2206 return NULL;
2207 return PySSL_RAND(len, 0);
2208}
2209
2210PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2211"RAND_bytes(n) -> bytes\n\
2212\n\
2213Generate n cryptographically strong pseudo-random bytes.");
2214
2215static PyObject *
2216PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2217{
2218 int len;
2219 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2220 return NULL;
2221 return PySSL_RAND(len, 1);
2222}
2223
2224PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2225"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2226\n\
2227Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2228generated are cryptographically strong.");
2229
2230static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002231PySSL_RAND_status(PyObject *self)
2232{
Christian Heimes217cfd12007-12-02 14:31:20 +00002233 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002234}
2235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002236PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002237"RAND_status() -> 0 or 1\n\
2238\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002239Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2240It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2241using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002242
2243static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002244PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002245{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002246 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002247 int bytes;
2248
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002249 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2250 PyUnicode_FSConverter, &path))
2251 return NULL;
2252
2253 bytes = RAND_egd(PyBytes_AsString(path));
2254 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002255 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002256 PyErr_SetString(PySSLErrorObject,
2257 "EGD connection failed or EGD did not return "
2258 "enough data to seed the PRNG");
2259 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002260 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002261 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002262}
2263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002264PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002265"RAND_egd(path) -> bytes\n\
2266\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002267Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2268Returns number of bytes read. Raises SSLError if connection to EGD\n\
2269fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002270
2271#endif
2272
Bill Janssen40a0f662008-08-12 16:56:25 +00002273
2274
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002275/* List of functions exported by this module. */
2276
2277static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 {"_test_decode_cert", PySSL_test_decode_certificate,
2279 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002280#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2282 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002283 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2284 PySSL_RAND_bytes_doc},
2285 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2286 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002287 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 PySSL_RAND_egd_doc},
2289 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2290 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002293};
2294
2295
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002296#ifdef WITH_THREAD
2297
2298/* an implementation of OpenSSL threading operations in terms
2299 of the Python C thread library */
2300
2301static PyThread_type_lock *_ssl_locks = NULL;
2302
2303static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002305}
2306
Bill Janssen6e027db2007-11-15 22:23:56 +00002307static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 (int mode, int n, const char *file, int line) {
2309 /* this function is needed to perform locking on shared data
2310 structures. (Note that OpenSSL uses a number of global data
2311 structures that will be implicitly shared whenever multiple
2312 threads use OpenSSL.) Multi-threaded applications will
2313 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 locking_function() must be able to handle up to
2316 CRYPTO_num_locks() different mutex locks. It sets the n-th
2317 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 file and line are the file number of the function setting the
2320 lock. They can be useful for debugging.
2321 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 if ((_ssl_locks == NULL) ||
2324 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2325 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 if (mode & CRYPTO_LOCK) {
2328 PyThread_acquire_lock(_ssl_locks[n], 1);
2329 } else {
2330 PyThread_release_lock(_ssl_locks[n]);
2331 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002332}
2333
2334static int _setup_ssl_threads(void) {
2335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 if (_ssl_locks == NULL) {
2339 _ssl_locks_count = CRYPTO_num_locks();
2340 _ssl_locks = (PyThread_type_lock *)
2341 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2342 if (_ssl_locks == NULL)
2343 return 0;
2344 memset(_ssl_locks, 0,
2345 sizeof(PyThread_type_lock) * _ssl_locks_count);
2346 for (i = 0; i < _ssl_locks_count; i++) {
2347 _ssl_locks[i] = PyThread_allocate_lock();
2348 if (_ssl_locks[i] == NULL) {
2349 unsigned int j;
2350 for (j = 0; j < i; j++) {
2351 PyThread_free_lock(_ssl_locks[j]);
2352 }
2353 free(_ssl_locks);
2354 return 0;
2355 }
2356 }
2357 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2358 CRYPTO_set_id_callback(_ssl_thread_id_function);
2359 }
2360 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002361}
2362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002365PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002366"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002367for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002368
Martin v. Löwis1a214512008-06-11 05:26:20 +00002369
2370static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 PyModuleDef_HEAD_INIT,
2372 "_ssl",
2373 module_doc,
2374 -1,
2375 PySSL_methods,
2376 NULL,
2377 NULL,
2378 NULL,
2379 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002380};
2381
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002382
2383static void
2384parse_openssl_version(unsigned long libver,
2385 unsigned int *major, unsigned int *minor,
2386 unsigned int *fix, unsigned int *patch,
2387 unsigned int *status)
2388{
2389 *status = libver & 0xF;
2390 libver >>= 4;
2391 *patch = libver & 0xFF;
2392 libver >>= 8;
2393 *fix = libver & 0xFF;
2394 libver >>= 8;
2395 *minor = libver & 0xFF;
2396 libver >>= 8;
2397 *major = libver & 0xFF;
2398}
2399
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002400PyDoc_STRVAR(SSLError_doc,
2401"An error occurred in the SSL implementation.");
2402
Antoine Pitrou41032a62011-10-27 23:56:55 +02002403PyDoc_STRVAR(SSLZeroReturnError_doc,
2404"SSL/TLS session closed cleanly.");
2405
2406PyDoc_STRVAR(SSLWantReadError_doc,
2407"Non-blocking SSL socket needs to read more data\n"
2408"before the requested operation can be completed.");
2409
2410PyDoc_STRVAR(SSLWantWriteError_doc,
2411"Non-blocking SSL socket needs to write more data\n"
2412"before the requested operation can be completed.");
2413
2414PyDoc_STRVAR(SSLSyscallError_doc,
2415"System error when attempting SSL operation.");
2416
2417PyDoc_STRVAR(SSLEOFError_doc,
2418"SSL/TLS connection terminated abruptly.");
2419
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002420
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002421PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002422PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002423{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 PyObject *m, *d, *r;
2425 unsigned long libver;
2426 unsigned int major, minor, fix, patch, status;
2427 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002428
Antoine Pitrou152efa22010-05-16 18:19:27 +00002429 if (PyType_Ready(&PySSLContext_Type) < 0)
2430 return NULL;
2431 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 m = PyModule_Create(&_sslmodule);
2435 if (m == NULL)
2436 return NULL;
2437 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 /* Load _socket module and its C API */
2440 socket_api = PySocketModule_ImportModuleAndAPI();
2441 if (!socket_api)
2442 return NULL;
2443 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 /* Init OpenSSL */
2446 SSL_load_error_strings();
2447 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002448#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 /* note that this will start threading if not already started */
2450 if (!_setup_ssl_threads()) {
2451 return NULL;
2452 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002453#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002457 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2458 SSLError_doc,
2459 PyExc_OSError,
2460 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 if (PySSLErrorObject == NULL)
2462 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002463 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2464 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2465 PySSLErrorObject, NULL);
2466 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2467 "ssl.SSLWantReadError", SSLWantReadError_doc,
2468 PySSLErrorObject, NULL);
2469 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2470 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2471 PySSLErrorObject, NULL);
2472 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2473 "ssl.SSLSyscallError", SSLSyscallError_doc,
2474 PySSLErrorObject, NULL);
2475 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2476 "ssl.SSLEOFError", SSLEOFError_doc,
2477 PySSLErrorObject, NULL);
2478 if (PySSLZeroReturnErrorObject == NULL
2479 || PySSLWantReadErrorObject == NULL
2480 || PySSLWantWriteErrorObject == NULL
2481 || PySSLSyscallErrorObject == NULL
2482 || PySSLEOFErrorObject == NULL)
2483 return NULL;
2484 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2485 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2486 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2487 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2488 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2489 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002491 if (PyDict_SetItemString(d, "_SSLContext",
2492 (PyObject *)&PySSLContext_Type) != 0)
2493 return NULL;
2494 if (PyDict_SetItemString(d, "_SSLSocket",
2495 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 return NULL;
2497 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2498 PY_SSL_ERROR_ZERO_RETURN);
2499 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2500 PY_SSL_ERROR_WANT_READ);
2501 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2502 PY_SSL_ERROR_WANT_WRITE);
2503 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2504 PY_SSL_ERROR_WANT_X509_LOOKUP);
2505 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2506 PY_SSL_ERROR_SYSCALL);
2507 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2508 PY_SSL_ERROR_SSL);
2509 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2510 PY_SSL_ERROR_WANT_CONNECT);
2511 /* non ssl.h errorcodes */
2512 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2513 PY_SSL_ERROR_EOF);
2514 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2515 PY_SSL_ERROR_INVALID_ERROR_CODE);
2516 /* cert requirements */
2517 PyModule_AddIntConstant(m, "CERT_NONE",
2518 PY_SSL_CERT_NONE);
2519 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2520 PY_SSL_CERT_OPTIONAL);
2521 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2522 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002525#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2527 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002528#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2530 PY_SSL_VERSION_SSL3);
2531 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2532 PY_SSL_VERSION_SSL23);
2533 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2534 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002535
Antoine Pitroub5218772010-05-21 09:56:06 +00002536 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002537 PyModule_AddIntConstant(m, "OP_ALL",
2538 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002539 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2540 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2541 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002542 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2543 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002544 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002545 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002546#ifdef SSL_OP_NO_COMPRESSION
2547 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2548 SSL_OP_NO_COMPRESSION);
2549#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002550
Antoine Pitroud5323212010-10-22 18:19:07 +00002551#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2552 r = Py_True;
2553#else
2554 r = Py_False;
2555#endif
2556 Py_INCREF(r);
2557 PyModule_AddObject(m, "HAS_SNI", r);
2558
Antoine Pitroud6494802011-07-21 01:11:30 +02002559#if HAVE_OPENSSL_FINISHED
2560 r = Py_True;
2561#else
2562 r = Py_False;
2563#endif
2564 Py_INCREF(r);
2565 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2566
Antoine Pitrou501da612011-12-21 09:27:41 +01002567#ifdef OPENSSL_NO_ECDH
2568 r = Py_False;
2569#else
2570 r = Py_True;
2571#endif
2572 Py_INCREF(r);
2573 PyModule_AddObject(m, "HAS_ECDH", r);
2574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 /* OpenSSL version */
2576 /* SSLeay() gives us the version of the library linked against,
2577 which could be different from the headers version.
2578 */
2579 libver = SSLeay();
2580 r = PyLong_FromUnsignedLong(libver);
2581 if (r == NULL)
2582 return NULL;
2583 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2584 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002585 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2587 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2588 return NULL;
2589 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2590 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2591 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002592
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002593 libver = OPENSSL_VERSION_NUMBER;
2594 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2595 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2596 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2597 return NULL;
2598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002599 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002600}