stream_peer_openssl.cpp 14 KB

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