/Modules/_ssl.c

http://unladen-swallow.googlecode.com/ · C · 1638 lines · 1305 code · 208 blank · 125 comment · 341 complexity · 2912a1f48f5be2acd5ce6f3d16f6b558 MD5 · raw file

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