aclk_otp.c 28 KB

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