aclk_otp.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "aclk_otp.h"
  3. #include "aclk_util.h"
  4. #include "aclk.h"
  5. #include "daemon/common.h"
  6. #include "mqtt_websockets/c-rbuf/include/ringbuffer.h"
  7. static int aclk_https_request(https_req_t *request, https_req_response_t *response) {
  8. int rc;
  9. // wrapper for ACLK only which loads ACLK specific proxy settings
  10. // then only calls https_request
  11. struct mqtt_wss_proxy proxy_conf = { .host = NULL, .port = 0, .username = NULL, .password = NULL, .type = MQTT_WSS_DIRECT };
  12. aclk_set_proxy((char**)&proxy_conf.host, &proxy_conf.port, (char**)&proxy_conf.username, (char**)&proxy_conf.password, &proxy_conf.type);
  13. if (proxy_conf.type == MQTT_WSS_PROXY_HTTP) {
  14. request->proxy_host = (char*)proxy_conf.host; // TODO make it const as well
  15. request->proxy_port = proxy_conf.port;
  16. request->proxy_username = proxy_conf.username;
  17. request->proxy_password = proxy_conf.password;
  18. }
  19. rc = https_request(request, response);
  20. freez((char*)proxy_conf.host);
  21. freez((char*)proxy_conf.username);
  22. freez((char*)proxy_conf.password);
  23. return rc;
  24. }
  25. struct auth_data {
  26. char *client_id;
  27. char *username;
  28. char *passwd;
  29. };
  30. #define PARSE_ENV_JSON_CHK_TYPE(it, type, name) \
  31. if (json_object_get_type(json_object_iter_peek_value(it)) != type) { \
  32. error("value of key \"%s\" should be %s", name, #type); \
  33. goto exit; \
  34. }
  35. #define JSON_KEY_CLIENTID "clientID"
  36. #define JSON_KEY_USER "username"
  37. #define JSON_KEY_PASS "password"
  38. #define JSON_KEY_TOPICS "topics"
  39. static int parse_passwd_response(const char *json_str, struct auth_data *auth) {
  40. int rc = 1;
  41. json_object *json;
  42. struct json_object_iterator it;
  43. struct json_object_iterator itEnd;
  44. json = json_tokener_parse(json_str);
  45. if (!json) {
  46. error("JSON-C failed to parse the payload of http response of /env endpoint");
  47. return 1;
  48. }
  49. it = json_object_iter_begin(json);
  50. itEnd = json_object_iter_end(json);
  51. while (!json_object_iter_equal(&it, &itEnd)) {
  52. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_CLIENTID)) {
  53. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_CLIENTID)
  54. auth->client_id = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  55. json_object_iter_next(&it);
  56. continue;
  57. }
  58. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_USER)) {
  59. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_USER)
  60. auth->username = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  61. json_object_iter_next(&it);
  62. continue;
  63. }
  64. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_PASS)) {
  65. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_PASS)
  66. auth->passwd = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  67. json_object_iter_next(&it);
  68. continue;
  69. }
  70. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_TOPICS)) {
  71. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_array, JSON_KEY_TOPICS)
  72. if (aclk_generate_topic_cache(json_object_iter_peek_value(&it))) {
  73. error("Failed to generate topic cache!");
  74. goto exit;
  75. }
  76. json_object_iter_next(&it);
  77. continue;
  78. }
  79. error("Unknown key \"%s\" in passwd response payload. Ignoring", json_object_iter_peek_name(&it));
  80. json_object_iter_next(&it);
  81. }
  82. if (!auth->client_id) {
  83. error(JSON_KEY_CLIENTID " is compulsory key in /password response");
  84. goto exit;
  85. }
  86. if (!auth->passwd) {
  87. error(JSON_KEY_PASS " is compulsory in /password response");
  88. goto exit;
  89. }
  90. if (!auth->username) {
  91. error(JSON_KEY_USER " is compulsory in /password response");
  92. goto exit;
  93. }
  94. rc = 0;
  95. exit:
  96. json_object_put(json);
  97. return rc;
  98. }
  99. #define JSON_KEY_ERTRY "errorNonRetryable"
  100. #define JSON_KEY_EDELAY "errorRetryDelaySeconds"
  101. #define JSON_KEY_EEC "errorCode"
  102. #define JSON_KEY_EMSGKEY "errorMsgKey"
  103. #define JSON_KEY_EMSG "errorMessage"
  104. #if JSON_C_MINOR_VERSION >= 13
  105. static const char *get_json_str_by_path(json_object *json, const char *path) {
  106. json_object *ptr;
  107. if (json_pointer_get(json, path, &ptr)) {
  108. error("Missing compulsory key \"%s\" in error response", path);
  109. return NULL;
  110. }
  111. if (json_object_get_type(ptr) != json_type_string) {
  112. error("Value of Key \"%s\" in error response should be string", path);
  113. return NULL;
  114. }
  115. return json_object_get_string(ptr);
  116. }
  117. static int aclk_parse_otp_error(const char *json_str) {
  118. int rc = 1;
  119. json_object *json, *ptr;
  120. const char *ec;
  121. const char *ek;
  122. const char *emsg;
  123. int block_retry = -1, backoff = -1;
  124. json = json_tokener_parse(json_str);
  125. if (!json) {
  126. error("JSON-C failed to parse the payload of http response of /env endpoint");
  127. return 1;
  128. }
  129. if ((ec = get_json_str_by_path(json, "/" JSON_KEY_EEC)) == NULL)
  130. goto exit;
  131. if ((ek = get_json_str_by_path(json, "/" JSON_KEY_EMSGKEY)) == NULL)
  132. goto exit;
  133. if ((emsg = get_json_str_by_path(json, "/" JSON_KEY_EMSG)) == NULL)
  134. goto exit;
  135. // optional field
  136. if (!json_pointer_get(json, "/" JSON_KEY_ERTRY, &ptr)) {
  137. if (json_object_get_type(ptr) != json_type_boolean) {
  138. error("Error response Key " "/" JSON_KEY_ERTRY " should be of boolean type");
  139. goto exit;
  140. }
  141. block_retry = json_object_get_boolean(ptr);
  142. }
  143. // optional field
  144. if (!json_pointer_get(json, "/" JSON_KEY_EDELAY, &ptr)) {
  145. if (json_object_get_type(ptr) != json_type_int) {
  146. error("Error response Key " "/" JSON_KEY_EDELAY " should be of integer type");
  147. goto exit;
  148. }
  149. backoff = json_object_get_int(ptr);
  150. }
  151. if (block_retry > 0)
  152. aclk_disable_runtime = 1;
  153. if (backoff > 0)
  154. aclk_block_until = now_monotonic_sec() + backoff;
  155. error("Cloud returned EC=\"%s\", Msg-Key:\"%s\", Msg:\"%s\", BlockRetry:%s, Backoff:%ds (-1 unset by cloud)", ec, ek, emsg, block_retry > 0 ? "true" : "false", backoff);
  156. rc = 0;
  157. exit:
  158. json_object_put(json);
  159. return rc;
  160. }
  161. #else
  162. static int aclk_parse_otp_error(const char *json_str) {
  163. int rc = 1;
  164. int block_retry = -1, backoff = -1;
  165. const char *ec = NULL;
  166. const char *ek = NULL;
  167. const char *emsg = NULL;
  168. json_object *json;
  169. struct json_object_iterator it;
  170. struct json_object_iterator itEnd;
  171. json = json_tokener_parse(json_str);
  172. if (!json) {
  173. error("JSON-C failed to parse the payload of http response of /env endpoint");
  174. return 1;
  175. }
  176. it = json_object_iter_begin(json);
  177. itEnd = json_object_iter_end(json);
  178. while (!json_object_iter_equal(&it, &itEnd)) {
  179. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_EMSG)) {
  180. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_EMSG)
  181. emsg = json_object_get_string(json_object_iter_peek_value(&it));
  182. json_object_iter_next(&it);
  183. continue;
  184. }
  185. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_EMSGKEY)) {
  186. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_EMSGKEY)
  187. ek = json_object_get_string(json_object_iter_peek_value(&it));
  188. json_object_iter_next(&it);
  189. continue;
  190. }
  191. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_EEC)) {
  192. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_EEC)
  193. ec = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  194. json_object_iter_next(&it);
  195. continue;
  196. }
  197. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_EDELAY)) {
  198. if (json_object_get_type(json_object_iter_peek_value(&it)) != json_type_int) {
  199. error("value of key " JSON_KEY_EDELAY " should be integer");
  200. goto exit;
  201. }
  202. backoff = json_object_get_int(json_object_iter_peek_value(&it));
  203. json_object_iter_next(&it);
  204. continue;
  205. }
  206. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_ERTRY)) {
  207. if (json_object_get_type(json_object_iter_peek_value(&it)) != json_type_boolean) {
  208. error("value of key " JSON_KEY_ERTRY " should be integer");
  209. goto exit;
  210. }
  211. block_retry = json_object_get_boolean(json_object_iter_peek_value(&it));
  212. json_object_iter_next(&it);
  213. continue;
  214. }
  215. error("Unknown key \"%s\" in error response payload. Ignoring", json_object_iter_peek_name(&it));
  216. json_object_iter_next(&it);
  217. }
  218. if (block_retry > 0)
  219. aclk_disable_runtime = 1;
  220. if (backoff > 0)
  221. aclk_block_until = now_monotonic_sec() + backoff;
  222. error("Cloud returned EC=\"%s\", Msg-Key:\"%s\", Msg:\"%s\", BlockRetry:%s, Backoff:%ds (-1 unset by cloud)", ec, ek, emsg, block_retry > 0 ? "true" : "false", backoff);
  223. rc = 0;
  224. exit:
  225. json_object_put(json);
  226. return rc;
  227. }
  228. #endif
  229. #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  230. static EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void)
  231. {
  232. EVP_ENCODE_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
  233. if (ctx != NULL) {
  234. memset(ctx, 0, sizeof(*ctx));
  235. }
  236. return ctx;
  237. }
  238. static void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx)
  239. {
  240. OPENSSL_free(ctx);
  241. return;
  242. }
  243. #endif
  244. #define CHALLENGE_LEN 256
  245. #define CHALLENGE_LEN_BASE64 344
  246. inline static int base64_decode_helper(unsigned char *out, int *outl, const unsigned char *in, int in_len)
  247. {
  248. unsigned char remaining_data[CHALLENGE_LEN];
  249. EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
  250. EVP_DecodeInit(ctx);
  251. EVP_DecodeUpdate(ctx, out, outl, in, in_len);
  252. int remainder = 0;
  253. EVP_DecodeFinal(ctx, remaining_data, &remainder);
  254. EVP_ENCODE_CTX_free(ctx);
  255. if (remainder) {
  256. error("Unexpected data at EVP_DecodeFinal");
  257. return 1;
  258. }
  259. return 0;
  260. }
  261. #define OTP_URL_PREFIX "/api/v1/auth/node/"
  262. int aclk_get_otp_challenge(url_t *target, const char *agent_id, unsigned char **challenge, int *challenge_bytes)
  263. {
  264. int rc = 1;
  265. https_req_t req = HTTPS_REQ_T_INITIALIZER;
  266. https_req_response_t resp = HTTPS_REQ_RESPONSE_T_INITIALIZER;
  267. BUFFER *url = buffer_create(strlen(OTP_URL_PREFIX) + UUID_STR_LEN + 20, &netdata_buffers_statistics.buffers_aclk);
  268. req.host = target->host;
  269. req.port = target->port;
  270. buffer_sprintf(url, "%s/node/%s/challenge", target->path, agent_id);
  271. req.url = (char *)buffer_tostring(url);
  272. if (aclk_https_request(&req, &resp)) {
  273. error ("ACLK_OTP Challenge failed");
  274. buffer_free(url);
  275. return 1;
  276. }
  277. if (resp.http_code != 200) {
  278. error ("ACLK_OTP Challenge HTTP code not 200 OK (got %d)", resp.http_code);
  279. buffer_free(url);
  280. if (resp.payload_size)
  281. aclk_parse_otp_error(resp.payload);
  282. goto cleanup_resp;
  283. }
  284. buffer_free(url);
  285. info ("ACLK_OTP Got Challenge from Cloud");
  286. json_object *json = json_tokener_parse(resp.payload);
  287. if (!json) {
  288. error ("Couldn't parse HTTP GET challenge payload");
  289. goto cleanup_resp;
  290. }
  291. json_object *challenge_json;
  292. if (!json_object_object_get_ex(json, "challenge", &challenge_json)) {
  293. error ("No key named \"challenge\" in the returned JSON");
  294. goto cleanup_json;
  295. }
  296. if (!json_object_is_type(challenge_json, json_type_string)) {
  297. error ("\"challenge\" is not a string JSON type");
  298. goto cleanup_json;
  299. }
  300. const char *challenge_base64;
  301. if (!(challenge_base64 = json_object_get_string(challenge_json))) {
  302. error("Failed to extract challenge from JSON object");
  303. goto cleanup_json;
  304. }
  305. if (strlen(challenge_base64) != CHALLENGE_LEN_BASE64) {
  306. error("Received Challenge has unexpected length of %zu (expected %d)", strlen(challenge_base64), CHALLENGE_LEN_BASE64);
  307. goto cleanup_json;
  308. }
  309. *challenge = mallocz((CHALLENGE_LEN_BASE64 / 4) * 3);
  310. base64_decode_helper(*challenge, challenge_bytes, (const unsigned char*)challenge_base64, strlen(challenge_base64));
  311. if (*challenge_bytes != CHALLENGE_LEN) {
  312. error("Unexpected challenge length of %d instead of %d", *challenge_bytes, CHALLENGE_LEN);
  313. freez(*challenge);
  314. *challenge = NULL;
  315. goto cleanup_json;
  316. }
  317. rc = 0;
  318. cleanup_json:
  319. json_object_put(json);
  320. cleanup_resp:
  321. https_req_response_free(&resp);
  322. return rc;
  323. }
  324. int aclk_send_otp_response(const char *agent_id, const unsigned char *response, int response_bytes, url_t *target, struct auth_data *mqtt_auth)
  325. {
  326. int len;
  327. int rc = 1;
  328. https_req_t req = HTTPS_REQ_T_INITIALIZER;
  329. https_req_response_t resp = HTTPS_REQ_RESPONSE_T_INITIALIZER;
  330. req.host = target->host;
  331. req.port = target->port;
  332. req.request_type = HTTP_REQ_POST;
  333. unsigned char base64[CHALLENGE_LEN_BASE64 + 1];
  334. memset(base64, 0, CHALLENGE_LEN_BASE64 + 1);
  335. base64_encode_helper(base64, &len, response, response_bytes);
  336. BUFFER *url = buffer_create(strlen(OTP_URL_PREFIX) + UUID_STR_LEN + 20, &netdata_buffers_statistics.buffers_aclk);
  337. BUFFER *resp_json = buffer_create(strlen(OTP_URL_PREFIX) + UUID_STR_LEN + 20, &netdata_buffers_statistics.buffers_aclk);
  338. buffer_sprintf(url, "%s/node/%s/password", target->path, agent_id);
  339. buffer_sprintf(resp_json, "{\"response\":\"%s\"}", base64);
  340. req.url = (char *)buffer_tostring(url);
  341. req.payload = (char *)buffer_tostring(resp_json);
  342. req.payload_size = strlen(req.payload);
  343. if (aclk_https_request(&req, &resp)) {
  344. error ("ACLK_OTP Password error trying to post result to password");
  345. goto cleanup_buffers;
  346. }
  347. if (resp.http_code != 201) {
  348. error ("ACLK_OTP Password HTTP code not 201 Created (got %d)", resp.http_code);
  349. if (resp.payload_size)
  350. aclk_parse_otp_error(resp.payload);
  351. goto cleanup_response;
  352. }
  353. info ("ACLK_OTP Got Password from Cloud");
  354. if (parse_passwd_response(resp.payload, mqtt_auth)){
  355. error("Error parsing response of password endpoint");
  356. goto cleanup_response;
  357. }
  358. rc = 0;
  359. cleanup_response:
  360. https_req_response_free(&resp);
  361. cleanup_buffers:
  362. buffer_free(resp_json);
  363. buffer_free(url);
  364. return rc;
  365. }
  366. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  367. static int private_decrypt(EVP_PKEY *p_key, unsigned char * enc_data, int data_len, unsigned char **decrypted)
  368. #else
  369. static int private_decrypt(RSA *p_key, unsigned char * enc_data, int data_len, unsigned char **decrypted)
  370. #endif
  371. {
  372. int result;
  373. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  374. size_t outlen = EVP_PKEY_size(p_key);
  375. EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(p_key, NULL);
  376. if (!ctx)
  377. return 1;
  378. if (EVP_PKEY_decrypt_init(ctx) <= 0)
  379. return 1;
  380. if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_OAEP_PADDING) <= 0)
  381. return 1;
  382. *decrypted = mallocz(outlen);
  383. if (EVP_PKEY_decrypt(ctx, *decrypted, &outlen, enc_data, data_len) == 1)
  384. result = (int) outlen;
  385. else
  386. result = -1;
  387. #else
  388. *decrypted = mallocz(RSA_size(p_key));
  389. result = RSA_private_decrypt(data_len, enc_data, *decrypted, p_key, RSA_PKCS1_OAEP_PADDING);
  390. #endif
  391. if (result == -1)
  392. {
  393. char err[512];
  394. ERR_error_string_n(ERR_get_error(), err, sizeof(err));
  395. error("Decryption of the challenge failed: %s", err);
  396. }
  397. return result;
  398. }
  399. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  400. int aclk_get_mqtt_otp(EVP_PKEY *p_key, char **mqtt_id, char **mqtt_usr, char **mqtt_pass, url_t *target)
  401. #else
  402. int aclk_get_mqtt_otp(RSA *p_key, char **mqtt_id, char **mqtt_usr, char **mqtt_pass, url_t *target)
  403. #endif
  404. {
  405. unsigned char *challenge = NULL;
  406. int challenge_bytes;
  407. char *agent_id = get_agent_claimid();
  408. if (agent_id == NULL) {
  409. error("Agent was not claimed - cannot perform challenge/response");
  410. return 1;
  411. }
  412. // Get Challenge
  413. if (aclk_get_otp_challenge(target, agent_id, &challenge, &challenge_bytes)) {
  414. error("Error getting challenge");
  415. freez(agent_id);
  416. return 1;
  417. }
  418. // Decrypt Challenge / Get response
  419. unsigned char *response_plaintext;
  420. int response_plaintext_bytes = private_decrypt(p_key, challenge, challenge_bytes, &response_plaintext);
  421. if (response_plaintext_bytes < 0) {
  422. error ("Couldn't decrypt the challenge received");
  423. freez(response_plaintext);
  424. freez(challenge);
  425. freez(agent_id);
  426. return 1;
  427. }
  428. freez(challenge);
  429. // Encode and Send Challenge
  430. struct auth_data data = { .client_id = NULL, .passwd = NULL, .username = NULL };
  431. if (aclk_send_otp_response(agent_id, response_plaintext, response_plaintext_bytes, target, &data)) {
  432. error("Error getting response");
  433. freez(response_plaintext);
  434. freez(agent_id);
  435. return 1;
  436. }
  437. *mqtt_pass = data.passwd;
  438. *mqtt_usr = data.username;
  439. *mqtt_id = data.client_id;
  440. freez(response_plaintext);
  441. freez(agent_id);
  442. return 0;
  443. }
  444. #define JSON_KEY_ENC "encoding"
  445. #define JSON_KEY_AUTH_ENDPOINT "authEndpoint"
  446. #define JSON_KEY_TRP "transports"
  447. #define JSON_KEY_TRP_TYPE "type"
  448. #define JSON_KEY_TRP_ENDPOINT "endpoint"
  449. #define JSON_KEY_BACKOFF "backoff"
  450. #define JSON_KEY_BACKOFF_BASE "base"
  451. #define JSON_KEY_BACKOFF_MAX "maxSeconds"
  452. #define JSON_KEY_BACKOFF_MIN "minSeconds"
  453. #define JSON_KEY_CAPS "capabilities"
  454. static int parse_json_env_transport(json_object *json, aclk_transport_desc_t *trp) {
  455. struct json_object_iterator it;
  456. struct json_object_iterator itEnd;
  457. it = json_object_iter_begin(json);
  458. itEnd = json_object_iter_end(json);
  459. while (!json_object_iter_equal(&it, &itEnd)) {
  460. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_TRP_TYPE)) {
  461. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_TRP_TYPE)
  462. if (trp->type != ACLK_TRP_UNKNOWN) {
  463. error(JSON_KEY_TRP_TYPE " set already");
  464. goto exit;
  465. }
  466. trp->type = aclk_transport_type_t_from_str(json_object_get_string(json_object_iter_peek_value(&it)));
  467. if (trp->type == ACLK_TRP_UNKNOWN) {
  468. error(JSON_KEY_TRP_TYPE " unknown type \"%s\"", json_object_get_string(json_object_iter_peek_value(&it)));
  469. goto exit;
  470. }
  471. json_object_iter_next(&it);
  472. continue;
  473. }
  474. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_TRP_ENDPOINT)) {
  475. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_TRP_ENDPOINT)
  476. if (trp->endpoint) {
  477. error(JSON_KEY_TRP_ENDPOINT " set already");
  478. goto exit;
  479. }
  480. trp->endpoint = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  481. json_object_iter_next(&it);
  482. continue;
  483. }
  484. error ("unknown JSON key in dictionary (\"%s\")", json_object_iter_peek_name(&it));
  485. json_object_iter_next(&it);
  486. }
  487. if (!trp->endpoint) {
  488. error (JSON_KEY_TRP_ENDPOINT " is missing from JSON dictionary");
  489. goto exit;
  490. }
  491. if (trp->type == ACLK_TRP_UNKNOWN) {
  492. error ("transport type not set");
  493. goto exit;
  494. }
  495. return 0;
  496. exit:
  497. aclk_transport_desc_t_destroy(trp);
  498. return 1;
  499. }
  500. static int parse_json_env_transports(json_object *json_array, aclk_env_t *env) {
  501. aclk_transport_desc_t *trp;
  502. json_object *obj;
  503. if (env->transports) {
  504. error("transports have been set already");
  505. return 1;
  506. }
  507. env->transport_count = json_object_array_length(json_array);
  508. env->transports = callocz(env->transport_count , sizeof(aclk_transport_desc_t *));
  509. for (size_t i = 0; i < env->transport_count; i++) {
  510. trp = callocz(1, sizeof(aclk_transport_desc_t));
  511. obj = json_object_array_get_idx(json_array, i);
  512. if (parse_json_env_transport(obj, trp)) {
  513. error("error parsing transport idx %d", (int)i);
  514. freez(trp);
  515. return 1;
  516. }
  517. env->transports[i] = trp;
  518. }
  519. return 0;
  520. }
  521. #define MATCHED_CORRECT 1
  522. #define MATCHED_ERROR -1
  523. #define NOT_MATCHED 0
  524. static int parse_json_backoff_int(struct json_object_iterator *it, int *out, const char* name, int min, int max) {
  525. if (!strcmp(json_object_iter_peek_name(it), name)) {
  526. if (json_object_get_type(json_object_iter_peek_value(it)) != json_type_int) {
  527. error("Could not parse \"%s\". Not an integer as expected.", name);
  528. return MATCHED_ERROR;
  529. }
  530. *out = json_object_get_int(json_object_iter_peek_value(it));
  531. if (*out < min || *out > max) {
  532. error("Value of \"%s\"=%d out of range (%d-%d).", name, *out, min, max);
  533. return MATCHED_ERROR;
  534. }
  535. return MATCHED_CORRECT;
  536. }
  537. return NOT_MATCHED;
  538. }
  539. static int parse_json_backoff(json_object *json, aclk_backoff_t *backoff) {
  540. struct json_object_iterator it;
  541. struct json_object_iterator itEnd;
  542. int ret;
  543. it = json_object_iter_begin(json);
  544. itEnd = json_object_iter_end(json);
  545. while (!json_object_iter_equal(&it, &itEnd)) {
  546. if ( (ret = parse_json_backoff_int(&it, &backoff->base, JSON_KEY_BACKOFF_BASE, 1, 10)) ) {
  547. if (ret == MATCHED_ERROR) {
  548. return 1;
  549. }
  550. json_object_iter_next(&it);
  551. continue;
  552. }
  553. if ( (ret = parse_json_backoff_int(&it, &backoff->max_s, JSON_KEY_BACKOFF_MAX, 500, INT_MAX)) ) {
  554. if (ret == MATCHED_ERROR) {
  555. return 1;
  556. }
  557. json_object_iter_next(&it);
  558. continue;
  559. }
  560. if ( (ret = parse_json_backoff_int(&it, &backoff->min_s, JSON_KEY_BACKOFF_MIN, 0, INT_MAX)) ) {
  561. if (ret == MATCHED_ERROR) {
  562. return 1;
  563. }
  564. json_object_iter_next(&it);
  565. continue;
  566. }
  567. error ("unknown JSON key in dictionary (\"%s\")", json_object_iter_peek_name(&it));
  568. json_object_iter_next(&it);
  569. }
  570. return 0;
  571. }
  572. static int parse_json_env_caps(json_object *json, aclk_env_t *env) {
  573. json_object *obj;
  574. const char *str;
  575. if (env->capabilities) {
  576. error("transports have been set already");
  577. return 1;
  578. }
  579. env->capability_count = json_object_array_length(json);
  580. // empty capabilities list is allowed
  581. if (!env->capability_count)
  582. return 0;
  583. env->capabilities = callocz(env->capability_count , sizeof(char *));
  584. for (size_t i = 0; i < env->capability_count; i++) {
  585. obj = json_object_array_get_idx(json, i);
  586. if (json_object_get_type(obj) != json_type_string) {
  587. error("Capability at index %d not a string!", (int)i);
  588. return 1;
  589. }
  590. str = json_object_get_string(obj);
  591. if (!str) {
  592. error("Error parsing capabilities");
  593. return 1;
  594. }
  595. env->capabilities[i] = strdupz(str);
  596. }
  597. return 0;
  598. }
  599. static int parse_json_env(const char *json_str, aclk_env_t *env) {
  600. json_object *json;
  601. struct json_object_iterator it;
  602. struct json_object_iterator itEnd;
  603. json = json_tokener_parse(json_str);
  604. if (!json) {
  605. error("JSON-C failed to parse the payload of http response of /env endpoint");
  606. return 1;
  607. }
  608. it = json_object_iter_begin(json);
  609. itEnd = json_object_iter_end(json);
  610. while (!json_object_iter_equal(&it, &itEnd)) {
  611. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_AUTH_ENDPOINT)) {
  612. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_AUTH_ENDPOINT)
  613. if (env->auth_endpoint) {
  614. error("authEndpoint set already");
  615. goto exit;
  616. }
  617. env->auth_endpoint = strdupz(json_object_get_string(json_object_iter_peek_value(&it)));
  618. json_object_iter_next(&it);
  619. continue;
  620. }
  621. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_ENC)) {
  622. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_string, JSON_KEY_ENC)
  623. if (env->encoding != ACLK_ENC_UNKNOWN) {
  624. error(JSON_KEY_ENC " set already");
  625. goto exit;
  626. }
  627. env->encoding = aclk_encoding_type_t_from_str(json_object_get_string(json_object_iter_peek_value(&it)));
  628. json_object_iter_next(&it);
  629. continue;
  630. }
  631. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_TRP)) {
  632. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_array, JSON_KEY_TRP)
  633. json_object *now = json_object_iter_peek_value(&it);
  634. parse_json_env_transports(now, env);
  635. json_object_iter_next(&it);
  636. continue;
  637. }
  638. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_BACKOFF)) {
  639. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_object, JSON_KEY_BACKOFF)
  640. if (parse_json_backoff(json_object_iter_peek_value(&it), &env->backoff)) {
  641. env->backoff.base = 0;
  642. error("Error parsing Backoff parameters in env");
  643. goto exit;
  644. }
  645. json_object_iter_next(&it);
  646. continue;
  647. }
  648. if (!strcmp(json_object_iter_peek_name(&it), JSON_KEY_CAPS)) {
  649. PARSE_ENV_JSON_CHK_TYPE(&it, json_type_array, JSON_KEY_CAPS)
  650. if (parse_json_env_caps(json_object_iter_peek_value(&it), env)) {
  651. error("Error parsing capabilities list");
  652. goto exit;
  653. }
  654. json_object_iter_next(&it);
  655. continue;
  656. }
  657. error ("unknown JSON key in dictionary (\"%s\")", json_object_iter_peek_name(&it));
  658. json_object_iter_next(&it);
  659. }
  660. // Check all compulsory keys have been set
  661. if (env->transport_count < 1) {
  662. error("env has to return at least one transport");
  663. goto exit;
  664. }
  665. if (!env->auth_endpoint) {
  666. error(JSON_KEY_AUTH_ENDPOINT " is compulsory");
  667. goto exit;
  668. }
  669. if (env->encoding == ACLK_ENC_UNKNOWN) {
  670. error(JSON_KEY_ENC " is compulsory");
  671. goto exit;
  672. }
  673. if (!env->backoff.base) {
  674. error(JSON_KEY_BACKOFF " is compulsory");
  675. goto exit;
  676. }
  677. json_object_put(json);
  678. return 0;
  679. exit:
  680. aclk_env_t_destroy(env);
  681. json_object_put(json);
  682. return 1;
  683. }
  684. int aclk_get_env(aclk_env_t *env, const char* aclk_hostname, int aclk_port) {
  685. BUFFER *buf = buffer_create(1024, &netdata_buffers_statistics.buffers_aclk);
  686. https_req_t req = HTTPS_REQ_T_INITIALIZER;
  687. https_req_response_t resp = HTTPS_REQ_RESPONSE_T_INITIALIZER;
  688. req.request_type = HTTP_REQ_GET;
  689. char *agent_id = get_agent_claimid();
  690. if (agent_id == NULL)
  691. {
  692. error("Agent was not claimed - cannot perform challenge/response");
  693. buffer_free(buf);
  694. return 1;
  695. }
  696. buffer_sprintf(buf, "/api/v1/env?v=%s&cap=proto,ctx&claim_id=%s", &(VERSION[1]) /* skip 'v' at beginning */, agent_id);
  697. freez(agent_id);
  698. req.host = (char*)aclk_hostname;
  699. req.port = aclk_port;
  700. req.url = buf->buffer;
  701. if (aclk_https_request(&req, &resp)) {
  702. error("Error trying to contact env endpoint");
  703. https_req_response_free(&resp);
  704. buffer_free(buf);
  705. return 1;
  706. }
  707. if (resp.http_code != 200) {
  708. error("The HTTP code not 200 OK (Got %d)", resp.http_code);
  709. if (resp.payload_size)
  710. aclk_parse_otp_error(resp.payload);
  711. https_req_response_free(&resp);
  712. buffer_free(buf);
  713. return 1;
  714. }
  715. if (!resp.payload || !resp.payload_size) {
  716. error("Unexpected empty payload as response to /env call");
  717. https_req_response_free(&resp);
  718. buffer_free(buf);
  719. return 1;
  720. }
  721. if (parse_json_env(resp.payload, env)) {
  722. error ("error parsing /env message");
  723. https_req_response_free(&resp);
  724. buffer_free(buf);
  725. return 1;
  726. }
  727. info("Getting Cloud /env successful");
  728. https_req_response_free(&resp);
  729. buffer_free(buf);
  730. return 0;
  731. }