blob: 97fc07f718f01d451b0dd493a6142bb1e5d7b06f [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 */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100550 if (rdn != NULL) {
551 if (PyList_GET_SIZE(rdn) > 0) {
552 rdnt = PyList_AsTuple(rdn);
553 Py_DECREF(rdn);
554 if (rdnt == NULL)
555 goto fail0;
556 retcode = PyList_Append(dn, rdnt);
557 Py_DECREF(rdnt);
558 if (retcode < 0)
559 goto fail0;
560 }
561 else {
562 Py_DECREF(rdn);
563 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 /* convert list to tuple */
567 rdnt = PyList_AsTuple(dn);
568 Py_DECREF(dn);
569 if (rdnt == NULL)
570 return NULL;
571 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572
573 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000575
576 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 Py_XDECREF(dn);
578 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579}
580
581static PyObject *
582_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 /* this code follows the procedure outlined in
585 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
586 function to extract the STACK_OF(GENERAL_NAME),
587 then iterates through the stack to add the
588 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 int i, j;
591 PyObject *peer_alt_names = Py_None;
592 PyObject *v, *t;
593 X509_EXTENSION *ext = NULL;
594 GENERAL_NAMES *names = NULL;
595 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000596 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 BIO *biobuf = NULL;
598 char buf[2048];
599 char *vptr;
600 int len;
601 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000602#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000604#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000606#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 if (certificate == NULL)
609 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 /* get a memory buffer */
612 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200614 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 while ((i = X509_get_ext_by_NID(
616 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 if (peer_alt_names == Py_None) {
619 peer_alt_names = PyList_New(0);
620 if (peer_alt_names == NULL)
621 goto fail;
622 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 /* now decode the altName */
625 ext = X509_get_ext(certificate, i);
626 if(!(method = X509V3_EXT_get(ext))) {
627 PyErr_SetString
628 (PySSLErrorObject,
629 ERRSTR("No method for internalizing subjectAltName!"));
630 goto fail;
631 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 p = ext->value->data;
634 if (method->it)
635 names = (GENERAL_NAMES*)
636 (ASN1_item_d2i(NULL,
637 &p,
638 ext->value->length,
639 ASN1_ITEM_ptr(method->it)));
640 else
641 names = (GENERAL_NAMES*)
642 (method->d2i(NULL,
643 &p,
644 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000650 name = sk_GENERAL_NAME_value(names, j);
651 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 /* we special-case DirName as a tuple of
654 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 t = PyTuple_New(2);
657 if (t == NULL) {
658 goto fail;
659 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 v = PyUnicode_FromString("DirName");
662 if (v == NULL) {
663 Py_DECREF(t);
664 goto fail;
665 }
666 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 v = _create_tuple_for_X509_NAME (name->d.dirn);
669 if (v == NULL) {
670 Py_DECREF(t);
671 goto fail;
672 }
673 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 (void) BIO_reset(biobuf);
680 GENERAL_NAME_print(biobuf, name);
681 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
682 if (len < 0) {
683 _setSSLError(NULL, 0, __FILE__, __LINE__);
684 goto fail;
685 }
686 vptr = strchr(buf, ':');
687 if (vptr == NULL)
688 goto fail;
689 t = PyTuple_New(2);
690 if (t == NULL)
691 goto fail;
692 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
693 if (v == NULL) {
694 Py_DECREF(t);
695 goto fail;
696 }
697 PyTuple_SET_ITEM(t, 0, v);
698 v = PyUnicode_FromStringAndSize((vptr + 1),
699 (len - (vptr - buf + 1)));
700 if (v == NULL) {
701 Py_DECREF(t);
702 goto fail;
703 }
704 PyTuple_SET_ITEM(t, 1, v);
705 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 if (PyList_Append(peer_alt_names, t) < 0) {
710 Py_DECREF(t);
711 goto fail;
712 }
713 Py_DECREF(t);
714 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100715 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 }
717 BIO_free(biobuf);
718 if (peer_alt_names != Py_None) {
719 v = PyList_AsTuple(peer_alt_names);
720 Py_DECREF(peer_alt_names);
721 return v;
722 } else {
723 return peer_alt_names;
724 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000725
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
727 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 if (biobuf != NULL)
729 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 if (peer_alt_names != Py_None) {
732 Py_XDECREF(peer_alt_names);
733 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736}
737
738static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000739_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 PyObject *retval = NULL;
742 BIO *biobuf = NULL;
743 PyObject *peer;
744 PyObject *peer_alt_names = NULL;
745 PyObject *issuer;
746 PyObject *version;
747 PyObject *sn_obj;
748 ASN1_INTEGER *serialNumber;
749 char buf[2048];
750 int len;
751 ASN1_TIME *notBefore, *notAfter;
752 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 retval = PyDict_New();
755 if (retval == NULL)
756 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 peer = _create_tuple_for_X509_NAME(
759 X509_get_subject_name(certificate));
760 if (peer == NULL)
761 goto fail0;
762 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
763 Py_DECREF(peer);
764 goto fail0;
765 }
766 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000767
Antoine Pitroufb046912010-11-09 20:21:19 +0000768 issuer = _create_tuple_for_X509_NAME(
769 X509_get_issuer_name(certificate));
770 if (issuer == NULL)
771 goto fail0;
772 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000774 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000776 Py_DECREF(issuer);
777
778 version = PyLong_FromLong(X509_get_version(certificate) + 1);
779 if (PyDict_SetItemString(retval, "version", version) < 0) {
780 Py_DECREF(version);
781 goto fail0;
782 }
783 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* get a memory buffer */
786 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000787
Antoine Pitroufb046912010-11-09 20:21:19 +0000788 (void) BIO_reset(biobuf);
789 serialNumber = X509_get_serialNumber(certificate);
790 /* should not exceed 20 octets, 160 bits, so buf is big enough */
791 i2a_ASN1_INTEGER(biobuf, serialNumber);
792 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
793 if (len < 0) {
794 _setSSLError(NULL, 0, __FILE__, __LINE__);
795 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000797 sn_obj = PyUnicode_FromStringAndSize(buf, len);
798 if (sn_obj == NULL)
799 goto fail1;
800 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
801 Py_DECREF(sn_obj);
802 goto fail1;
803 }
804 Py_DECREF(sn_obj);
805
806 (void) BIO_reset(biobuf);
807 notBefore = X509_get_notBefore(certificate);
808 ASN1_TIME_print(biobuf, notBefore);
809 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
810 if (len < 0) {
811 _setSSLError(NULL, 0, __FILE__, __LINE__);
812 goto fail1;
813 }
814 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
815 if (pnotBefore == NULL)
816 goto fail1;
817 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
818 Py_DECREF(pnotBefore);
819 goto fail1;
820 }
821 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 (void) BIO_reset(biobuf);
824 notAfter = X509_get_notAfter(certificate);
825 ASN1_TIME_print(biobuf, notAfter);
826 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
827 if (len < 0) {
828 _setSSLError(NULL, 0, __FILE__, __LINE__);
829 goto fail1;
830 }
831 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
832 if (pnotAfter == NULL)
833 goto fail1;
834 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
835 Py_DECREF(pnotAfter);
836 goto fail1;
837 }
838 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 peer_alt_names = _get_peer_alt_names(certificate);
843 if (peer_alt_names == NULL)
844 goto fail1;
845 else if (peer_alt_names != Py_None) {
846 if (PyDict_SetItemString(retval, "subjectAltName",
847 peer_alt_names) < 0) {
848 Py_DECREF(peer_alt_names);
849 goto fail1;
850 }
851 Py_DECREF(peer_alt_names);
852 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 BIO_free(biobuf);
855 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000856
857 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 if (biobuf != NULL)
859 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000860 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 Py_XDECREF(retval);
862 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000863}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000864
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865
866static PyObject *
867PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000870 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 X509 *x=NULL;
872 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873
Antoine Pitroufb046912010-11-09 20:21:19 +0000874 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
875 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 if ((cert=BIO_new(BIO_s_file())) == NULL) {
879 PyErr_SetString(PySSLErrorObject,
880 "Can't malloc memory to read file");
881 goto fail0;
882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Victor Stinner3800e1e2010-05-16 21:23:48 +0000884 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 PyErr_SetString(PySSLErrorObject,
886 "Can't open file");
887 goto fail0;
888 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
891 if (x == NULL) {
892 PyErr_SetString(PySSLErrorObject,
893 "Error decoding PEM-encoded file");
894 goto fail0;
895 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896
Antoine Pitroufb046912010-11-09 20:21:19 +0000897 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000898 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
900 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000901 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 if (cert != NULL) BIO_free(cert);
903 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904}
905
906
907static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000908PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 PyObject *retval = NULL;
911 int len;
912 int verification;
913 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
916 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 if (!self->peer_cert)
919 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 if (PyObject_IsTrue(binary_mode)) {
922 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 bytes_buf = NULL;
927 len = i2d_X509(self->peer_cert, &bytes_buf);
928 if (len < 0) {
929 PySSL_SetError(self, len, __FILE__, __LINE__);
930 return NULL;
931 }
932 /* this is actually an immutable bytes sequence */
933 retval = PyBytes_FromStringAndSize
934 ((const char *) bytes_buf, len);
935 OPENSSL_free(bytes_buf);
936 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000939 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 if ((verification & SSL_VERIFY_PEER) == 0)
941 return PyDict_New();
942 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000943 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945}
946
947PyDoc_STRVAR(PySSL_peercert_doc,
948"peer_certificate([der=False]) -> certificate\n\
949\n\
950Returns the certificate for the peer. If no certificate was provided,\n\
951returns None. If a certificate was provided, but not validated, returns\n\
952an empty dictionary. Otherwise returns a dict containing information\n\
953about the peer certificate.\n\
954\n\
955If the optional argument is True, returns a DER-encoded copy of the\n\
956peer certificate, or None if no certificate was provided. This will\n\
957return the certificate even if it wasn't validated.");
958
Antoine Pitrou152efa22010-05-16 18:19:27 +0000959static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000962 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 char *cipher_name;
964 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000967 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 current = SSL_get_current_cipher(self->ssl);
969 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000970 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 retval = PyTuple_New(3);
973 if (retval == NULL)
974 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 cipher_name = (char *) SSL_CIPHER_get_name(current);
977 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000978 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 PyTuple_SET_ITEM(retval, 0, Py_None);
980 } else {
981 v = PyUnicode_FromString(cipher_name);
982 if (v == NULL)
983 goto fail0;
984 PyTuple_SET_ITEM(retval, 0, v);
985 }
986 cipher_protocol = SSL_CIPHER_get_version(current);
987 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000988 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 PyTuple_SET_ITEM(retval, 1, Py_None);
990 } else {
991 v = PyUnicode_FromString(cipher_protocol);
992 if (v == NULL)
993 goto fail0;
994 PyTuple_SET_ITEM(retval, 1, v);
995 }
996 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
997 if (v == NULL)
998 goto fail0;
999 PyTuple_SET_ITEM(retval, 2, v);
1000 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001001
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 Py_DECREF(retval);
1004 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001005}
1006
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001007static PyObject *PySSL_compression(PySSLSocket *self) {
1008#ifdef OPENSSL_NO_COMP
1009 Py_RETURN_NONE;
1010#else
1011 const COMP_METHOD *comp_method;
1012 const char *short_name;
1013
1014 if (self->ssl == NULL)
1015 Py_RETURN_NONE;
1016 comp_method = SSL_get_current_compression(self->ssl);
1017 if (comp_method == NULL || comp_method->type == NID_undef)
1018 Py_RETURN_NONE;
1019 short_name = OBJ_nid2sn(comp_method->type);
1020 if (short_name == NULL)
1021 Py_RETURN_NONE;
1022 return PyUnicode_DecodeFSDefault(short_name);
1023#endif
1024}
1025
Antoine Pitrou152efa22010-05-16 18:19:27 +00001026static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001027{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 if (self->peer_cert) /* Possible not to have one? */
1029 X509_free (self->peer_cert);
1030 if (self->ssl)
1031 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 Py_XDECREF(self->Socket);
1033 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001034}
1035
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001036/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001037 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001038 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001039 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001040
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001041static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001042check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001043{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 fd_set fds;
1045 struct timeval tv;
1046 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1049 if (s->sock_timeout < 0.0)
1050 return SOCKET_IS_BLOCKING;
1051 else if (s->sock_timeout == 0.0)
1052 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 /* Guard against closed socket */
1055 if (s->sock_fd < 0)
1056 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 /* Prefer poll, if available, since you can poll() any fd
1059 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001060#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 {
1062 struct pollfd pollfd;
1063 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 pollfd.fd = s->sock_fd;
1066 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 /* s->sock_timeout is in seconds, timeout in ms */
1069 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1070 PySSL_BEGIN_ALLOW_THREADS
1071 rc = poll(&pollfd, 1, timeout);
1072 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 goto normal_return;
1075 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001076#endif
1077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001079 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001081
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 /* Construct the arguments to select */
1083 tv.tv_sec = (int)s->sock_timeout;
1084 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1085 FD_ZERO(&fds);
1086 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001087
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 /* See if the socket is ready */
1089 PySSL_BEGIN_ALLOW_THREADS
1090 if (writing)
1091 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1092 else
1093 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1094 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001095
Bill Janssen6e027db2007-11-15 22:23:56 +00001096#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001097normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001098#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1100 (when we are able to write or when there's something to read) */
1101 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001102}
1103
Antoine Pitrou152efa22010-05-16 18:19:27 +00001104static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001105{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 Py_buffer buf;
1107 int len;
1108 int sockstate;
1109 int err;
1110 int nonblocking;
1111 PySocketSockObject *sock
1112 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 if (((PyObject*)sock) == Py_None) {
1115 _setSSLError("Underlying socket connection gone",
1116 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1117 return NULL;
1118 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001119 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001121 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1122 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001124 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125
1126 /* just in case the blocking state of the socket has been changed */
1127 nonblocking = (sock->sock_timeout >= 0.0);
1128 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1129 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1130
1131 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1132 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001133 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 "The write operation timed out");
1135 goto error;
1136 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1137 PyErr_SetString(PySSLErrorObject,
1138 "Underlying socket has been closed.");
1139 goto error;
1140 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1141 PyErr_SetString(PySSLErrorObject,
1142 "Underlying socket too large for select().");
1143 goto error;
1144 }
1145 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 PySSL_BEGIN_ALLOW_THREADS
1147 len = SSL_write(self->ssl, buf.buf, buf.len);
1148 err = SSL_get_error(self->ssl, len);
1149 PySSL_END_ALLOW_THREADS
1150 if (PyErr_CheckSignals()) {
1151 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001152 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001154 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001156 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 } else {
1158 sockstate = SOCKET_OPERATION_OK;
1159 }
1160 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001161 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 "The write operation timed out");
1163 goto error;
1164 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1165 PyErr_SetString(PySSLErrorObject,
1166 "Underlying socket has been closed.");
1167 goto error;
1168 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1169 break;
1170 }
1171 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001172
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001173 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 PyBuffer_Release(&buf);
1175 if (len > 0)
1176 return PyLong_FromLong(len);
1177 else
1178 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001179
1180error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001181 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 PyBuffer_Release(&buf);
1183 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001184}
1185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001186PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001187"write(s) -> len\n\
1188\n\
1189Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001190of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001191
Antoine Pitrou152efa22010-05-16 18:19:27 +00001192static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001193{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 PySSL_BEGIN_ALLOW_THREADS
1197 count = SSL_pending(self->ssl);
1198 PySSL_END_ALLOW_THREADS
1199 if (count < 0)
1200 return PySSL_SetError(self, count, __FILE__, __LINE__);
1201 else
1202 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001203}
1204
1205PyDoc_STRVAR(PySSL_SSLpending_doc,
1206"pending() -> count\n\
1207\n\
1208Returns the number of already decrypted bytes available for read,\n\
1209pending on the connection.\n");
1210
Antoine Pitrou152efa22010-05-16 18:19:27 +00001211static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001212{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 PyObject *dest = NULL;
1214 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001216 int len, count;
1217 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 int sockstate;
1219 int err;
1220 int nonblocking;
1221 PySocketSockObject *sock
1222 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001223
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 if (((PyObject*)sock) == Py_None) {
1225 _setSSLError("Underlying socket connection gone",
1226 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1227 return NULL;
1228 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001229 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001231 buf.obj = NULL;
1232 buf.buf = NULL;
1233 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001234 goto error;
1235
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001236 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1237 dest = PyBytes_FromStringAndSize(NULL, len);
1238 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001239 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001240 mem = PyBytes_AS_STRING(dest);
1241 }
1242 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001244 mem = buf.buf;
1245 if (len <= 0 || len > buf.len) {
1246 len = (int) buf.len;
1247 if (buf.len != len) {
1248 PyErr_SetString(PyExc_OverflowError,
1249 "maximum length can't fit in a C 'int'");
1250 goto error;
1251 }
1252 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 }
1254
1255 /* just in case the blocking state of the socket has been changed */
1256 nonblocking = (sock->sock_timeout >= 0.0);
1257 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1258 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1259
1260 /* first check if there are bytes ready to be read */
1261 PySSL_BEGIN_ALLOW_THREADS
1262 count = SSL_pending(self->ssl);
1263 PySSL_END_ALLOW_THREADS
1264
1265 if (!count) {
1266 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1267 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001268 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 "The read operation timed out");
1270 goto error;
1271 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1272 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001273 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 goto error;
1275 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1276 count = 0;
1277 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001278 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 }
1280 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 PySSL_BEGIN_ALLOW_THREADS
1282 count = SSL_read(self->ssl, mem, len);
1283 err = SSL_get_error(self->ssl, count);
1284 PySSL_END_ALLOW_THREADS
1285 if (PyErr_CheckSignals())
1286 goto error;
1287 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001288 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001290 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1292 (SSL_get_shutdown(self->ssl) ==
1293 SSL_RECEIVED_SHUTDOWN))
1294 {
1295 count = 0;
1296 goto done;
1297 } else {
1298 sockstate = SOCKET_OPERATION_OK;
1299 }
1300 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001301 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 "The read operation timed out");
1303 goto error;
1304 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1305 break;
1306 }
1307 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1308 if (count <= 0) {
1309 PySSL_SetError(self, count, __FILE__, __LINE__);
1310 goto error;
1311 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001312
1313done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001314 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001316 _PyBytes_Resize(&dest, count);
1317 return dest;
1318 }
1319 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 PyBuffer_Release(&buf);
1321 return PyLong_FromLong(count);
1322 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001323
1324error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001325 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001326 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001327 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001328 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001331}
1332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001333PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001334"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001335\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001336Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001337
Antoine Pitrou152efa22010-05-16 18:19:27 +00001338static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001339{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 int err, ssl_err, sockstate, nonblocking;
1341 int zeros = 0;
1342 PySocketSockObject *sock
1343 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 /* Guard against closed socket */
1346 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1347 _setSSLError("Underlying socket connection gone",
1348 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1349 return NULL;
1350 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001351 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352
1353 /* Just in case the blocking state of the socket has been changed */
1354 nonblocking = (sock->sock_timeout >= 0.0);
1355 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1356 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1357
1358 while (1) {
1359 PySSL_BEGIN_ALLOW_THREADS
1360 /* Disable read-ahead so that unwrap can work correctly.
1361 * Otherwise OpenSSL might read in too much data,
1362 * eating clear text data that happens to be
1363 * transmitted after the SSL shutdown.
1364 * Should be safe to call repeatedly everytime this
1365 * function is used and the shutdown_seen_zero != 0
1366 * condition is met.
1367 */
1368 if (self->shutdown_seen_zero)
1369 SSL_set_read_ahead(self->ssl, 0);
1370 err = SSL_shutdown(self->ssl);
1371 PySSL_END_ALLOW_THREADS
1372 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1373 if (err > 0)
1374 break;
1375 if (err == 0) {
1376 /* Don't loop endlessly; instead preserve legacy
1377 behaviour of trying SSL_shutdown() only twice.
1378 This looks necessary for OpenSSL < 0.9.8m */
1379 if (++zeros > 1)
1380 break;
1381 /* Shutdown was sent, now try receiving */
1382 self->shutdown_seen_zero = 1;
1383 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001384 }
1385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001386 /* Possibly retry shutdown until timeout or failure */
1387 ssl_err = SSL_get_error(self->ssl, err);
1388 if (ssl_err == SSL_ERROR_WANT_READ)
1389 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1390 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1391 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1392 else
1393 break;
1394 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1395 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001396 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 "The read operation timed out");
1398 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001399 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001401 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 }
1403 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1404 PyErr_SetString(PySSLErrorObject,
1405 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001406 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 }
1408 else if (sockstate != SOCKET_OPERATION_OK)
1409 /* Retain the SSL error code */
1410 break;
1411 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001412
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001413 if (err < 0) {
1414 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001417 else
1418 /* It's already INCREF'ed */
1419 return (PyObject *) sock;
1420
1421error:
1422 Py_DECREF(sock);
1423 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001424}
1425
1426PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1427"shutdown(s) -> socket\n\
1428\n\
1429Does the SSL shutdown handshake with the remote end, and returns\n\
1430the underlying socket object.");
1431
Antoine Pitroud6494802011-07-21 01:11:30 +02001432#if HAVE_OPENSSL_FINISHED
1433static PyObject *
1434PySSL_tls_unique_cb(PySSLSocket *self)
1435{
1436 PyObject *retval = NULL;
1437 char buf[PySSL_CB_MAXLEN];
1438 int len;
1439
1440 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1441 /* if session is resumed XOR we are the client */
1442 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1443 }
1444 else {
1445 /* if a new session XOR we are the server */
1446 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1447 }
1448
1449 /* It cannot be negative in current OpenSSL version as of July 2011 */
1450 assert(len >= 0);
1451 if (len == 0)
1452 Py_RETURN_NONE;
1453
1454 retval = PyBytes_FromStringAndSize(buf, len);
1455
1456 return retval;
1457}
1458
1459PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1460"tls_unique_cb() -> bytes\n\
1461\n\
1462Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1463\n\
1464If the TLS handshake is not yet complete, None is returned");
1465
1466#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001467
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001468static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1470 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1471 PySSL_SSLwrite_doc},
1472 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1473 PySSL_SSLread_doc},
1474 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1475 PySSL_SSLpending_doc},
1476 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1477 PySSL_peercert_doc},
1478 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001479 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1481 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001482#if HAVE_OPENSSL_FINISHED
1483 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1484 PySSL_tls_unique_cb_doc},
1485#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487};
1488
Antoine Pitrou152efa22010-05-16 18:19:27 +00001489static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001491 "_ssl._SSLSocket", /*tp_name*/
1492 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 0, /*tp_itemsize*/
1494 /* methods */
1495 (destructor)PySSL_dealloc, /*tp_dealloc*/
1496 0, /*tp_print*/
1497 0, /*tp_getattr*/
1498 0, /*tp_setattr*/
1499 0, /*tp_reserved*/
1500 0, /*tp_repr*/
1501 0, /*tp_as_number*/
1502 0, /*tp_as_sequence*/
1503 0, /*tp_as_mapping*/
1504 0, /*tp_hash*/
1505 0, /*tp_call*/
1506 0, /*tp_str*/
1507 0, /*tp_getattro*/
1508 0, /*tp_setattro*/
1509 0, /*tp_as_buffer*/
1510 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1511 0, /*tp_doc*/
1512 0, /*tp_traverse*/
1513 0, /*tp_clear*/
1514 0, /*tp_richcompare*/
1515 0, /*tp_weaklistoffset*/
1516 0, /*tp_iter*/
1517 0, /*tp_iternext*/
1518 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001519};
1520
Antoine Pitrou152efa22010-05-16 18:19:27 +00001521
1522/*
1523 * _SSLContext objects
1524 */
1525
1526static PyObject *
1527context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1528{
1529 char *kwlist[] = {"protocol", NULL};
1530 PySSLContext *self;
1531 int proto_version = PY_SSL_VERSION_SSL23;
1532 SSL_CTX *ctx = NULL;
1533
1534 if (!PyArg_ParseTupleAndKeywords(
1535 args, kwds, "i:_SSLContext", kwlist,
1536 &proto_version))
1537 return NULL;
1538
1539 PySSL_BEGIN_ALLOW_THREADS
1540 if (proto_version == PY_SSL_VERSION_TLS1)
1541 ctx = SSL_CTX_new(TLSv1_method());
1542 else if (proto_version == PY_SSL_VERSION_SSL3)
1543 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001544#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001545 else if (proto_version == PY_SSL_VERSION_SSL2)
1546 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001547#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001548 else if (proto_version == PY_SSL_VERSION_SSL23)
1549 ctx = SSL_CTX_new(SSLv23_method());
1550 else
1551 proto_version = -1;
1552 PySSL_END_ALLOW_THREADS
1553
1554 if (proto_version == -1) {
1555 PyErr_SetString(PyExc_ValueError,
1556 "invalid protocol version");
1557 return NULL;
1558 }
1559 if (ctx == NULL) {
1560 PyErr_SetString(PySSLErrorObject,
1561 "failed to allocate SSL context");
1562 return NULL;
1563 }
1564
1565 assert(type != NULL && type->tp_alloc != NULL);
1566 self = (PySSLContext *) type->tp_alloc(type, 0);
1567 if (self == NULL) {
1568 SSL_CTX_free(ctx);
1569 return NULL;
1570 }
1571 self->ctx = ctx;
1572 /* Defaults */
1573 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001574 SSL_CTX_set_options(self->ctx,
1575 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001576
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001577#define SID_CTX "Python"
1578 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1579 sizeof(SID_CTX));
1580#undef SID_CTX
1581
Antoine Pitrou152efa22010-05-16 18:19:27 +00001582 return (PyObject *)self;
1583}
1584
1585static void
1586context_dealloc(PySSLContext *self)
1587{
1588 SSL_CTX_free(self->ctx);
1589 Py_TYPE(self)->tp_free(self);
1590}
1591
1592static PyObject *
1593set_ciphers(PySSLContext *self, PyObject *args)
1594{
1595 int ret;
1596 const char *cipherlist;
1597
1598 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1599 return NULL;
1600 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1601 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001602 /* Clearing the error queue is necessary on some OpenSSL versions,
1603 otherwise the error will be reported again when another SSL call
1604 is done. */
1605 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001606 PyErr_SetString(PySSLErrorObject,
1607 "No cipher can be selected.");
1608 return NULL;
1609 }
1610 Py_RETURN_NONE;
1611}
1612
1613static PyObject *
1614get_verify_mode(PySSLContext *self, void *c)
1615{
1616 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1617 case SSL_VERIFY_NONE:
1618 return PyLong_FromLong(PY_SSL_CERT_NONE);
1619 case SSL_VERIFY_PEER:
1620 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1621 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1622 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1623 }
1624 PyErr_SetString(PySSLErrorObject,
1625 "invalid return value from SSL_CTX_get_verify_mode");
1626 return NULL;
1627}
1628
1629static int
1630set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1631{
1632 int n, mode;
1633 if (!PyArg_Parse(arg, "i", &n))
1634 return -1;
1635 if (n == PY_SSL_CERT_NONE)
1636 mode = SSL_VERIFY_NONE;
1637 else if (n == PY_SSL_CERT_OPTIONAL)
1638 mode = SSL_VERIFY_PEER;
1639 else if (n == PY_SSL_CERT_REQUIRED)
1640 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1641 else {
1642 PyErr_SetString(PyExc_ValueError,
1643 "invalid value for verify_mode");
1644 return -1;
1645 }
1646 SSL_CTX_set_verify(self->ctx, mode, NULL);
1647 return 0;
1648}
1649
1650static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001651get_options(PySSLContext *self, void *c)
1652{
1653 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1654}
1655
1656static int
1657set_options(PySSLContext *self, PyObject *arg, void *c)
1658{
1659 long new_opts, opts, set, clear;
1660 if (!PyArg_Parse(arg, "l", &new_opts))
1661 return -1;
1662 opts = SSL_CTX_get_options(self->ctx);
1663 clear = opts & ~new_opts;
1664 set = ~opts & new_opts;
1665 if (clear) {
1666#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1667 SSL_CTX_clear_options(self->ctx, clear);
1668#else
1669 PyErr_SetString(PyExc_ValueError,
1670 "can't clear options before OpenSSL 0.9.8m");
1671 return -1;
1672#endif
1673 }
1674 if (set)
1675 SSL_CTX_set_options(self->ctx, set);
1676 return 0;
1677}
1678
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001679typedef struct {
1680 PyThreadState *thread_state;
1681 PyObject *callable;
1682 char *password;
1683 Py_ssize_t size;
1684 int error;
1685} _PySSLPasswordInfo;
1686
1687static int
1688_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1689 const char *bad_type_error)
1690{
1691 /* Set the password and size fields of a _PySSLPasswordInfo struct
1692 from a unicode, bytes, or byte array object.
1693 The password field will be dynamically allocated and must be freed
1694 by the caller */
1695 PyObject *password_bytes = NULL;
1696 const char *data = NULL;
1697 Py_ssize_t size;
1698
1699 if (PyUnicode_Check(password)) {
1700 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1701 if (!password_bytes) {
1702 goto error;
1703 }
1704 data = PyBytes_AS_STRING(password_bytes);
1705 size = PyBytes_GET_SIZE(password_bytes);
1706 } else if (PyBytes_Check(password)) {
1707 data = PyBytes_AS_STRING(password);
1708 size = PyBytes_GET_SIZE(password);
1709 } else if (PyByteArray_Check(password)) {
1710 data = PyByteArray_AS_STRING(password);
1711 size = PyByteArray_GET_SIZE(password);
1712 } else {
1713 PyErr_SetString(PyExc_TypeError, bad_type_error);
1714 goto error;
1715 }
1716
1717 free(pw_info->password);
1718 pw_info->password = malloc(size);
1719 if (!pw_info->password) {
1720 PyErr_SetString(PyExc_MemoryError,
1721 "unable to allocate password buffer");
1722 goto error;
1723 }
1724 memcpy(pw_info->password, data, size);
1725 pw_info->size = size;
1726
1727 Py_XDECREF(password_bytes);
1728 return 1;
1729
1730error:
1731 Py_XDECREF(password_bytes);
1732 return 0;
1733}
1734
1735static int
1736_password_callback(char *buf, int size, int rwflag, void *userdata)
1737{
1738 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1739 PyObject *fn_ret = NULL;
1740
1741 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1742
1743 if (pw_info->callable) {
1744 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1745 if (!fn_ret) {
1746 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1747 core python API, so we could use it to add a frame here */
1748 goto error;
1749 }
1750
1751 if (!_pwinfo_set(pw_info, fn_ret,
1752 "password callback must return a string")) {
1753 goto error;
1754 }
1755 Py_CLEAR(fn_ret);
1756 }
1757
1758 if (pw_info->size > size) {
1759 PyErr_Format(PyExc_ValueError,
1760 "password cannot be longer than %d bytes", size);
1761 goto error;
1762 }
1763
1764 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1765 memcpy(buf, pw_info->password, pw_info->size);
1766 return pw_info->size;
1767
1768error:
1769 Py_XDECREF(fn_ret);
1770 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1771 pw_info->error = 1;
1772 return -1;
1773}
1774
Antoine Pitroub5218772010-05-21 09:56:06 +00001775static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001776load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1777{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001778 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1779 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001780 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001781 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1782 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1783 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001784 int r;
1785
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001786 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001787 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001788 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001789 "O|OO:load_cert_chain", kwlist,
1790 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001791 return NULL;
1792 if (keyfile == Py_None)
1793 keyfile = NULL;
1794 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1795 PyErr_SetString(PyExc_TypeError,
1796 "certfile should be a valid filesystem path");
1797 return NULL;
1798 }
1799 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1800 PyErr_SetString(PyExc_TypeError,
1801 "keyfile should be a valid filesystem path");
1802 goto error;
1803 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001804 if (password && password != Py_None) {
1805 if (PyCallable_Check(password)) {
1806 pw_info.callable = password;
1807 } else if (!_pwinfo_set(&pw_info, password,
1808 "password should be a string or callable")) {
1809 goto error;
1810 }
1811 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1812 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1813 }
1814 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001815 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1816 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001817 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001818 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001819 if (pw_info.error) {
1820 ERR_clear_error();
1821 /* the password callback has already set the error information */
1822 }
1823 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001824 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001825 PyErr_SetFromErrno(PyExc_IOError);
1826 }
1827 else {
1828 _setSSLError(NULL, 0, __FILE__, __LINE__);
1829 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001830 goto error;
1831 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001832 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001833 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001834 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1835 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001836 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1837 Py_CLEAR(keyfile_bytes);
1838 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001839 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001840 if (pw_info.error) {
1841 ERR_clear_error();
1842 /* the password callback has already set the error information */
1843 }
1844 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001845 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001846 PyErr_SetFromErrno(PyExc_IOError);
1847 }
1848 else {
1849 _setSSLError(NULL, 0, __FILE__, __LINE__);
1850 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001851 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001852 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001853 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001854 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001855 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001856 if (r != 1) {
1857 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001858 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001859 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001860 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1861 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1862 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001863 Py_RETURN_NONE;
1864
1865error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001866 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1867 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1868 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001869 Py_XDECREF(keyfile_bytes);
1870 Py_XDECREF(certfile_bytes);
1871 return NULL;
1872}
1873
1874static PyObject *
1875load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1876{
1877 char *kwlist[] = {"cafile", "capath", NULL};
1878 PyObject *cafile = NULL, *capath = NULL;
1879 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1880 const char *cafile_buf = NULL, *capath_buf = NULL;
1881 int r;
1882
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001883 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001884 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1885 "|OO:load_verify_locations", kwlist,
1886 &cafile, &capath))
1887 return NULL;
1888 if (cafile == Py_None)
1889 cafile = NULL;
1890 if (capath == Py_None)
1891 capath = NULL;
1892 if (cafile == NULL && capath == NULL) {
1893 PyErr_SetString(PyExc_TypeError,
1894 "cafile and capath cannot be both omitted");
1895 return NULL;
1896 }
1897 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1898 PyErr_SetString(PyExc_TypeError,
1899 "cafile should be a valid filesystem path");
1900 return NULL;
1901 }
1902 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001903 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001904 PyErr_SetString(PyExc_TypeError,
1905 "capath should be a valid filesystem path");
1906 return NULL;
1907 }
1908 if (cafile)
1909 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1910 if (capath)
1911 capath_buf = PyBytes_AS_STRING(capath_bytes);
1912 PySSL_BEGIN_ALLOW_THREADS
1913 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1914 PySSL_END_ALLOW_THREADS
1915 Py_XDECREF(cafile_bytes);
1916 Py_XDECREF(capath_bytes);
1917 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001918 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001919 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001920 PyErr_SetFromErrno(PyExc_IOError);
1921 }
1922 else {
1923 _setSSLError(NULL, 0, __FILE__, __LINE__);
1924 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001925 return NULL;
1926 }
1927 Py_RETURN_NONE;
1928}
1929
1930static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001931load_dh_params(PySSLContext *self, PyObject *filepath)
1932{
1933 FILE *f;
1934 DH *dh;
1935
1936 f = _Py_fopen(filepath, "rb");
1937 if (f == NULL) {
1938 if (!PyErr_Occurred())
1939 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1940 return NULL;
1941 }
1942 errno = 0;
1943 PySSL_BEGIN_ALLOW_THREADS
1944 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
1945 PySSL_END_ALLOW_THREADS
1946 if (dh == NULL) {
1947 if (errno != 0) {
1948 ERR_clear_error();
1949 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1950 }
1951 else {
1952 _setSSLError(NULL, 0, __FILE__, __LINE__);
1953 }
1954 return NULL;
1955 }
1956 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
1957 _setSSLError(NULL, 0, __FILE__, __LINE__);
1958 DH_free(dh);
1959 Py_RETURN_NONE;
1960}
1961
1962static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001963context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1964{
Antoine Pitroud5323212010-10-22 18:19:07 +00001965 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001966 PySocketSockObject *sock;
1967 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001968 char *hostname = NULL;
1969 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001970
Antoine Pitroud5323212010-10-22 18:19:07 +00001971 /* server_hostname is either None (or absent), or to be encoded
1972 using the idna encoding. */
1973 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001974 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001975 &sock, &server_side,
1976 Py_TYPE(Py_None), &hostname_obj)) {
1977 PyErr_Clear();
1978 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1979 PySocketModule.Sock_Type,
1980 &sock, &server_side,
1981 "idna", &hostname))
1982 return NULL;
1983#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1984 PyMem_Free(hostname);
1985 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1986 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001987 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001988#endif
1989 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001990
Antoine Pitroud5323212010-10-22 18:19:07 +00001991 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1992 hostname);
1993 if (hostname != NULL)
1994 PyMem_Free(hostname);
1995 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001996}
1997
Antoine Pitroub0182c82010-10-12 20:09:02 +00001998static PyObject *
1999session_stats(PySSLContext *self, PyObject *unused)
2000{
2001 int r;
2002 PyObject *value, *stats = PyDict_New();
2003 if (!stats)
2004 return NULL;
2005
2006#define ADD_STATS(SSL_NAME, KEY_NAME) \
2007 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2008 if (value == NULL) \
2009 goto error; \
2010 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2011 Py_DECREF(value); \
2012 if (r < 0) \
2013 goto error;
2014
2015 ADD_STATS(number, "number");
2016 ADD_STATS(connect, "connect");
2017 ADD_STATS(connect_good, "connect_good");
2018 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2019 ADD_STATS(accept, "accept");
2020 ADD_STATS(accept_good, "accept_good");
2021 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2022 ADD_STATS(accept, "accept");
2023 ADD_STATS(hits, "hits");
2024 ADD_STATS(misses, "misses");
2025 ADD_STATS(timeouts, "timeouts");
2026 ADD_STATS(cache_full, "cache_full");
2027
2028#undef ADD_STATS
2029
2030 return stats;
2031
2032error:
2033 Py_DECREF(stats);
2034 return NULL;
2035}
2036
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002037static PyObject *
2038set_default_verify_paths(PySSLContext *self, PyObject *unused)
2039{
2040 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2041 _setSSLError(NULL, 0, __FILE__, __LINE__);
2042 return NULL;
2043 }
2044 Py_RETURN_NONE;
2045}
2046
Antoine Pitrou501da612011-12-21 09:27:41 +01002047#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002048static PyObject *
2049set_ecdh_curve(PySSLContext *self, PyObject *name)
2050{
2051 PyObject *name_bytes;
2052 int nid;
2053 EC_KEY *key;
2054
2055 if (!PyUnicode_FSConverter(name, &name_bytes))
2056 return NULL;
2057 assert(PyBytes_Check(name_bytes));
2058 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2059 Py_DECREF(name_bytes);
2060 if (nid == 0) {
2061 PyErr_Format(PyExc_ValueError,
2062 "unknown elliptic curve name %R", name);
2063 return NULL;
2064 }
2065 key = EC_KEY_new_by_curve_name(nid);
2066 if (key == NULL) {
2067 _setSSLError(NULL, 0, __FILE__, __LINE__);
2068 return NULL;
2069 }
2070 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2071 EC_KEY_free(key);
2072 Py_RETURN_NONE;
2073}
Antoine Pitrou501da612011-12-21 09:27:41 +01002074#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002075
Antoine Pitrou152efa22010-05-16 18:19:27 +00002076static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002077 {"options", (getter) get_options,
2078 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002079 {"verify_mode", (getter) get_verify_mode,
2080 (setter) set_verify_mode, NULL},
2081 {NULL}, /* sentinel */
2082};
2083
2084static struct PyMethodDef context_methods[] = {
2085 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2086 METH_VARARGS | METH_KEYWORDS, NULL},
2087 {"set_ciphers", (PyCFunction) set_ciphers,
2088 METH_VARARGS, NULL},
2089 {"load_cert_chain", (PyCFunction) load_cert_chain,
2090 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002091 {"load_dh_params", (PyCFunction) load_dh_params,
2092 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002093 {"load_verify_locations", (PyCFunction) load_verify_locations,
2094 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002095 {"session_stats", (PyCFunction) session_stats,
2096 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002097 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2098 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002099#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002100 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2101 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002102#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002103 {NULL, NULL} /* sentinel */
2104};
2105
2106static PyTypeObject PySSLContext_Type = {
2107 PyVarObject_HEAD_INIT(NULL, 0)
2108 "_ssl._SSLContext", /*tp_name*/
2109 sizeof(PySSLContext), /*tp_basicsize*/
2110 0, /*tp_itemsize*/
2111 (destructor)context_dealloc, /*tp_dealloc*/
2112 0, /*tp_print*/
2113 0, /*tp_getattr*/
2114 0, /*tp_setattr*/
2115 0, /*tp_reserved*/
2116 0, /*tp_repr*/
2117 0, /*tp_as_number*/
2118 0, /*tp_as_sequence*/
2119 0, /*tp_as_mapping*/
2120 0, /*tp_hash*/
2121 0, /*tp_call*/
2122 0, /*tp_str*/
2123 0, /*tp_getattro*/
2124 0, /*tp_setattro*/
2125 0, /*tp_as_buffer*/
2126 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2127 0, /*tp_doc*/
2128 0, /*tp_traverse*/
2129 0, /*tp_clear*/
2130 0, /*tp_richcompare*/
2131 0, /*tp_weaklistoffset*/
2132 0, /*tp_iter*/
2133 0, /*tp_iternext*/
2134 context_methods, /*tp_methods*/
2135 0, /*tp_members*/
2136 context_getsetlist, /*tp_getset*/
2137 0, /*tp_base*/
2138 0, /*tp_dict*/
2139 0, /*tp_descr_get*/
2140 0, /*tp_descr_set*/
2141 0, /*tp_dictoffset*/
2142 0, /*tp_init*/
2143 0, /*tp_alloc*/
2144 context_new, /*tp_new*/
2145};
2146
2147
2148
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002149#ifdef HAVE_OPENSSL_RAND
2150
2151/* helper routines for seeding the SSL PRNG */
2152static PyObject *
2153PySSL_RAND_add(PyObject *self, PyObject *args)
2154{
2155 char *buf;
2156 int len;
2157 double entropy;
2158
2159 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002160 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002161 RAND_add(buf, len, entropy);
2162 Py_INCREF(Py_None);
2163 return Py_None;
2164}
2165
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002166PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002167"RAND_add(string, entropy)\n\
2168\n\
2169Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002170bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002171
2172static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002173PySSL_RAND(int len, int pseudo)
2174{
2175 int ok;
2176 PyObject *bytes;
2177 unsigned long err;
2178 const char *errstr;
2179 PyObject *v;
2180
2181 bytes = PyBytes_FromStringAndSize(NULL, len);
2182 if (bytes == NULL)
2183 return NULL;
2184 if (pseudo) {
2185 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2186 if (ok == 0 || ok == 1)
2187 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2188 }
2189 else {
2190 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2191 if (ok == 1)
2192 return bytes;
2193 }
2194 Py_DECREF(bytes);
2195
2196 err = ERR_get_error();
2197 errstr = ERR_reason_error_string(err);
2198 v = Py_BuildValue("(ks)", err, errstr);
2199 if (v != NULL) {
2200 PyErr_SetObject(PySSLErrorObject, v);
2201 Py_DECREF(v);
2202 }
2203 return NULL;
2204}
2205
2206static PyObject *
2207PySSL_RAND_bytes(PyObject *self, PyObject *args)
2208{
2209 int len;
2210 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2211 return NULL;
2212 return PySSL_RAND(len, 0);
2213}
2214
2215PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2216"RAND_bytes(n) -> bytes\n\
2217\n\
2218Generate n cryptographically strong pseudo-random bytes.");
2219
2220static PyObject *
2221PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2222{
2223 int len;
2224 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2225 return NULL;
2226 return PySSL_RAND(len, 1);
2227}
2228
2229PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2230"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2231\n\
2232Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2233generated are cryptographically strong.");
2234
2235static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002236PySSL_RAND_status(PyObject *self)
2237{
Christian Heimes217cfd12007-12-02 14:31:20 +00002238 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002239}
2240
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002241PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002242"RAND_status() -> 0 or 1\n\
2243\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002244Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2245It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2246using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002247
2248static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002249PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002250{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002251 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002252 int bytes;
2253
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002254 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2255 PyUnicode_FSConverter, &path))
2256 return NULL;
2257
2258 bytes = RAND_egd(PyBytes_AsString(path));
2259 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002260 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002261 PyErr_SetString(PySSLErrorObject,
2262 "EGD connection failed or EGD did not return "
2263 "enough data to seed the PRNG");
2264 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002265 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002266 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002267}
2268
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002269PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002270"RAND_egd(path) -> bytes\n\
2271\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002272Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2273Returns number of bytes read. Raises SSLError if connection to EGD\n\
2274fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002275
2276#endif
2277
Bill Janssen40a0f662008-08-12 16:56:25 +00002278
2279
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002280/* List of functions exported by this module. */
2281
2282static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 {"_test_decode_cert", PySSL_test_decode_certificate,
2284 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002285#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2287 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002288 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2289 PySSL_RAND_bytes_doc},
2290 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2291 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002292 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 PySSL_RAND_egd_doc},
2294 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2295 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002296#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002298};
2299
2300
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002301#ifdef WITH_THREAD
2302
2303/* an implementation of OpenSSL threading operations in terms
2304 of the Python C thread library */
2305
2306static PyThread_type_lock *_ssl_locks = NULL;
2307
2308static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002310}
2311
Bill Janssen6e027db2007-11-15 22:23:56 +00002312static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 (int mode, int n, const char *file, int line) {
2314 /* this function is needed to perform locking on shared data
2315 structures. (Note that OpenSSL uses a number of global data
2316 structures that will be implicitly shared whenever multiple
2317 threads use OpenSSL.) Multi-threaded applications will
2318 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 locking_function() must be able to handle up to
2321 CRYPTO_num_locks() different mutex locks. It sets the n-th
2322 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 file and line are the file number of the function setting the
2325 lock. They can be useful for debugging.
2326 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 if ((_ssl_locks == NULL) ||
2329 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2330 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 if (mode & CRYPTO_LOCK) {
2333 PyThread_acquire_lock(_ssl_locks[n], 1);
2334 } else {
2335 PyThread_release_lock(_ssl_locks[n]);
2336 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337}
2338
2339static int _setup_ssl_threads(void) {
2340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 if (_ssl_locks == NULL) {
2344 _ssl_locks_count = CRYPTO_num_locks();
2345 _ssl_locks = (PyThread_type_lock *)
2346 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2347 if (_ssl_locks == NULL)
2348 return 0;
2349 memset(_ssl_locks, 0,
2350 sizeof(PyThread_type_lock) * _ssl_locks_count);
2351 for (i = 0; i < _ssl_locks_count; i++) {
2352 _ssl_locks[i] = PyThread_allocate_lock();
2353 if (_ssl_locks[i] == NULL) {
2354 unsigned int j;
2355 for (j = 0; j < i; j++) {
2356 PyThread_free_lock(_ssl_locks[j]);
2357 }
2358 free(_ssl_locks);
2359 return 0;
2360 }
2361 }
2362 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2363 CRYPTO_set_id_callback(_ssl_thread_id_function);
2364 }
2365 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002366}
2367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002370PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002371"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002372for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002373
Martin v. Löwis1a214512008-06-11 05:26:20 +00002374
2375static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 PyModuleDef_HEAD_INIT,
2377 "_ssl",
2378 module_doc,
2379 -1,
2380 PySSL_methods,
2381 NULL,
2382 NULL,
2383 NULL,
2384 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002385};
2386
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002387
2388static void
2389parse_openssl_version(unsigned long libver,
2390 unsigned int *major, unsigned int *minor,
2391 unsigned int *fix, unsigned int *patch,
2392 unsigned int *status)
2393{
2394 *status = libver & 0xF;
2395 libver >>= 4;
2396 *patch = libver & 0xFF;
2397 libver >>= 8;
2398 *fix = libver & 0xFF;
2399 libver >>= 8;
2400 *minor = libver & 0xFF;
2401 libver >>= 8;
2402 *major = libver & 0xFF;
2403}
2404
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002405PyDoc_STRVAR(SSLError_doc,
2406"An error occurred in the SSL implementation.");
2407
Antoine Pitrou41032a62011-10-27 23:56:55 +02002408PyDoc_STRVAR(SSLZeroReturnError_doc,
2409"SSL/TLS session closed cleanly.");
2410
2411PyDoc_STRVAR(SSLWantReadError_doc,
2412"Non-blocking SSL socket needs to read more data\n"
2413"before the requested operation can be completed.");
2414
2415PyDoc_STRVAR(SSLWantWriteError_doc,
2416"Non-blocking SSL socket needs to write more data\n"
2417"before the requested operation can be completed.");
2418
2419PyDoc_STRVAR(SSLSyscallError_doc,
2420"System error when attempting SSL operation.");
2421
2422PyDoc_STRVAR(SSLEOFError_doc,
2423"SSL/TLS connection terminated abruptly.");
2424
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002425
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002426PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002427PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002428{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002429 PyObject *m, *d, *r;
2430 unsigned long libver;
2431 unsigned int major, minor, fix, patch, status;
2432 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002433
Antoine Pitrou152efa22010-05-16 18:19:27 +00002434 if (PyType_Ready(&PySSLContext_Type) < 0)
2435 return NULL;
2436 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 m = PyModule_Create(&_sslmodule);
2440 if (m == NULL)
2441 return NULL;
2442 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002443
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002444 /* Load _socket module and its C API */
2445 socket_api = PySocketModule_ImportModuleAndAPI();
2446 if (!socket_api)
2447 return NULL;
2448 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 /* Init OpenSSL */
2451 SSL_load_error_strings();
2452 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002453#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 /* note that this will start threading if not already started */
2455 if (!_setup_ssl_threads()) {
2456 return NULL;
2457 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002458#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002462 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2463 SSLError_doc,
2464 PyExc_OSError,
2465 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 if (PySSLErrorObject == NULL)
2467 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002468 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2469 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2470 PySSLErrorObject, NULL);
2471 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2472 "ssl.SSLWantReadError", SSLWantReadError_doc,
2473 PySSLErrorObject, NULL);
2474 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2475 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2476 PySSLErrorObject, NULL);
2477 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2478 "ssl.SSLSyscallError", SSLSyscallError_doc,
2479 PySSLErrorObject, NULL);
2480 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2481 "ssl.SSLEOFError", SSLEOFError_doc,
2482 PySSLErrorObject, NULL);
2483 if (PySSLZeroReturnErrorObject == NULL
2484 || PySSLWantReadErrorObject == NULL
2485 || PySSLWantWriteErrorObject == NULL
2486 || PySSLSyscallErrorObject == NULL
2487 || PySSLEOFErrorObject == NULL)
2488 return NULL;
2489 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2490 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2491 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2492 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2493 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2494 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002496 if (PyDict_SetItemString(d, "_SSLContext",
2497 (PyObject *)&PySSLContext_Type) != 0)
2498 return NULL;
2499 if (PyDict_SetItemString(d, "_SSLSocket",
2500 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002501 return NULL;
2502 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2503 PY_SSL_ERROR_ZERO_RETURN);
2504 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2505 PY_SSL_ERROR_WANT_READ);
2506 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2507 PY_SSL_ERROR_WANT_WRITE);
2508 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2509 PY_SSL_ERROR_WANT_X509_LOOKUP);
2510 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2511 PY_SSL_ERROR_SYSCALL);
2512 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2513 PY_SSL_ERROR_SSL);
2514 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2515 PY_SSL_ERROR_WANT_CONNECT);
2516 /* non ssl.h errorcodes */
2517 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2518 PY_SSL_ERROR_EOF);
2519 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2520 PY_SSL_ERROR_INVALID_ERROR_CODE);
2521 /* cert requirements */
2522 PyModule_AddIntConstant(m, "CERT_NONE",
2523 PY_SSL_CERT_NONE);
2524 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2525 PY_SSL_CERT_OPTIONAL);
2526 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2527 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002530#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2532 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002533#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2535 PY_SSL_VERSION_SSL3);
2536 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2537 PY_SSL_VERSION_SSL23);
2538 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2539 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002540
Antoine Pitroub5218772010-05-21 09:56:06 +00002541 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002542 PyModule_AddIntConstant(m, "OP_ALL",
2543 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002544 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2545 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2546 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002547 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2548 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002549 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002550 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002551#ifdef SSL_OP_NO_COMPRESSION
2552 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2553 SSL_OP_NO_COMPRESSION);
2554#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002555
Antoine Pitroud5323212010-10-22 18:19:07 +00002556#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2557 r = Py_True;
2558#else
2559 r = Py_False;
2560#endif
2561 Py_INCREF(r);
2562 PyModule_AddObject(m, "HAS_SNI", r);
2563
Antoine Pitroud6494802011-07-21 01:11:30 +02002564#if HAVE_OPENSSL_FINISHED
2565 r = Py_True;
2566#else
2567 r = Py_False;
2568#endif
2569 Py_INCREF(r);
2570 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2571
Antoine Pitrou501da612011-12-21 09:27:41 +01002572#ifdef OPENSSL_NO_ECDH
2573 r = Py_False;
2574#else
2575 r = Py_True;
2576#endif
2577 Py_INCREF(r);
2578 PyModule_AddObject(m, "HAS_ECDH", r);
2579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 /* OpenSSL version */
2581 /* SSLeay() gives us the version of the library linked against,
2582 which could be different from the headers version.
2583 */
2584 libver = SSLeay();
2585 r = PyLong_FromUnsignedLong(libver);
2586 if (r == NULL)
2587 return NULL;
2588 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2589 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002590 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2592 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2593 return NULL;
2594 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2595 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2596 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002597
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002598 libver = OPENSSL_VERSION_NUMBER;
2599 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2600 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2601 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2602 return NULL;
2603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002605}