stream_peer_openssl.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. /*************************************************************************/
  2. /* stream_peer_openssl.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "stream_peer_openssl.h"
  31. //hostname matching code from curl
  32. //#include <openssl/applink.c> // To prevent crashing (see the OpenSSL FAQ)
  33. bool StreamPeerOpenSSL::_match_host_name(const char *name, const char *hostname) {
  34. return Tool_Curl_cert_hostcheck(name, hostname) == CURL_HOST_MATCH;
  35. //print_line("MATCH: "+String(name)+" vs "+String(hostname));
  36. //return true;
  37. }
  38. Error StreamPeerOpenSSL::_match_common_name(const char *hostname, const X509 *server_cert) {
  39. // Find the position of the CN field in the Subject field of the certificate
  40. int common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *)server_cert), NID_commonName, -1);
  41. ERR_FAIL_COND_V(common_name_loc < 0, ERR_INVALID_PARAMETER);
  42. // Extract the CN field
  43. X509_NAME_ENTRY *common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *)server_cert), common_name_loc);
  44. ERR_FAIL_COND_V(common_name_entry == NULL, ERR_INVALID_PARAMETER);
  45. // Convert the CN field to a C string
  46. ASN1_STRING *common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
  47. ERR_FAIL_COND_V(common_name_asn1 == NULL, ERR_INVALID_PARAMETER);
  48. char *common_name_str = (char *)ASN1_STRING_data(common_name_asn1);
  49. // Make sure there isn't an embedded NUL character in the CN
  50. bool malformed_certificate = (size_t)ASN1_STRING_length(common_name_asn1) != strlen(common_name_str);
  51. ERR_FAIL_COND_V(malformed_certificate, ERR_INVALID_PARAMETER);
  52. // Compare expected hostname with the CN
  53. return _match_host_name(common_name_str, hostname) ? OK : FAILED;
  54. }
  55. /**
  56. * Tries to find a match for hostname in the certificate's Subject Alternative Name extension.
  57. *
  58. */
  59. Error StreamPeerOpenSSL::_match_subject_alternative_name(const char *hostname, const X509 *server_cert) {
  60. Error result = FAILED;
  61. int i;
  62. int san_names_nb = -1;
  63. STACK_OF(GENERAL_NAME) *san_names = NULL;
  64. // Try to extract the names within the SAN extension from the certificate
  65. san_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i((X509 *)server_cert, NID_subject_alt_name, NULL, NULL);
  66. if (san_names == NULL) {
  67. return ERR_FILE_NOT_FOUND;
  68. }
  69. san_names_nb = sk_GENERAL_NAME_num(san_names);
  70. // Check each name within the extension
  71. for (i = 0; i < san_names_nb; i++) {
  72. const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
  73. if (current_name->type == GEN_DNS) {
  74. // Current name is a DNS name, let's check it
  75. char *dns_name = (char *)ASN1_STRING_data(current_name->d.dNSName);
  76. // Make sure there isn't an embedded NUL character in the DNS name
  77. if ((size_t)ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) {
  78. result = ERR_INVALID_PARAMETER;
  79. break;
  80. } else { // Compare expected hostname with the DNS name
  81. if (_match_host_name(dns_name, hostname)) {
  82. result = OK;
  83. break;
  84. }
  85. }
  86. }
  87. }
  88. sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
  89. return result;
  90. }
  91. /* See http://archives.seul.org/libevent/users/Jan-2013/msg00039.html */
  92. int StreamPeerOpenSSL::_cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg) {
  93. /* This is the function that OpenSSL would call if we hadn't called
  94. * SSL_CTX_set_cert_verify_callback(). Therefore, we are "wrapping"
  95. * the default functionality, rather than replacing it. */
  96. bool base_cert_valid = X509_verify_cert(x509_ctx);
  97. if (!base_cert_valid) {
  98. print_line("Cause: " + String(X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx))));
  99. ERR_print_errors_fp(stdout);
  100. }
  101. X509 *server_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
  102. ERR_FAIL_COND_V(!server_cert, 0);
  103. char cert_str[256];
  104. X509_NAME_oneline(X509_get_subject_name(server_cert),
  105. cert_str, sizeof(cert_str));
  106. print_line("CERT STR: " + String(cert_str));
  107. print_line("VALID: " + itos(base_cert_valid));
  108. if (!base_cert_valid)
  109. return 0;
  110. StreamPeerOpenSSL *ssl = (StreamPeerOpenSSL *)arg;
  111. if (ssl->validate_hostname) {
  112. Error err = _match_subject_alternative_name(ssl->hostname.utf8().get_data(), server_cert);
  113. if (err == ERR_FILE_NOT_FOUND) {
  114. err = _match_common_name(ssl->hostname.utf8().get_data(), server_cert);
  115. }
  116. if (err != OK) {
  117. ssl->status = STATUS_ERROR_HOSTNAME_MISMATCH;
  118. return 0;
  119. }
  120. }
  121. return 1;
  122. }
  123. int StreamPeerOpenSSL::_bio_create(BIO *b) {
  124. b->init = 1;
  125. b->num = 0;
  126. b->ptr = NULL;
  127. b->flags = 0;
  128. return 1;
  129. }
  130. int StreamPeerOpenSSL::_bio_destroy(BIO *b) {
  131. if (b == NULL)
  132. return 0;
  133. b->ptr = NULL; /* sb_tls_remove() will free it */
  134. b->init = 0;
  135. b->flags = 0;
  136. return 1;
  137. }
  138. int StreamPeerOpenSSL::_bio_read(BIO *b, char *buf, int len) {
  139. if (buf == NULL || len <= 0) return 0;
  140. StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr;
  141. ERR_FAIL_COND_V(sp == NULL, 0);
  142. BIO_clear_retry_flags(b);
  143. if (sp->use_blocking) {
  144. Error err = sp->base->get_data((uint8_t *)buf, len);
  145. if (err != OK) {
  146. return -1;
  147. }
  148. return len;
  149. } else {
  150. int got;
  151. Error err = sp->base->get_partial_data((uint8_t *)buf, len, got);
  152. if (err != OK) {
  153. return -1;
  154. }
  155. if (got == 0) {
  156. BIO_set_retry_read(b);
  157. }
  158. return got;
  159. }
  160. //unreachable
  161. return 0;
  162. }
  163. int StreamPeerOpenSSL::_bio_write(BIO *b, const char *buf, int len) {
  164. if (buf == NULL || len <= 0) return 0;
  165. StreamPeerOpenSSL *sp = (StreamPeerOpenSSL *)b->ptr;
  166. ERR_FAIL_COND_V(sp == NULL, 0);
  167. BIO_clear_retry_flags(b);
  168. if (sp->use_blocking) {
  169. Error err = sp->base->put_data((const uint8_t *)buf, len);
  170. if (err != OK) {
  171. return -1;
  172. }
  173. return len;
  174. } else {
  175. int sent;
  176. Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent);
  177. if (err != OK) {
  178. return -1;
  179. }
  180. if (sent == 0) {
  181. BIO_set_retry_write(b);
  182. }
  183. return sent;
  184. }
  185. //unreachable
  186. return 0;
  187. }
  188. long StreamPeerOpenSSL::_bio_ctrl(BIO *b, int cmd, long num, void *ptr) {
  189. if (cmd == BIO_CTRL_FLUSH) {
  190. /* The OpenSSL library needs this */
  191. return 1;
  192. }
  193. return 0;
  194. }
  195. int StreamPeerOpenSSL::_bio_gets(BIO *b, char *buf, int len) {
  196. return -1;
  197. }
  198. int StreamPeerOpenSSL::_bio_puts(BIO *b, const char *str) {
  199. return _bio_write(b, str, strlen(str));
  200. }
  201. BIO_METHOD StreamPeerOpenSSL::_bio_method = {
  202. /* it's a source/sink BIO */
  203. (100 | 0x400),
  204. "streampeer glue",
  205. _bio_write,
  206. _bio_read,
  207. _bio_puts,
  208. _bio_gets,
  209. _bio_ctrl,
  210. _bio_create,
  211. _bio_destroy
  212. };
  213. Error StreamPeerOpenSSL::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
  214. if (connected)
  215. disconnect_from_stream();
  216. hostname = p_for_hostname;
  217. status = STATUS_DISCONNECTED;
  218. // Set up a SSL_CTX object, which will tell our BIO object how to do its work
  219. ctx = SSL_CTX_new(SSLv23_client_method());
  220. base = p_base;
  221. validate_certs = p_validate_certs;
  222. validate_hostname = p_for_hostname != "";
  223. if (p_validate_certs) {
  224. if (certs.size()) {
  225. //yay for undocumented OpenSSL functions
  226. X509_STORE *store = SSL_CTX_get_cert_store(ctx);
  227. for (int i = 0; i < certs.size(); i++) {
  228. X509_STORE_add_cert(store, certs[i]);
  229. }
  230. #if 0
  231. const unsigned char *in=(const unsigned char *)certs.ptr();
  232. X509 *Cert = d2i_X509(NULL, &in, certs.size()-1);
  233. if (!Cert) {
  234. print_line(String(ERR_error_string(ERR_get_error(),NULL)));
  235. }
  236. ERR_FAIL_COND_V(!Cert,ERR_PARSE_ERROR);
  237. X509_STORE *store = SSL_CTX_get_cert_store(ctx);
  238. X509_STORE_add_cert(store,Cert);
  239. //char *str = X509_NAME_oneline(X509_get_subject_name(Cert),0,0);
  240. //printf ("subject: %s\n", str); /* [1] */
  241. #endif
  242. }
  243. //used for testing
  244. //int res = SSL_CTX_load_verify_locations(ctx,"/etc/ssl/certs/ca-certificates.crt",NULL);
  245. //print_line("verify locations res: "+itos(res));
  246. /* Ask OpenSSL to verify the server certificate. Note that this
  247. * does NOT include verifying that the hostname is correct.
  248. * So, by itself, this means anyone with any legitimate
  249. * CA-issued certificate for any website, can impersonate any
  250. * other website in the world. This is not good. See "The
  251. * Most Dangerous Code in the World" article at
  252. * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
  253. */
  254. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
  255. /* This is how we solve the problem mentioned in the previous
  256. * comment. We "wrap" OpenSSL's validation routine in our
  257. * own routine, which also validates the hostname by calling
  258. * the code provided by iSECPartners. Note that even though
  259. * the "Everything You've Always Wanted to Know About
  260. * Certificate Validation With OpenSSL (But Were Afraid to
  261. * Ask)" paper from iSECPartners says very explicitly not to
  262. * call SSL_CTX_set_cert_verify_callback (at the bottom of
  263. * page 2), what we're doing here is safe because our
  264. * cert_verify_callback() calls X509_verify_cert(), which is
  265. * OpenSSL's built-in routine which would have been called if
  266. * we hadn't set the callback. Therefore, we're just
  267. * "wrapping" OpenSSL's routine, not replacing it. */
  268. SSL_CTX_set_cert_verify_callback(ctx, _cert_verify_callback, this);
  269. //Let the verify_callback catch the verify_depth error so that we get an appropriate error in the logfile. (??)
  270. SSL_CTX_set_verify_depth(ctx, max_cert_chain_depth + 1);
  271. }
  272. ssl = SSL_new(ctx);
  273. bio = BIO_new(&_bio_method);
  274. bio->ptr = this;
  275. SSL_set_bio(ssl, bio, bio);
  276. if (p_for_hostname != String()) {
  277. SSL_set_tlsext_host_name(ssl, p_for_hostname.utf8().get_data());
  278. }
  279. use_blocking = true; // let handshake use blocking
  280. // Set the SSL to automatically retry on failure.
  281. SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
  282. // Same as before, try to connect.
  283. int result = SSL_connect(ssl);
  284. print_line("CONNECTION RESULT: " + itos(result));
  285. if (result < 1) {
  286. ERR_print_errors_fp(stdout);
  287. _print_error(result);
  288. }
  289. X509 *peer = SSL_get_peer_certificate(ssl);
  290. if (peer) {
  291. bool cert_ok = SSL_get_verify_result(ssl) == X509_V_OK;
  292. print_line("cert_ok: " + itos(cert_ok));
  293. } else if (validate_certs) {
  294. status = STATUS_ERROR_NO_CERTIFICATE;
  295. }
  296. connected = true;
  297. status = STATUS_CONNECTED;
  298. return OK;
  299. }
  300. Error StreamPeerOpenSSL::accept_stream(Ref<StreamPeer> p_base) {
  301. return ERR_UNAVAILABLE;
  302. }
  303. void StreamPeerOpenSSL::_print_error(int err) {
  304. err = SSL_get_error(ssl, err);
  305. switch (err) {
  306. case SSL_ERROR_NONE: ERR_PRINT("NO ERROR: The TLS/SSL I/O operation completed"); break;
  307. case SSL_ERROR_ZERO_RETURN: ERR_PRINT("The TLS/SSL connection has been closed.");
  308. case SSL_ERROR_WANT_READ:
  309. case SSL_ERROR_WANT_WRITE:
  310. ERR_PRINT("The operation did not complete.");
  311. break;
  312. case SSL_ERROR_WANT_CONNECT:
  313. case SSL_ERROR_WANT_ACCEPT:
  314. ERR_PRINT("The connect/accept operation did not complete");
  315. break;
  316. case SSL_ERROR_WANT_X509_LOOKUP:
  317. ERR_PRINT("The operation did not complete because an application callback set by SSL_CTX_set_client_cert_cb() has asked to be called again.");
  318. break;
  319. case SSL_ERROR_SYSCALL:
  320. ERR_PRINT("Some I/O error occurred. The OpenSSL error queue may contain more information on the error.");
  321. break;
  322. case SSL_ERROR_SSL:
  323. ERR_PRINT("A failure in the SSL library occurred, usually a protocol error.");
  324. break;
  325. }
  326. }
  327. Error StreamPeerOpenSSL::put_data(const uint8_t *p_data, int p_bytes) {
  328. ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
  329. while (p_bytes > 0) {
  330. int ret = SSL_write(ssl, p_data, p_bytes);
  331. if (ret <= 0) {
  332. _print_error(ret);
  333. disconnect_from_stream();
  334. return ERR_CONNECTION_ERROR;
  335. }
  336. p_data += ret;
  337. p_bytes -= ret;
  338. }
  339. return OK;
  340. }
  341. Error StreamPeerOpenSSL::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
  342. ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
  343. if (p_bytes == 0)
  344. return OK;
  345. Error err = put_data(p_data, p_bytes);
  346. if (err != OK)
  347. return err;
  348. r_sent = p_bytes;
  349. return OK;
  350. }
  351. Error StreamPeerOpenSSL::get_data(uint8_t *p_buffer, int p_bytes) {
  352. ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
  353. while (p_bytes > 0) {
  354. int ret = SSL_read(ssl, p_buffer, p_bytes);
  355. if (ret <= 0) {
  356. _print_error(ret);
  357. disconnect_from_stream();
  358. return ERR_CONNECTION_ERROR;
  359. }
  360. p_buffer += ret;
  361. p_bytes -= ret;
  362. }
  363. return OK;
  364. }
  365. Error StreamPeerOpenSSL::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
  366. ERR_FAIL_COND_V(!connected, ERR_UNCONFIGURED);
  367. if (p_bytes == 0) {
  368. r_received = 0;
  369. return OK;
  370. }
  371. Error err = get_data(p_buffer, p_bytes);
  372. if (err != OK)
  373. return err;
  374. r_received = p_bytes;
  375. return OK;
  376. }
  377. int StreamPeerOpenSSL::get_available_bytes() const {
  378. ERR_FAIL_COND_V(!connected, 0);
  379. return SSL_pending(ssl);
  380. }
  381. StreamPeerOpenSSL::StreamPeerOpenSSL() {
  382. ctx = NULL;
  383. ssl = NULL;
  384. bio = NULL;
  385. connected = false;
  386. use_blocking = true; //might be improved int the future, but for now it always blocks
  387. max_cert_chain_depth = 9;
  388. flags = 0;
  389. }
  390. void StreamPeerOpenSSL::disconnect_from_stream() {
  391. if (!connected)
  392. return;
  393. SSL_shutdown(ssl);
  394. SSL_free(ssl);
  395. SSL_CTX_free(ctx);
  396. base = Ref<StreamPeer>();
  397. connected = false;
  398. validate_certs = false;
  399. validate_hostname = false;
  400. status = STATUS_DISCONNECTED;
  401. }
  402. StreamPeerOpenSSL::Status StreamPeerOpenSSL::get_status() const {
  403. return status;
  404. }
  405. StreamPeerOpenSSL::~StreamPeerOpenSSL() {
  406. disconnect_from_stream();
  407. }
  408. StreamPeerSSL *StreamPeerOpenSSL::_create_func() {
  409. return memnew(StreamPeerOpenSSL);
  410. }
  411. Vector<X509 *> StreamPeerOpenSSL::certs;
  412. void StreamPeerOpenSSL::_load_certs(const PoolByteArray &p_array) {
  413. PoolByteArray::Read r = p_array.read();
  414. BIO *mem = BIO_new(BIO_s_mem());
  415. BIO_puts(mem, (const char *)r.ptr());
  416. while (true) {
  417. X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
  418. if (!cert)
  419. break;
  420. certs.push_back(cert);
  421. }
  422. BIO_free(mem);
  423. }
  424. void StreamPeerOpenSSL::initialize_ssl() {
  425. available = true;
  426. load_certs_func = _load_certs;
  427. _create = _create_func;
  428. CRYPTO_malloc_init(); // Initialize malloc, free, etc for OpenSSL's use
  429. SSL_library_init(); // Initialize OpenSSL's SSL libraries
  430. SSL_load_error_strings(); // Load SSL error strings
  431. ERR_load_BIO_strings(); // Load BIO error strings
  432. OpenSSL_add_all_algorithms(); // Load all available encryption algorithms
  433. String certs_path = GLOBAL_DEF("network/ssl/certificates", "");
  434. ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt"));
  435. if (certs_path != "") {
  436. FileAccess *f = FileAccess::open(certs_path, FileAccess::READ);
  437. if (f) {
  438. PoolByteArray arr;
  439. int flen = f->get_len();
  440. arr.resize(flen + 1);
  441. {
  442. PoolByteArray::Write w = arr.write();
  443. f->get_buffer(w.ptr(), flen);
  444. w[flen] = 0; //end f string
  445. }
  446. memdelete(f);
  447. _load_certs(arr);
  448. print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size()));
  449. }
  450. }
  451. String config_path = GLOBAL_DEF("network/ssl/config", "");
  452. ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/config", PropertyInfo(Variant::STRING, "network/ssl/config", PROPERTY_HINT_FILE, "*.cnf"));
  453. if (config_path != "") {
  454. Vector<uint8_t> data = FileAccess::get_file_as_array(config_path);
  455. if (data.size()) {
  456. data.push_back(0);
  457. BIO *mem = BIO_new(BIO_s_mem());
  458. BIO_puts(mem, (const char *)data.ptr());
  459. while (true) {
  460. X509 *cert = PEM_read_bio_X509(mem, NULL, 0, NULL);
  461. if (!cert)
  462. break;
  463. certs.push_back(cert);
  464. }
  465. BIO_free(mem);
  466. }
  467. print_line("Loaded certs from '" + certs_path + "': " + itos(certs.size()));
  468. }
  469. }
  470. void StreamPeerOpenSSL::finalize_ssl() {
  471. for (int i = 0; i < certs.size(); i++) {
  472. X509_free(certs[i]);
  473. }
  474. certs.clear();
  475. }