blob: 8225e68f1d4e1aa66425ed2c26f681c86c92d56e [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
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100148/* ECDH support got added to OpenSSL in 0.9.8 */
149#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
150# define OPENSSL_NO_ECDH
151#endif
152
153
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000154typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000155 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000156 SSL_CTX *ctx;
157} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158
Antoine Pitrou152efa22010-05-16 18:19:27 +0000159typedef struct {
160 PyObject_HEAD
161 PyObject *Socket; /* weakref to socket on which we're layered */
162 SSL *ssl;
163 X509 *peer_cert;
164 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200165 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000166} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000167
Antoine Pitrou152efa22010-05-16 18:19:27 +0000168static PyTypeObject PySSLContext_Type;
169static PyTypeObject PySSLSocket_Type;
170
171static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
172static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000173static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000174 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000175static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
176static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177
Antoine Pitrou152efa22010-05-16 18:19:27 +0000178#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
179#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000180
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000181typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000182 SOCKET_IS_NONBLOCKING,
183 SOCKET_IS_BLOCKING,
184 SOCKET_HAS_TIMED_OUT,
185 SOCKET_HAS_BEEN_CLOSED,
186 SOCKET_TOO_LARGE_FOR_SELECT,
187 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000188} timeout_state;
189
Thomas Woutersed03b412007-08-28 21:37:11 +0000190/* Wrap error strings with filename and line # */
191#define STRINGIFY1(x) #x
192#define STRINGIFY2(x) STRINGIFY1(x)
193#define ERRSTR1(x,y,z) (x ":" y ": " z)
194#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
195
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000196/* XXX It might be helpful to augment the error message generated
197 below with the name of the SSL function that generated the error.
198 I expect it's obvious most of the time.
199*/
200
201static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000203{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000204 PyObject *v;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200205 PyObject *type = PySSLErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000206 char buf[2048];
207 char *errstr;
208 int err;
209 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 assert(ret <= 0);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 if (obj->ssl != NULL) {
214 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000216 switch (err) {
217 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200218 errstr = "TLS/SSL connection has been closed (EOF)";
219 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 p = PY_SSL_ERROR_ZERO_RETURN;
221 break;
222 case SSL_ERROR_WANT_READ:
223 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200224 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 p = PY_SSL_ERROR_WANT_READ;
226 break;
227 case SSL_ERROR_WANT_WRITE:
228 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200229 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000230 errstr = "The operation did not complete (write)";
231 break;
232 case SSL_ERROR_WANT_X509_LOOKUP:
233 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000234 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000235 break;
236 case SSL_ERROR_WANT_CONNECT:
237 p = PY_SSL_ERROR_WANT_CONNECT;
238 errstr = "The operation did not complete (connect)";
239 break;
240 case SSL_ERROR_SYSCALL:
241 {
242 unsigned long e = ERR_get_error();
243 if (e == 0) {
244 PySocketSockObject *s
245 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
246 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000247 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200248 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000249 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000250 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000251 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000252 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000253 ERR_clear_error();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000254 v = s->errorhandler();
255 Py_DECREF(s);
256 return v;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000257 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000258 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200259 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000260 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000261 }
262 } else {
263 p = PY_SSL_ERROR_SYSCALL;
264 /* XXX Protected by global interpreter lock */
265 errstr = ERR_error_string(e, NULL);
266 }
267 break;
268 }
269 case SSL_ERROR_SSL:
270 {
271 unsigned long e = ERR_get_error();
272 p = PY_SSL_ERROR_SSL;
273 if (e != 0)
274 /* XXX Protected by global interpreter lock */
275 errstr = ERR_error_string(e, NULL);
276 else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000277 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000278 }
279 break;
280 }
281 default:
282 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
283 errstr = "Invalid error code";
284 }
285 } else {
286 errstr = ERR_error_string(ERR_peek_last_error(), NULL);
287 }
288 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000289 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 v = Py_BuildValue("(is)", p, buf);
291 if (v != NULL) {
Antoine Pitrou41032a62011-10-27 23:56:55 +0200292 PyErr_SetObject(type, v);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 Py_DECREF(v);
294 }
295 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296}
297
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000298static PyObject *
299_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000301 char buf[2048];
302 PyObject *v;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 if (errstr == NULL) {
305 errcode = ERR_peek_last_error();
306 errstr = ERR_error_string(errcode, NULL);
307 }
308 PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000309 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000310 v = Py_BuildValue("(is)", errcode, buf);
311 if (v != NULL) {
312 PyErr_SetObject(PySSLErrorObject, v);
313 Py_DECREF(v);
314 }
315 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000316}
317
Antoine Pitrou152efa22010-05-16 18:19:27 +0000318static PySSLSocket *
319newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000320 enum py_ssl_server_or_client socket_type,
321 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000322{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000324
Antoine Pitrou152efa22010-05-16 18:19:27 +0000325 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000326 if (self == NULL)
327 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000329 self->peer_cert = NULL;
330 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000331 self->Socket = NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000333 /* Make sure the SSL error state is initialized */
334 (void) ERR_get_state();
335 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000337 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000339 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000341#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000343#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000344
Antoine Pitroud5323212010-10-22 18:19:07 +0000345#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
346 if (server_hostname != NULL)
347 SSL_set_tlsext_host_name(self->ssl, server_hostname);
348#endif
349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000350 /* If the socket is in non-blocking mode or timeout mode, set the BIO
351 * to non-blocking mode (blocking is the default)
352 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000353 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000354 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
355 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
356 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000358 PySSL_BEGIN_ALLOW_THREADS
359 if (socket_type == PY_SSL_CLIENT)
360 SSL_set_connect_state(self->ssl);
361 else
362 SSL_set_accept_state(self->ssl);
363 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000364
Antoine Pitroud6494802011-07-21 01:11:30 +0200365 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000366 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000367 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000368}
369
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000370/* SSL object methods */
371
Antoine Pitrou152efa22010-05-16 18:19:27 +0000372static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000373{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 int ret;
375 int err;
376 int sockstate, nonblocking;
377 PySocketSockObject *sock
378 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000380 if (((PyObject*)sock) == Py_None) {
381 _setSSLError("Underlying socket connection gone",
382 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
383 return NULL;
384 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000385 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 /* just in case the blocking state of the socket has been changed */
388 nonblocking = (sock->sock_timeout >= 0.0);
389 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
390 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 /* Actually negotiate SSL connection */
393 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000395 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 ret = SSL_do_handshake(self->ssl);
397 err = SSL_get_error(self->ssl, ret);
398 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000399 if (PyErr_CheckSignals())
400 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 if (err == SSL_ERROR_WANT_READ) {
402 sockstate = check_socket_and_wait_for_timeout(sock, 0);
403 } else if (err == SSL_ERROR_WANT_WRITE) {
404 sockstate = check_socket_and_wait_for_timeout(sock, 1);
405 } else {
406 sockstate = SOCKET_OPERATION_OK;
407 }
408 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000409 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000410 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000411 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000412 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
413 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000414 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000415 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
417 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000418 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000419 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000420 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
421 break;
422 }
423 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 if (ret < 1)
426 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000428 if (self->peer_cert)
429 X509_free (self->peer_cert);
430 PySSL_BEGIN_ALLOW_THREADS
431 self->peer_cert = SSL_get_peer_certificate(self->ssl);
432 PySSL_END_ALLOW_THREADS
433
434 Py_INCREF(Py_None);
435 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000436
437error:
438 Py_DECREF(sock);
439 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000440}
441
Thomas Woutersed03b412007-08-28 21:37:11 +0000442static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000443_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 char namebuf[X509_NAME_MAXLEN];
446 int buflen;
447 PyObject *name_obj;
448 PyObject *value_obj;
449 PyObject *attr;
450 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
453 if (buflen < 0) {
454 _setSSLError(NULL, 0, __FILE__, __LINE__);
455 goto fail;
456 }
457 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
458 if (name_obj == NULL)
459 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
462 if (buflen < 0) {
463 _setSSLError(NULL, 0, __FILE__, __LINE__);
464 Py_DECREF(name_obj);
465 goto fail;
466 }
467 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000468 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000469 OPENSSL_free(valuebuf);
470 if (value_obj == NULL) {
471 Py_DECREF(name_obj);
472 goto fail;
473 }
474 attr = PyTuple_New(2);
475 if (attr == NULL) {
476 Py_DECREF(name_obj);
477 Py_DECREF(value_obj);
478 goto fail;
479 }
480 PyTuple_SET_ITEM(attr, 0, name_obj);
481 PyTuple_SET_ITEM(attr, 1, value_obj);
482 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000483
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000486}
487
488static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000489_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000490{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
492 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
493 PyObject *rdnt;
494 PyObject *attr = NULL; /* tuple to hold an attribute */
495 int entry_count = X509_NAME_entry_count(xname);
496 X509_NAME_ENTRY *entry;
497 ASN1_OBJECT *name;
498 ASN1_STRING *value;
499 int index_counter;
500 int rdn_level = -1;
501 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 dn = PyList_New(0);
504 if (dn == NULL)
505 return NULL;
506 /* now create another tuple to hold the top-level RDN */
507 rdn = PyList_New(0);
508 if (rdn == NULL)
509 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 for (index_counter = 0;
512 index_counter < entry_count;
513 index_counter++)
514 {
515 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 /* check to see if we've gotten to a new RDN */
518 if (rdn_level >= 0) {
519 if (rdn_level != entry->set) {
520 /* yes, new RDN */
521 /* add old RDN to DN */
522 rdnt = PyList_AsTuple(rdn);
523 Py_DECREF(rdn);
524 if (rdnt == NULL)
525 goto fail0;
526 retcode = PyList_Append(dn, rdnt);
527 Py_DECREF(rdnt);
528 if (retcode < 0)
529 goto fail0;
530 /* create new RDN */
531 rdn = PyList_New(0);
532 if (rdn == NULL)
533 goto fail0;
534 }
535 }
536 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 /* now add this attribute to the current RDN */
539 name = X509_NAME_ENTRY_get_object(entry);
540 value = X509_NAME_ENTRY_get_data(entry);
541 attr = _create_tuple_for_attribute(name, value);
542 /*
543 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
544 entry->set,
545 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
546 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
547 */
548 if (attr == NULL)
549 goto fail1;
550 retcode = PyList_Append(rdn, attr);
551 Py_DECREF(attr);
552 if (retcode < 0)
553 goto fail1;
554 }
555 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100556 if (rdn != NULL) {
557 if (PyList_GET_SIZE(rdn) > 0) {
558 rdnt = PyList_AsTuple(rdn);
559 Py_DECREF(rdn);
560 if (rdnt == NULL)
561 goto fail0;
562 retcode = PyList_Append(dn, rdnt);
563 Py_DECREF(rdnt);
564 if (retcode < 0)
565 goto fail0;
566 }
567 else {
568 Py_DECREF(rdn);
569 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 /* convert list to tuple */
573 rdnt = PyList_AsTuple(dn);
574 Py_DECREF(dn);
575 if (rdnt == NULL)
576 return NULL;
577 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
579 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
582 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 Py_XDECREF(dn);
584 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585}
586
587static PyObject *
588_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 /* this code follows the procedure outlined in
591 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
592 function to extract the STACK_OF(GENERAL_NAME),
593 then iterates through the stack to add the
594 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 int i, j;
597 PyObject *peer_alt_names = Py_None;
598 PyObject *v, *t;
599 X509_EXTENSION *ext = NULL;
600 GENERAL_NAMES *names = NULL;
601 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000602 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000603 BIO *biobuf = NULL;
604 char buf[2048];
605 char *vptr;
606 int len;
607 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000608#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000610#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000612#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 if (certificate == NULL)
615 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 /* get a memory buffer */
618 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200620 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 while ((i = X509_get_ext_by_NID(
622 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 if (peer_alt_names == Py_None) {
625 peer_alt_names = PyList_New(0);
626 if (peer_alt_names == NULL)
627 goto fail;
628 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 /* now decode the altName */
631 ext = X509_get_ext(certificate, i);
632 if(!(method = X509V3_EXT_get(ext))) {
633 PyErr_SetString
634 (PySSLErrorObject,
635 ERRSTR("No method for internalizing subjectAltName!"));
636 goto fail;
637 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 p = ext->value->data;
640 if (method->it)
641 names = (GENERAL_NAMES*)
642 (ASN1_item_d2i(NULL,
643 &p,
644 ext->value->length,
645 ASN1_ITEM_ptr(method->it)));
646 else
647 names = (GENERAL_NAMES*)
648 (method->d2i(NULL,
649 &p,
650 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 name = sk_GENERAL_NAME_value(names, j);
657 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 /* we special-case DirName as a tuple of
660 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 t = PyTuple_New(2);
663 if (t == NULL) {
664 goto fail;
665 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 v = PyUnicode_FromString("DirName");
668 if (v == NULL) {
669 Py_DECREF(t);
670 goto fail;
671 }
672 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 v = _create_tuple_for_X509_NAME (name->d.dirn);
675 if (v == NULL) {
676 Py_DECREF(t);
677 goto fail;
678 }
679 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 (void) BIO_reset(biobuf);
686 GENERAL_NAME_print(biobuf, name);
687 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
688 if (len < 0) {
689 _setSSLError(NULL, 0, __FILE__, __LINE__);
690 goto fail;
691 }
692 vptr = strchr(buf, ':');
693 if (vptr == NULL)
694 goto fail;
695 t = PyTuple_New(2);
696 if (t == NULL)
697 goto fail;
698 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
699 if (v == NULL) {
700 Py_DECREF(t);
701 goto fail;
702 }
703 PyTuple_SET_ITEM(t, 0, v);
704 v = PyUnicode_FromStringAndSize((vptr + 1),
705 (len - (vptr - buf + 1)));
706 if (v == NULL) {
707 Py_DECREF(t);
708 goto fail;
709 }
710 PyTuple_SET_ITEM(t, 1, v);
711 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 if (PyList_Append(peer_alt_names, t) < 0) {
716 Py_DECREF(t);
717 goto fail;
718 }
719 Py_DECREF(t);
720 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100721 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 }
723 BIO_free(biobuf);
724 if (peer_alt_names != Py_None) {
725 v = PyList_AsTuple(peer_alt_names);
726 Py_DECREF(peer_alt_names);
727 return v;
728 } else {
729 return peer_alt_names;
730 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000731
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
733 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 if (biobuf != NULL)
735 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 if (peer_alt_names != Py_None) {
738 Py_XDECREF(peer_alt_names);
739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742}
743
744static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000745_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 PyObject *retval = NULL;
748 BIO *biobuf = NULL;
749 PyObject *peer;
750 PyObject *peer_alt_names = NULL;
751 PyObject *issuer;
752 PyObject *version;
753 PyObject *sn_obj;
754 ASN1_INTEGER *serialNumber;
755 char buf[2048];
756 int len;
757 ASN1_TIME *notBefore, *notAfter;
758 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 retval = PyDict_New();
761 if (retval == NULL)
762 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 peer = _create_tuple_for_X509_NAME(
765 X509_get_subject_name(certificate));
766 if (peer == NULL)
767 goto fail0;
768 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
769 Py_DECREF(peer);
770 goto fail0;
771 }
772 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000773
Antoine Pitroufb046912010-11-09 20:21:19 +0000774 issuer = _create_tuple_for_X509_NAME(
775 X509_get_issuer_name(certificate));
776 if (issuer == NULL)
777 goto fail0;
778 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000780 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000782 Py_DECREF(issuer);
783
784 version = PyLong_FromLong(X509_get_version(certificate) + 1);
785 if (PyDict_SetItemString(retval, "version", version) < 0) {
786 Py_DECREF(version);
787 goto fail0;
788 }
789 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 /* get a memory buffer */
792 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000793
Antoine Pitroufb046912010-11-09 20:21:19 +0000794 (void) BIO_reset(biobuf);
795 serialNumber = X509_get_serialNumber(certificate);
796 /* should not exceed 20 octets, 160 bits, so buf is big enough */
797 i2a_ASN1_INTEGER(biobuf, serialNumber);
798 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
799 if (len < 0) {
800 _setSSLError(NULL, 0, __FILE__, __LINE__);
801 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000803 sn_obj = PyUnicode_FromStringAndSize(buf, len);
804 if (sn_obj == NULL)
805 goto fail1;
806 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
807 Py_DECREF(sn_obj);
808 goto fail1;
809 }
810 Py_DECREF(sn_obj);
811
812 (void) BIO_reset(biobuf);
813 notBefore = X509_get_notBefore(certificate);
814 ASN1_TIME_print(biobuf, notBefore);
815 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
816 if (len < 0) {
817 _setSSLError(NULL, 0, __FILE__, __LINE__);
818 goto fail1;
819 }
820 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
821 if (pnotBefore == NULL)
822 goto fail1;
823 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
824 Py_DECREF(pnotBefore);
825 goto fail1;
826 }
827 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 (void) BIO_reset(biobuf);
830 notAfter = X509_get_notAfter(certificate);
831 ASN1_TIME_print(biobuf, notAfter);
832 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
833 if (len < 0) {
834 _setSSLError(NULL, 0, __FILE__, __LINE__);
835 goto fail1;
836 }
837 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
838 if (pnotAfter == NULL)
839 goto fail1;
840 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
841 Py_DECREF(pnotAfter);
842 goto fail1;
843 }
844 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 peer_alt_names = _get_peer_alt_names(certificate);
849 if (peer_alt_names == NULL)
850 goto fail1;
851 else if (peer_alt_names != Py_None) {
852 if (PyDict_SetItemString(retval, "subjectAltName",
853 peer_alt_names) < 0) {
854 Py_DECREF(peer_alt_names);
855 goto fail1;
856 }
857 Py_DECREF(peer_alt_names);
858 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000859
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 BIO_free(biobuf);
861 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000862
863 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 if (biobuf != NULL)
865 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000866 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 Py_XDECREF(retval);
868 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000869}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000870
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
872static PyObject *
873PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000876 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 X509 *x=NULL;
878 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroufb046912010-11-09 20:21:19 +0000880 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
881 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 if ((cert=BIO_new(BIO_s_file())) == NULL) {
885 PyErr_SetString(PySSLErrorObject,
886 "Can't malloc memory to read file");
887 goto fail0;
888 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Victor Stinner3800e1e2010-05-16 21:23:48 +0000890 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 PyErr_SetString(PySSLErrorObject,
892 "Can't open file");
893 goto fail0;
894 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
897 if (x == NULL) {
898 PyErr_SetString(PySSLErrorObject,
899 "Error decoding PEM-encoded file");
900 goto fail0;
901 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902
Antoine Pitroufb046912010-11-09 20:21:19 +0000903 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +0000904 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905
906 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +0000907 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 if (cert != NULL) BIO_free(cert);
909 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000910}
911
912
913static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000914PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 PyObject *retval = NULL;
917 int len;
918 int verification;
919 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
922 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 if (!self->peer_cert)
925 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 if (PyObject_IsTrue(binary_mode)) {
928 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 bytes_buf = NULL;
933 len = i2d_X509(self->peer_cert, &bytes_buf);
934 if (len < 0) {
935 PySSL_SetError(self, len, __FILE__, __LINE__);
936 return NULL;
937 }
938 /* this is actually an immutable bytes sequence */
939 retval = PyBytes_FromStringAndSize
940 ((const char *) bytes_buf, len);
941 OPENSSL_free(bytes_buf);
942 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000945 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 if ((verification & SSL_VERIFY_PEER) == 0)
947 return PyDict_New();
948 else
Antoine Pitroufb046912010-11-09 20:21:19 +0000949 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951}
952
953PyDoc_STRVAR(PySSL_peercert_doc,
954"peer_certificate([der=False]) -> certificate\n\
955\n\
956Returns the certificate for the peer. If no certificate was provided,\n\
957returns None. If a certificate was provided, but not validated, returns\n\
958an empty dictionary. Otherwise returns a dict containing information\n\
959about the peer certificate.\n\
960\n\
961If the optional argument is True, returns a DER-encoded copy of the\n\
962peer certificate, or None if no certificate was provided. This will\n\
963return the certificate even if it wasn't validated.");
964
Antoine Pitrou152efa22010-05-16 18:19:27 +0000965static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000968 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 char *cipher_name;
970 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000973 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 current = SSL_get_current_cipher(self->ssl);
975 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000976 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 retval = PyTuple_New(3);
979 if (retval == NULL)
980 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 cipher_name = (char *) SSL_CIPHER_get_name(current);
983 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000984 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 PyTuple_SET_ITEM(retval, 0, Py_None);
986 } else {
987 v = PyUnicode_FromString(cipher_name);
988 if (v == NULL)
989 goto fail0;
990 PyTuple_SET_ITEM(retval, 0, v);
991 }
992 cipher_protocol = SSL_CIPHER_get_version(current);
993 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +0000994 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 PyTuple_SET_ITEM(retval, 1, Py_None);
996 } else {
997 v = PyUnicode_FromString(cipher_protocol);
998 if (v == NULL)
999 goto fail0;
1000 PyTuple_SET_ITEM(retval, 1, v);
1001 }
1002 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1003 if (v == NULL)
1004 goto fail0;
1005 PyTuple_SET_ITEM(retval, 2, v);
1006 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001008 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 Py_DECREF(retval);
1010 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011}
1012
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001013static PyObject *PySSL_compression(PySSLSocket *self) {
1014#ifdef OPENSSL_NO_COMP
1015 Py_RETURN_NONE;
1016#else
1017 const COMP_METHOD *comp_method;
1018 const char *short_name;
1019
1020 if (self->ssl == NULL)
1021 Py_RETURN_NONE;
1022 comp_method = SSL_get_current_compression(self->ssl);
1023 if (comp_method == NULL || comp_method->type == NID_undef)
1024 Py_RETURN_NONE;
1025 short_name = OBJ_nid2sn(comp_method->type);
1026 if (short_name == NULL)
1027 Py_RETURN_NONE;
1028 return PyUnicode_DecodeFSDefault(short_name);
1029#endif
1030}
1031
Antoine Pitrou152efa22010-05-16 18:19:27 +00001032static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001033{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 if (self->peer_cert) /* Possible not to have one? */
1035 X509_free (self->peer_cert);
1036 if (self->ssl)
1037 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 Py_XDECREF(self->Socket);
1039 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001040}
1041
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001043 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001044 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001045 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001046
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001047static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001048check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001049{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 fd_set fds;
1051 struct timeval tv;
1052 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1055 if (s->sock_timeout < 0.0)
1056 return SOCKET_IS_BLOCKING;
1057 else if (s->sock_timeout == 0.0)
1058 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 /* Guard against closed socket */
1061 if (s->sock_fd < 0)
1062 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 /* Prefer poll, if available, since you can poll() any fd
1065 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001066#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 {
1068 struct pollfd pollfd;
1069 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 pollfd.fd = s->sock_fd;
1072 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 /* s->sock_timeout is in seconds, timeout in ms */
1075 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1076 PySSL_BEGIN_ALLOW_THREADS
1077 rc = poll(&pollfd, 1, timeout);
1078 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 goto normal_return;
1081 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001082#endif
1083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001085 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001087
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 /* Construct the arguments to select */
1089 tv.tv_sec = (int)s->sock_timeout;
1090 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1091 FD_ZERO(&fds);
1092 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 /* See if the socket is ready */
1095 PySSL_BEGIN_ALLOW_THREADS
1096 if (writing)
1097 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1098 else
1099 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1100 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001101
Bill Janssen6e027db2007-11-15 22:23:56 +00001102#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001103normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001104#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1106 (when we are able to write or when there's something to read) */
1107 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001108}
1109
Antoine Pitrou152efa22010-05-16 18:19:27 +00001110static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001111{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 Py_buffer buf;
1113 int len;
1114 int sockstate;
1115 int err;
1116 int nonblocking;
1117 PySocketSockObject *sock
1118 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 if (((PyObject*)sock) == Py_None) {
1121 _setSSLError("Underlying socket connection gone",
1122 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1123 return NULL;
1124 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001125 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001127 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1128 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001130 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131
1132 /* just in case the blocking state of the socket has been changed */
1133 nonblocking = (sock->sock_timeout >= 0.0);
1134 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1135 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1136
1137 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1138 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001139 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 "The write operation timed out");
1141 goto error;
1142 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1143 PyErr_SetString(PySSLErrorObject,
1144 "Underlying socket has been closed.");
1145 goto error;
1146 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1147 PyErr_SetString(PySSLErrorObject,
1148 "Underlying socket too large for select().");
1149 goto error;
1150 }
1151 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 PySSL_BEGIN_ALLOW_THREADS
1153 len = SSL_write(self->ssl, buf.buf, buf.len);
1154 err = SSL_get_error(self->ssl, len);
1155 PySSL_END_ALLOW_THREADS
1156 if (PyErr_CheckSignals()) {
1157 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001158 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001160 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001162 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 } else {
1164 sockstate = SOCKET_OPERATION_OK;
1165 }
1166 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001167 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 "The write operation timed out");
1169 goto error;
1170 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1171 PyErr_SetString(PySSLErrorObject,
1172 "Underlying socket has been closed.");
1173 goto error;
1174 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1175 break;
1176 }
1177 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001178
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001179 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 PyBuffer_Release(&buf);
1181 if (len > 0)
1182 return PyLong_FromLong(len);
1183 else
1184 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001185
1186error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001187 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 PyBuffer_Release(&buf);
1189 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001190}
1191
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001192PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001193"write(s) -> len\n\
1194\n\
1195Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001196of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001197
Antoine Pitrou152efa22010-05-16 18:19:27 +00001198static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001199{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 PySSL_BEGIN_ALLOW_THREADS
1203 count = SSL_pending(self->ssl);
1204 PySSL_END_ALLOW_THREADS
1205 if (count < 0)
1206 return PySSL_SetError(self, count, __FILE__, __LINE__);
1207 else
1208 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001209}
1210
1211PyDoc_STRVAR(PySSL_SSLpending_doc,
1212"pending() -> count\n\
1213\n\
1214Returns the number of already decrypted bytes available for read,\n\
1215pending on the connection.\n");
1216
Antoine Pitrou152efa22010-05-16 18:19:27 +00001217static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001218{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 PyObject *dest = NULL;
1220 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001222 int len, count;
1223 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 int sockstate;
1225 int err;
1226 int nonblocking;
1227 PySocketSockObject *sock
1228 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 if (((PyObject*)sock) == Py_None) {
1231 _setSSLError("Underlying socket connection gone",
1232 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1233 return NULL;
1234 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001235 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001237 buf.obj = NULL;
1238 buf.buf = NULL;
1239 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001240 goto error;
1241
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001242 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1243 dest = PyBytes_FromStringAndSize(NULL, len);
1244 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001245 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001246 mem = PyBytes_AS_STRING(dest);
1247 }
1248 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001250 mem = buf.buf;
1251 if (len <= 0 || len > buf.len) {
1252 len = (int) buf.len;
1253 if (buf.len != len) {
1254 PyErr_SetString(PyExc_OverflowError,
1255 "maximum length can't fit in a C 'int'");
1256 goto error;
1257 }
1258 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 }
1260
1261 /* just in case the blocking state of the socket has been changed */
1262 nonblocking = (sock->sock_timeout >= 0.0);
1263 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1264 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1265
1266 /* first check if there are bytes ready to be read */
1267 PySSL_BEGIN_ALLOW_THREADS
1268 count = SSL_pending(self->ssl);
1269 PySSL_END_ALLOW_THREADS
1270
1271 if (!count) {
1272 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1273 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001274 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 "The read operation timed out");
1276 goto error;
1277 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1278 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001279 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 goto error;
1281 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1282 count = 0;
1283 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001284 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 }
1286 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 PySSL_BEGIN_ALLOW_THREADS
1288 count = SSL_read(self->ssl, mem, len);
1289 err = SSL_get_error(self->ssl, count);
1290 PySSL_END_ALLOW_THREADS
1291 if (PyErr_CheckSignals())
1292 goto error;
1293 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001294 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001296 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1298 (SSL_get_shutdown(self->ssl) ==
1299 SSL_RECEIVED_SHUTDOWN))
1300 {
1301 count = 0;
1302 goto done;
1303 } else {
1304 sockstate = SOCKET_OPERATION_OK;
1305 }
1306 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001307 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 "The read operation timed out");
1309 goto error;
1310 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1311 break;
1312 }
1313 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1314 if (count <= 0) {
1315 PySSL_SetError(self, count, __FILE__, __LINE__);
1316 goto error;
1317 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001318
1319done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001320 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001322 _PyBytes_Resize(&dest, count);
1323 return dest;
1324 }
1325 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 PyBuffer_Release(&buf);
1327 return PyLong_FromLong(count);
1328 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001329
1330error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001331 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001332 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001333 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001334 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001337}
1338
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001339PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001340"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001341\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001342Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001343
Antoine Pitrou152efa22010-05-16 18:19:27 +00001344static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001345{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 int err, ssl_err, sockstate, nonblocking;
1347 int zeros = 0;
1348 PySocketSockObject *sock
1349 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 /* Guard against closed socket */
1352 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1353 _setSSLError("Underlying socket connection gone",
1354 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1355 return NULL;
1356 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001357 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358
1359 /* Just in case the blocking state of the socket has been changed */
1360 nonblocking = (sock->sock_timeout >= 0.0);
1361 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1362 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1363
1364 while (1) {
1365 PySSL_BEGIN_ALLOW_THREADS
1366 /* Disable read-ahead so that unwrap can work correctly.
1367 * Otherwise OpenSSL might read in too much data,
1368 * eating clear text data that happens to be
1369 * transmitted after the SSL shutdown.
1370 * Should be safe to call repeatedly everytime this
1371 * function is used and the shutdown_seen_zero != 0
1372 * condition is met.
1373 */
1374 if (self->shutdown_seen_zero)
1375 SSL_set_read_ahead(self->ssl, 0);
1376 err = SSL_shutdown(self->ssl);
1377 PySSL_END_ALLOW_THREADS
1378 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1379 if (err > 0)
1380 break;
1381 if (err == 0) {
1382 /* Don't loop endlessly; instead preserve legacy
1383 behaviour of trying SSL_shutdown() only twice.
1384 This looks necessary for OpenSSL < 0.9.8m */
1385 if (++zeros > 1)
1386 break;
1387 /* Shutdown was sent, now try receiving */
1388 self->shutdown_seen_zero = 1;
1389 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001390 }
1391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 /* Possibly retry shutdown until timeout or failure */
1393 ssl_err = SSL_get_error(self->ssl, err);
1394 if (ssl_err == SSL_ERROR_WANT_READ)
1395 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1396 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1397 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1398 else
1399 break;
1400 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1401 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001402 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 "The read operation timed out");
1404 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001405 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001407 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 }
1409 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1410 PyErr_SetString(PySSLErrorObject,
1411 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001412 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 }
1414 else if (sockstate != SOCKET_OPERATION_OK)
1415 /* Retain the SSL error code */
1416 break;
1417 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001418
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001419 if (err < 0) {
1420 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001423 else
1424 /* It's already INCREF'ed */
1425 return (PyObject *) sock;
1426
1427error:
1428 Py_DECREF(sock);
1429 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001430}
1431
1432PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1433"shutdown(s) -> socket\n\
1434\n\
1435Does the SSL shutdown handshake with the remote end, and returns\n\
1436the underlying socket object.");
1437
Antoine Pitroud6494802011-07-21 01:11:30 +02001438#if HAVE_OPENSSL_FINISHED
1439static PyObject *
1440PySSL_tls_unique_cb(PySSLSocket *self)
1441{
1442 PyObject *retval = NULL;
1443 char buf[PySSL_CB_MAXLEN];
1444 int len;
1445
1446 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1447 /* if session is resumed XOR we are the client */
1448 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1449 }
1450 else {
1451 /* if a new session XOR we are the server */
1452 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1453 }
1454
1455 /* It cannot be negative in current OpenSSL version as of July 2011 */
1456 assert(len >= 0);
1457 if (len == 0)
1458 Py_RETURN_NONE;
1459
1460 retval = PyBytes_FromStringAndSize(buf, len);
1461
1462 return retval;
1463}
1464
1465PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1466"tls_unique_cb() -> bytes\n\
1467\n\
1468Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1469\n\
1470If the TLS handshake is not yet complete, None is returned");
1471
1472#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001473
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001474static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001475 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1476 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1477 PySSL_SSLwrite_doc},
1478 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1479 PySSL_SSLread_doc},
1480 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1481 PySSL_SSLpending_doc},
1482 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1483 PySSL_peercert_doc},
1484 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001485 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1487 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001488#if HAVE_OPENSSL_FINISHED
1489 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1490 PySSL_tls_unique_cb_doc},
1491#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001493};
1494
Antoine Pitrou152efa22010-05-16 18:19:27 +00001495static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001497 "_ssl._SSLSocket", /*tp_name*/
1498 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 0, /*tp_itemsize*/
1500 /* methods */
1501 (destructor)PySSL_dealloc, /*tp_dealloc*/
1502 0, /*tp_print*/
1503 0, /*tp_getattr*/
1504 0, /*tp_setattr*/
1505 0, /*tp_reserved*/
1506 0, /*tp_repr*/
1507 0, /*tp_as_number*/
1508 0, /*tp_as_sequence*/
1509 0, /*tp_as_mapping*/
1510 0, /*tp_hash*/
1511 0, /*tp_call*/
1512 0, /*tp_str*/
1513 0, /*tp_getattro*/
1514 0, /*tp_setattro*/
1515 0, /*tp_as_buffer*/
1516 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1517 0, /*tp_doc*/
1518 0, /*tp_traverse*/
1519 0, /*tp_clear*/
1520 0, /*tp_richcompare*/
1521 0, /*tp_weaklistoffset*/
1522 0, /*tp_iter*/
1523 0, /*tp_iternext*/
1524 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001525};
1526
Antoine Pitrou152efa22010-05-16 18:19:27 +00001527
1528/*
1529 * _SSLContext objects
1530 */
1531
1532static PyObject *
1533context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1534{
1535 char *kwlist[] = {"protocol", NULL};
1536 PySSLContext *self;
1537 int proto_version = PY_SSL_VERSION_SSL23;
1538 SSL_CTX *ctx = NULL;
1539
1540 if (!PyArg_ParseTupleAndKeywords(
1541 args, kwds, "i:_SSLContext", kwlist,
1542 &proto_version))
1543 return NULL;
1544
1545 PySSL_BEGIN_ALLOW_THREADS
1546 if (proto_version == PY_SSL_VERSION_TLS1)
1547 ctx = SSL_CTX_new(TLSv1_method());
1548 else if (proto_version == PY_SSL_VERSION_SSL3)
1549 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001550#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001551 else if (proto_version == PY_SSL_VERSION_SSL2)
1552 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001553#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001554 else if (proto_version == PY_SSL_VERSION_SSL23)
1555 ctx = SSL_CTX_new(SSLv23_method());
1556 else
1557 proto_version = -1;
1558 PySSL_END_ALLOW_THREADS
1559
1560 if (proto_version == -1) {
1561 PyErr_SetString(PyExc_ValueError,
1562 "invalid protocol version");
1563 return NULL;
1564 }
1565 if (ctx == NULL) {
1566 PyErr_SetString(PySSLErrorObject,
1567 "failed to allocate SSL context");
1568 return NULL;
1569 }
1570
1571 assert(type != NULL && type->tp_alloc != NULL);
1572 self = (PySSLContext *) type->tp_alloc(type, 0);
1573 if (self == NULL) {
1574 SSL_CTX_free(ctx);
1575 return NULL;
1576 }
1577 self->ctx = ctx;
1578 /* Defaults */
1579 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001580 SSL_CTX_set_options(self->ctx,
1581 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001582
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001583#define SID_CTX "Python"
1584 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1585 sizeof(SID_CTX));
1586#undef SID_CTX
1587
Antoine Pitrou152efa22010-05-16 18:19:27 +00001588 return (PyObject *)self;
1589}
1590
1591static void
1592context_dealloc(PySSLContext *self)
1593{
1594 SSL_CTX_free(self->ctx);
1595 Py_TYPE(self)->tp_free(self);
1596}
1597
1598static PyObject *
1599set_ciphers(PySSLContext *self, PyObject *args)
1600{
1601 int ret;
1602 const char *cipherlist;
1603
1604 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1605 return NULL;
1606 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1607 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001608 /* Clearing the error queue is necessary on some OpenSSL versions,
1609 otherwise the error will be reported again when another SSL call
1610 is done. */
1611 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001612 PyErr_SetString(PySSLErrorObject,
1613 "No cipher can be selected.");
1614 return NULL;
1615 }
1616 Py_RETURN_NONE;
1617}
1618
1619static PyObject *
1620get_verify_mode(PySSLContext *self, void *c)
1621{
1622 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1623 case SSL_VERIFY_NONE:
1624 return PyLong_FromLong(PY_SSL_CERT_NONE);
1625 case SSL_VERIFY_PEER:
1626 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1627 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1628 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1629 }
1630 PyErr_SetString(PySSLErrorObject,
1631 "invalid return value from SSL_CTX_get_verify_mode");
1632 return NULL;
1633}
1634
1635static int
1636set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1637{
1638 int n, mode;
1639 if (!PyArg_Parse(arg, "i", &n))
1640 return -1;
1641 if (n == PY_SSL_CERT_NONE)
1642 mode = SSL_VERIFY_NONE;
1643 else if (n == PY_SSL_CERT_OPTIONAL)
1644 mode = SSL_VERIFY_PEER;
1645 else if (n == PY_SSL_CERT_REQUIRED)
1646 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1647 else {
1648 PyErr_SetString(PyExc_ValueError,
1649 "invalid value for verify_mode");
1650 return -1;
1651 }
1652 SSL_CTX_set_verify(self->ctx, mode, NULL);
1653 return 0;
1654}
1655
1656static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001657get_options(PySSLContext *self, void *c)
1658{
1659 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1660}
1661
1662static int
1663set_options(PySSLContext *self, PyObject *arg, void *c)
1664{
1665 long new_opts, opts, set, clear;
1666 if (!PyArg_Parse(arg, "l", &new_opts))
1667 return -1;
1668 opts = SSL_CTX_get_options(self->ctx);
1669 clear = opts & ~new_opts;
1670 set = ~opts & new_opts;
1671 if (clear) {
1672#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1673 SSL_CTX_clear_options(self->ctx, clear);
1674#else
1675 PyErr_SetString(PyExc_ValueError,
1676 "can't clear options before OpenSSL 0.9.8m");
1677 return -1;
1678#endif
1679 }
1680 if (set)
1681 SSL_CTX_set_options(self->ctx, set);
1682 return 0;
1683}
1684
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001685typedef struct {
1686 PyThreadState *thread_state;
1687 PyObject *callable;
1688 char *password;
1689 Py_ssize_t size;
1690 int error;
1691} _PySSLPasswordInfo;
1692
1693static int
1694_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1695 const char *bad_type_error)
1696{
1697 /* Set the password and size fields of a _PySSLPasswordInfo struct
1698 from a unicode, bytes, or byte array object.
1699 The password field will be dynamically allocated and must be freed
1700 by the caller */
1701 PyObject *password_bytes = NULL;
1702 const char *data = NULL;
1703 Py_ssize_t size;
1704
1705 if (PyUnicode_Check(password)) {
1706 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1707 if (!password_bytes) {
1708 goto error;
1709 }
1710 data = PyBytes_AS_STRING(password_bytes);
1711 size = PyBytes_GET_SIZE(password_bytes);
1712 } else if (PyBytes_Check(password)) {
1713 data = PyBytes_AS_STRING(password);
1714 size = PyBytes_GET_SIZE(password);
1715 } else if (PyByteArray_Check(password)) {
1716 data = PyByteArray_AS_STRING(password);
1717 size = PyByteArray_GET_SIZE(password);
1718 } else {
1719 PyErr_SetString(PyExc_TypeError, bad_type_error);
1720 goto error;
1721 }
1722
1723 free(pw_info->password);
1724 pw_info->password = malloc(size);
1725 if (!pw_info->password) {
1726 PyErr_SetString(PyExc_MemoryError,
1727 "unable to allocate password buffer");
1728 goto error;
1729 }
1730 memcpy(pw_info->password, data, size);
1731 pw_info->size = size;
1732
1733 Py_XDECREF(password_bytes);
1734 return 1;
1735
1736error:
1737 Py_XDECREF(password_bytes);
1738 return 0;
1739}
1740
1741static int
1742_password_callback(char *buf, int size, int rwflag, void *userdata)
1743{
1744 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1745 PyObject *fn_ret = NULL;
1746
1747 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1748
1749 if (pw_info->callable) {
1750 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1751 if (!fn_ret) {
1752 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1753 core python API, so we could use it to add a frame here */
1754 goto error;
1755 }
1756
1757 if (!_pwinfo_set(pw_info, fn_ret,
1758 "password callback must return a string")) {
1759 goto error;
1760 }
1761 Py_CLEAR(fn_ret);
1762 }
1763
1764 if (pw_info->size > size) {
1765 PyErr_Format(PyExc_ValueError,
1766 "password cannot be longer than %d bytes", size);
1767 goto error;
1768 }
1769
1770 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1771 memcpy(buf, pw_info->password, pw_info->size);
1772 return pw_info->size;
1773
1774error:
1775 Py_XDECREF(fn_ret);
1776 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1777 pw_info->error = 1;
1778 return -1;
1779}
1780
Antoine Pitroub5218772010-05-21 09:56:06 +00001781static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001782load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
1783{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001784 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
1785 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001786 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001787 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
1788 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
1789 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00001790 int r;
1791
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001792 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00001793 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001795 "O|OO:load_cert_chain", kwlist,
1796 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00001797 return NULL;
1798 if (keyfile == Py_None)
1799 keyfile = NULL;
1800 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
1801 PyErr_SetString(PyExc_TypeError,
1802 "certfile should be a valid filesystem path");
1803 return NULL;
1804 }
1805 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
1806 PyErr_SetString(PyExc_TypeError,
1807 "keyfile should be a valid filesystem path");
1808 goto error;
1809 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001810 if (password && password != Py_None) {
1811 if (PyCallable_Check(password)) {
1812 pw_info.callable = password;
1813 } else if (!_pwinfo_set(&pw_info, password,
1814 "password should be a string or callable")) {
1815 goto error;
1816 }
1817 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
1818 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
1819 }
1820 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821 r = SSL_CTX_use_certificate_chain_file(self->ctx,
1822 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001823 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001824 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001825 if (pw_info.error) {
1826 ERR_clear_error();
1827 /* the password callback has already set the error information */
1828 }
1829 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001830 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001831 PyErr_SetFromErrno(PyExc_IOError);
1832 }
1833 else {
1834 _setSSLError(NULL, 0, __FILE__, __LINE__);
1835 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001836 goto error;
1837 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001838 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02001839 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001840 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
1841 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001842 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
1843 Py_CLEAR(keyfile_bytes);
1844 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001845 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001846 if (pw_info.error) {
1847 ERR_clear_error();
1848 /* the password callback has already set the error information */
1849 }
1850 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001851 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001852 PyErr_SetFromErrno(PyExc_IOError);
1853 }
1854 else {
1855 _setSSLError(NULL, 0, __FILE__, __LINE__);
1856 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001857 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001858 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001859 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001860 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001861 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001862 if (r != 1) {
1863 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001864 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001865 }
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_RETURN_NONE;
1870
1871error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001872 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
1873 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
1874 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001875 Py_XDECREF(keyfile_bytes);
1876 Py_XDECREF(certfile_bytes);
1877 return NULL;
1878}
1879
1880static PyObject *
1881load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
1882{
1883 char *kwlist[] = {"cafile", "capath", NULL};
1884 PyObject *cafile = NULL, *capath = NULL;
1885 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
1886 const char *cafile_buf = NULL, *capath_buf = NULL;
1887 int r;
1888
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001889 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001890 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1891 "|OO:load_verify_locations", kwlist,
1892 &cafile, &capath))
1893 return NULL;
1894 if (cafile == Py_None)
1895 cafile = NULL;
1896 if (capath == Py_None)
1897 capath = NULL;
1898 if (cafile == NULL && capath == NULL) {
1899 PyErr_SetString(PyExc_TypeError,
1900 "cafile and capath cannot be both omitted");
1901 return NULL;
1902 }
1903 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
1904 PyErr_SetString(PyExc_TypeError,
1905 "cafile should be a valid filesystem path");
1906 return NULL;
1907 }
1908 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00001909 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001910 PyErr_SetString(PyExc_TypeError,
1911 "capath should be a valid filesystem path");
1912 return NULL;
1913 }
1914 if (cafile)
1915 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
1916 if (capath)
1917 capath_buf = PyBytes_AS_STRING(capath_bytes);
1918 PySSL_BEGIN_ALLOW_THREADS
1919 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
1920 PySSL_END_ALLOW_THREADS
1921 Py_XDECREF(cafile_bytes);
1922 Py_XDECREF(capath_bytes);
1923 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001924 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00001925 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00001926 PyErr_SetFromErrno(PyExc_IOError);
1927 }
1928 else {
1929 _setSSLError(NULL, 0, __FILE__, __LINE__);
1930 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001931 return NULL;
1932 }
1933 Py_RETURN_NONE;
1934}
1935
1936static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01001937load_dh_params(PySSLContext *self, PyObject *filepath)
1938{
1939 FILE *f;
1940 DH *dh;
1941
1942 f = _Py_fopen(filepath, "rb");
1943 if (f == NULL) {
1944 if (!PyErr_Occurred())
1945 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1946 return NULL;
1947 }
1948 errno = 0;
1949 PySSL_BEGIN_ALLOW_THREADS
1950 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
1951 PySSL_END_ALLOW_THREADS
1952 if (dh == NULL) {
1953 if (errno != 0) {
1954 ERR_clear_error();
1955 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
1956 }
1957 else {
1958 _setSSLError(NULL, 0, __FILE__, __LINE__);
1959 }
1960 return NULL;
1961 }
1962 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
1963 _setSSLError(NULL, 0, __FILE__, __LINE__);
1964 DH_free(dh);
1965 Py_RETURN_NONE;
1966}
1967
1968static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001969context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
1970{
Antoine Pitroud5323212010-10-22 18:19:07 +00001971 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00001972 PySocketSockObject *sock;
1973 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00001974 char *hostname = NULL;
1975 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001976
Antoine Pitroud5323212010-10-22 18:19:07 +00001977 /* server_hostname is either None (or absent), or to be encoded
1978 using the idna encoding. */
1979 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00001980 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00001981 &sock, &server_side,
1982 Py_TYPE(Py_None), &hostname_obj)) {
1983 PyErr_Clear();
1984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
1985 PySocketModule.Sock_Type,
1986 &sock, &server_side,
1987 "idna", &hostname))
1988 return NULL;
1989#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
1990 PyMem_Free(hostname);
1991 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
1992 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00001993 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00001994#endif
1995 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00001996
Antoine Pitroud5323212010-10-22 18:19:07 +00001997 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
1998 hostname);
1999 if (hostname != NULL)
2000 PyMem_Free(hostname);
2001 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002002}
2003
Antoine Pitroub0182c82010-10-12 20:09:02 +00002004static PyObject *
2005session_stats(PySSLContext *self, PyObject *unused)
2006{
2007 int r;
2008 PyObject *value, *stats = PyDict_New();
2009 if (!stats)
2010 return NULL;
2011
2012#define ADD_STATS(SSL_NAME, KEY_NAME) \
2013 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2014 if (value == NULL) \
2015 goto error; \
2016 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2017 Py_DECREF(value); \
2018 if (r < 0) \
2019 goto error;
2020
2021 ADD_STATS(number, "number");
2022 ADD_STATS(connect, "connect");
2023 ADD_STATS(connect_good, "connect_good");
2024 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2025 ADD_STATS(accept, "accept");
2026 ADD_STATS(accept_good, "accept_good");
2027 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2028 ADD_STATS(accept, "accept");
2029 ADD_STATS(hits, "hits");
2030 ADD_STATS(misses, "misses");
2031 ADD_STATS(timeouts, "timeouts");
2032 ADD_STATS(cache_full, "cache_full");
2033
2034#undef ADD_STATS
2035
2036 return stats;
2037
2038error:
2039 Py_DECREF(stats);
2040 return NULL;
2041}
2042
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002043static PyObject *
2044set_default_verify_paths(PySSLContext *self, PyObject *unused)
2045{
2046 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2047 _setSSLError(NULL, 0, __FILE__, __LINE__);
2048 return NULL;
2049 }
2050 Py_RETURN_NONE;
2051}
2052
Antoine Pitrou501da612011-12-21 09:27:41 +01002053#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002054static PyObject *
2055set_ecdh_curve(PySSLContext *self, PyObject *name)
2056{
2057 PyObject *name_bytes;
2058 int nid;
2059 EC_KEY *key;
2060
2061 if (!PyUnicode_FSConverter(name, &name_bytes))
2062 return NULL;
2063 assert(PyBytes_Check(name_bytes));
2064 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2065 Py_DECREF(name_bytes);
2066 if (nid == 0) {
2067 PyErr_Format(PyExc_ValueError,
2068 "unknown elliptic curve name %R", name);
2069 return NULL;
2070 }
2071 key = EC_KEY_new_by_curve_name(nid);
2072 if (key == NULL) {
2073 _setSSLError(NULL, 0, __FILE__, __LINE__);
2074 return NULL;
2075 }
2076 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2077 EC_KEY_free(key);
2078 Py_RETURN_NONE;
2079}
Antoine Pitrou501da612011-12-21 09:27:41 +01002080#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002081
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002083 {"options", (getter) get_options,
2084 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002085 {"verify_mode", (getter) get_verify_mode,
2086 (setter) set_verify_mode, NULL},
2087 {NULL}, /* sentinel */
2088};
2089
2090static struct PyMethodDef context_methods[] = {
2091 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2092 METH_VARARGS | METH_KEYWORDS, NULL},
2093 {"set_ciphers", (PyCFunction) set_ciphers,
2094 METH_VARARGS, NULL},
2095 {"load_cert_chain", (PyCFunction) load_cert_chain,
2096 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002097 {"load_dh_params", (PyCFunction) load_dh_params,
2098 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002099 {"load_verify_locations", (PyCFunction) load_verify_locations,
2100 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002101 {"session_stats", (PyCFunction) session_stats,
2102 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002103 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2104 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002105#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002106 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2107 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002108#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002109 {NULL, NULL} /* sentinel */
2110};
2111
2112static PyTypeObject PySSLContext_Type = {
2113 PyVarObject_HEAD_INIT(NULL, 0)
2114 "_ssl._SSLContext", /*tp_name*/
2115 sizeof(PySSLContext), /*tp_basicsize*/
2116 0, /*tp_itemsize*/
2117 (destructor)context_dealloc, /*tp_dealloc*/
2118 0, /*tp_print*/
2119 0, /*tp_getattr*/
2120 0, /*tp_setattr*/
2121 0, /*tp_reserved*/
2122 0, /*tp_repr*/
2123 0, /*tp_as_number*/
2124 0, /*tp_as_sequence*/
2125 0, /*tp_as_mapping*/
2126 0, /*tp_hash*/
2127 0, /*tp_call*/
2128 0, /*tp_str*/
2129 0, /*tp_getattro*/
2130 0, /*tp_setattro*/
2131 0, /*tp_as_buffer*/
2132 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2133 0, /*tp_doc*/
2134 0, /*tp_traverse*/
2135 0, /*tp_clear*/
2136 0, /*tp_richcompare*/
2137 0, /*tp_weaklistoffset*/
2138 0, /*tp_iter*/
2139 0, /*tp_iternext*/
2140 context_methods, /*tp_methods*/
2141 0, /*tp_members*/
2142 context_getsetlist, /*tp_getset*/
2143 0, /*tp_base*/
2144 0, /*tp_dict*/
2145 0, /*tp_descr_get*/
2146 0, /*tp_descr_set*/
2147 0, /*tp_dictoffset*/
2148 0, /*tp_init*/
2149 0, /*tp_alloc*/
2150 context_new, /*tp_new*/
2151};
2152
2153
2154
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002155#ifdef HAVE_OPENSSL_RAND
2156
2157/* helper routines for seeding the SSL PRNG */
2158static PyObject *
2159PySSL_RAND_add(PyObject *self, PyObject *args)
2160{
2161 char *buf;
2162 int len;
2163 double entropy;
2164
2165 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002166 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002167 RAND_add(buf, len, entropy);
2168 Py_INCREF(Py_None);
2169 return Py_None;
2170}
2171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002172PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002173"RAND_add(string, entropy)\n\
2174\n\
2175Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002176bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002177
2178static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002179PySSL_RAND(int len, int pseudo)
2180{
2181 int ok;
2182 PyObject *bytes;
2183 unsigned long err;
2184 const char *errstr;
2185 PyObject *v;
2186
2187 bytes = PyBytes_FromStringAndSize(NULL, len);
2188 if (bytes == NULL)
2189 return NULL;
2190 if (pseudo) {
2191 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2192 if (ok == 0 || ok == 1)
2193 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2194 }
2195 else {
2196 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2197 if (ok == 1)
2198 return bytes;
2199 }
2200 Py_DECREF(bytes);
2201
2202 err = ERR_get_error();
2203 errstr = ERR_reason_error_string(err);
2204 v = Py_BuildValue("(ks)", err, errstr);
2205 if (v != NULL) {
2206 PyErr_SetObject(PySSLErrorObject, v);
2207 Py_DECREF(v);
2208 }
2209 return NULL;
2210}
2211
2212static PyObject *
2213PySSL_RAND_bytes(PyObject *self, PyObject *args)
2214{
2215 int len;
2216 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2217 return NULL;
2218 return PySSL_RAND(len, 0);
2219}
2220
2221PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2222"RAND_bytes(n) -> bytes\n\
2223\n\
2224Generate n cryptographically strong pseudo-random bytes.");
2225
2226static PyObject *
2227PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2228{
2229 int len;
2230 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2231 return NULL;
2232 return PySSL_RAND(len, 1);
2233}
2234
2235PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2236"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2237\n\
2238Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2239generated are cryptographically strong.");
2240
2241static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002242PySSL_RAND_status(PyObject *self)
2243{
Christian Heimes217cfd12007-12-02 14:31:20 +00002244 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002245}
2246
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002247PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002248"RAND_status() -> 0 or 1\n\
2249\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002250Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2251It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2252using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002253
2254static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002255PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002256{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002257 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002258 int bytes;
2259
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002260 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2261 PyUnicode_FSConverter, &path))
2262 return NULL;
2263
2264 bytes = RAND_egd(PyBytes_AsString(path));
2265 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002266 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002267 PyErr_SetString(PySSLErrorObject,
2268 "EGD connection failed or EGD did not return "
2269 "enough data to seed the PRNG");
2270 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002271 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002272 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002273}
2274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002275PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002276"RAND_egd(path) -> bytes\n\
2277\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002278Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2279Returns number of bytes read. Raises SSLError if connection to EGD\n\
2280fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002281
2282#endif
2283
Bill Janssen40a0f662008-08-12 16:56:25 +00002284
2285
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002286/* List of functions exported by this module. */
2287
2288static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 {"_test_decode_cert", PySSL_test_decode_certificate,
2290 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2293 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002294 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2295 PySSL_RAND_bytes_doc},
2296 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2297 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002298 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 PySSL_RAND_egd_doc},
2300 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2301 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002304};
2305
2306
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002307#ifdef WITH_THREAD
2308
2309/* an implementation of OpenSSL threading operations in terms
2310 of the Python C thread library */
2311
2312static PyThread_type_lock *_ssl_locks = NULL;
2313
2314static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002316}
2317
Bill Janssen6e027db2007-11-15 22:23:56 +00002318static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 (int mode, int n, const char *file, int line) {
2320 /* this function is needed to perform locking on shared data
2321 structures. (Note that OpenSSL uses a number of global data
2322 structures that will be implicitly shared whenever multiple
2323 threads use OpenSSL.) Multi-threaded applications will
2324 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 locking_function() must be able to handle up to
2327 CRYPTO_num_locks() different mutex locks. It sets the n-th
2328 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 file and line are the file number of the function setting the
2331 lock. They can be useful for debugging.
2332 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 if ((_ssl_locks == NULL) ||
2335 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2336 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 if (mode & CRYPTO_LOCK) {
2339 PyThread_acquire_lock(_ssl_locks[n], 1);
2340 } else {
2341 PyThread_release_lock(_ssl_locks[n]);
2342 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002343}
2344
2345static int _setup_ssl_threads(void) {
2346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002349 if (_ssl_locks == NULL) {
2350 _ssl_locks_count = CRYPTO_num_locks();
2351 _ssl_locks = (PyThread_type_lock *)
2352 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2353 if (_ssl_locks == NULL)
2354 return 0;
2355 memset(_ssl_locks, 0,
2356 sizeof(PyThread_type_lock) * _ssl_locks_count);
2357 for (i = 0; i < _ssl_locks_count; i++) {
2358 _ssl_locks[i] = PyThread_allocate_lock();
2359 if (_ssl_locks[i] == NULL) {
2360 unsigned int j;
2361 for (j = 0; j < i; j++) {
2362 PyThread_free_lock(_ssl_locks[j]);
2363 }
2364 free(_ssl_locks);
2365 return 0;
2366 }
2367 }
2368 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2369 CRYPTO_set_id_callback(_ssl_thread_id_function);
2370 }
2371 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002372}
2373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002376PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002377"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002378for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002379
Martin v. Löwis1a214512008-06-11 05:26:20 +00002380
2381static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002382 PyModuleDef_HEAD_INIT,
2383 "_ssl",
2384 module_doc,
2385 -1,
2386 PySSL_methods,
2387 NULL,
2388 NULL,
2389 NULL,
2390 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002391};
2392
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002393
2394static void
2395parse_openssl_version(unsigned long libver,
2396 unsigned int *major, unsigned int *minor,
2397 unsigned int *fix, unsigned int *patch,
2398 unsigned int *status)
2399{
2400 *status = libver & 0xF;
2401 libver >>= 4;
2402 *patch = libver & 0xFF;
2403 libver >>= 8;
2404 *fix = libver & 0xFF;
2405 libver >>= 8;
2406 *minor = libver & 0xFF;
2407 libver >>= 8;
2408 *major = libver & 0xFF;
2409}
2410
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002411PyDoc_STRVAR(SSLError_doc,
2412"An error occurred in the SSL implementation.");
2413
Antoine Pitrou41032a62011-10-27 23:56:55 +02002414PyDoc_STRVAR(SSLZeroReturnError_doc,
2415"SSL/TLS session closed cleanly.");
2416
2417PyDoc_STRVAR(SSLWantReadError_doc,
2418"Non-blocking SSL socket needs to read more data\n"
2419"before the requested operation can be completed.");
2420
2421PyDoc_STRVAR(SSLWantWriteError_doc,
2422"Non-blocking SSL socket needs to write more data\n"
2423"before the requested operation can be completed.");
2424
2425PyDoc_STRVAR(SSLSyscallError_doc,
2426"System error when attempting SSL operation.");
2427
2428PyDoc_STRVAR(SSLEOFError_doc,
2429"SSL/TLS connection terminated abruptly.");
2430
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002431
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002432PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002433PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002434{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 PyObject *m, *d, *r;
2436 unsigned long libver;
2437 unsigned int major, minor, fix, patch, status;
2438 PySocketModule_APIObject *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002439
Antoine Pitrou152efa22010-05-16 18:19:27 +00002440 if (PyType_Ready(&PySSLContext_Type) < 0)
2441 return NULL;
2442 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 m = PyModule_Create(&_sslmodule);
2446 if (m == NULL)
2447 return NULL;
2448 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 /* Load _socket module and its C API */
2451 socket_api = PySocketModule_ImportModuleAndAPI();
2452 if (!socket_api)
2453 return NULL;
2454 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 /* Init OpenSSL */
2457 SSL_load_error_strings();
2458 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002459#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002460 /* note that this will start threading if not already started */
2461 if (!_setup_ssl_threads()) {
2462 return NULL;
2463 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002464#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002466
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002467 /* Add symbols to module dict */
Antoine Pitroua0e0e232011-10-22 23:41:52 +02002468 PySSLErrorObject = PyErr_NewExceptionWithDoc("ssl.SSLError",
2469 SSLError_doc,
2470 PyExc_OSError,
2471 NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 if (PySSLErrorObject == NULL)
2473 return NULL;
Antoine Pitrou41032a62011-10-27 23:56:55 +02002474 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2475 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2476 PySSLErrorObject, NULL);
2477 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2478 "ssl.SSLWantReadError", SSLWantReadError_doc,
2479 PySSLErrorObject, NULL);
2480 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2481 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2482 PySSLErrorObject, NULL);
2483 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2484 "ssl.SSLSyscallError", SSLSyscallError_doc,
2485 PySSLErrorObject, NULL);
2486 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2487 "ssl.SSLEOFError", SSLEOFError_doc,
2488 PySSLErrorObject, NULL);
2489 if (PySSLZeroReturnErrorObject == NULL
2490 || PySSLWantReadErrorObject == NULL
2491 || PySSLWantWriteErrorObject == NULL
2492 || PySSLSyscallErrorObject == NULL
2493 || PySSLEOFErrorObject == NULL)
2494 return NULL;
2495 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2496 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2497 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2498 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2499 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2500 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002501 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002502 if (PyDict_SetItemString(d, "_SSLContext",
2503 (PyObject *)&PySSLContext_Type) != 0)
2504 return NULL;
2505 if (PyDict_SetItemString(d, "_SSLSocket",
2506 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 return NULL;
2508 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2509 PY_SSL_ERROR_ZERO_RETURN);
2510 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2511 PY_SSL_ERROR_WANT_READ);
2512 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2513 PY_SSL_ERROR_WANT_WRITE);
2514 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2515 PY_SSL_ERROR_WANT_X509_LOOKUP);
2516 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2517 PY_SSL_ERROR_SYSCALL);
2518 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2519 PY_SSL_ERROR_SSL);
2520 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2521 PY_SSL_ERROR_WANT_CONNECT);
2522 /* non ssl.h errorcodes */
2523 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2524 PY_SSL_ERROR_EOF);
2525 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2526 PY_SSL_ERROR_INVALID_ERROR_CODE);
2527 /* cert requirements */
2528 PyModule_AddIntConstant(m, "CERT_NONE",
2529 PY_SSL_CERT_NONE);
2530 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2531 PY_SSL_CERT_OPTIONAL);
2532 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2533 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002536#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2538 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002539#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2541 PY_SSL_VERSION_SSL3);
2542 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2543 PY_SSL_VERSION_SSL23);
2544 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2545 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002546
Antoine Pitroub5218772010-05-21 09:56:06 +00002547 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002548 PyModule_AddIntConstant(m, "OP_ALL",
2549 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002550 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2551 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2552 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002553 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2554 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002555 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002556#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002557 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002558#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002559#ifdef SSL_OP_NO_COMPRESSION
2560 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2561 SSL_OP_NO_COMPRESSION);
2562#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002563
Antoine Pitroud5323212010-10-22 18:19:07 +00002564#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2565 r = Py_True;
2566#else
2567 r = Py_False;
2568#endif
2569 Py_INCREF(r);
2570 PyModule_AddObject(m, "HAS_SNI", r);
2571
Antoine Pitroud6494802011-07-21 01:11:30 +02002572#if HAVE_OPENSSL_FINISHED
2573 r = Py_True;
2574#else
2575 r = Py_False;
2576#endif
2577 Py_INCREF(r);
2578 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2579
Antoine Pitrou501da612011-12-21 09:27:41 +01002580#ifdef OPENSSL_NO_ECDH
2581 r = Py_False;
2582#else
2583 r = Py_True;
2584#endif
2585 Py_INCREF(r);
2586 PyModule_AddObject(m, "HAS_ECDH", r);
2587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002588 /* OpenSSL version */
2589 /* SSLeay() gives us the version of the library linked against,
2590 which could be different from the headers version.
2591 */
2592 libver = SSLeay();
2593 r = PyLong_FromUnsignedLong(libver);
2594 if (r == NULL)
2595 return NULL;
2596 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2597 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002598 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002599 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2600 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2601 return NULL;
2602 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2603 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2604 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002605
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002606 libver = OPENSSL_VERSION_NUMBER;
2607 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2608 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2609 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2610 return NULL;
2611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002613}