keys.c 11 KB

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