]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | /* SSL socket module\r |
2 | \r | |
3 | SSL support based on patches by Brian E Gallew and Laszlo Kovacs.\r | |
4 | Re-worked a bit by Bill Janssen to add server-side support and\r | |
5 | certificate decoding. Chris Stawarz contributed some non-blocking\r | |
6 | patches.\r | |
7 | \r | |
8 | This module is imported by ssl.py. It should *not* be used\r | |
9 | directly.\r | |
10 | \r | |
11 | XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?\r | |
12 | \r | |
13 | XXX integrate several "shutdown modes" as suggested in\r | |
14 | http://bugs.python.org/issue8108#msg102867 ?\r | |
15 | */\r | |
16 | \r | |
17 | #include "Python.h"\r | |
18 | \r | |
19 | #ifdef WITH_THREAD\r | |
20 | #include "pythread.h"\r | |
21 | #define PySSL_BEGIN_ALLOW_THREADS { \\r | |
22 | PyThreadState *_save = NULL; \\r | |
23 | if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}\r | |
24 | #define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)};\r | |
25 | #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};\r | |
26 | #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \\r | |
27 | }\r | |
28 | \r | |
29 | #else /* no WITH_THREAD */\r | |
30 | \r | |
31 | #define PySSL_BEGIN_ALLOW_THREADS\r | |
32 | #define PySSL_BLOCK_THREADS\r | |
33 | #define PySSL_UNBLOCK_THREADS\r | |
34 | #define PySSL_END_ALLOW_THREADS\r | |
35 | \r | |
36 | #endif\r | |
37 | \r | |
38 | enum py_ssl_error {\r | |
39 | /* these mirror ssl.h */\r | |
40 | PY_SSL_ERROR_NONE,\r | |
41 | PY_SSL_ERROR_SSL,\r | |
42 | PY_SSL_ERROR_WANT_READ,\r | |
43 | PY_SSL_ERROR_WANT_WRITE,\r | |
44 | PY_SSL_ERROR_WANT_X509_LOOKUP,\r | |
45 | PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */\r | |
46 | PY_SSL_ERROR_ZERO_RETURN,\r | |
47 | PY_SSL_ERROR_WANT_CONNECT,\r | |
48 | /* start of non ssl.h errorcodes */\r | |
49 | PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */\r | |
50 | PY_SSL_ERROR_INVALID_ERROR_CODE\r | |
51 | };\r | |
52 | \r | |
53 | enum py_ssl_server_or_client {\r | |
54 | PY_SSL_CLIENT,\r | |
55 | PY_SSL_SERVER\r | |
56 | };\r | |
57 | \r | |
58 | enum py_ssl_cert_requirements {\r | |
59 | PY_SSL_CERT_NONE,\r | |
60 | PY_SSL_CERT_OPTIONAL,\r | |
61 | PY_SSL_CERT_REQUIRED\r | |
62 | };\r | |
63 | \r | |
64 | enum py_ssl_version {\r | |
65 | #ifndef OPENSSL_NO_SSL2\r | |
66 | PY_SSL_VERSION_SSL2,\r | |
67 | #endif\r | |
68 | PY_SSL_VERSION_SSL3=1,\r | |
69 | PY_SSL_VERSION_SSL23,\r | |
70 | PY_SSL_VERSION_TLS1\r | |
71 | };\r | |
72 | \r | |
73 | /* Include symbols from _socket module */\r | |
74 | #include "socketmodule.h"\r | |
75 | \r | |
76 | #if defined(HAVE_POLL_H)\r | |
77 | #include <poll.h>\r | |
78 | #elif defined(HAVE_SYS_POLL_H)\r | |
79 | #include <sys/poll.h>\r | |
80 | #endif\r | |
81 | \r | |
82 | /* Include OpenSSL header files */\r | |
83 | #include "openssl/rsa.h"\r | |
84 | #include "openssl/crypto.h"\r | |
85 | #include "openssl/x509.h"\r | |
86 | #include "openssl/x509v3.h"\r | |
87 | #include "openssl/pem.h"\r | |
88 | #include "openssl/ssl.h"\r | |
89 | #include "openssl/err.h"\r | |
90 | #include "openssl/rand.h"\r | |
91 | \r | |
92 | /* SSL error object */\r | |
93 | static PyObject *PySSLErrorObject;\r | |
94 | \r | |
95 | #ifdef WITH_THREAD\r | |
96 | \r | |
97 | /* serves as a flag to see whether we've initialized the SSL thread support. */\r | |
98 | /* 0 means no, greater than 0 means yes */\r | |
99 | \r | |
100 | static unsigned int _ssl_locks_count = 0;\r | |
101 | \r | |
102 | #endif /* def WITH_THREAD */\r | |
103 | \r | |
104 | /* SSL socket object */\r | |
105 | \r | |
106 | #define X509_NAME_MAXLEN 256\r | |
107 | \r | |
108 | /* RAND_* APIs got added to OpenSSL in 0.9.5 */\r | |
109 | #if OPENSSL_VERSION_NUMBER >= 0x0090500fL\r | |
110 | # define HAVE_OPENSSL_RAND 1\r | |
111 | #else\r | |
112 | # undef HAVE_OPENSSL_RAND\r | |
113 | #endif\r | |
114 | \r | |
115 | typedef struct {\r | |
116 | PyObject_HEAD\r | |
117 | PySocketSockObject *Socket; /* Socket on which we're layered */\r | |
118 | SSL_CTX* ctx;\r | |
119 | SSL* ssl;\r | |
120 | X509* peer_cert;\r | |
121 | char server[X509_NAME_MAXLEN];\r | |
122 | char issuer[X509_NAME_MAXLEN];\r | |
123 | int shutdown_seen_zero;\r | |
124 | \r | |
125 | } PySSLObject;\r | |
126 | \r | |
127 | static PyTypeObject PySSL_Type;\r | |
128 | static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args);\r | |
129 | static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args);\r | |
130 | static int check_socket_and_wait_for_timeout(PySocketSockObject *s,\r | |
131 | int writing);\r | |
132 | static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args);\r | |
133 | static PyObject *PySSL_cipher(PySSLObject *self);\r | |
134 | \r | |
135 | #define PySSLObject_Check(v) (Py_TYPE(v) == &PySSL_Type)\r | |
136 | \r | |
137 | typedef enum {\r | |
138 | SOCKET_IS_NONBLOCKING,\r | |
139 | SOCKET_IS_BLOCKING,\r | |
140 | SOCKET_HAS_TIMED_OUT,\r | |
141 | SOCKET_HAS_BEEN_CLOSED,\r | |
142 | SOCKET_TOO_LARGE_FOR_SELECT,\r | |
143 | SOCKET_OPERATION_OK\r | |
144 | } timeout_state;\r | |
145 | \r | |
146 | /* Wrap error strings with filename and line # */\r | |
147 | #define STRINGIFY1(x) #x\r | |
148 | #define STRINGIFY2(x) STRINGIFY1(x)\r | |
149 | #define ERRSTR1(x,y,z) (x ":" y ": " z)\r | |
150 | #define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)\r | |
151 | \r | |
152 | /* XXX It might be helpful to augment the error message generated\r | |
153 | below with the name of the SSL function that generated the error.\r | |
154 | I expect it's obvious most of the time.\r | |
155 | */\r | |
156 | \r | |
157 | static PyObject *\r | |
158 | PySSL_SetError(PySSLObject *obj, int ret, char *filename, int lineno)\r | |
159 | {\r | |
160 | PyObject *v;\r | |
161 | char buf[2048];\r | |
162 | char *errstr;\r | |
163 | int err;\r | |
164 | enum py_ssl_error p = PY_SSL_ERROR_NONE;\r | |
165 | \r | |
166 | assert(ret <= 0);\r | |
167 | \r | |
168 | if (obj->ssl != NULL) {\r | |
169 | err = SSL_get_error(obj->ssl, ret);\r | |
170 | \r | |
171 | switch (err) {\r | |
172 | case SSL_ERROR_ZERO_RETURN:\r | |
173 | errstr = "TLS/SSL connection has been closed";\r | |
174 | p = PY_SSL_ERROR_ZERO_RETURN;\r | |
175 | break;\r | |
176 | case SSL_ERROR_WANT_READ:\r | |
177 | errstr = "The operation did not complete (read)";\r | |
178 | p = PY_SSL_ERROR_WANT_READ;\r | |
179 | break;\r | |
180 | case SSL_ERROR_WANT_WRITE:\r | |
181 | p = PY_SSL_ERROR_WANT_WRITE;\r | |
182 | errstr = "The operation did not complete (write)";\r | |
183 | break;\r | |
184 | case SSL_ERROR_WANT_X509_LOOKUP:\r | |
185 | p = PY_SSL_ERROR_WANT_X509_LOOKUP;\r | |
186 | errstr = "The operation did not complete (X509 lookup)";\r | |
187 | break;\r | |
188 | case SSL_ERROR_WANT_CONNECT:\r | |
189 | p = PY_SSL_ERROR_WANT_CONNECT;\r | |
190 | errstr = "The operation did not complete (connect)";\r | |
191 | break;\r | |
192 | case SSL_ERROR_SYSCALL:\r | |
193 | {\r | |
194 | unsigned long e = ERR_get_error();\r | |
195 | if (e == 0) {\r | |
196 | if (ret == 0 || !obj->Socket) {\r | |
197 | p = PY_SSL_ERROR_EOF;\r | |
198 | errstr = "EOF occurred in violation of protocol";\r | |
199 | } else if (ret == -1) {\r | |
200 | /* underlying BIO reported an I/O error */\r | |
201 | ERR_clear_error();\r | |
202 | return obj->Socket->errorhandler();\r | |
203 | } else { /* possible? */\r | |
204 | p = PY_SSL_ERROR_SYSCALL;\r | |
205 | errstr = "Some I/O error occurred";\r | |
206 | }\r | |
207 | } else {\r | |
208 | p = PY_SSL_ERROR_SYSCALL;\r | |
209 | /* XXX Protected by global interpreter lock */\r | |
210 | errstr = ERR_error_string(e, NULL);\r | |
211 | }\r | |
212 | break;\r | |
213 | }\r | |
214 | case SSL_ERROR_SSL:\r | |
215 | {\r | |
216 | unsigned long e = ERR_get_error();\r | |
217 | p = PY_SSL_ERROR_SSL;\r | |
218 | if (e != 0)\r | |
219 | /* XXX Protected by global interpreter lock */\r | |
220 | errstr = ERR_error_string(e, NULL);\r | |
221 | else { /* possible? */\r | |
222 | errstr = "A failure in the SSL library occurred";\r | |
223 | }\r | |
224 | break;\r | |
225 | }\r | |
226 | default:\r | |
227 | p = PY_SSL_ERROR_INVALID_ERROR_CODE;\r | |
228 | errstr = "Invalid error code";\r | |
229 | }\r | |
230 | } else {\r | |
231 | errstr = ERR_error_string(ERR_peek_last_error(), NULL);\r | |
232 | }\r | |
233 | PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);\r | |
234 | ERR_clear_error();\r | |
235 | v = Py_BuildValue("(is)", p, buf);\r | |
236 | if (v != NULL) {\r | |
237 | PyErr_SetObject(PySSLErrorObject, v);\r | |
238 | Py_DECREF(v);\r | |
239 | }\r | |
240 | return NULL;\r | |
241 | }\r | |
242 | \r | |
243 | static PyObject *\r | |
244 | _setSSLError (char *errstr, int errcode, char *filename, int lineno) {\r | |
245 | \r | |
246 | char buf[2048];\r | |
247 | PyObject *v;\r | |
248 | \r | |
249 | if (errstr == NULL) {\r | |
250 | errcode = ERR_peek_last_error();\r | |
251 | errstr = ERR_error_string(errcode, NULL);\r | |
252 | }\r | |
253 | PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr);\r | |
254 | ERR_clear_error();\r | |
255 | v = Py_BuildValue("(is)", errcode, buf);\r | |
256 | if (v != NULL) {\r | |
257 | PyErr_SetObject(PySSLErrorObject, v);\r | |
258 | Py_DECREF(v);\r | |
259 | }\r | |
260 | return NULL;\r | |
261 | }\r | |
262 | \r | |
263 | static PySSLObject *\r | |
264 | newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file,\r | |
265 | enum py_ssl_server_or_client socket_type,\r | |
266 | enum py_ssl_cert_requirements certreq,\r | |
267 | enum py_ssl_version proto_version,\r | |
268 | char *cacerts_file, char *ciphers)\r | |
269 | {\r | |
270 | PySSLObject *self;\r | |
271 | char *errstr = NULL;\r | |
272 | int ret;\r | |
273 | int verification_mode;\r | |
274 | \r | |
275 | self = PyObject_New(PySSLObject, &PySSL_Type); /* Create new object */\r | |
276 | if (self == NULL)\r | |
277 | return NULL;\r | |
278 | memset(self->server, '\0', sizeof(char) * X509_NAME_MAXLEN);\r | |
279 | memset(self->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);\r | |
280 | self->peer_cert = NULL;\r | |
281 | self->ssl = NULL;\r | |
282 | self->ctx = NULL;\r | |
283 | self->Socket = NULL;\r | |
284 | \r | |
285 | /* Make sure the SSL error state is initialized */\r | |
286 | (void) ERR_get_state();\r | |
287 | ERR_clear_error();\r | |
288 | \r | |
289 | if ((key_file && !cert_file) || (!key_file && cert_file)) {\r | |
290 | errstr = ERRSTR("Both the key & certificate files "\r | |
291 | "must be specified");\r | |
292 | goto fail;\r | |
293 | }\r | |
294 | \r | |
295 | if ((socket_type == PY_SSL_SERVER) &&\r | |
296 | ((key_file == NULL) || (cert_file == NULL))) {\r | |
297 | errstr = ERRSTR("Both the key & certificate files "\r | |
298 | "must be specified for server-side operation");\r | |
299 | goto fail;\r | |
300 | }\r | |
301 | \r | |
302 | PySSL_BEGIN_ALLOW_THREADS\r | |
303 | if (proto_version == PY_SSL_VERSION_TLS1)\r | |
304 | self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */\r | |
305 | else if (proto_version == PY_SSL_VERSION_SSL3)\r | |
306 | self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */\r | |
307 | #ifndef OPENSSL_NO_SSL2\r | |
308 | else if (proto_version == PY_SSL_VERSION_SSL2)\r | |
309 | self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */\r | |
310 | #endif\r | |
311 | else if (proto_version == PY_SSL_VERSION_SSL23)\r | |
312 | self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */\r | |
313 | PySSL_END_ALLOW_THREADS\r | |
314 | \r | |
315 | if (self->ctx == NULL) {\r | |
316 | errstr = ERRSTR("Invalid SSL protocol variant specified.");\r | |
317 | goto fail;\r | |
318 | }\r | |
319 | \r | |
320 | if (ciphers != NULL) {\r | |
321 | ret = SSL_CTX_set_cipher_list(self->ctx, ciphers);\r | |
322 | if (ret == 0) {\r | |
323 | errstr = ERRSTR("No cipher can be selected.");\r | |
324 | goto fail;\r | |
325 | }\r | |
326 | }\r | |
327 | \r | |
328 | if (certreq != PY_SSL_CERT_NONE) {\r | |
329 | if (cacerts_file == NULL) {\r | |
330 | errstr = ERRSTR("No root certificates specified for "\r | |
331 | "verification of other-side certificates.");\r | |
332 | goto fail;\r | |
333 | } else {\r | |
334 | PySSL_BEGIN_ALLOW_THREADS\r | |
335 | ret = SSL_CTX_load_verify_locations(self->ctx,\r | |
336 | cacerts_file,\r | |
337 | NULL);\r | |
338 | PySSL_END_ALLOW_THREADS\r | |
339 | if (ret != 1) {\r | |
340 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
341 | goto fail;\r | |
342 | }\r | |
343 | }\r | |
344 | }\r | |
345 | if (key_file) {\r | |
346 | PySSL_BEGIN_ALLOW_THREADS\r | |
347 | ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file,\r | |
348 | SSL_FILETYPE_PEM);\r | |
349 | PySSL_END_ALLOW_THREADS\r | |
350 | if (ret != 1) {\r | |
351 | _setSSLError(NULL, ret, __FILE__, __LINE__);\r | |
352 | goto fail;\r | |
353 | }\r | |
354 | \r | |
355 | PySSL_BEGIN_ALLOW_THREADS\r | |
356 | ret = SSL_CTX_use_certificate_chain_file(self->ctx,\r | |
357 | cert_file);\r | |
358 | PySSL_END_ALLOW_THREADS\r | |
359 | if (ret != 1) {\r | |
360 | /*\r | |
361 | fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",\r | |
362 | ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);\r | |
363 | */\r | |
364 | if (ERR_peek_last_error() != 0) {\r | |
365 | _setSSLError(NULL, ret, __FILE__, __LINE__);\r | |
366 | goto fail;\r | |
367 | }\r | |
368 | }\r | |
369 | }\r | |
370 | \r | |
371 | /* ssl compatibility */\r | |
372 | SSL_CTX_set_options(self->ctx, SSL_OP_ALL);\r | |
373 | \r | |
374 | verification_mode = SSL_VERIFY_NONE;\r | |
375 | if (certreq == PY_SSL_CERT_OPTIONAL)\r | |
376 | verification_mode = SSL_VERIFY_PEER;\r | |
377 | else if (certreq == PY_SSL_CERT_REQUIRED)\r | |
378 | verification_mode = (SSL_VERIFY_PEER |\r | |
379 | SSL_VERIFY_FAIL_IF_NO_PEER_CERT);\r | |
380 | SSL_CTX_set_verify(self->ctx, verification_mode,\r | |
381 | NULL); /* set verify lvl */\r | |
382 | \r | |
383 | PySSL_BEGIN_ALLOW_THREADS\r | |
384 | self->ssl = SSL_new(self->ctx); /* New ssl struct */\r | |
385 | PySSL_END_ALLOW_THREADS\r | |
386 | SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */\r | |
387 | #ifdef SSL_MODE_AUTO_RETRY\r | |
388 | SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);\r | |
389 | #endif\r | |
390 | \r | |
391 | /* If the socket is in non-blocking mode or timeout mode, set the BIO\r | |
392 | * to non-blocking mode (blocking is the default)\r | |
393 | */\r | |
394 | if (Sock->sock_timeout >= 0.0) {\r | |
395 | /* Set both the read and write BIO's to non-blocking mode */\r | |
396 | BIO_set_nbio(SSL_get_rbio(self->ssl), 1);\r | |
397 | BIO_set_nbio(SSL_get_wbio(self->ssl), 1);\r | |
398 | }\r | |
399 | \r | |
400 | PySSL_BEGIN_ALLOW_THREADS\r | |
401 | if (socket_type == PY_SSL_CLIENT)\r | |
402 | SSL_set_connect_state(self->ssl);\r | |
403 | else\r | |
404 | SSL_set_accept_state(self->ssl);\r | |
405 | PySSL_END_ALLOW_THREADS\r | |
406 | \r | |
407 | self->Socket = Sock;\r | |
408 | Py_INCREF(self->Socket);\r | |
409 | return self;\r | |
410 | fail:\r | |
411 | if (errstr)\r | |
412 | PyErr_SetString(PySSLErrorObject, errstr);\r | |
413 | Py_DECREF(self);\r | |
414 | return NULL;\r | |
415 | }\r | |
416 | \r | |
417 | static PyObject *\r | |
418 | PySSL_sslwrap(PyObject *self, PyObject *args)\r | |
419 | {\r | |
420 | PySocketSockObject *Sock;\r | |
421 | int server_side = 0;\r | |
422 | int verification_mode = PY_SSL_CERT_NONE;\r | |
423 | int protocol = PY_SSL_VERSION_SSL23;\r | |
424 | char *key_file = NULL;\r | |
425 | char *cert_file = NULL;\r | |
426 | char *cacerts_file = NULL;\r | |
427 | char *ciphers = NULL;\r | |
428 | \r | |
429 | if (!PyArg_ParseTuple(args, "O!i|zziizz:sslwrap",\r | |
430 | PySocketModule.Sock_Type,\r | |
431 | &Sock,\r | |
432 | &server_side,\r | |
433 | &key_file, &cert_file,\r | |
434 | &verification_mode, &protocol,\r | |
435 | &cacerts_file, &ciphers))\r | |
436 | return NULL;\r | |
437 | \r | |
438 | /*\r | |
439 | fprintf(stderr,\r | |
440 | "server_side is %d, keyfile %p, certfile %p, verify_mode %d, "\r | |
441 | "protocol %d, certs %p\n",\r | |
442 | server_side, key_file, cert_file, verification_mode,\r | |
443 | protocol, cacerts_file);\r | |
444 | */\r | |
445 | \r | |
446 | return (PyObject *) newPySSLObject(Sock, key_file, cert_file,\r | |
447 | server_side, verification_mode,\r | |
448 | protocol, cacerts_file,\r | |
449 | ciphers);\r | |
450 | }\r | |
451 | \r | |
452 | PyDoc_STRVAR(ssl_doc,\r | |
453 | "sslwrap(socket, server_side, [keyfile, certfile, certs_mode, protocol,\n"\r | |
454 | " cacertsfile, ciphers]) -> sslobject");\r | |
455 | \r | |
456 | /* SSL object methods */\r | |
457 | \r | |
458 | static PyObject *PySSL_SSLdo_handshake(PySSLObject *self)\r | |
459 | {\r | |
460 | int ret;\r | |
461 | int err;\r | |
462 | int sockstate, nonblocking;\r | |
463 | \r | |
464 | /* just in case the blocking state of the socket has been changed */\r | |
465 | nonblocking = (self->Socket->sock_timeout >= 0.0);\r | |
466 | BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);\r | |
467 | BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);\r | |
468 | \r | |
469 | /* Actually negotiate SSL connection */\r | |
470 | /* XXX If SSL_do_handshake() returns 0, it's also a failure. */\r | |
471 | do {\r | |
472 | PySSL_BEGIN_ALLOW_THREADS\r | |
473 | ret = SSL_do_handshake(self->ssl);\r | |
474 | err = SSL_get_error(self->ssl, ret);\r | |
475 | PySSL_END_ALLOW_THREADS\r | |
476 | if(PyErr_CheckSignals()) {\r | |
477 | return NULL;\r | |
478 | }\r | |
479 | if (err == SSL_ERROR_WANT_READ) {\r | |
480 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);\r | |
481 | } else if (err == SSL_ERROR_WANT_WRITE) {\r | |
482 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);\r | |
483 | } else {\r | |
484 | sockstate = SOCKET_OPERATION_OK;\r | |
485 | }\r | |
486 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
487 | PyErr_SetString(PySSLErrorObject,\r | |
488 | ERRSTR("The handshake operation timed out"));\r | |
489 | return NULL;\r | |
490 | } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {\r | |
491 | PyErr_SetString(PySSLErrorObject,\r | |
492 | ERRSTR("Underlying socket has been closed."));\r | |
493 | return NULL;\r | |
494 | } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {\r | |
495 | PyErr_SetString(PySSLErrorObject,\r | |
496 | ERRSTR("Underlying socket too large for select()."));\r | |
497 | return NULL;\r | |
498 | } else if (sockstate == SOCKET_IS_NONBLOCKING) {\r | |
499 | break;\r | |
500 | }\r | |
501 | } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);\r | |
502 | if (ret < 1)\r | |
503 | return PySSL_SetError(self, ret, __FILE__, __LINE__);\r | |
504 | \r | |
505 | if (self->peer_cert)\r | |
506 | X509_free (self->peer_cert);\r | |
507 | PySSL_BEGIN_ALLOW_THREADS\r | |
508 | if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) {\r | |
509 | X509_NAME_oneline(X509_get_subject_name(self->peer_cert),\r | |
510 | self->server, X509_NAME_MAXLEN);\r | |
511 | X509_NAME_oneline(X509_get_issuer_name(self->peer_cert),\r | |
512 | self->issuer, X509_NAME_MAXLEN);\r | |
513 | }\r | |
514 | PySSL_END_ALLOW_THREADS\r | |
515 | \r | |
516 | Py_INCREF(Py_None);\r | |
517 | return Py_None;\r | |
518 | }\r | |
519 | \r | |
520 | static PyObject *\r | |
521 | PySSL_server(PySSLObject *self)\r | |
522 | {\r | |
523 | return PyString_FromString(self->server);\r | |
524 | }\r | |
525 | \r | |
526 | static PyObject *\r | |
527 | PySSL_issuer(PySSLObject *self)\r | |
528 | {\r | |
529 | return PyString_FromString(self->issuer);\r | |
530 | }\r | |
531 | \r | |
532 | static PyObject *\r | |
533 | _create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {\r | |
534 | \r | |
535 | char namebuf[X509_NAME_MAXLEN];\r | |
536 | int buflen;\r | |
537 | PyObject *name_obj;\r | |
538 | PyObject *value_obj;\r | |
539 | PyObject *attr;\r | |
540 | unsigned char *valuebuf = NULL;\r | |
541 | \r | |
542 | buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);\r | |
543 | if (buflen < 0) {\r | |
544 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
545 | goto fail;\r | |
546 | }\r | |
547 | name_obj = PyString_FromStringAndSize(namebuf, buflen);\r | |
548 | if (name_obj == NULL)\r | |
549 | goto fail;\r | |
550 | \r | |
551 | buflen = ASN1_STRING_to_UTF8(&valuebuf, value);\r | |
552 | if (buflen < 0) {\r | |
553 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
554 | Py_DECREF(name_obj);\r | |
555 | goto fail;\r | |
556 | }\r | |
557 | value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,\r | |
558 | buflen, "strict");\r | |
559 | OPENSSL_free(valuebuf);\r | |
560 | if (value_obj == NULL) {\r | |
561 | Py_DECREF(name_obj);\r | |
562 | goto fail;\r | |
563 | }\r | |
564 | attr = PyTuple_New(2);\r | |
565 | if (attr == NULL) {\r | |
566 | Py_DECREF(name_obj);\r | |
567 | Py_DECREF(value_obj);\r | |
568 | goto fail;\r | |
569 | }\r | |
570 | PyTuple_SET_ITEM(attr, 0, name_obj);\r | |
571 | PyTuple_SET_ITEM(attr, 1, value_obj);\r | |
572 | return attr;\r | |
573 | \r | |
574 | fail:\r | |
575 | return NULL;\r | |
576 | }\r | |
577 | \r | |
578 | static PyObject *\r | |
579 | _create_tuple_for_X509_NAME (X509_NAME *xname)\r | |
580 | {\r | |
581 | PyObject *dn = NULL; /* tuple which represents the "distinguished name" */\r | |
582 | PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */\r | |
583 | PyObject *rdnt;\r | |
584 | PyObject *attr = NULL; /* tuple to hold an attribute */\r | |
585 | int entry_count = X509_NAME_entry_count(xname);\r | |
586 | X509_NAME_ENTRY *entry;\r | |
587 | ASN1_OBJECT *name;\r | |
588 | ASN1_STRING *value;\r | |
589 | int index_counter;\r | |
590 | int rdn_level = -1;\r | |
591 | int retcode;\r | |
592 | \r | |
593 | dn = PyList_New(0);\r | |
594 | if (dn == NULL)\r | |
595 | return NULL;\r | |
596 | /* now create another tuple to hold the top-level RDN */\r | |
597 | rdn = PyList_New(0);\r | |
598 | if (rdn == NULL)\r | |
599 | goto fail0;\r | |
600 | \r | |
601 | for (index_counter = 0;\r | |
602 | index_counter < entry_count;\r | |
603 | index_counter++)\r | |
604 | {\r | |
605 | entry = X509_NAME_get_entry(xname, index_counter);\r | |
606 | \r | |
607 | /* check to see if we've gotten to a new RDN */\r | |
608 | if (rdn_level >= 0) {\r | |
609 | if (rdn_level != entry->set) {\r | |
610 | /* yes, new RDN */\r | |
611 | /* add old RDN to DN */\r | |
612 | rdnt = PyList_AsTuple(rdn);\r | |
613 | Py_DECREF(rdn);\r | |
614 | if (rdnt == NULL)\r | |
615 | goto fail0;\r | |
616 | retcode = PyList_Append(dn, rdnt);\r | |
617 | Py_DECREF(rdnt);\r | |
618 | if (retcode < 0)\r | |
619 | goto fail0;\r | |
620 | /* create new RDN */\r | |
621 | rdn = PyList_New(0);\r | |
622 | if (rdn == NULL)\r | |
623 | goto fail0;\r | |
624 | }\r | |
625 | }\r | |
626 | rdn_level = entry->set;\r | |
627 | \r | |
628 | /* now add this attribute to the current RDN */\r | |
629 | name = X509_NAME_ENTRY_get_object(entry);\r | |
630 | value = X509_NAME_ENTRY_get_data(entry);\r | |
631 | attr = _create_tuple_for_attribute(name, value);\r | |
632 | /*\r | |
633 | fprintf(stderr, "RDN level %d, attribute %s: %s\n",\r | |
634 | entry->set,\r | |
635 | PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)),\r | |
636 | PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1)));\r | |
637 | */\r | |
638 | if (attr == NULL)\r | |
639 | goto fail1;\r | |
640 | retcode = PyList_Append(rdn, attr);\r | |
641 | Py_DECREF(attr);\r | |
642 | if (retcode < 0)\r | |
643 | goto fail1;\r | |
644 | }\r | |
645 | /* now, there's typically a dangling RDN */\r | |
646 | if ((rdn != NULL) && (PyList_Size(rdn) > 0)) {\r | |
647 | rdnt = PyList_AsTuple(rdn);\r | |
648 | Py_DECREF(rdn);\r | |
649 | if (rdnt == NULL)\r | |
650 | goto fail0;\r | |
651 | retcode = PyList_Append(dn, rdnt);\r | |
652 | Py_DECREF(rdnt);\r | |
653 | if (retcode < 0)\r | |
654 | goto fail0;\r | |
655 | }\r | |
656 | \r | |
657 | /* convert list to tuple */\r | |
658 | rdnt = PyList_AsTuple(dn);\r | |
659 | Py_DECREF(dn);\r | |
660 | if (rdnt == NULL)\r | |
661 | return NULL;\r | |
662 | return rdnt;\r | |
663 | \r | |
664 | fail1:\r | |
665 | Py_XDECREF(rdn);\r | |
666 | \r | |
667 | fail0:\r | |
668 | Py_XDECREF(dn);\r | |
669 | return NULL;\r | |
670 | }\r | |
671 | \r | |
672 | static PyObject *\r | |
673 | _get_peer_alt_names (X509 *certificate) {\r | |
674 | \r | |
675 | /* this code follows the procedure outlined in\r | |
676 | OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()\r | |
677 | function to extract the STACK_OF(GENERAL_NAME),\r | |
678 | then iterates through the stack to add the\r | |
679 | names. */\r | |
680 | \r | |
681 | int i, j;\r | |
682 | PyObject *peer_alt_names = Py_None;\r | |
683 | PyObject *v, *t;\r | |
684 | X509_EXTENSION *ext = NULL;\r | |
685 | GENERAL_NAMES *names = NULL;\r | |
686 | GENERAL_NAME *name;\r | |
687 | const X509V3_EXT_METHOD *method;\r | |
688 | BIO *biobuf = NULL;\r | |
689 | char buf[2048];\r | |
690 | char *vptr;\r | |
691 | int len;\r | |
692 | /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */\r | |
693 | #if OPENSSL_VERSION_NUMBER >= 0x009060dfL\r | |
694 | const unsigned char *p;\r | |
695 | #else\r | |
696 | unsigned char *p;\r | |
697 | #endif\r | |
698 | \r | |
699 | if (certificate == NULL)\r | |
700 | return peer_alt_names;\r | |
701 | \r | |
702 | /* get a memory buffer */\r | |
703 | biobuf = BIO_new(BIO_s_mem());\r | |
704 | \r | |
705 | i = 0;\r | |
706 | while ((i = X509_get_ext_by_NID(\r | |
707 | certificate, NID_subject_alt_name, i)) >= 0) {\r | |
708 | \r | |
709 | if (peer_alt_names == Py_None) {\r | |
710 | peer_alt_names = PyList_New(0);\r | |
711 | if (peer_alt_names == NULL)\r | |
712 | goto fail;\r | |
713 | }\r | |
714 | \r | |
715 | /* now decode the altName */\r | |
716 | ext = X509_get_ext(certificate, i);\r | |
717 | if(!(method = X509V3_EXT_get(ext))) {\r | |
718 | PyErr_SetString(PySSLErrorObject,\r | |
719 | ERRSTR("No method for internalizing subjectAltName!"));\r | |
720 | goto fail;\r | |
721 | }\r | |
722 | \r | |
723 | p = ext->value->data;\r | |
724 | if (method->it)\r | |
725 | names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL,\r | |
726 | &p,\r | |
727 | ext->value->length,\r | |
728 | ASN1_ITEM_ptr(method->it)));\r | |
729 | else\r | |
730 | names = (GENERAL_NAMES*) (method->d2i(NULL,\r | |
731 | &p,\r | |
732 | ext->value->length));\r | |
733 | \r | |
734 | for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {\r | |
735 | \r | |
736 | /* get a rendering of each name in the set of names */\r | |
737 | \r | |
738 | name = sk_GENERAL_NAME_value(names, j);\r | |
739 | if (name->type == GEN_DIRNAME) {\r | |
740 | \r | |
741 | /* we special-case DirName as a tuple of tuples of attributes */\r | |
742 | \r | |
743 | t = PyTuple_New(2);\r | |
744 | if (t == NULL) {\r | |
745 | goto fail;\r | |
746 | }\r | |
747 | \r | |
748 | v = PyString_FromString("DirName");\r | |
749 | if (v == NULL) {\r | |
750 | Py_DECREF(t);\r | |
751 | goto fail;\r | |
752 | }\r | |
753 | PyTuple_SET_ITEM(t, 0, v);\r | |
754 | \r | |
755 | v = _create_tuple_for_X509_NAME (name->d.dirn);\r | |
756 | if (v == NULL) {\r | |
757 | Py_DECREF(t);\r | |
758 | goto fail;\r | |
759 | }\r | |
760 | PyTuple_SET_ITEM(t, 1, v);\r | |
761 | \r | |
762 | } else {\r | |
763 | \r | |
764 | /* for everything else, we use the OpenSSL print form */\r | |
765 | \r | |
766 | (void) BIO_reset(biobuf);\r | |
767 | GENERAL_NAME_print(biobuf, name);\r | |
768 | len = BIO_gets(biobuf, buf, sizeof(buf)-1);\r | |
769 | if (len < 0) {\r | |
770 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
771 | goto fail;\r | |
772 | }\r | |
773 | vptr = strchr(buf, ':');\r | |
774 | if (vptr == NULL)\r | |
775 | goto fail;\r | |
776 | t = PyTuple_New(2);\r | |
777 | if (t == NULL)\r | |
778 | goto fail;\r | |
779 | v = PyString_FromStringAndSize(buf, (vptr - buf));\r | |
780 | if (v == NULL) {\r | |
781 | Py_DECREF(t);\r | |
782 | goto fail;\r | |
783 | }\r | |
784 | PyTuple_SET_ITEM(t, 0, v);\r | |
785 | v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1)));\r | |
786 | if (v == NULL) {\r | |
787 | Py_DECREF(t);\r | |
788 | goto fail;\r | |
789 | }\r | |
790 | PyTuple_SET_ITEM(t, 1, v);\r | |
791 | }\r | |
792 | \r | |
793 | /* and add that rendering to the list */\r | |
794 | \r | |
795 | if (PyList_Append(peer_alt_names, t) < 0) {\r | |
796 | Py_DECREF(t);\r | |
797 | goto fail;\r | |
798 | }\r | |
799 | Py_DECREF(t);\r | |
800 | }\r | |
801 | }\r | |
802 | BIO_free(biobuf);\r | |
803 | if (peer_alt_names != Py_None) {\r | |
804 | v = PyList_AsTuple(peer_alt_names);\r | |
805 | Py_DECREF(peer_alt_names);\r | |
806 | return v;\r | |
807 | } else {\r | |
808 | return peer_alt_names;\r | |
809 | }\r | |
810 | \r | |
811 | \r | |
812 | fail:\r | |
813 | if (biobuf != NULL)\r | |
814 | BIO_free(biobuf);\r | |
815 | \r | |
816 | if (peer_alt_names != Py_None) {\r | |
817 | Py_XDECREF(peer_alt_names);\r | |
818 | }\r | |
819 | \r | |
820 | return NULL;\r | |
821 | }\r | |
822 | \r | |
823 | static PyObject *\r | |
824 | _decode_certificate (X509 *certificate, int verbose) {\r | |
825 | \r | |
826 | PyObject *retval = NULL;\r | |
827 | BIO *biobuf = NULL;\r | |
828 | PyObject *peer;\r | |
829 | PyObject *peer_alt_names = NULL;\r | |
830 | PyObject *issuer;\r | |
831 | PyObject *version;\r | |
832 | PyObject *sn_obj;\r | |
833 | ASN1_INTEGER *serialNumber;\r | |
834 | char buf[2048];\r | |
835 | int len;\r | |
836 | ASN1_TIME *notBefore, *notAfter;\r | |
837 | PyObject *pnotBefore, *pnotAfter;\r | |
838 | \r | |
839 | retval = PyDict_New();\r | |
840 | if (retval == NULL)\r | |
841 | return NULL;\r | |
842 | \r | |
843 | peer = _create_tuple_for_X509_NAME(\r | |
844 | X509_get_subject_name(certificate));\r | |
845 | if (peer == NULL)\r | |
846 | goto fail0;\r | |
847 | if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {\r | |
848 | Py_DECREF(peer);\r | |
849 | goto fail0;\r | |
850 | }\r | |
851 | Py_DECREF(peer);\r | |
852 | \r | |
853 | if (verbose) {\r | |
854 | issuer = _create_tuple_for_X509_NAME(\r | |
855 | X509_get_issuer_name(certificate));\r | |
856 | if (issuer == NULL)\r | |
857 | goto fail0;\r | |
858 | if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {\r | |
859 | Py_DECREF(issuer);\r | |
860 | goto fail0;\r | |
861 | }\r | |
862 | Py_DECREF(issuer);\r | |
863 | \r | |
864 | version = PyInt_FromLong(X509_get_version(certificate) + 1);\r | |
865 | if (PyDict_SetItemString(retval, "version", version) < 0) {\r | |
866 | Py_DECREF(version);\r | |
867 | goto fail0;\r | |
868 | }\r | |
869 | Py_DECREF(version);\r | |
870 | }\r | |
871 | \r | |
872 | /* get a memory buffer */\r | |
873 | biobuf = BIO_new(BIO_s_mem());\r | |
874 | \r | |
875 | if (verbose) {\r | |
876 | \r | |
877 | (void) BIO_reset(biobuf);\r | |
878 | serialNumber = X509_get_serialNumber(certificate);\r | |
879 | /* should not exceed 20 octets, 160 bits, so buf is big enough */\r | |
880 | i2a_ASN1_INTEGER(biobuf, serialNumber);\r | |
881 | len = BIO_gets(biobuf, buf, sizeof(buf)-1);\r | |
882 | if (len < 0) {\r | |
883 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
884 | goto fail1;\r | |
885 | }\r | |
886 | sn_obj = PyString_FromStringAndSize(buf, len);\r | |
887 | if (sn_obj == NULL)\r | |
888 | goto fail1;\r | |
889 | if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {\r | |
890 | Py_DECREF(sn_obj);\r | |
891 | goto fail1;\r | |
892 | }\r | |
893 | Py_DECREF(sn_obj);\r | |
894 | \r | |
895 | (void) BIO_reset(biobuf);\r | |
896 | notBefore = X509_get_notBefore(certificate);\r | |
897 | ASN1_TIME_print(biobuf, notBefore);\r | |
898 | len = BIO_gets(biobuf, buf, sizeof(buf)-1);\r | |
899 | if (len < 0) {\r | |
900 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
901 | goto fail1;\r | |
902 | }\r | |
903 | pnotBefore = PyString_FromStringAndSize(buf, len);\r | |
904 | if (pnotBefore == NULL)\r | |
905 | goto fail1;\r | |
906 | if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {\r | |
907 | Py_DECREF(pnotBefore);\r | |
908 | goto fail1;\r | |
909 | }\r | |
910 | Py_DECREF(pnotBefore);\r | |
911 | }\r | |
912 | \r | |
913 | (void) BIO_reset(biobuf);\r | |
914 | notAfter = X509_get_notAfter(certificate);\r | |
915 | ASN1_TIME_print(biobuf, notAfter);\r | |
916 | len = BIO_gets(biobuf, buf, sizeof(buf)-1);\r | |
917 | if (len < 0) {\r | |
918 | _setSSLError(NULL, 0, __FILE__, __LINE__);\r | |
919 | goto fail1;\r | |
920 | }\r | |
921 | pnotAfter = PyString_FromStringAndSize(buf, len);\r | |
922 | if (pnotAfter == NULL)\r | |
923 | goto fail1;\r | |
924 | if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {\r | |
925 | Py_DECREF(pnotAfter);\r | |
926 | goto fail1;\r | |
927 | }\r | |
928 | Py_DECREF(pnotAfter);\r | |
929 | \r | |
930 | /* Now look for subjectAltName */\r | |
931 | \r | |
932 | peer_alt_names = _get_peer_alt_names(certificate);\r | |
933 | if (peer_alt_names == NULL)\r | |
934 | goto fail1;\r | |
935 | else if (peer_alt_names != Py_None) {\r | |
936 | if (PyDict_SetItemString(retval, "subjectAltName",\r | |
937 | peer_alt_names) < 0) {\r | |
938 | Py_DECREF(peer_alt_names);\r | |
939 | goto fail1;\r | |
940 | }\r | |
941 | Py_DECREF(peer_alt_names);\r | |
942 | }\r | |
943 | \r | |
944 | BIO_free(biobuf);\r | |
945 | return retval;\r | |
946 | \r | |
947 | fail1:\r | |
948 | if (biobuf != NULL)\r | |
949 | BIO_free(biobuf);\r | |
950 | fail0:\r | |
951 | Py_XDECREF(retval);\r | |
952 | return NULL;\r | |
953 | }\r | |
954 | \r | |
955 | \r | |
956 | static PyObject *\r | |
957 | PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {\r | |
958 | \r | |
959 | PyObject *retval = NULL;\r | |
960 | char *filename = NULL;\r | |
961 | X509 *x=NULL;\r | |
962 | BIO *cert;\r | |
963 | int verbose = 1;\r | |
964 | \r | |
965 | if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose))\r | |
966 | return NULL;\r | |
967 | \r | |
968 | if ((cert=BIO_new(BIO_s_file())) == NULL) {\r | |
969 | PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file");\r | |
970 | goto fail0;\r | |
971 | }\r | |
972 | \r | |
973 | if (BIO_read_filename(cert,filename) <= 0) {\r | |
974 | PyErr_SetString(PySSLErrorObject, "Can't open file");\r | |
975 | goto fail0;\r | |
976 | }\r | |
977 | \r | |
978 | x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);\r | |
979 | if (x == NULL) {\r | |
980 | PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file");\r | |
981 | goto fail0;\r | |
982 | }\r | |
983 | \r | |
984 | retval = _decode_certificate(x, verbose);\r | |
985 | X509_free(x);\r | |
986 | \r | |
987 | fail0:\r | |
988 | \r | |
989 | if (cert != NULL) BIO_free(cert);\r | |
990 | return retval;\r | |
991 | }\r | |
992 | \r | |
993 | \r | |
994 | static PyObject *\r | |
995 | PySSL_peercert(PySSLObject *self, PyObject *args)\r | |
996 | {\r | |
997 | PyObject *retval = NULL;\r | |
998 | int len;\r | |
999 | int verification;\r | |
1000 | PyObject *binary_mode = Py_None;\r | |
1001 | \r | |
1002 | if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))\r | |
1003 | return NULL;\r | |
1004 | \r | |
1005 | if (!self->peer_cert)\r | |
1006 | Py_RETURN_NONE;\r | |
1007 | \r | |
1008 | if (PyObject_IsTrue(binary_mode)) {\r | |
1009 | /* return cert in DER-encoded format */\r | |
1010 | \r | |
1011 | unsigned char *bytes_buf = NULL;\r | |
1012 | \r | |
1013 | bytes_buf = NULL;\r | |
1014 | len = i2d_X509(self->peer_cert, &bytes_buf);\r | |
1015 | if (len < 0) {\r | |
1016 | PySSL_SetError(self, len, __FILE__, __LINE__);\r | |
1017 | return NULL;\r | |
1018 | }\r | |
1019 | retval = PyString_FromStringAndSize((const char *) bytes_buf, len);\r | |
1020 | OPENSSL_free(bytes_buf);\r | |
1021 | return retval;\r | |
1022 | \r | |
1023 | } else {\r | |
1024 | \r | |
1025 | verification = SSL_CTX_get_verify_mode(self->ctx);\r | |
1026 | if ((verification & SSL_VERIFY_PEER) == 0)\r | |
1027 | return PyDict_New();\r | |
1028 | else\r | |
1029 | return _decode_certificate (self->peer_cert, 0);\r | |
1030 | }\r | |
1031 | }\r | |
1032 | \r | |
1033 | PyDoc_STRVAR(PySSL_peercert_doc,\r | |
1034 | "peer_certificate([der=False]) -> certificate\n\\r | |
1035 | \n\\r | |
1036 | Returns the certificate for the peer. If no certificate was provided,\n\\r | |
1037 | returns None. If a certificate was provided, but not validated, returns\n\\r | |
1038 | an empty dictionary. Otherwise returns a dict containing information\n\\r | |
1039 | about the peer certificate.\n\\r | |
1040 | \n\\r | |
1041 | If the optional argument is True, returns a DER-encoded copy of the\n\\r | |
1042 | peer certificate, or None if no certificate was provided. This will\n\\r | |
1043 | return the certificate even if it wasn't validated.");\r | |
1044 | \r | |
1045 | static PyObject *PySSL_cipher (PySSLObject *self) {\r | |
1046 | \r | |
1047 | PyObject *retval, *v;\r | |
1048 | const SSL_CIPHER *current;\r | |
1049 | char *cipher_name;\r | |
1050 | char *cipher_protocol;\r | |
1051 | \r | |
1052 | if (self->ssl == NULL)\r | |
1053 | Py_RETURN_NONE;\r | |
1054 | current = SSL_get_current_cipher(self->ssl);\r | |
1055 | if (current == NULL)\r | |
1056 | Py_RETURN_NONE;\r | |
1057 | \r | |
1058 | retval = PyTuple_New(3);\r | |
1059 | if (retval == NULL)\r | |
1060 | return NULL;\r | |
1061 | \r | |
1062 | cipher_name = (char *) SSL_CIPHER_get_name(current);\r | |
1063 | if (cipher_name == NULL) {\r | |
1064 | Py_INCREF(Py_None);\r | |
1065 | PyTuple_SET_ITEM(retval, 0, Py_None);\r | |
1066 | } else {\r | |
1067 | v = PyString_FromString(cipher_name);\r | |
1068 | if (v == NULL)\r | |
1069 | goto fail0;\r | |
1070 | PyTuple_SET_ITEM(retval, 0, v);\r | |
1071 | }\r | |
1072 | cipher_protocol = SSL_CIPHER_get_version(current);\r | |
1073 | if (cipher_protocol == NULL) {\r | |
1074 | Py_INCREF(Py_None);\r | |
1075 | PyTuple_SET_ITEM(retval, 1, Py_None);\r | |
1076 | } else {\r | |
1077 | v = PyString_FromString(cipher_protocol);\r | |
1078 | if (v == NULL)\r | |
1079 | goto fail0;\r | |
1080 | PyTuple_SET_ITEM(retval, 1, v);\r | |
1081 | }\r | |
1082 | v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL));\r | |
1083 | if (v == NULL)\r | |
1084 | goto fail0;\r | |
1085 | PyTuple_SET_ITEM(retval, 2, v);\r | |
1086 | return retval;\r | |
1087 | \r | |
1088 | fail0:\r | |
1089 | Py_DECREF(retval);\r | |
1090 | return NULL;\r | |
1091 | }\r | |
1092 | \r | |
1093 | static void PySSL_dealloc(PySSLObject *self)\r | |
1094 | {\r | |
1095 | if (self->peer_cert) /* Possible not to have one? */\r | |
1096 | X509_free (self->peer_cert);\r | |
1097 | if (self->ssl)\r | |
1098 | SSL_free(self->ssl);\r | |
1099 | if (self->ctx)\r | |
1100 | SSL_CTX_free(self->ctx);\r | |
1101 | Py_XDECREF(self->Socket);\r | |
1102 | PyObject_Del(self);\r | |
1103 | }\r | |
1104 | \r | |
1105 | /* If the socket has a timeout, do a select()/poll() on the socket.\r | |
1106 | The argument writing indicates the direction.\r | |
1107 | Returns one of the possibilities in the timeout_state enum (above).\r | |
1108 | */\r | |
1109 | \r | |
1110 | static int\r | |
1111 | check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)\r | |
1112 | {\r | |
1113 | fd_set fds;\r | |
1114 | struct timeval tv;\r | |
1115 | int rc;\r | |
1116 | \r | |
1117 | /* Nothing to do unless we're in timeout mode (not non-blocking) */\r | |
1118 | if (s->sock_timeout < 0.0)\r | |
1119 | return SOCKET_IS_BLOCKING;\r | |
1120 | else if (s->sock_timeout == 0.0)\r | |
1121 | return SOCKET_IS_NONBLOCKING;\r | |
1122 | \r | |
1123 | /* Guard against closed socket */\r | |
1124 | if (s->sock_fd < 0)\r | |
1125 | return SOCKET_HAS_BEEN_CLOSED;\r | |
1126 | \r | |
1127 | /* Prefer poll, if available, since you can poll() any fd\r | |
1128 | * which can't be done with select(). */\r | |
1129 | #ifdef HAVE_POLL\r | |
1130 | {\r | |
1131 | struct pollfd pollfd;\r | |
1132 | int timeout;\r | |
1133 | \r | |
1134 | pollfd.fd = s->sock_fd;\r | |
1135 | pollfd.events = writing ? POLLOUT : POLLIN;\r | |
1136 | \r | |
1137 | /* s->sock_timeout is in seconds, timeout in ms */\r | |
1138 | timeout = (int)(s->sock_timeout * 1000 + 0.5);\r | |
1139 | PySSL_BEGIN_ALLOW_THREADS\r | |
1140 | rc = poll(&pollfd, 1, timeout);\r | |
1141 | PySSL_END_ALLOW_THREADS\r | |
1142 | \r | |
1143 | goto normal_return;\r | |
1144 | }\r | |
1145 | #endif\r | |
1146 | \r | |
1147 | /* Guard against socket too large for select*/\r | |
1148 | #ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE\r | |
1149 | if (s->sock_fd >= FD_SETSIZE)\r | |
1150 | return SOCKET_TOO_LARGE_FOR_SELECT;\r | |
1151 | #endif\r | |
1152 | \r | |
1153 | /* Construct the arguments to select */\r | |
1154 | tv.tv_sec = (int)s->sock_timeout;\r | |
1155 | tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);\r | |
1156 | FD_ZERO(&fds);\r | |
1157 | FD_SET(s->sock_fd, &fds);\r | |
1158 | \r | |
1159 | /* See if the socket is ready */\r | |
1160 | PySSL_BEGIN_ALLOW_THREADS\r | |
1161 | if (writing)\r | |
1162 | rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);\r | |
1163 | else\r | |
1164 | rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);\r | |
1165 | PySSL_END_ALLOW_THREADS\r | |
1166 | \r | |
1167 | #ifdef HAVE_POLL\r | |
1168 | normal_return:\r | |
1169 | #endif\r | |
1170 | /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise\r | |
1171 | (when we are able to write or when there's something to read) */\r | |
1172 | return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;\r | |
1173 | }\r | |
1174 | \r | |
1175 | static PyObject *PySSL_SSLwrite(PySSLObject *self, PyObject *args)\r | |
1176 | {\r | |
1177 | Py_buffer buf;\r | |
1178 | int len;\r | |
1179 | int sockstate;\r | |
1180 | int err;\r | |
1181 | int nonblocking;\r | |
1182 | \r | |
1183 | if (!PyArg_ParseTuple(args, "s*:write", &buf))\r | |
1184 | return NULL;\r | |
1185 | \r | |
1186 | /* just in case the blocking state of the socket has been changed */\r | |
1187 | nonblocking = (self->Socket->sock_timeout >= 0.0);\r | |
1188 | BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);\r | |
1189 | BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);\r | |
1190 | \r | |
1191 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);\r | |
1192 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
1193 | PyErr_SetString(PySSLErrorObject,\r | |
1194 | "The write operation timed out");\r | |
1195 | goto error;\r | |
1196 | } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {\r | |
1197 | PyErr_SetString(PySSLErrorObject,\r | |
1198 | "Underlying socket has been closed.");\r | |
1199 | goto error;\r | |
1200 | } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {\r | |
1201 | PyErr_SetString(PySSLErrorObject,\r | |
1202 | "Underlying socket too large for select().");\r | |
1203 | goto error;\r | |
1204 | }\r | |
1205 | do {\r | |
1206 | PySSL_BEGIN_ALLOW_THREADS\r | |
1207 | len = SSL_write(self->ssl, buf.buf, buf.len);\r | |
1208 | err = SSL_get_error(self->ssl, len);\r | |
1209 | PySSL_END_ALLOW_THREADS\r | |
1210 | if (PyErr_CheckSignals()) {\r | |
1211 | goto error;\r | |
1212 | }\r | |
1213 | if (err == SSL_ERROR_WANT_READ) {\r | |
1214 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);\r | |
1215 | } else if (err == SSL_ERROR_WANT_WRITE) {\r | |
1216 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);\r | |
1217 | } else {\r | |
1218 | sockstate = SOCKET_OPERATION_OK;\r | |
1219 | }\r | |
1220 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
1221 | PyErr_SetString(PySSLErrorObject,\r | |
1222 | "The write operation timed out");\r | |
1223 | goto error;\r | |
1224 | } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {\r | |
1225 | PyErr_SetString(PySSLErrorObject,\r | |
1226 | "Underlying socket has been closed.");\r | |
1227 | goto error;\r | |
1228 | } else if (sockstate == SOCKET_IS_NONBLOCKING) {\r | |
1229 | break;\r | |
1230 | }\r | |
1231 | } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);\r | |
1232 | \r | |
1233 | PyBuffer_Release(&buf);\r | |
1234 | if (len > 0)\r | |
1235 | return PyInt_FromLong(len);\r | |
1236 | else\r | |
1237 | return PySSL_SetError(self, len, __FILE__, __LINE__);\r | |
1238 | \r | |
1239 | error:\r | |
1240 | PyBuffer_Release(&buf);\r | |
1241 | return NULL;\r | |
1242 | }\r | |
1243 | \r | |
1244 | PyDoc_STRVAR(PySSL_SSLwrite_doc,\r | |
1245 | "write(s) -> len\n\\r | |
1246 | \n\\r | |
1247 | Writes the string s into the SSL object. Returns the number\n\\r | |
1248 | of bytes written.");\r | |
1249 | \r | |
1250 | static PyObject *PySSL_SSLpending(PySSLObject *self)\r | |
1251 | {\r | |
1252 | int count = 0;\r | |
1253 | \r | |
1254 | PySSL_BEGIN_ALLOW_THREADS\r | |
1255 | count = SSL_pending(self->ssl);\r | |
1256 | PySSL_END_ALLOW_THREADS\r | |
1257 | if (count < 0)\r | |
1258 | return PySSL_SetError(self, count, __FILE__, __LINE__);\r | |
1259 | else\r | |
1260 | return PyInt_FromLong(count);\r | |
1261 | }\r | |
1262 | \r | |
1263 | PyDoc_STRVAR(PySSL_SSLpending_doc,\r | |
1264 | "pending() -> count\n\\r | |
1265 | \n\\r | |
1266 | Returns the number of already decrypted bytes available for read,\n\\r | |
1267 | pending on the connection.\n");\r | |
1268 | \r | |
1269 | static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args)\r | |
1270 | {\r | |
1271 | PyObject *buf;\r | |
1272 | int count = 0;\r | |
1273 | int len = 1024;\r | |
1274 | int sockstate;\r | |
1275 | int err;\r | |
1276 | int nonblocking;\r | |
1277 | \r | |
1278 | if (!PyArg_ParseTuple(args, "|i:read", &len))\r | |
1279 | return NULL;\r | |
1280 | \r | |
1281 | if (!(buf = PyString_FromStringAndSize((char *) 0, len)))\r | |
1282 | return NULL;\r | |
1283 | \r | |
1284 | /* just in case the blocking state of the socket has been changed */\r | |
1285 | nonblocking = (self->Socket->sock_timeout >= 0.0);\r | |
1286 | BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);\r | |
1287 | BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);\r | |
1288 | \r | |
1289 | /* first check if there are bytes ready to be read */\r | |
1290 | PySSL_BEGIN_ALLOW_THREADS\r | |
1291 | count = SSL_pending(self->ssl);\r | |
1292 | PySSL_END_ALLOW_THREADS\r | |
1293 | \r | |
1294 | if (!count) {\r | |
1295 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);\r | |
1296 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
1297 | PyErr_SetString(PySSLErrorObject,\r | |
1298 | "The read operation timed out");\r | |
1299 | Py_DECREF(buf);\r | |
1300 | return NULL;\r | |
1301 | } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {\r | |
1302 | PyErr_SetString(PySSLErrorObject,\r | |
1303 | "Underlying socket too large for select().");\r | |
1304 | Py_DECREF(buf);\r | |
1305 | return NULL;\r | |
1306 | } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {\r | |
1307 | if (SSL_get_shutdown(self->ssl) !=\r | |
1308 | SSL_RECEIVED_SHUTDOWN)\r | |
1309 | {\r | |
1310 | Py_DECREF(buf);\r | |
1311 | PyErr_SetString(PySSLErrorObject,\r | |
1312 | "Socket closed without SSL shutdown handshake");\r | |
1313 | return NULL;\r | |
1314 | } else {\r | |
1315 | /* should contain a zero-length string */\r | |
1316 | _PyString_Resize(&buf, 0);\r | |
1317 | return buf;\r | |
1318 | }\r | |
1319 | }\r | |
1320 | }\r | |
1321 | do {\r | |
1322 | PySSL_BEGIN_ALLOW_THREADS\r | |
1323 | count = SSL_read(self->ssl, PyString_AsString(buf), len);\r | |
1324 | err = SSL_get_error(self->ssl, count);\r | |
1325 | PySSL_END_ALLOW_THREADS\r | |
1326 | if(PyErr_CheckSignals()) {\r | |
1327 | Py_DECREF(buf);\r | |
1328 | return NULL;\r | |
1329 | }\r | |
1330 | if (err == SSL_ERROR_WANT_READ) {\r | |
1331 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);\r | |
1332 | } else if (err == SSL_ERROR_WANT_WRITE) {\r | |
1333 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);\r | |
1334 | } else if ((err == SSL_ERROR_ZERO_RETURN) &&\r | |
1335 | (SSL_get_shutdown(self->ssl) ==\r | |
1336 | SSL_RECEIVED_SHUTDOWN))\r | |
1337 | {\r | |
1338 | _PyString_Resize(&buf, 0);\r | |
1339 | return buf;\r | |
1340 | } else {\r | |
1341 | sockstate = SOCKET_OPERATION_OK;\r | |
1342 | }\r | |
1343 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
1344 | PyErr_SetString(PySSLErrorObject,\r | |
1345 | "The read operation timed out");\r | |
1346 | Py_DECREF(buf);\r | |
1347 | return NULL;\r | |
1348 | } else if (sockstate == SOCKET_IS_NONBLOCKING) {\r | |
1349 | break;\r | |
1350 | }\r | |
1351 | } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);\r | |
1352 | if (count <= 0) {\r | |
1353 | Py_DECREF(buf);\r | |
1354 | return PySSL_SetError(self, count, __FILE__, __LINE__);\r | |
1355 | }\r | |
1356 | if (count != len)\r | |
1357 | _PyString_Resize(&buf, count);\r | |
1358 | return buf;\r | |
1359 | }\r | |
1360 | \r | |
1361 | PyDoc_STRVAR(PySSL_SSLread_doc,\r | |
1362 | "read([len]) -> string\n\\r | |
1363 | \n\\r | |
1364 | Read up to len bytes from the SSL socket.");\r | |
1365 | \r | |
1366 | static PyObject *PySSL_SSLshutdown(PySSLObject *self)\r | |
1367 | {\r | |
1368 | int err, ssl_err, sockstate, nonblocking;\r | |
1369 | int zeros = 0;\r | |
1370 | \r | |
1371 | /* Guard against closed socket */\r | |
1372 | if (self->Socket->sock_fd < 0) {\r | |
1373 | PyErr_SetString(PySSLErrorObject,\r | |
1374 | "Underlying socket has been closed.");\r | |
1375 | return NULL;\r | |
1376 | }\r | |
1377 | \r | |
1378 | /* Just in case the blocking state of the socket has been changed */\r | |
1379 | nonblocking = (self->Socket->sock_timeout >= 0.0);\r | |
1380 | BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);\r | |
1381 | BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);\r | |
1382 | \r | |
1383 | while (1) {\r | |
1384 | PySSL_BEGIN_ALLOW_THREADS\r | |
1385 | /* Disable read-ahead so that unwrap can work correctly.\r | |
1386 | * Otherwise OpenSSL might read in too much data,\r | |
1387 | * eating clear text data that happens to be\r | |
1388 | * transmitted after the SSL shutdown.\r | |
1389 | * Should be safe to call repeatedly everytime this\r | |
1390 | * function is used and the shutdown_seen_zero != 0\r | |
1391 | * condition is met.\r | |
1392 | */\r | |
1393 | if (self->shutdown_seen_zero)\r | |
1394 | SSL_set_read_ahead(self->ssl, 0);\r | |
1395 | err = SSL_shutdown(self->ssl);\r | |
1396 | PySSL_END_ALLOW_THREADS\r | |
1397 | /* If err == 1, a secure shutdown with SSL_shutdown() is complete */\r | |
1398 | if (err > 0)\r | |
1399 | break;\r | |
1400 | if (err == 0) {\r | |
1401 | /* Don't loop endlessly; instead preserve legacy\r | |
1402 | behaviour of trying SSL_shutdown() only twice.\r | |
1403 | This looks necessary for OpenSSL < 0.9.8m */\r | |
1404 | if (++zeros > 1)\r | |
1405 | break;\r | |
1406 | /* Shutdown was sent, now try receiving */\r | |
1407 | self->shutdown_seen_zero = 1;\r | |
1408 | continue;\r | |
1409 | }\r | |
1410 | \r | |
1411 | /* Possibly retry shutdown until timeout or failure */\r | |
1412 | ssl_err = SSL_get_error(self->ssl, err);\r | |
1413 | if (ssl_err == SSL_ERROR_WANT_READ)\r | |
1414 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 0);\r | |
1415 | else if (ssl_err == SSL_ERROR_WANT_WRITE)\r | |
1416 | sockstate = check_socket_and_wait_for_timeout(self->Socket, 1);\r | |
1417 | else\r | |
1418 | break;\r | |
1419 | if (sockstate == SOCKET_HAS_TIMED_OUT) {\r | |
1420 | if (ssl_err == SSL_ERROR_WANT_READ)\r | |
1421 | PyErr_SetString(PySSLErrorObject,\r | |
1422 | "The read operation timed out");\r | |
1423 | else\r | |
1424 | PyErr_SetString(PySSLErrorObject,\r | |
1425 | "The write operation timed out");\r | |
1426 | return NULL;\r | |
1427 | }\r | |
1428 | else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {\r | |
1429 | PyErr_SetString(PySSLErrorObject,\r | |
1430 | "Underlying socket too large for select().");\r | |
1431 | return NULL;\r | |
1432 | }\r | |
1433 | else if (sockstate != SOCKET_OPERATION_OK)\r | |
1434 | /* Retain the SSL error code */\r | |
1435 | break;\r | |
1436 | }\r | |
1437 | \r | |
1438 | if (err < 0)\r | |
1439 | return PySSL_SetError(self, err, __FILE__, __LINE__);\r | |
1440 | else {\r | |
1441 | Py_INCREF(self->Socket);\r | |
1442 | return (PyObject *) (self->Socket);\r | |
1443 | }\r | |
1444 | }\r | |
1445 | \r | |
1446 | PyDoc_STRVAR(PySSL_SSLshutdown_doc,\r | |
1447 | "shutdown(s) -> socket\n\\r | |
1448 | \n\\r | |
1449 | Does the SSL shutdown handshake with the remote end, and returns\n\\r | |
1450 | the underlying socket object.");\r | |
1451 | \r | |
1452 | static PyMethodDef PySSLMethods[] = {\r | |
1453 | {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},\r | |
1454 | {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,\r | |
1455 | PySSL_SSLwrite_doc},\r | |
1456 | {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,\r | |
1457 | PySSL_SSLread_doc},\r | |
1458 | {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,\r | |
1459 | PySSL_SSLpending_doc},\r | |
1460 | {"server", (PyCFunction)PySSL_server, METH_NOARGS},\r | |
1461 | {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS},\r | |
1462 | {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,\r | |
1463 | PySSL_peercert_doc},\r | |
1464 | {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},\r | |
1465 | {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,\r | |
1466 | PySSL_SSLshutdown_doc},\r | |
1467 | {NULL, NULL}\r | |
1468 | };\r | |
1469 | \r | |
1470 | static PyObject *PySSL_getattr(PySSLObject *self, char *name)\r | |
1471 | {\r | |
1472 | return Py_FindMethod(PySSLMethods, (PyObject *)self, name);\r | |
1473 | }\r | |
1474 | \r | |
1475 | static PyTypeObject PySSL_Type = {\r | |
1476 | PyVarObject_HEAD_INIT(NULL, 0)\r | |
1477 | "ssl.SSLContext", /*tp_name*/\r | |
1478 | sizeof(PySSLObject), /*tp_basicsize*/\r | |
1479 | 0, /*tp_itemsize*/\r | |
1480 | /* methods */\r | |
1481 | (destructor)PySSL_dealloc, /*tp_dealloc*/\r | |
1482 | 0, /*tp_print*/\r | |
1483 | (getattrfunc)PySSL_getattr, /*tp_getattr*/\r | |
1484 | 0, /*tp_setattr*/\r | |
1485 | 0, /*tp_compare*/\r | |
1486 | 0, /*tp_repr*/\r | |
1487 | 0, /*tp_as_number*/\r | |
1488 | 0, /*tp_as_sequence*/\r | |
1489 | 0, /*tp_as_mapping*/\r | |
1490 | 0, /*tp_hash*/\r | |
1491 | };\r | |
1492 | \r | |
1493 | #ifdef HAVE_OPENSSL_RAND\r | |
1494 | \r | |
1495 | /* helper routines for seeding the SSL PRNG */\r | |
1496 | static PyObject *\r | |
1497 | PySSL_RAND_add(PyObject *self, PyObject *args)\r | |
1498 | {\r | |
1499 | char *buf;\r | |
1500 | int len;\r | |
1501 | double entropy;\r | |
1502 | \r | |
1503 | if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))\r | |
1504 | return NULL;\r | |
1505 | RAND_add(buf, len, entropy);\r | |
1506 | Py_INCREF(Py_None);\r | |
1507 | return Py_None;\r | |
1508 | }\r | |
1509 | \r | |
1510 | PyDoc_STRVAR(PySSL_RAND_add_doc,\r | |
1511 | "RAND_add(string, entropy)\n\\r | |
1512 | \n\\r | |
1513 | Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\\r | |
1514 | bound on the entropy contained in string. See RFC 1750.");\r | |
1515 | \r | |
1516 | static PyObject *\r | |
1517 | PySSL_RAND_status(PyObject *self)\r | |
1518 | {\r | |
1519 | return PyInt_FromLong(RAND_status());\r | |
1520 | }\r | |
1521 | \r | |
1522 | PyDoc_STRVAR(PySSL_RAND_status_doc,\r | |
1523 | "RAND_status() -> 0 or 1\n\\r | |
1524 | \n\\r | |
1525 | Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\\r | |
1526 | It is necessary to seed the PRNG with RAND_add() on some platforms before\n\\r | |
1527 | using the ssl() function.");\r | |
1528 | \r | |
1529 | static PyObject *\r | |
1530 | PySSL_RAND_egd(PyObject *self, PyObject *arg)\r | |
1531 | {\r | |
1532 | int bytes;\r | |
1533 | \r | |
1534 | if (!PyString_Check(arg))\r | |
1535 | return PyErr_Format(PyExc_TypeError,\r | |
1536 | "RAND_egd() expected string, found %s",\r | |
1537 | Py_TYPE(arg)->tp_name);\r | |
1538 | bytes = RAND_egd(PyString_AS_STRING(arg));\r | |
1539 | if (bytes == -1) {\r | |
1540 | PyErr_SetString(PySSLErrorObject,\r | |
1541 | "EGD connection failed or EGD did not return "\r | |
1542 | "enough data to seed the PRNG");\r | |
1543 | return NULL;\r | |
1544 | }\r | |
1545 | return PyInt_FromLong(bytes);\r | |
1546 | }\r | |
1547 | \r | |
1548 | PyDoc_STRVAR(PySSL_RAND_egd_doc,\r | |
1549 | "RAND_egd(path) -> bytes\n\\r | |
1550 | \n\\r | |
1551 | Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\\r | |
1552 | Returns number of bytes read. Raises SSLError if connection to EGD\n\\r | |
1553 | fails or if it does provide enough data to seed PRNG.");\r | |
1554 | \r | |
1555 | #endif\r | |
1556 | \r | |
1557 | /* List of functions exported by this module. */\r | |
1558 | \r | |
1559 | static PyMethodDef PySSL_methods[] = {\r | |
1560 | {"sslwrap", PySSL_sslwrap,\r | |
1561 | METH_VARARGS, ssl_doc},\r | |
1562 | {"_test_decode_cert", PySSL_test_decode_certificate,\r | |
1563 | METH_VARARGS},\r | |
1564 | #ifdef HAVE_OPENSSL_RAND\r | |
1565 | {"RAND_add", PySSL_RAND_add, METH_VARARGS,\r | |
1566 | PySSL_RAND_add_doc},\r | |
1567 | {"RAND_egd", PySSL_RAND_egd, METH_O,\r | |
1568 | PySSL_RAND_egd_doc},\r | |
1569 | {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,\r | |
1570 | PySSL_RAND_status_doc},\r | |
1571 | #endif\r | |
1572 | {NULL, NULL} /* Sentinel */\r | |
1573 | };\r | |
1574 | \r | |
1575 | \r | |
1576 | #ifdef WITH_THREAD\r | |
1577 | \r | |
1578 | /* an implementation of OpenSSL threading operations in terms\r | |
1579 | of the Python C thread library */\r | |
1580 | \r | |
1581 | static PyThread_type_lock *_ssl_locks = NULL;\r | |
1582 | \r | |
1583 | static unsigned long _ssl_thread_id_function (void) {\r | |
1584 | return PyThread_get_thread_ident();\r | |
1585 | }\r | |
1586 | \r | |
1587 | static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) {\r | |
1588 | /* this function is needed to perform locking on shared data\r | |
1589 | structures. (Note that OpenSSL uses a number of global data\r | |
1590 | structures that will be implicitly shared whenever multiple threads\r | |
1591 | use OpenSSL.) Multi-threaded applications will crash at random if\r | |
1592 | it is not set.\r | |
1593 | \r | |
1594 | locking_function() must be able to handle up to CRYPTO_num_locks()\r | |
1595 | different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and\r | |
1596 | releases it otherwise.\r | |
1597 | \r | |
1598 | file and line are the file number of the function setting the\r | |
1599 | lock. They can be useful for debugging.\r | |
1600 | */\r | |
1601 | \r | |
1602 | if ((_ssl_locks == NULL) ||\r | |
1603 | (n < 0) || ((unsigned)n >= _ssl_locks_count))\r | |
1604 | return;\r | |
1605 | \r | |
1606 | if (mode & CRYPTO_LOCK) {\r | |
1607 | PyThread_acquire_lock(_ssl_locks[n], 1);\r | |
1608 | } else {\r | |
1609 | PyThread_release_lock(_ssl_locks[n]);\r | |
1610 | }\r | |
1611 | }\r | |
1612 | \r | |
1613 | static int _setup_ssl_threads(void) {\r | |
1614 | \r | |
1615 | unsigned int i;\r | |
1616 | \r | |
1617 | if (_ssl_locks == NULL) {\r | |
1618 | _ssl_locks_count = CRYPTO_num_locks();\r | |
1619 | _ssl_locks = (PyThread_type_lock *)\r | |
1620 | malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);\r | |
1621 | if (_ssl_locks == NULL)\r | |
1622 | return 0;\r | |
1623 | memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count);\r | |
1624 | for (i = 0; i < _ssl_locks_count; i++) {\r | |
1625 | _ssl_locks[i] = PyThread_allocate_lock();\r | |
1626 | if (_ssl_locks[i] == NULL) {\r | |
1627 | unsigned int j;\r | |
1628 | for (j = 0; j < i; j++) {\r | |
1629 | PyThread_free_lock(_ssl_locks[j]);\r | |
1630 | }\r | |
1631 | free(_ssl_locks);\r | |
1632 | return 0;\r | |
1633 | }\r | |
1634 | }\r | |
1635 | CRYPTO_set_locking_callback(_ssl_thread_locking_function);\r | |
1636 | CRYPTO_set_id_callback(_ssl_thread_id_function);\r | |
1637 | }\r | |
1638 | return 1;\r | |
1639 | }\r | |
1640 | \r | |
1641 | #endif /* def HAVE_THREAD */\r | |
1642 | \r | |
1643 | PyDoc_STRVAR(module_doc,\r | |
1644 | "Implementation module for SSL socket operations. See the socket module\n\\r | |
1645 | for documentation.");\r | |
1646 | \r | |
1647 | PyMODINIT_FUNC\r | |
1648 | init_ssl(void)\r | |
1649 | {\r | |
1650 | PyObject *m, *d, *r;\r | |
1651 | unsigned long libver;\r | |
1652 | unsigned int major, minor, fix, patch, status;\r | |
1653 | \r | |
1654 | Py_TYPE(&PySSL_Type) = &PyType_Type;\r | |
1655 | \r | |
1656 | m = Py_InitModule3("_ssl", PySSL_methods, module_doc);\r | |
1657 | if (m == NULL)\r | |
1658 | return;\r | |
1659 | d = PyModule_GetDict(m);\r | |
1660 | \r | |
1661 | /* Load _socket module and its C API */\r | |
1662 | if (PySocketModule_ImportModuleAndAPI())\r | |
1663 | return;\r | |
1664 | \r | |
1665 | /* Init OpenSSL */\r | |
1666 | SSL_load_error_strings();\r | |
1667 | SSL_library_init();\r | |
1668 | #ifdef WITH_THREAD\r | |
1669 | /* note that this will start threading if not already started */\r | |
1670 | if (!_setup_ssl_threads()) {\r | |
1671 | return;\r | |
1672 | }\r | |
1673 | #endif\r | |
1674 | OpenSSL_add_all_algorithms();\r | |
1675 | \r | |
1676 | /* Add symbols to module dict */\r | |
1677 | PySSLErrorObject = PyErr_NewException("ssl.SSLError",\r | |
1678 | PySocketModule.error,\r | |
1679 | NULL);\r | |
1680 | if (PySSLErrorObject == NULL)\r | |
1681 | return;\r | |
1682 | if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0)\r | |
1683 | return;\r | |
1684 | if (PyDict_SetItemString(d, "SSLType",\r | |
1685 | (PyObject *)&PySSL_Type) != 0)\r | |
1686 | return;\r | |
1687 | PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",\r | |
1688 | PY_SSL_ERROR_ZERO_RETURN);\r | |
1689 | PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",\r | |
1690 | PY_SSL_ERROR_WANT_READ);\r | |
1691 | PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",\r | |
1692 | PY_SSL_ERROR_WANT_WRITE);\r | |
1693 | PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",\r | |
1694 | PY_SSL_ERROR_WANT_X509_LOOKUP);\r | |
1695 | PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",\r | |
1696 | PY_SSL_ERROR_SYSCALL);\r | |
1697 | PyModule_AddIntConstant(m, "SSL_ERROR_SSL",\r | |
1698 | PY_SSL_ERROR_SSL);\r | |
1699 | PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",\r | |
1700 | PY_SSL_ERROR_WANT_CONNECT);\r | |
1701 | /* non ssl.h errorcodes */\r | |
1702 | PyModule_AddIntConstant(m, "SSL_ERROR_EOF",\r | |
1703 | PY_SSL_ERROR_EOF);\r | |
1704 | PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",\r | |
1705 | PY_SSL_ERROR_INVALID_ERROR_CODE);\r | |
1706 | /* cert requirements */\r | |
1707 | PyModule_AddIntConstant(m, "CERT_NONE",\r | |
1708 | PY_SSL_CERT_NONE);\r | |
1709 | PyModule_AddIntConstant(m, "CERT_OPTIONAL",\r | |
1710 | PY_SSL_CERT_OPTIONAL);\r | |
1711 | PyModule_AddIntConstant(m, "CERT_REQUIRED",\r | |
1712 | PY_SSL_CERT_REQUIRED);\r | |
1713 | \r | |
1714 | /* protocol versions */\r | |
1715 | #ifndef OPENSSL_NO_SSL2\r | |
1716 | PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",\r | |
1717 | PY_SSL_VERSION_SSL2);\r | |
1718 | #endif\r | |
1719 | PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",\r | |
1720 | PY_SSL_VERSION_SSL3);\r | |
1721 | PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",\r | |
1722 | PY_SSL_VERSION_SSL23);\r | |
1723 | PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",\r | |
1724 | PY_SSL_VERSION_TLS1);\r | |
1725 | \r | |
1726 | /* OpenSSL version */\r | |
1727 | /* SSLeay() gives us the version of the library linked against,\r | |
1728 | which could be different from the headers version.\r | |
1729 | */\r | |
1730 | libver = SSLeay();\r | |
1731 | r = PyLong_FromUnsignedLong(libver);\r | |
1732 | if (r == NULL)\r | |
1733 | return;\r | |
1734 | if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))\r | |
1735 | return;\r | |
1736 | status = libver & 0xF;\r | |
1737 | libver >>= 4;\r | |
1738 | patch = libver & 0xFF;\r | |
1739 | libver >>= 8;\r | |
1740 | fix = libver & 0xFF;\r | |
1741 | libver >>= 8;\r | |
1742 | minor = libver & 0xFF;\r | |
1743 | libver >>= 8;\r | |
1744 | major = libver & 0xFF;\r | |
1745 | r = Py_BuildValue("IIIII", major, minor, fix, patch, status);\r | |
1746 | if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))\r | |
1747 | return;\r | |
1748 | r = PyString_FromString(SSLeay_version(SSLEAY_VERSION));\r | |
1749 | if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))\r | |
1750 | return;\r | |
1751 | }\r |