security.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. #include "../libnetdata.h"
  2. #ifdef ENABLE_HTTPS
  3. SSL_CTX *netdata_ssl_exporting_ctx =NULL;
  4. SSL_CTX *netdata_ssl_streaming_sender_ctx =NULL;
  5. SSL_CTX *netdata_ssl_web_server_ctx =NULL;
  6. const char *netdata_ssl_security_key =NULL;
  7. const char *netdata_ssl_security_cert =NULL;
  8. const char *tls_version=NULL;
  9. const char *tls_ciphers=NULL;
  10. bool netdata_ssl_validate_certificate = true;
  11. bool netdata_ssl_validate_certificate_sender = true;
  12. static SOCKET_PEERS netdata_ssl_peers(NETDATA_SSL *ssl) {
  13. int sock_fd;
  14. if(unlikely(!ssl->conn))
  15. sock_fd = -1;
  16. else
  17. sock_fd = SSL_get_rfd(ssl->conn);
  18. return socket_peers(sock_fd);
  19. }
  20. static void netdata_ssl_log_error_queue(const char *call, NETDATA_SSL *ssl, unsigned long err) {
  21. nd_log_limit_static_thread_var(erl, 1, 0);
  22. if(err == SSL_ERROR_NONE)
  23. err = ERR_get_error();
  24. if(err == SSL_ERROR_NONE)
  25. return;
  26. do {
  27. char *code;
  28. switch (err) {
  29. case SSL_ERROR_SSL:
  30. code = "SSL_ERROR_SSL";
  31. ssl->state = NETDATA_SSL_STATE_FAILED;
  32. break;
  33. case SSL_ERROR_WANT_READ:
  34. code = "SSL_ERROR_WANT_READ";
  35. break;
  36. case SSL_ERROR_WANT_WRITE:
  37. code = "SSL_ERROR_WANT_WRITE";
  38. break;
  39. case SSL_ERROR_WANT_X509_LOOKUP:
  40. code = "SSL_ERROR_WANT_X509_LOOKUP";
  41. break;
  42. case SSL_ERROR_SYSCALL:
  43. code = "SSL_ERROR_SYSCALL";
  44. ssl->state = NETDATA_SSL_STATE_FAILED;
  45. break;
  46. case SSL_ERROR_ZERO_RETURN:
  47. code = "SSL_ERROR_ZERO_RETURN";
  48. break;
  49. case SSL_ERROR_WANT_CONNECT:
  50. code = "SSL_ERROR_WANT_CONNECT";
  51. break;
  52. case SSL_ERROR_WANT_ACCEPT:
  53. code = "SSL_ERROR_WANT_ACCEPT";
  54. break;
  55. #ifdef SSL_ERROR_WANT_ASYNC
  56. case SSL_ERROR_WANT_ASYNC:
  57. code = "SSL_ERROR_WANT_ASYNC";
  58. break;
  59. #endif
  60. #ifdef SSL_ERROR_WANT_ASYNC_JOB
  61. case SSL_ERROR_WANT_ASYNC_JOB:
  62. code = "SSL_ERROR_WANT_ASYNC_JOB";
  63. break;
  64. #endif
  65. #ifdef SSL_ERROR_WANT_CLIENT_HELLO_CB
  66. case SSL_ERROR_WANT_CLIENT_HELLO_CB:
  67. code = "SSL_ERROR_WANT_CLIENT_HELLO_CB";
  68. break;
  69. #endif
  70. #ifdef SSL_ERROR_WANT_RETRY_VERIFY
  71. case SSL_ERROR_WANT_RETRY_VERIFY:
  72. code = "SSL_ERROR_WANT_RETRY_VERIFY";
  73. break;
  74. #endif
  75. default:
  76. code = "SSL_ERROR_UNKNOWN";
  77. break;
  78. }
  79. char str[1024 + 1];
  80. ERR_error_string_n(err, str, 1024);
  81. str[1024] = '\0';
  82. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  83. nd_log_limit(&erl, NDLS_DAEMON, NDLP_ERR,
  84. "SSL: %s() on socket local [[%s]:%d] <-> remote [[%s]:%d], returned error %lu (%s): %s",
  85. call, peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, err, code, str);
  86. } while((err = ERR_get_error()));
  87. }
  88. bool netdata_ssl_open_ext(NETDATA_SSL *ssl, SSL_CTX *ctx, int fd, const unsigned char *alpn_protos, unsigned int alpn_protos_len) {
  89. errno = 0;
  90. ssl->ssl_errno = 0;
  91. if(ssl->conn) {
  92. if(!ctx || SSL_get_SSL_CTX(ssl->conn) != ctx) {
  93. SSL_free(ssl->conn);
  94. ssl->conn = NULL;
  95. }
  96. else if (SSL_clear(ssl->conn) == 0) {
  97. netdata_ssl_log_error_queue("SSL_clear", ssl, SSL_ERROR_NONE);
  98. SSL_free(ssl->conn);
  99. ssl->conn = NULL;
  100. }
  101. }
  102. if(!ssl->conn) {
  103. if(!ctx) {
  104. internal_error(true, "SSL: not CTX given");
  105. ssl->state = NETDATA_SSL_STATE_FAILED;
  106. return false;
  107. }
  108. ssl->conn = SSL_new(ctx);
  109. if (!ssl->conn) {
  110. netdata_ssl_log_error_queue("SSL_new", ssl, SSL_ERROR_NONE);
  111. ssl->state = NETDATA_SSL_STATE_FAILED;
  112. return false;
  113. }
  114. if (alpn_protos && alpn_protos_len > 0)
  115. SSL_set_alpn_protos(ssl->conn, alpn_protos, alpn_protos_len);
  116. }
  117. if(SSL_set_fd(ssl->conn, fd) != 1) {
  118. netdata_ssl_log_error_queue("SSL_set_fd", ssl, SSL_ERROR_NONE);
  119. ssl->state = NETDATA_SSL_STATE_FAILED;
  120. return false;
  121. }
  122. ssl->state = NETDATA_SSL_STATE_INIT;
  123. ERR_clear_error();
  124. return true;
  125. }
  126. bool netdata_ssl_open(NETDATA_SSL *ssl, SSL_CTX *ctx, int fd) {
  127. return netdata_ssl_open_ext(ssl, ctx, fd, NULL, 0);
  128. }
  129. void netdata_ssl_close(NETDATA_SSL *ssl) {
  130. errno = 0;
  131. ssl->ssl_errno = 0;
  132. if(ssl->conn) {
  133. if(SSL_connection(ssl)) {
  134. int ret = SSL_shutdown(ssl->conn);
  135. if(ret == 0)
  136. SSL_shutdown(ssl->conn);
  137. }
  138. SSL_free(ssl->conn);
  139. ERR_clear_error();
  140. }
  141. *ssl = NETDATA_SSL_UNSET_CONNECTION;
  142. }
  143. static inline bool is_handshake_complete(NETDATA_SSL *ssl, const char *op) {
  144. nd_log_limit_static_thread_var(erl, 1, 0);
  145. if(unlikely(!ssl->conn)) {
  146. internal_error(true, "SSL: trying to %s on a NULL connection", op);
  147. return false;
  148. }
  149. switch(ssl->state) {
  150. case NETDATA_SSL_STATE_NOT_SSL: {
  151. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  152. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  153. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on non-SSL connection",
  154. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  155. return false;
  156. }
  157. case NETDATA_SSL_STATE_INIT: {
  158. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  159. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  160. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on an incomplete connection",
  161. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  162. return false;
  163. }
  164. case NETDATA_SSL_STATE_FAILED: {
  165. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  166. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  167. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on a failed connection",
  168. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  169. return false;
  170. }
  171. case NETDATA_SSL_STATE_COMPLETE: {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. /*
  178. * netdata_ssl_read() should return the same as read():
  179. *
  180. * Positive value: The read() function succeeded and read some bytes. The exact number of bytes read is returned.
  181. *
  182. * Zero: For files and sockets, a return value of zero signifies end-of-file (EOF), meaning no more data is available
  183. * for reading. For sockets, this usually means the other side has closed the connection.
  184. *
  185. * -1: An error occurred. The specific error can be found by examining the errno variable.
  186. * EAGAIN or EWOULDBLOCK: The file descriptor is in non-blocking mode, and the read operation would block.
  187. * (These are often the same value, but can be different on some systems.)
  188. */
  189. ssize_t netdata_ssl_read(NETDATA_SSL *ssl, void *buf, size_t num) {
  190. errno = 0;
  191. ssl->ssl_errno = 0;
  192. if(unlikely(!is_handshake_complete(ssl, "read")))
  193. return -1;
  194. int bytes = SSL_read(ssl->conn, buf, (int)num);
  195. if(unlikely(bytes <= 0)) {
  196. int err = SSL_get_error(ssl->conn, bytes);
  197. if (err == SSL_ERROR_ZERO_RETURN) {
  198. ssl->ssl_errno = err;
  199. return 0;
  200. }
  201. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
  202. ssl->ssl_errno = err;
  203. errno = EWOULDBLOCK;
  204. }
  205. else
  206. netdata_ssl_log_error_queue("SSL_read", ssl, err);
  207. bytes = -1; // according to read() or recv()
  208. }
  209. return bytes;
  210. }
  211. /*
  212. * netdata_ssl_write() should return the same as write():
  213. *
  214. * Positive value: The write() function succeeded and wrote some bytes. The exact number of bytes written is returned.
  215. *
  216. * Zero: It's technically possible for write() to return zero, indicating that zero bytes were written. However, for a
  217. * socket, this generally does not happen unless the size of the data to be written is zero.
  218. *
  219. * -1: An error occurred. The specific error can be found by examining the errno variable.
  220. * EAGAIN or EWOULDBLOCK: The file descriptor is in non-blocking mode, and the write operation would block.
  221. * (These are often the same value, but can be different on some systems.)
  222. */
  223. ssize_t netdata_ssl_write(NETDATA_SSL *ssl, const void *buf, size_t num) {
  224. errno = 0;
  225. ssl->ssl_errno = 0;
  226. if(unlikely(!is_handshake_complete(ssl, "write")))
  227. return -1;
  228. int bytes = SSL_write(ssl->conn, (uint8_t *)buf, (int)num);
  229. if(unlikely(bytes <= 0)) {
  230. int err = SSL_get_error(ssl->conn, bytes);
  231. if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
  232. ssl->ssl_errno = err;
  233. errno = EWOULDBLOCK;
  234. }
  235. else
  236. netdata_ssl_log_error_queue("SSL_write", ssl, err);
  237. bytes = -1; // according to write() or send()
  238. }
  239. return bytes;
  240. }
  241. static inline bool is_handshake_initialized(NETDATA_SSL *ssl, const char *op) {
  242. nd_log_limit_static_thread_var(erl, 1, 0);
  243. if(unlikely(!ssl->conn)) {
  244. internal_error(true, "SSL: trying to %s on a NULL connection", op);
  245. return false;
  246. }
  247. switch(ssl->state) {
  248. case NETDATA_SSL_STATE_NOT_SSL: {
  249. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  250. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  251. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on non-SSL connection",
  252. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  253. return false;
  254. }
  255. case NETDATA_SSL_STATE_INIT: {
  256. return true;
  257. }
  258. case NETDATA_SSL_STATE_FAILED: {
  259. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  260. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  261. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on a failed connection",
  262. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  263. return false;
  264. }
  265. case NETDATA_SSL_STATE_COMPLETE: {
  266. SOCKET_PEERS peers = netdata_ssl_peers(ssl);
  267. nd_log_limit(&erl, NDLS_DAEMON, NDLP_WARNING,
  268. "SSL: on socket local [[%s]:%d] <-> remote [[%s]:%d], attempt to %s on an complete connection",
  269. peers.local.ip, peers.local.port, peers.peer.ip, peers.peer.port, op);
  270. return false;
  271. }
  272. }
  273. return false;
  274. }
  275. #define WANT_READ_WRITE_TIMEOUT_MS 10
  276. static inline bool want_read_write_should_retry(NETDATA_SSL *ssl, int err) {
  277. int ssl_errno = SSL_get_error(ssl->conn, err);
  278. if(ssl_errno == SSL_ERROR_WANT_READ || ssl_errno == SSL_ERROR_WANT_WRITE) {
  279. struct pollfd pfds[1] = { [0] = {
  280. .fd = SSL_get_rfd(ssl->conn),
  281. .events = (short)(((ssl_errno == SSL_ERROR_WANT_READ ) ? POLLIN : 0) |
  282. ((ssl_errno == SSL_ERROR_WANT_WRITE) ? POLLOUT : 0)),
  283. }};
  284. if(poll(pfds, 1, WANT_READ_WRITE_TIMEOUT_MS) <= 0)
  285. return false; // timeout (0) or error (<0)
  286. return true; // we have activity, so we should retry
  287. }
  288. return false; // an unknown error
  289. }
  290. bool netdata_ssl_connect(NETDATA_SSL *ssl) {
  291. errno = 0;
  292. ssl->ssl_errno = 0;
  293. if(unlikely(!is_handshake_initialized(ssl, "connect")))
  294. return false;
  295. SSL_set_connect_state(ssl->conn);
  296. int err;
  297. while ((err = SSL_connect(ssl->conn)) != 1) {
  298. if(!want_read_write_should_retry(ssl, err))
  299. break;
  300. }
  301. if (err != 1) {
  302. err = SSL_get_error(ssl->conn, err);
  303. netdata_ssl_log_error_queue("SSL_connect", ssl, err);
  304. ssl->state = NETDATA_SSL_STATE_FAILED;
  305. return false;
  306. }
  307. ssl->state = NETDATA_SSL_STATE_COMPLETE;
  308. return true;
  309. }
  310. bool netdata_ssl_accept(NETDATA_SSL *ssl) {
  311. errno = 0;
  312. ssl->ssl_errno = 0;
  313. if(unlikely(!is_handshake_initialized(ssl, "accept")))
  314. return false;
  315. SSL_set_accept_state(ssl->conn);
  316. int err;
  317. while ((err = SSL_accept(ssl->conn)) != 1) {
  318. if(!want_read_write_should_retry(ssl, err))
  319. break;
  320. }
  321. if (err != 1) {
  322. err = SSL_get_error(ssl->conn, err);
  323. netdata_ssl_log_error_queue("SSL_accept", ssl, err);
  324. ssl->state = NETDATA_SSL_STATE_FAILED;
  325. return false;
  326. }
  327. ssl->state = NETDATA_SSL_STATE_COMPLETE;
  328. return true;
  329. }
  330. /**
  331. * Info Callback
  332. *
  333. * Function used as callback for the OpenSSL Library
  334. *
  335. * @param ssl a pointer to the SSL structure of the client
  336. * @param where the variable with the flags set.
  337. * @param ret the return of the caller
  338. */
  339. static void netdata_ssl_info_callback(const SSL *ssl, int where, int ret __maybe_unused) {
  340. (void)ssl;
  341. if (where & SSL_CB_ALERT) {
  342. netdata_log_debug(D_WEB_CLIENT,"SSL INFO CALLBACK %s %s", SSL_alert_type_string(ret), SSL_alert_desc_string_long(ret));
  343. }
  344. }
  345. /**
  346. * OpenSSL Library
  347. *
  348. * Starts the openssl library for the Netdata.
  349. */
  350. void netdata_ssl_initialize_openssl() {
  351. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  352. # if (SSLEAY_VERSION_NUMBER >= OPENSSL_VERSION_097)
  353. OPENSSL_config(NULL);
  354. # endif
  355. SSL_load_error_strings();
  356. SSL_library_init();
  357. #else
  358. if (OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL) != 1) {
  359. netdata_log_error("SSL library cannot be initialized.");
  360. }
  361. #endif
  362. }
  363. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_110
  364. /**
  365. * TLS version
  366. *
  367. * Returns the TLS version depending of the user input.
  368. *
  369. * @param lversion is the user input.
  370. *
  371. * @return it returns the version number.
  372. */
  373. static int netdata_ssl_select_tls_version(const char *lversion) {
  374. if (!strcmp(lversion, "1") || !strcmp(lversion, "1.0"))
  375. return TLS1_VERSION;
  376. else if (!strcmp(lversion, "1.1"))
  377. return TLS1_1_VERSION;
  378. else if (!strcmp(lversion, "1.2"))
  379. return TLS1_2_VERSION;
  380. #if defined(TLS1_3_VERSION)
  381. else if (!strcmp(lversion, "1.3"))
  382. return TLS1_3_VERSION;
  383. #endif
  384. #if defined(TLS_MAX_VERSION)
  385. return TLS_MAX_VERSION;
  386. #else
  387. return TLS1_2_VERSION;
  388. #endif
  389. }
  390. #endif
  391. /**
  392. * Initialize Openssl Client
  393. *
  394. * Starts the client context with TLS 1.2.
  395. *
  396. * @return It returns the context on success or NULL otherwise
  397. */
  398. SSL_CTX * netdata_ssl_create_client_ctx(unsigned long mode) {
  399. SSL_CTX *ctx;
  400. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  401. ctx = SSL_CTX_new(SSLv23_client_method());
  402. #else
  403. ctx = SSL_CTX_new(TLS_client_method());
  404. #endif
  405. if(ctx) {
  406. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  407. SSL_CTX_set_options (ctx,SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION);
  408. #else
  409. SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
  410. # if defined(TLS_MAX_VERSION)
  411. SSL_CTX_set_max_proto_version(ctx, TLS_MAX_VERSION);
  412. # elif defined(TLS1_3_VERSION)
  413. SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
  414. # elif defined(TLS1_2_VERSION)
  415. SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
  416. # endif
  417. #endif
  418. }
  419. if(mode)
  420. SSL_CTX_set_mode(ctx, mode);
  421. return ctx;
  422. }
  423. /**
  424. * Initialize OpenSSL server
  425. *
  426. * Starts the server context with TLS 1.2 and load the certificate.
  427. *
  428. * @return It returns the context on success or NULL otherwise
  429. */
  430. static SSL_CTX * netdata_ssl_create_server_ctx(unsigned long mode) {
  431. SSL_CTX *ctx;
  432. char lerror[512];
  433. static int netdata_id_context = 1;
  434. //TO DO: Confirm the necessity to check return for other OPENSSL function
  435. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  436. ctx = SSL_CTX_new(SSLv23_server_method());
  437. if (!ctx) {
  438. netdata_log_error("Cannot create a new SSL context, netdata won't encrypt communication");
  439. return NULL;
  440. }
  441. SSL_CTX_use_certificate_file(ctx, netdata_ssl_security_cert, SSL_FILETYPE_PEM);
  442. #else
  443. ctx = SSL_CTX_new(TLS_server_method());
  444. if (!ctx) {
  445. netdata_log_error("Cannot create a new SSL context, netdata won't encrypt communication");
  446. return NULL;
  447. }
  448. SSL_CTX_use_certificate_chain_file(ctx, netdata_ssl_security_cert);
  449. #endif
  450. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  451. SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_COMPRESSION);
  452. #else
  453. SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
  454. SSL_CTX_set_max_proto_version(ctx, netdata_ssl_select_tls_version(tls_version));
  455. if(tls_ciphers && strcmp(tls_ciphers, "none") != 0) {
  456. if (!SSL_CTX_set_cipher_list(ctx, tls_ciphers)) {
  457. netdata_log_error("SSL error. cannot set the cipher list");
  458. }
  459. }
  460. #endif
  461. SSL_CTX_use_PrivateKey_file(ctx, netdata_ssl_security_key,SSL_FILETYPE_PEM);
  462. if (!SSL_CTX_check_private_key(ctx)) {
  463. ERR_error_string_n(ERR_get_error(),lerror,sizeof(lerror));
  464. netdata_log_error("SSL cannot check the private key: %s",lerror);
  465. SSL_CTX_free(ctx);
  466. return NULL;
  467. }
  468. SSL_CTX_set_session_id_context(ctx,(void*)&netdata_id_context,(unsigned int)sizeof(netdata_id_context));
  469. SSL_CTX_set_info_callback(ctx, netdata_ssl_info_callback);
  470. #if (OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_095)
  471. SSL_CTX_set_verify_depth(ctx,1);
  472. #endif
  473. netdata_log_debug(D_WEB_CLIENT,"SSL GLOBAL CONTEXT STARTED\n");
  474. SSL_CTX_set_mode(ctx, mode);
  475. return ctx;
  476. }
  477. /**
  478. * Start SSL
  479. *
  480. * Call the correct function to start the SSL context.
  481. *
  482. * @param selector informs the context that must be initialized, the following list has the valid values:
  483. * NETDATA_SSL_CONTEXT_SERVER - the server context
  484. * NETDATA_SSL_CONTEXT_STREAMING - Starts the streaming context.
  485. * NETDATA_SSL_CONTEXT_EXPORTING - Starts the OpenTSDB context
  486. */
  487. void netdata_ssl_initialize_ctx(int selector) {
  488. static SPINLOCK sp = NETDATA_SPINLOCK_INITIALIZER;
  489. spinlock_lock(&sp);
  490. switch (selector) {
  491. case NETDATA_SSL_WEB_SERVER_CTX: {
  492. if(!netdata_ssl_web_server_ctx) {
  493. struct stat statbuf;
  494. if (stat(netdata_ssl_security_key, &statbuf) || stat(netdata_ssl_security_cert, &statbuf))
  495. netdata_log_info("To use encryption it is necessary to set \"ssl certificate\" and \"ssl key\" in [web] !\n");
  496. else {
  497. netdata_ssl_web_server_ctx = netdata_ssl_create_server_ctx(
  498. SSL_MODE_ENABLE_PARTIAL_WRITE |
  499. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
  500. // SSL_MODE_AUTO_RETRY |
  501. 0);
  502. if(netdata_ssl_web_server_ctx && !netdata_ssl_validate_certificate)
  503. SSL_CTX_set_verify(netdata_ssl_web_server_ctx, SSL_VERIFY_NONE, NULL);
  504. }
  505. }
  506. break;
  507. }
  508. case NETDATA_SSL_STREAMING_SENDER_CTX: {
  509. if(!netdata_ssl_streaming_sender_ctx) {
  510. //This is necessary for the stream, because it is working sometimes with nonblock socket.
  511. //It returns the bitmask after to change, there is not any description of errors in the documentation
  512. netdata_ssl_streaming_sender_ctx = netdata_ssl_create_client_ctx(
  513. SSL_MODE_ENABLE_PARTIAL_WRITE |
  514. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
  515. // SSL_MODE_AUTO_RETRY |
  516. 0
  517. );
  518. if(netdata_ssl_streaming_sender_ctx && !netdata_ssl_validate_certificate_sender)
  519. SSL_CTX_set_verify(netdata_ssl_streaming_sender_ctx, SSL_VERIFY_NONE, NULL);
  520. }
  521. break;
  522. }
  523. case NETDATA_SSL_EXPORTING_CTX: {
  524. if(!netdata_ssl_exporting_ctx) {
  525. netdata_ssl_exporting_ctx = netdata_ssl_create_client_ctx(0);
  526. if(netdata_ssl_exporting_ctx && !netdata_ssl_validate_certificate)
  527. SSL_CTX_set_verify(netdata_ssl_exporting_ctx, SSL_VERIFY_NONE, NULL);
  528. }
  529. break;
  530. }
  531. }
  532. spinlock_unlock(&sp);
  533. }
  534. /**
  535. * Clean Open SSL
  536. *
  537. * Clean all the allocated contexts from netdata.
  538. */
  539. void netdata_ssl_cleanup()
  540. {
  541. if (netdata_ssl_web_server_ctx) {
  542. SSL_CTX_free(netdata_ssl_web_server_ctx);
  543. netdata_ssl_web_server_ctx = NULL;
  544. }
  545. if (netdata_ssl_streaming_sender_ctx) {
  546. SSL_CTX_free(netdata_ssl_streaming_sender_ctx);
  547. netdata_ssl_streaming_sender_ctx = NULL;
  548. }
  549. if (netdata_ssl_exporting_ctx) {
  550. SSL_CTX_free(netdata_ssl_exporting_ctx);
  551. netdata_ssl_exporting_ctx = NULL;
  552. }
  553. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  554. ERR_free_strings();
  555. #endif
  556. }
  557. /**
  558. * Test Certificate
  559. *
  560. * Check the certificate of Netdata parent
  561. *
  562. * @param ssl is the connection structure
  563. *
  564. * @return It returns 0 on success and -1 otherwise
  565. */
  566. int security_test_certificate(SSL *ssl) {
  567. X509* cert = SSL_get_peer_certificate(ssl);
  568. int ret;
  569. long status;
  570. if (!cert) {
  571. return -1;
  572. }
  573. status = SSL_get_verify_result(ssl);
  574. if((X509_V_OK != status))
  575. {
  576. char error[512];
  577. ERR_error_string_n(ERR_get_error(), error, sizeof(error));
  578. netdata_log_error("SSL RFC4158 check: We have a invalid certificate, the tests result with %ld and message %s", status, error);
  579. ret = -1;
  580. } else {
  581. ret = 0;
  582. }
  583. return ret;
  584. }
  585. /**
  586. * Location for context
  587. *
  588. * Case the user give us a directory with the certificates available and
  589. * the Netdata parent certificate, we use this function to validate the certificate.
  590. *
  591. * @param ctx the context where the path will be set.
  592. * @param file the file with Netdata parent certificate.
  593. * @param path the directory where the certificates are stored.
  594. *
  595. * @return It returns 0 on success and -1 otherwise.
  596. */
  597. int ssl_security_location_for_context(SSL_CTX *ctx, char *file, char *path) {
  598. int load_custom = 1, load_default = 1;
  599. if (file || path) {
  600. if(!SSL_CTX_load_verify_locations(ctx, file, path)) {
  601. netdata_log_info("Netdata can not verify custom CAfile or CApath for parent's SSL certificate, so it will use the default OpenSSL configuration to validate certificates!");
  602. load_custom = 0;
  603. }
  604. }
  605. if(!SSL_CTX_set_default_verify_paths(ctx)) {
  606. netdata_log_info("Can not verify default OpenSSL configuration to validate certificates!");
  607. load_default = 0;
  608. }
  609. if (load_custom == 0 && load_default == 0)
  610. return -1;
  611. return 0;
  612. }
  613. #endif