keys.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. /* Set default umask for file creation. */
  268. umask(0337);
  269. for (int i = 0; alg[i] != NULL; i++) {
  270. json_auto_t* jwk = jwk_generate(alg[i]);
  271. if (!jwk) {
  272. return 0;
  273. }
  274. __attribute__ ((__cleanup__(cleanup_str))) char* thp = jwk_thumbprint(jwk, DEFAULT_THP_HASH);
  275. if (!thp) {
  276. return 0;
  277. }
  278. if (snprintf(path, PATH_MAX, "%s/%s.jwk", jwkdir, thp) < 0) {
  279. fprintf(stderr, "Unable to prepare variable with file full path (%s)\n", thp);
  280. return 0;
  281. }
  282. path[sizeof(path) - 1] = '\0';
  283. if (json_dump_file(jwk, path, 0) == -1) {
  284. fprintf(stderr, "Error saving JWK to file (%s)\n", path);
  285. return 0;
  286. }
  287. /* Set 0440 permission for the new key. */
  288. if (chmod(path, S_IRUSR | S_IRGRP) == -1) {
  289. fprintf(stderr, "Unable to set permissions for JWK file (%s)\n", path);
  290. return 0;
  291. }
  292. }
  293. return 1;
  294. }
  295. static struct tang_keys_info*
  296. load_keys(const char* jwkdir)
  297. {
  298. struct tang_keys_info* tki = new_tang_keys_info();
  299. if (!tki) {
  300. return NULL;
  301. }
  302. struct dirent* d;
  303. DIR* dir = opendir(jwkdir);
  304. if (!dir) {
  305. free_tang_keys_info(tki);
  306. return NULL;
  307. }
  308. char filepath[PATH_MAX];
  309. const char* pattern = ".jwk";
  310. while ((d = readdir(dir)) != NULL) {
  311. if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
  312. continue;
  313. }
  314. char* dot = strrchr(d->d_name, '.');
  315. if (!dot) {
  316. continue;
  317. }
  318. if (strcmp(dot, pattern) == 0) {
  319. /* Found a file with .jwk extension. */
  320. if (snprintf(filepath, PATH_MAX, "%s/%s", jwkdir, d->d_name) < 0) {
  321. fprintf(stderr, "Unable to prepare variable with file full path (%s); skipping\n", d->d_name);
  322. continue;
  323. }
  324. filepath[sizeof(filepath) - 1] = '\0';
  325. json_error_t error;
  326. json_auto_t* json = json_load_file(filepath, 0, &error);
  327. if (!json) {
  328. fprintf(stderr, "Cannot load JSON file (%s); skipping\n", filepath);
  329. fprintf(stderr, "error text %s, line %d, col %d, pos %d\n",
  330. error.text, error.line, error.column, error.position);
  331. continue;
  332. }
  333. json_t* arr = tki->m_keys;
  334. if (d->d_name[0] == '.') {
  335. arr = tki->m_rotated_keys;
  336. tki->m_rotated_keys_count++;
  337. } else {
  338. tki->m_keys_count++;
  339. }
  340. if (json_array_append(arr, json) == -1) {
  341. fprintf(stderr, "Unable to append JSON (%s) to array; skipping\n", d->d_name);
  342. continue;
  343. }
  344. }
  345. }
  346. closedir(dir);
  347. return tki;
  348. }
  349. struct tang_keys_info*
  350. read_keys(const char* jwkdir)
  351. {
  352. struct tang_keys_info* tki = load_keys(jwkdir);
  353. if (!tki) {
  354. return NULL;
  355. }
  356. if (tki->m_keys_count == 0) {
  357. /* Let's attempt to create a new pair of keys. */
  358. free_tang_keys_info(tki);
  359. if (!create_new_keys(jwkdir)) {
  360. return NULL;
  361. }
  362. tki = load_keys(jwkdir);
  363. }
  364. if (!prepare_payload_and_sign(tki)) {
  365. free_tang_keys_info(tki);
  366. return NULL;
  367. }
  368. return tki;
  369. }
  370. json_t*
  371. find_jws(struct tang_keys_info* tki, const char* thp)
  372. {
  373. if (!tki) {
  374. return NULL;
  375. }
  376. if (thp == NULL) {
  377. /* Default advertisement. */
  378. json_auto_t* jws = jwk_sign(tki->m_payload, tki->m_sign);
  379. if (!jws) {
  380. return NULL;
  381. }
  382. return json_incref(jws);
  383. }
  384. json_auto_t* jwk = find_by_thp(tki, thp);
  385. if (!jwk_valid_for_signing(jwk)) {
  386. return NULL;
  387. }
  388. json_auto_t* sign = json_deep_copy(tki->m_sign);
  389. if (json_array_append(sign, jwk) == -1) {
  390. return NULL;
  391. }
  392. json_auto_t* jws = jwk_sign(tki->m_payload, sign);
  393. if (!jws) {
  394. return NULL;
  395. }
  396. return json_incref(jws);
  397. }
  398. json_t*
  399. find_jwk(struct tang_keys_info* tki, const char* thp)
  400. {
  401. if (!tki || !thp) {
  402. return NULL;
  403. }
  404. return find_by_thp(tki, thp);
  405. }