keys.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright (c) 2020 Red Hat, Inc.
  4. * Author: Sergio Correia <scorreia@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. #include <sys/stat.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <dirent.h>
  23. #include <stdio.h>
  24. #include <jose/b64.h>
  25. #include <jose/jwk.h>
  26. #include <jose/jws.h>
  27. #include "keys.h"
  28. #ifndef PATH_MAX
  29. #define PATH_MAX 4096
  30. #endif
  31. /* Default hash to use with JWK thumbprints (S256 = SHA-256). */
  32. #define DEFAULT_THP_HASH "S256"
  33. static const char**
  34. supported_hashes(void)
  35. {
  36. /* TODO: check if jose has a way to export the hash algorithms it
  37. * supports. */
  38. static const char* hashes[] = {"S1", "S224", "S256", "S384", "S512", NULL};
  39. return hashes;
  40. }
  41. static int
  42. is_hash(const char* alg)
  43. {
  44. if (!alg) {
  45. return 0;
  46. }
  47. const char** algs = supported_hashes();
  48. for (size_t a = 0; algs[a]; a++) {
  49. if (strcmp(alg, algs[a]) == 0) {
  50. return 1;
  51. }
  52. }
  53. return 0;
  54. }
  55. static json_t*
  56. jwk_generate(const char* alg)
  57. {
  58. json_auto_t* jalg = json_pack("{s:s}", "alg", alg);
  59. if (!jalg) {
  60. fprintf(stderr, "Error packing JSON with alg %s\n", alg);
  61. return NULL;
  62. }
  63. if (!jose_jwk_gen(NULL, jalg)) {
  64. fprintf(stderr, "Error generating JWK with alg %s\n", alg);
  65. return NULL;
  66. }
  67. return json_incref(jalg);
  68. }
  69. static char*
  70. jwk_thumbprint(const json_t* jwk, const char* alg)
  71. {
  72. size_t elen = 0;
  73. size_t dlen = 0;
  74. if (!jwk) {
  75. fprintf(stderr, "Invalid JWK\n");
  76. return NULL;
  77. }
  78. if (!alg || !is_hash(alg)) {
  79. fprintf(stderr, "Invalid hash algorithm (%s)\n", alg);
  80. return NULL;
  81. }
  82. dlen = jose_jwk_thp_buf(NULL, NULL, alg, NULL, 0);
  83. if (dlen == SIZE_MAX) {
  84. fprintf(stderr, "Error determining hash size for %s\n", alg);
  85. return NULL;
  86. }
  87. elen = jose_b64_enc_buf(NULL, dlen, NULL, 0);
  88. if (elen == SIZE_MAX) {
  89. fprintf(stderr, "Error determining encoded size for %s\n", alg);
  90. return NULL;
  91. }
  92. uint8_t dec[dlen];
  93. char enc[elen];
  94. if (!jose_jwk_thp_buf(NULL, jwk, alg, dec, sizeof(dec))) {
  95. fprintf(stderr, "Error making thumbprint\n");
  96. return NULL;
  97. }
  98. if (jose_b64_enc_buf(dec, dlen, enc, sizeof(enc)) != elen) {
  99. fprintf(stderr, "Error encoding data Base64\n");
  100. return NULL;
  101. }
  102. return strndup(enc, elen);
  103. }
  104. void
  105. free_tang_keys_info(struct tang_keys_info* tki)
  106. {
  107. if (!tki) {
  108. return;
  109. }
  110. json_t* to_free[] = {tki->m_keys, tki->m_rotated_keys,
  111. tki->m_payload, tki->m_sign
  112. };
  113. size_t len = sizeof(to_free) / sizeof(to_free[0]);
  114. for (size_t i = 0; i < len; i++) {
  115. if (to_free[i] == NULL) {
  116. continue;
  117. }
  118. json_decref(to_free[i]);
  119. }
  120. free(tki);
  121. }
  122. void
  123. cleanup_tang_keys_info(struct tang_keys_info** tki)
  124. {
  125. if (!tki || !*tki) {
  126. return;
  127. }
  128. free_tang_keys_info(*tki);
  129. *tki = NULL;
  130. }
  131. static struct tang_keys_info*
  132. new_tang_keys_info(void)
  133. {
  134. struct tang_keys_info* tki = calloc(1, sizeof(*tki));
  135. if (!tki) {
  136. return NULL;
  137. }
  138. tki->m_keys = json_array();
  139. tki->m_rotated_keys = json_array();
  140. tki->m_payload = json_array();
  141. tki->m_sign = json_array();
  142. if (!tki->m_keys || !tki->m_rotated_keys ||
  143. !tki->m_payload || !tki->m_sign) {
  144. free_tang_keys_info(tki);
  145. return NULL;
  146. }
  147. tki->m_keys_count = 0;
  148. return tki;
  149. }
  150. static int
  151. jwk_valid_for(const json_t* jwk, const char* use)
  152. {
  153. if (!jwk || !use) {
  154. return 0;
  155. }
  156. return jose_jwk_prm(NULL, jwk, false, use);
  157. }
  158. static int
  159. jwk_valid_for_signing_and_verifying(const json_t* jwk)
  160. {
  161. const char* uses[] = {"sign", "verify", NULL};
  162. int ret = 1;
  163. for (int i = 0; uses[i]; i++) {
  164. if (!jwk_valid_for(jwk, uses[i])) {
  165. ret = 0;
  166. break;
  167. }
  168. }
  169. return ret;
  170. }
  171. static int
  172. jwk_valid_for_signing(const json_t* jwk)
  173. {
  174. return jwk_valid_for(jwk, "sign");
  175. }
  176. static int
  177. jwk_valid_for_deriving_keys(const json_t* jwk)
  178. {
  179. return jwk_valid_for(jwk, "deriveKey");
  180. }
  181. static void
  182. cleanup_str(char** str)
  183. {
  184. if (!str || !*str) {
  185. return;
  186. }
  187. free(*str);
  188. *str = NULL;
  189. }
  190. static json_t*
  191. jwk_sign(const json_t* to_sign, const json_t* sig_keys)
  192. {
  193. if (!sig_keys || !json_is_array(sig_keys) || !json_is_array(to_sign)) {
  194. return NULL;
  195. }
  196. json_auto_t* to_sign_copy = json_deep_copy(to_sign);
  197. if (!jose_jwk_pub(NULL, to_sign_copy)) {
  198. fprintf(stderr, "Error removing private material from data to sign\n");
  199. return NULL;
  200. }
  201. json_auto_t* payload = json_pack("{s:O}", "keys", to_sign_copy);
  202. json_auto_t* sig_template = json_pack("{s:{s:s}}",
  203. "protected", "cty", "jwk-set+json");
  204. __attribute__ ((__cleanup__(cleanup_str))) char* data_to_sign = json_dumps(payload, 0);
  205. json_auto_t* jws = json_pack("{s:o}", "payload",
  206. jose_b64_enc(data_to_sign, strlen(data_to_sign)));
  207. if (!jose_jws_sig(NULL, jws, sig_template, sig_keys)) {
  208. fprintf(stderr, "Error trying to jose_jws_sign\n");
  209. return NULL;
  210. }
  211. return json_incref(jws);
  212. }
  213. static json_t*
  214. find_by_thp(struct tang_keys_info* tki, const char* target)
  215. {
  216. if (!tki) {
  217. return NULL;
  218. }
  219. json_auto_t* keys = json_deep_copy(tki->m_keys);
  220. json_array_extend(keys, tki->m_rotated_keys);
  221. size_t idx;
  222. json_t* jwk;
  223. const char** hashes = supported_hashes();
  224. json_array_foreach(keys, idx, jwk) {
  225. for (int i = 0; hashes[i]; i++) {
  226. __attribute__ ((__cleanup__(cleanup_str))) char* thumbprint = jwk_thumbprint(jwk, hashes[i]);
  227. if (!thumbprint || strcmp(thumbprint, target) != 0) {
  228. continue;
  229. }
  230. return json_incref(jwk);
  231. }
  232. }
  233. return NULL;
  234. }
  235. static int
  236. prepare_payload_and_sign(struct tang_keys_info* tki)
  237. {
  238. if (!tki) {
  239. return 0;
  240. }
  241. size_t idx;
  242. json_t* jwk;
  243. json_array_foreach(tki->m_keys, idx, jwk) {
  244. if (jwk_valid_for_signing_and_verifying(jwk)) {
  245. if (json_array_append(tki->m_sign, jwk) == -1) {
  246. continue;
  247. }
  248. if (json_array_append(tki->m_payload, jwk) == -1) {
  249. continue;
  250. }
  251. } else if (jwk_valid_for_deriving_keys(jwk)) {
  252. if (json_array_append(tki->m_payload, jwk) == -1) {
  253. continue;
  254. }
  255. }
  256. }
  257. if (json_array_size(tki->m_sign) == 0 || json_array_size(tki->m_payload) == 0) {
  258. return 0;
  259. }
  260. return 1;
  261. }
  262. static int
  263. create_new_keys(const char* jwkdir)
  264. {
  265. const char* alg[] = {"ES512", "ECMR", NULL};
  266. char path[PATH_MAX];
  267. for (int i = 0; alg[i] != NULL; i++) {
  268. json_auto_t* jwk = jwk_generate(alg[i]);
  269. if (!jwk) {
  270. return 0;
  271. }
  272. __attribute__ ((__cleanup__(cleanup_str))) char* thp = jwk_thumbprint(jwk, DEFAULT_THP_HASH);
  273. if (!thp) {
  274. return 0;
  275. }
  276. if (snprintf(path, PATH_MAX, "%s/%s.jwk", jwkdir, thp) < 0) {
  277. fprintf(stderr, "Unable to prepare variable with file full path (%s)\n", thp);
  278. return 0;
  279. }
  280. path[sizeof(path) - 1] = '\0';
  281. if (json_dump_file(jwk, path, 0) == -1) {
  282. fprintf(stderr, "Error saving JWK to file (%s)\n", path);
  283. return 0;
  284. }
  285. /* Set 0440 permission for the new key. */
  286. if (chmod(path, S_IRUSR | S_IRGRP) == -1) {
  287. fprintf(stderr, "Unable to set permissions for JWK file (%s)\n", path);
  288. return 0;
  289. }
  290. }
  291. return 1;
  292. }
  293. static struct tang_keys_info*
  294. load_keys(const char* jwkdir)
  295. {
  296. struct tang_keys_info* tki = new_tang_keys_info();
  297. if (!tki) {
  298. return NULL;
  299. }
  300. struct dirent* d;
  301. DIR* dir = opendir(jwkdir);
  302. if (!dir) {
  303. free_tang_keys_info(tki);
  304. return NULL;
  305. }
  306. char filepath[PATH_MAX];
  307. const char* pattern = ".jwk";
  308. while ((d = readdir(dir)) != NULL) {
  309. if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
  310. continue;
  311. }
  312. char* dot = strrchr(d->d_name, '.');
  313. if (!dot) {
  314. continue;
  315. }
  316. if (strcmp(dot, pattern) == 0) {
  317. /* Found a file with .jwk extension. */
  318. if (snprintf(filepath, PATH_MAX, "%s/%s", jwkdir, d->d_name) < 0) {
  319. fprintf(stderr, "Unable to prepare variable with file full path (%s); skipping\n", d->d_name);
  320. continue;
  321. }
  322. filepath[sizeof(filepath) - 1] = '\0';
  323. json_auto_t* json = json_load_file(filepath, 0, NULL);
  324. if (!json) {
  325. fprintf(stderr, "Invalid JSON file (%s); skipping\n", filepath);
  326. continue;
  327. }
  328. json_t* arr = tki->m_keys;
  329. if (d->d_name[0] == '.') {
  330. arr = tki->m_rotated_keys;
  331. tki->m_rotated_keys_count++;
  332. } else {
  333. tki->m_keys_count++;
  334. }
  335. if (json_array_append(arr, json) == -1) {
  336. fprintf(stderr, "Unable to append JSON (%s) to array; skipping\n", d->d_name);
  337. continue;
  338. }
  339. }
  340. }
  341. closedir(dir);
  342. return tki;
  343. }
  344. struct tang_keys_info*
  345. read_keys(const char* jwkdir)
  346. {
  347. struct tang_keys_info* tki = load_keys(jwkdir);
  348. if (!tki) {
  349. return NULL;
  350. }
  351. if (tki->m_keys_count == 0) {
  352. /* Let's attempt to create a new pair of keys. */
  353. free_tang_keys_info(tki);
  354. if (!create_new_keys(jwkdir)) {
  355. return NULL;
  356. }
  357. tki = load_keys(jwkdir);
  358. }
  359. if (!prepare_payload_and_sign(tki)) {
  360. free_tang_keys_info(tki);
  361. return NULL;
  362. }
  363. return tki;
  364. }
  365. json_t*
  366. find_jws(struct tang_keys_info* tki, const char* thp)
  367. {
  368. if (!tki) {
  369. return NULL;
  370. }
  371. if (thp == NULL) {
  372. /* Default advertisement. */
  373. json_auto_t* jws = jwk_sign(tki->m_payload, tki->m_sign);
  374. if (!jws) {
  375. return NULL;
  376. }
  377. return json_incref(jws);
  378. }
  379. json_auto_t* jwk = find_by_thp(tki, thp);
  380. if (!jwk_valid_for_signing(jwk)) {
  381. return NULL;
  382. }
  383. json_auto_t* sign = json_deep_copy(tki->m_sign);
  384. if (json_array_append(sign, jwk) == -1) {
  385. return NULL;
  386. }
  387. json_auto_t* jws = jwk_sign(tki->m_payload, sign);
  388. if (!jws) {
  389. return NULL;
  390. }
  391. return json_incref(jws);
  392. }
  393. json_t*
  394. find_jwk(struct tang_keys_info* tki, const char* thp)
  395. {
  396. if (!tki || !thp) {
  397. return NULL;
  398. }
  399. return find_by_thp(tki, thp);
  400. }