1
0

tang.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright (c) 2016 Red Hat, Inc.
  4. * Author: Nathaniel McCallum <npmccallum@redhat.com>
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * NOTE WELL: This code is completely insecure for real-world workflows!
  21. *
  22. * In particular, it has two glaring security problems:
  23. *
  24. * 1. Server keys are implicitly trusted.
  25. * 2. No ephemeral keys are used to protect the recovery phase.
  26. *
  27. * However, the goal of this Nagios plugin is to determine if the server is
  28. * alive and properly handles well-formed requests. So we don't care about
  29. * security. If you are looking for an example of how to securely use Tang,
  30. * check out the Clevis project.
  31. */
  32. #define _GNU_SOURCE
  33. #include <http_parser.h>
  34. #include <jose/jose.h>
  35. #include <sys/types.h>
  36. #include <sys/socket.h>
  37. #include <netdb.h>
  38. #include <errno.h>
  39. #include <getopt.h>
  40. #include <limits.h>
  41. #include <string.h>
  42. #include <time.h>
  43. #include <unistd.h>
  44. #define conn_auto_t conn_t __attribute__((cleanup(conn_cleanup)))
  45. enum {
  46. NAGIOS_OK = 0,
  47. NAGIOS_WARN = 1,
  48. NAGIOS_CRIT = 2,
  49. NAGIOS_UNKN = 3
  50. };
  51. typedef struct {
  52. char data[4096];
  53. size_t used;
  54. int sock;
  55. } conn_t;
  56. typedef struct {
  57. char *data;
  58. size_t size;
  59. } body_t;
  60. typedef struct {
  61. char schm[PATH_MAX];
  62. char host[PATH_MAX];
  63. char srvc[PATH_MAX];
  64. char path[PATH_MAX];
  65. } url_t;
  66. static void
  67. conn_cleanup(conn_t **conn)
  68. {
  69. if (conn && *conn) {
  70. close((*conn)->sock);
  71. free(*conn);
  72. }
  73. }
  74. static conn_t *
  75. conn_open(const char *host, const char *srvc, int family)
  76. {
  77. const struct addrinfo hint = {
  78. .ai_socktype = SOCK_STREAM,
  79. .ai_family = family,
  80. };
  81. struct addrinfo *ais = NULL;
  82. conn_t *conn = NULL;
  83. int sock = -1;
  84. sock = getaddrinfo(host, srvc, &hint, &ais);
  85. switch (sock) {
  86. case 0: break;
  87. case EAI_AGAIN: errno = -EAGAIN; return NULL;
  88. case EAI_BADFLAGS: errno = -EINVAL; return NULL;
  89. case EAI_FAMILY: errno = -ENOTSUP; return NULL;
  90. case EAI_MEMORY: errno = -ENOMEM; return NULL;
  91. case EAI_SERVICE: errno = -EINVAL; return NULL;
  92. default: errno = -EIO; return NULL;
  93. }
  94. conn = calloc(1, sizeof(*conn));
  95. if (!conn) {
  96. freeaddrinfo(ais);
  97. return NULL;
  98. }
  99. for (const struct addrinfo *ai = ais; ai; ai = ai->ai_next) {
  100. conn->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  101. if (conn->sock < 0)
  102. continue;
  103. if (connect(conn->sock, ai->ai_addr, ai->ai_addrlen) != 0) {
  104. close(conn->sock);
  105. continue;
  106. }
  107. freeaddrinfo(ais);
  108. return conn;
  109. }
  110. freeaddrinfo(ais);
  111. free(conn);
  112. errno = -ENOENT;
  113. return NULL;
  114. }
  115. static int
  116. conn_send(const conn_t *conn, const char *fmt, ...)
  117. {
  118. va_list ap;
  119. int r;
  120. va_start(ap, fmt);
  121. r = vdprintf(conn->sock, fmt, ap);
  122. va_end(ap);
  123. return r;
  124. }
  125. static int
  126. on_body(http_parser *parser, const char *at, size_t length)
  127. {
  128. body_t *body = parser->data;
  129. char *tmp = NULL;
  130. tmp = realloc(body->data, body->size + length + 1);
  131. if (!tmp)
  132. return -errno;
  133. memcpy(&tmp[body->size], at, length);
  134. body->size += length;
  135. body->data = tmp;
  136. body->data[body->size] = 0;
  137. return 0;
  138. }
  139. static int
  140. on_message_complete(http_parser *parser)
  141. {
  142. http_parser_pause(parser, true);
  143. return 0;
  144. }
  145. static int
  146. conn_recv(conn_t *conn, char **body)
  147. {
  148. static const http_parser_settings settings = {
  149. .on_body = on_body,
  150. .on_message_complete = on_message_complete
  151. };
  152. body_t data = {};
  153. http_parser parser = { .data = &data };
  154. http_parser_init(&parser, HTTP_RESPONSE);
  155. for (;;) {
  156. ssize_t rcvd = 0;
  157. size_t prsd = 0;
  158. rcvd = recv(conn->sock, &conn->data[conn->used],
  159. sizeof(conn->data) - conn->used, 0);
  160. if (rcvd < 0) {
  161. free(data.data);
  162. return -errno;
  163. } else if (rcvd == 0) {
  164. free(data.data);
  165. return -EIO;
  166. }
  167. conn->used += rcvd;
  168. prsd = http_parser_execute(&parser, &settings, conn->data, conn->used);
  169. conn->used -= prsd;
  170. memmove(conn->data, &conn->data[prsd], conn->used);
  171. switch (parser.http_errno) {
  172. case HPE_OK: /* We need to process more data. */
  173. break;
  174. case HPE_PAUSED: /* We got one request. */
  175. *body = data.data;
  176. return parser.status_code;
  177. default: /* An error occurred. */
  178. free(data.data);
  179. return -EBADMSG;
  180. }
  181. }
  182. }
  183. static double
  184. curtime(void)
  185. {
  186. struct timespec ts = {};
  187. double out = 0;
  188. if (clock_gettime(CLOCK_MONOTONIC_RAW, &ts) == 0) {
  189. out = ts.tv_nsec;
  190. out /= 1000000000L;
  191. out += ts.tv_sec;
  192. }
  193. return out;
  194. }
  195. static void
  196. dump_perf(json_t *time)
  197. {
  198. const char *key = NULL;
  199. bool first = true;
  200. json_t *val = 0;
  201. json_object_foreach(time, key, val) {
  202. int v = 0;
  203. if (!first)
  204. printf(" ");
  205. else
  206. first = false;
  207. if (json_is_integer(val))
  208. v = json_integer_value(val);
  209. else if (json_is_real(val))
  210. v = json_real_value(val) * 1000000;
  211. printf("%s=%d", key, v);
  212. }
  213. }
  214. static int
  215. parse_url(const char *url, url_t *parts)
  216. {
  217. static const uint16_t mask = (1 << UF_SCHEMA) | (1 << UF_HOST);
  218. struct http_parser_url purl = {};
  219. if (http_parser_parse_url(url, strlen(url), false, &purl) != 0)
  220. return -EINVAL;
  221. if ((purl.field_set & mask) != mask)
  222. return -EINVAL;
  223. if (purl.field_data[UF_SCHEMA].len >= sizeof(parts->schm) ||
  224. purl.field_data[UF_HOST].len >= sizeof(parts->host) ||
  225. purl.field_data[UF_PORT].len >= sizeof(parts->srvc) ||
  226. purl.field_data[UF_PATH].len >= sizeof(parts->path))
  227. return -E2BIG;
  228. strncpy(parts->schm, &url[purl.field_data[UF_SCHEMA].off],
  229. purl.field_data[UF_SCHEMA].len);
  230. strncpy(parts->host, &url[purl.field_data[UF_HOST].off],
  231. purl.field_data[UF_HOST].len);
  232. if (purl.field_set & (1 << UF_PORT)) {
  233. strncpy(parts->srvc, &url[purl.field_data[UF_PORT].off],
  234. purl.field_data[UF_PORT].len);
  235. } else {
  236. strcpy(parts->srvc, parts->schm);
  237. }
  238. if (purl.field_set & (1 << UF_PATH)) {
  239. strncpy(parts->path, &url[purl.field_data[UF_PATH].off],
  240. purl.field_data[UF_PATH].len);
  241. }
  242. return 0;
  243. }
  244. static json_t *
  245. validate(const json_t *jws)
  246. {
  247. json_auto_t *jwkset = NULL;
  248. json_t *keys = NULL;
  249. size_t sigs = 0;
  250. jwkset = jose_b64_dec_load(json_object_get(jws, "payload"));
  251. if (!jwkset)
  252. return NULL;
  253. keys = json_object_get(jwkset, "keys");
  254. if (!json_is_array(keys))
  255. return NULL;
  256. for (size_t i = 0; i < json_array_size(keys); i++) {
  257. json_t *key = json_array_get(keys, i);
  258. if (!jose_jwk_prm(NULL, key, true, "verify"))
  259. continue;
  260. if (!jose_jws_ver(NULL, jws, NULL, key, true))
  261. return NULL;
  262. sigs++;
  263. }
  264. if (sigs == 0)
  265. return NULL;
  266. return json_incref(keys);
  267. }
  268. static bool
  269. nagios_recover(conn_t *con, const char *host, const char *path,
  270. const json_t *jwk, size_t *sig, size_t *rec, json_t *time)
  271. {
  272. json_auto_t *exc = NULL;
  273. json_auto_t *rep = NULL;
  274. json_auto_t *lcl = NULL;
  275. json_auto_t *kid = NULL;
  276. char *body = NULL;
  277. double s = 0;
  278. double e = 0;
  279. int r = 0;
  280. if (jose_jwk_prm(NULL, jwk, true, "verify")) {
  281. *sig += 1;
  282. return true;
  283. }
  284. if (!jose_jwk_prm(NULL, jwk, true, "deriveKey"))
  285. return true;
  286. kid = jose_jwk_thp(NULL, jwk, "S256");
  287. if (!kid)
  288. return true;
  289. lcl = json_pack("{s:O,s:O,s:s,s:[s]}",
  290. "kty", json_object_get(jwk, "kty"),
  291. "crv", json_object_get(jwk, "crv"),
  292. "alg", "ECMR",
  293. "key_ops", "deriveKey");
  294. if (!lcl)
  295. return false;
  296. if (!jose_jwk_gen(NULL, lcl))
  297. return false;
  298. exc = jose_jwk_exc(NULL, lcl, jwk);
  299. if (!exc)
  300. return false;
  301. if (!jose_jwk_pub(NULL, lcl))
  302. return false;
  303. body = json_dumps(lcl, JSON_SORT_KEYS | JSON_COMPACT);
  304. if (!body)
  305. return false;
  306. r = conn_send(con,
  307. "POST %s/rec/%s HTTP/1.1\r\n"
  308. "Content-Type: application/jwk+json\r\n"
  309. "Accept: application/jwk+json\r\n"
  310. "Content-Length: %zu\r\n"
  311. "Host: %s\r\n"
  312. "\r\n%s",
  313. path, json_string_value(kid), strlen(body), host, body);
  314. free(body);
  315. body = NULL;
  316. if (r < 0)
  317. return false;
  318. s = curtime();
  319. r = conn_recv(con, &body);
  320. e = curtime();
  321. if (r != 200) {
  322. if (r < 0)
  323. printf("Error performing recovery! %s\n", strerror(-r));
  324. else
  325. printf("Error performing recovery! HTTP Status %d\n", r);
  326. free(body);
  327. return false;
  328. }
  329. rep = json_loads(body, 0, NULL);
  330. free(body);
  331. if (!rep) {
  332. printf("Received invalid JSON in response body!\n");
  333. return false;
  334. }
  335. if (s == 0.0 || e == 0.0 ||
  336. json_array_append_new(time, json_real(e - s)) < 0) {
  337. printf("Error calculating performance metrics!\n");
  338. return false;
  339. }
  340. if (!jose_jwk_eql(NULL, exc, rep)) {
  341. printf("Recovered key doesn't match!\n");
  342. return false;
  343. }
  344. *rec += 1;
  345. return true;
  346. }
  347. static const struct option opts[] = {
  348. { "help", no_argument, .val = INT_MAX },
  349. { "url", required_argument, .val = 'u' },
  350. {}
  351. };
  352. int
  353. main(int argc, char *argv[])
  354. {
  355. json_auto_t *perf = NULL;
  356. json_auto_t *time = NULL;
  357. json_auto_t *keys = NULL;
  358. json_auto_t *adv = NULL;
  359. conn_auto_t *con = NULL;
  360. const char *url = NULL;
  361. char *body = NULL;
  362. url_t parts = {};
  363. size_t sig = 0;
  364. size_t exc = 0;
  365. double sum = 0;
  366. double s = 0;
  367. double e = 0;
  368. int r = 0;
  369. perf = json_object();
  370. time = json_array();
  371. if (!perf || !time)
  372. return NAGIOS_CRIT;
  373. for (int c; (c = getopt_long(argc, argv, "u:", opts, NULL)) >= 0; ) {
  374. switch (c) {
  375. case 'u': url = optarg; break;
  376. default: goto usage;
  377. }
  378. }
  379. if (!url)
  380. goto usage;
  381. r = parse_url(url, &parts);
  382. if (r < 0)
  383. return NAGIOS_CRIT;
  384. con = conn_open(parts.host, parts.srvc, AF_UNSPEC);
  385. if (!con) {
  386. printf("Unable to connect to server!\n");
  387. return NAGIOS_CRIT;
  388. }
  389. r = conn_send(con,
  390. "GET %s/adv HTTP/1.1\r\n"
  391. "Accept: application/jose+json\r\n"
  392. "Content-Length: 0\r\n"
  393. "Host: %s\r\n"
  394. "\r\n", parts.path, parts.host);
  395. if (r < 0)
  396. return NAGIOS_CRIT;
  397. s = curtime();
  398. r = conn_recv(con, &body);
  399. e = curtime();
  400. if (r != 200) {
  401. if (r < 0)
  402. printf("Error fetching advertisement! %s\n", strerror(-r));
  403. else
  404. printf("Error fetching advertisement! HTTP Status %d\n", r);
  405. free(body);
  406. return NAGIOS_CRIT;
  407. }
  408. if (s == 0.0 || e == 0.0 ||
  409. json_object_set_new(perf, "adv", json_real(e - s)) != 0) {
  410. printf("Error calculating performance metrics!\n");
  411. free(body);
  412. return NAGIOS_CRIT;
  413. }
  414. adv = json_loads(body, 0, NULL);
  415. free(body);
  416. if (!adv) {
  417. printf("Received invalid advertisement!\n");
  418. return NAGIOS_CRIT;
  419. }
  420. keys = validate(adv);
  421. if (!keys) {
  422. printf("Error validating advertisement!\n");
  423. return NAGIOS_CRIT;
  424. }
  425. for (size_t i = 0; i < json_array_size(keys); i++) {
  426. json_t *jwk = json_array_get(keys, i);
  427. if (!nagios_recover(con, parts.host, parts.path, jwk,
  428. &sig, &exc, time))
  429. return NAGIOS_CRIT;
  430. }
  431. if (exc == 0) {
  432. printf("Advertisement contains no exchange keys!\n");
  433. return NAGIOS_CRIT;
  434. }
  435. for (size_t i = 0; i < json_array_size(time); i++)
  436. sum += json_real_value(json_array_get(time, i));
  437. json_object_set_new(perf, "exc", json_real(sum / json_array_size(time)));
  438. json_object_set_new(perf, "nkeys", json_integer(json_array_size(keys)));
  439. json_object_set_new(perf, "nsigk", json_integer(sig));
  440. json_object_set_new(perf, "nexck", json_integer(exc));
  441. printf("OK|");
  442. dump_perf(perf);
  443. printf("\n");
  444. return NAGIOS_OK;
  445. usage:
  446. fprintf(stderr,
  447. "Usage: %s -u URL\n"
  448. "\n"
  449. " --help Show this usage message\n"
  450. " -u URL, --url URL Test the server at this URL\n"
  451. "", argv[0]);
  452. return NAGIOS_CRIT;
  453. }