stream_peer_mbed_tls.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*************************************************************************/
  2. /* stream_peer_mbed_tls.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_mbed_tls.h"
  31. #include "core/io/stream_peer_tcp.h"
  32. #include "core/os/file_access.h"
  33. #include <mbedtls/platform_util.h>
  34. static void my_debug(void *ctx, int level,
  35. const char *file, int line,
  36. const char *str) {
  37. printf("%s:%04d: %s", file, line, str);
  38. fflush(stdout);
  39. }
  40. void _print_error(int ret) {
  41. printf("mbedtls error: returned -0x%x\n\n", -ret);
  42. fflush(stdout);
  43. }
  44. int StreamPeerMbedTLS::bio_send(void *ctx, const unsigned char *buf, size_t len) {
  45. if (buf == NULL || len <= 0) return 0;
  46. StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx;
  47. ERR_FAIL_COND_V(sp == NULL, 0);
  48. int sent;
  49. Error err = sp->base->put_partial_data((const uint8_t *)buf, len, sent);
  50. if (err != OK) {
  51. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  52. }
  53. if (sent == 0) {
  54. return MBEDTLS_ERR_SSL_WANT_WRITE;
  55. }
  56. return sent;
  57. }
  58. int StreamPeerMbedTLS::bio_recv(void *ctx, unsigned char *buf, size_t len) {
  59. if (buf == NULL || len <= 0) return 0;
  60. StreamPeerMbedTLS *sp = (StreamPeerMbedTLS *)ctx;
  61. ERR_FAIL_COND_V(sp == NULL, 0);
  62. int got;
  63. Error err = sp->base->get_partial_data((uint8_t *)buf, len, got);
  64. if (err != OK) {
  65. return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
  66. }
  67. if (got == 0) {
  68. return MBEDTLS_ERR_SSL_WANT_READ;
  69. }
  70. return got;
  71. }
  72. void StreamPeerMbedTLS::_cleanup() {
  73. mbedtls_ssl_free(&ssl);
  74. mbedtls_ssl_config_free(&conf);
  75. mbedtls_ctr_drbg_free(&ctr_drbg);
  76. mbedtls_entropy_free(&entropy);
  77. base = Ref<StreamPeer>();
  78. status = STATUS_DISCONNECTED;
  79. }
  80. Error StreamPeerMbedTLS::_do_handshake() {
  81. int ret = 0;
  82. while ((ret = mbedtls_ssl_handshake(&ssl)) != 0) {
  83. if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  84. // An error occurred.
  85. ERR_PRINTS("TLS handshake error: " + itos(ret));
  86. _print_error(ret);
  87. disconnect_from_stream();
  88. status = STATUS_ERROR;
  89. return FAILED;
  90. }
  91. // Handshake is still in progress.
  92. if (!blocking_handshake) {
  93. // Will retry via poll later
  94. return OK;
  95. }
  96. }
  97. status = STATUS_CONNECTED;
  98. return OK;
  99. }
  100. Error StreamPeerMbedTLS::connect_to_stream(Ref<StreamPeer> p_base, bool p_validate_certs, const String &p_for_hostname) {
  101. base = p_base;
  102. int ret = 0;
  103. int authmode = p_validate_certs ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_NONE;
  104. mbedtls_ssl_init(&ssl);
  105. mbedtls_ssl_config_init(&conf);
  106. mbedtls_ctr_drbg_init(&ctr_drbg);
  107. mbedtls_entropy_init(&entropy);
  108. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);
  109. if (ret != 0) {
  110. ERR_PRINTS(" failed\n ! mbedtls_ctr_drbg_seed returned an error" + itos(ret));
  111. _cleanup();
  112. return FAILED;
  113. }
  114. mbedtls_ssl_config_defaults(&conf,
  115. MBEDTLS_SSL_IS_CLIENT,
  116. MBEDTLS_SSL_TRANSPORT_STREAM,
  117. MBEDTLS_SSL_PRESET_DEFAULT);
  118. mbedtls_ssl_conf_authmode(&conf, authmode);
  119. mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
  120. mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
  121. mbedtls_ssl_conf_dbg(&conf, my_debug, stdout);
  122. mbedtls_ssl_setup(&ssl, &conf);
  123. mbedtls_ssl_set_hostname(&ssl, p_for_hostname.utf8().get_data());
  124. mbedtls_ssl_set_bio(&ssl, this, bio_send, bio_recv, NULL);
  125. status = STATUS_HANDSHAKING;
  126. if ((ret = _do_handshake()) != OK) {
  127. status = STATUS_ERROR_HOSTNAME_MISMATCH;
  128. return FAILED;
  129. }
  130. return OK;
  131. }
  132. Error StreamPeerMbedTLS::accept_stream(Ref<StreamPeer> p_base) {
  133. return OK;
  134. }
  135. Error StreamPeerMbedTLS::put_data(const uint8_t *p_data, int p_bytes) {
  136. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
  137. Error err;
  138. int sent = 0;
  139. while (p_bytes > 0) {
  140. err = put_partial_data(p_data, p_bytes, sent);
  141. if (err != OK) {
  142. return err;
  143. }
  144. p_data += sent;
  145. p_bytes -= sent;
  146. }
  147. return OK;
  148. }
  149. Error StreamPeerMbedTLS::put_partial_data(const uint8_t *p_data, int p_bytes, int &r_sent) {
  150. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
  151. r_sent = 0;
  152. if (p_bytes == 0)
  153. return OK;
  154. int ret = mbedtls_ssl_write(&ssl, p_data, p_bytes);
  155. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  156. // Non blocking IO
  157. ret = 0;
  158. } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  159. // Clean close
  160. disconnect_from_stream();
  161. return ERR_FILE_EOF;
  162. } else if (ret <= 0) {
  163. _print_error(ret);
  164. disconnect_from_stream();
  165. return ERR_CONNECTION_ERROR;
  166. }
  167. r_sent = ret;
  168. return OK;
  169. }
  170. Error StreamPeerMbedTLS::get_data(uint8_t *p_buffer, int p_bytes) {
  171. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
  172. Error err;
  173. int got = 0;
  174. while (p_bytes > 0) {
  175. err = get_partial_data(p_buffer, p_bytes, got);
  176. if (err != OK) {
  177. return err;
  178. }
  179. p_buffer += got;
  180. p_bytes -= got;
  181. }
  182. return OK;
  183. }
  184. Error StreamPeerMbedTLS::get_partial_data(uint8_t *p_buffer, int p_bytes, int &r_received) {
  185. ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_UNCONFIGURED);
  186. r_received = 0;
  187. int ret = mbedtls_ssl_read(&ssl, p_buffer, p_bytes);
  188. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  189. ret = 0; // non blocking io
  190. } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  191. // Clean close
  192. disconnect_from_stream();
  193. return ERR_FILE_EOF;
  194. } else if (ret <= 0) {
  195. _print_error(ret);
  196. disconnect_from_stream();
  197. return ERR_CONNECTION_ERROR;
  198. }
  199. r_received = ret;
  200. return OK;
  201. }
  202. void StreamPeerMbedTLS::poll() {
  203. ERR_FAIL_COND(status != STATUS_CONNECTED && status != STATUS_HANDSHAKING);
  204. ERR_FAIL_COND(!base.is_valid());
  205. if (status == STATUS_HANDSHAKING) {
  206. _do_handshake();
  207. return;
  208. }
  209. // We could pass NULL as second parameter, but some behaviour sanitizers doesn't seem to like that.
  210. // Passing a 1 byte buffer to workaround it.
  211. uint8_t byte;
  212. int ret = mbedtls_ssl_read(&ssl, &byte, 0);
  213. if (ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  214. // Nothing to read/write (non blocking IO)
  215. } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  216. // Clean close (disconnect)
  217. disconnect_from_stream();
  218. return;
  219. } else if (ret < 0) {
  220. _print_error(ret);
  221. disconnect_from_stream();
  222. return;
  223. }
  224. Ref<StreamPeerTCP> tcp = base;
  225. if (tcp.is_valid() && tcp->get_status() != StreamPeerTCP::STATUS_CONNECTED) {
  226. disconnect_from_stream();
  227. return;
  228. }
  229. }
  230. int StreamPeerMbedTLS::get_available_bytes() const {
  231. ERR_FAIL_COND_V(status != STATUS_CONNECTED, 0);
  232. return mbedtls_ssl_get_bytes_avail(&ssl);
  233. }
  234. StreamPeerMbedTLS::StreamPeerMbedTLS() {
  235. status = STATUS_DISCONNECTED;
  236. }
  237. StreamPeerMbedTLS::~StreamPeerMbedTLS() {
  238. disconnect_from_stream();
  239. }
  240. void StreamPeerMbedTLS::disconnect_from_stream() {
  241. if (status != STATUS_CONNECTED && status != STATUS_HANDSHAKING)
  242. return;
  243. Ref<StreamPeerTCP> tcp = base;
  244. if (tcp.is_valid() && tcp->get_status() == StreamPeerTCP::STATUS_CONNECTED) {
  245. // We are still connected on the socket, try to send close notify.
  246. mbedtls_ssl_close_notify(&ssl);
  247. }
  248. _cleanup();
  249. }
  250. StreamPeerMbedTLS::Status StreamPeerMbedTLS::get_status() const {
  251. return status;
  252. }
  253. StreamPeerSSL *StreamPeerMbedTLS::_create_func() {
  254. return memnew(StreamPeerMbedTLS);
  255. }
  256. mbedtls_x509_crt StreamPeerMbedTLS::cacert;
  257. void StreamPeerMbedTLS::_load_certs(const PoolByteArray &p_array) {
  258. int arr_len = p_array.size();
  259. PoolByteArray::Read r = p_array.read();
  260. int err = mbedtls_x509_crt_parse(&cacert, &r[0], arr_len);
  261. if (err != 0) {
  262. WARN_PRINTS("Error parsing some certificates: " + itos(err));
  263. }
  264. }
  265. void StreamPeerMbedTLS::initialize_ssl() {
  266. _create = _create_func;
  267. load_certs_func = _load_certs;
  268. mbedtls_x509_crt_init(&cacert);
  269. #ifdef DEBUG_ENABLED
  270. mbedtls_debug_set_threshold(1);
  271. #endif
  272. available = true;
  273. }
  274. void StreamPeerMbedTLS::finalize_ssl() {
  275. available = false;
  276. _create = NULL;
  277. load_certs_func = NULL;
  278. mbedtls_x509_crt_free(&cacert);
  279. }