jwe.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010 - 2019 Andy Green <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to
  8. * deal in the Software without restriction, including without limitation the
  9. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. * sell copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. * IN THE SOFTWARE.
  23. */
  24. #include "private-lib-core.h"
  25. #include "private-lib-jose.h"
  26. #include "private-lib-jose-jwe.h"
  27. /*
  28. * Currently only support flattened or compact (implicitly single signature)
  29. */
  30. static const char * const jwe_json[] = {
  31. "protected",
  32. "iv",
  33. "ciphertext",
  34. "tag",
  35. "encrypted_key"
  36. };
  37. enum enum_jwe_complete_tokens {
  38. LWS_EJCT_PROTECTED,
  39. LWS_EJCT_IV,
  40. LWS_EJCT_CIPHERTEXT,
  41. LWS_EJCT_TAG,
  42. LWS_EJCT_RECIP_ENC_KEY,
  43. };
  44. /* parse a JWS complete or flattened JSON object */
  45. struct jwe_cb_args {
  46. struct lws_jws *jws;
  47. char *temp;
  48. int *temp_len;
  49. };
  50. static signed char
  51. lws_jwe_json_cb(struct lejp_ctx *ctx, char reason)
  52. {
  53. struct jwe_cb_args *args = (struct jwe_cb_args *)ctx->user;
  54. int n, m;
  55. if (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)
  56. return 0;
  57. switch (ctx->path_match - 1) {
  58. /* strings */
  59. case LWS_EJCT_PROTECTED: /* base64u: JOSE: must contain 'alg' */
  60. m = LJWS_JOSE;
  61. goto append_string;
  62. case LWS_EJCT_IV: /* base64u */
  63. m = LJWE_IV;
  64. goto append_string;
  65. case LWS_EJCT_CIPHERTEXT: /* base64u */
  66. m = LJWE_CTXT;
  67. goto append_string;
  68. case LWS_EJCT_TAG: /* base64u */
  69. m = LJWE_ATAG;
  70. goto append_string;
  71. case LWS_EJCT_RECIP_ENC_KEY: /* base64u */
  72. m = LJWE_EKEY;
  73. goto append_string;
  74. default:
  75. return -1;
  76. }
  77. return 0;
  78. append_string:
  79. if (*args->temp_len < ctx->npos) {
  80. lwsl_err("%s: out of parsing space\n", __func__);
  81. return -1;
  82. }
  83. /*
  84. * We keep both b64u and decoded in temp mapped using map / map_b64,
  85. * the jws signature is actually over the b64 content not the plaintext,
  86. * and we can't do it until we see the protected alg.
  87. */
  88. if (!args->jws->map_b64.buf[m]) {
  89. args->jws->map_b64.buf[m] = args->temp;
  90. args->jws->map_b64.len[m] = 0;
  91. }
  92. memcpy(args->temp, ctx->buf, ctx->npos);
  93. args->temp += ctx->npos;
  94. *args->temp_len -= ctx->npos;
  95. args->jws->map_b64.len[m] += ctx->npos;
  96. if (reason == LEJPCB_VAL_STR_END) {
  97. args->jws->map.buf[m] = args->temp;
  98. n = lws_b64_decode_string_len(
  99. (const char *)args->jws->map_b64.buf[m],
  100. args->jws->map_b64.len[m],
  101. (char *)args->temp, *args->temp_len);
  102. if (n < 0) {
  103. lwsl_err("%s: b64 decode failed\n", __func__);
  104. return -1;
  105. }
  106. args->temp += n;
  107. *args->temp_len -= n;
  108. args->jws->map.len[m] = n;
  109. }
  110. return 0;
  111. }
  112. int
  113. lws_jwe_json_parse(struct lws_jwe *jwe, const uint8_t *buf, int len,
  114. char *temp, int *temp_len)
  115. {
  116. struct jwe_cb_args args;
  117. struct lejp_ctx jctx;
  118. int m = 0;
  119. args.jws = &jwe->jws;
  120. args.temp = temp;
  121. args.temp_len = temp_len;
  122. lejp_construct(&jctx, lws_jwe_json_cb, &args, jwe_json,
  123. LWS_ARRAY_SIZE(jwe_json));
  124. m = lejp_parse(&jctx, (uint8_t *)buf, len);
  125. lejp_destruct(&jctx);
  126. if (m < 0) {
  127. lwsl_notice("%s: parse returned %d\n", __func__, m);
  128. return -1;
  129. }
  130. return 0;
  131. }
  132. void
  133. lws_jwe_init(struct lws_jwe *jwe, struct lws_context *context)
  134. {
  135. lws_jose_init(&jwe->jose);
  136. lws_jws_init(&jwe->jws, &jwe->jwk, context);
  137. memset(&jwe->jwk, 0, sizeof(jwe->jwk));
  138. jwe->recip = 0;
  139. jwe->cek_valid = 0;
  140. }
  141. void
  142. lws_jwe_destroy(struct lws_jwe *jwe)
  143. {
  144. lws_jws_destroy(&jwe->jws);
  145. lws_jose_destroy(&jwe->jose);
  146. lws_jwk_destroy(&jwe->jwk);
  147. /* cleanse the CEK we held on to in case of further encryptions of it */
  148. lws_explicit_bzero(jwe->cek, sizeof(jwe->cek));
  149. jwe->cek_valid = 0;
  150. }
  151. static uint8_t *
  152. be32(uint32_t i, uint32_t *p32)
  153. {
  154. uint8_t *p = (uint8_t *)p32;
  155. *p++ = (i >> 24) & 0xff;
  156. *p++ = (i >> 16) & 0xff;
  157. *p++ = (i >> 8) & 0xff;
  158. *p++ = i & 0xff;
  159. return (uint8_t *)p32;
  160. }
  161. /*
  162. * The key derivation process derives the agreed-upon key from the
  163. * shared secret Z established through the ECDH algorithm, per
  164. * Section 6.2.2.2 of [NIST.800-56A].
  165. *
  166. *
  167. * Key derivation is performed using the Concat KDF, as defined in
  168. * Section 5.8.1 of [NIST.800-56A], where the Digest Method is SHA-256.
  169. *
  170. * out must be prepared to take at least 32 bytes or the encrypted key size,
  171. * whichever is larger.
  172. */
  173. int
  174. lws_jwa_concat_kdf(struct lws_jwe *jwe, int direct, uint8_t *out,
  175. const uint8_t *shared_secret, int sslen)
  176. {
  177. int hlen = (int)lws_genhash_size(LWS_GENHASH_TYPE_SHA256), aidlen;
  178. struct lws_genhash_ctx hash_ctx;
  179. uint32_t ctr = 1, t;
  180. const char *aid;
  181. if (!jwe->jose.enc_alg || !jwe->jose.alg)
  182. return -1;
  183. /*
  184. * Hash
  185. *
  186. * AlgorithmID || PartyUInfo || PartyVInfo
  187. * {|| SuppPubInfo }{|| SuppPrivInfo }
  188. *
  189. * AlgorithmID
  190. *
  191. * The AlgorithmID value is of the form Datalen || Data, where Data
  192. * is a variable-length string of zero or more octets, and Datalen is
  193. * a fixed-length, big-endian 32-bit counter that indicates the
  194. * length (in octets) of Data. In the Direct Key Agreement case,
  195. * Data is set to the octets of the ASCII representation of the "enc"
  196. * Header Parameter value. In the Key Agreement with Key Wrapping
  197. * case, Data is set to the octets of the ASCII representation of the
  198. * "alg" (algorithm) Header Parameter value.
  199. */
  200. aid = direct ? jwe->jose.enc_alg->alg : jwe->jose.alg->alg;
  201. aidlen = (int)strlen(aid);
  202. /*
  203. * PartyUInfo (PartyVInfo is the same deal)
  204. *
  205. * The PartyUInfo value is of the form Datalen || Data, where Data is
  206. * a variable-length string of zero or more octets, and Datalen is a
  207. * fixed-length, big-endian 32-bit counter that indicates the length
  208. * (in octets) of Data. If an "apu" (agreement PartyUInfo) Header
  209. * Parameter is present, Data is set to the result of base64url
  210. * decoding the "apu" value and Datalen is set to the number of
  211. * octets in Data. Otherwise, Datalen is set to 0 and Data is set to
  212. * the empty octet sequence
  213. *
  214. * SuppPubInfo
  215. *
  216. * This is set to the keydatalen represented as a 32-bit big-endian
  217. * integer.
  218. *
  219. * keydatalen
  220. *
  221. * This is set to the number of bits in the desired output key. For
  222. * "ECDH-ES", this is length of the key used by the "enc" algorithm.
  223. * For "ECDH-ES+A128KW", "ECDH-ES+A192KW", and "ECDH-ES+A256KW", this
  224. * is 128, 192, and 256, respectively.
  225. *
  226. * Compute Hash i = H(counter || Z || OtherInfo).
  227. *
  228. * We must iteratively hash over key material that's larger than
  229. * one hash output size (256b for SHA-256)
  230. */
  231. while (ctr <= (uint32_t)((jwe->jose.enc_alg->keybits_fixed + (hlen - 1)) / hlen)) {
  232. /*
  233. * Key derivation is performed using the Concat KDF, as defined
  234. * in Section 5.8.1 of [NIST.800-56A], where the Digest Method
  235. * is SHA-256.
  236. */
  237. if (lws_genhash_init(&hash_ctx, LWS_GENHASH_TYPE_SHA256))
  238. return -1;
  239. if (/* counter */
  240. lws_genhash_update(&hash_ctx, be32(ctr++, &t), 4) ||
  241. /* Z */
  242. lws_genhash_update(&hash_ctx, shared_secret, sslen) ||
  243. /* other info */
  244. lws_genhash_update(&hash_ctx, be32((uint32_t)strlen(aid), &t), 4) ||
  245. lws_genhash_update(&hash_ctx, aid, aidlen) ||
  246. lws_genhash_update(&hash_ctx,
  247. be32(jwe->jose.e[LJJHI_APU].len, &t), 4) ||
  248. lws_genhash_update(&hash_ctx, jwe->jose.e[LJJHI_APU].buf,
  249. jwe->jose.e[LJJHI_APU].len) ||
  250. lws_genhash_update(&hash_ctx,
  251. be32(jwe->jose.e[LJJHI_APV].len, &t), 4) ||
  252. lws_genhash_update(&hash_ctx, jwe->jose.e[LJJHI_APV].buf,
  253. jwe->jose.e[LJJHI_APV].len) ||
  254. lws_genhash_update(&hash_ctx,
  255. be32(jwe->jose.enc_alg->keybits_fixed, &t),
  256. 4) ||
  257. lws_genhash_destroy(&hash_ctx, out)) {
  258. lwsl_err("%s: fail\n", __func__);
  259. lws_genhash_destroy(&hash_ctx, NULL);
  260. return -1;
  261. }
  262. out += hlen;
  263. }
  264. return 0;
  265. }
  266. void
  267. lws_jwe_be64(uint64_t c, uint8_t *p8)
  268. {
  269. int n;
  270. for (n = 56; n >= 0; n -= 8)
  271. *p8++ = (uint8_t)((c >> n) & 0xff);
  272. }
  273. int
  274. lws_jwe_auth_and_decrypt(struct lws_jwe *jwe, char *temp, int *temp_len)
  275. {
  276. int valid_aescbc_hmac, valid_aesgcm;
  277. char dotstar[96];
  278. if (lws_jwe_parse_jose(&jwe->jose, jwe->jws.map.buf[LJWS_JOSE],
  279. jwe->jws.map.len[LJWS_JOSE],
  280. temp, temp_len) < 0) {
  281. lws_strnncpy(dotstar, jwe->jws.map.buf[LJWS_JOSE],
  282. jwe->jws.map.len[LJWS_JOSE], sizeof(dotstar));
  283. lwsl_err("%s: JOSE parse '%s' failed\n", __func__, dotstar);
  284. return -1;
  285. }
  286. if (!jwe->jose.alg) {
  287. lws_strnncpy(dotstar, jwe->jws.map.buf[LJWS_JOSE],
  288. jwe->jws.map.len[LJWS_JOSE], sizeof(dotstar));
  289. lwsl_err("%s: no jose.alg: %s\n", __func__, dotstar);
  290. return -1;
  291. }
  292. valid_aescbc_hmac = jwe->jose.enc_alg &&
  293. jwe->jose.enc_alg->algtype_crypto == LWS_JOSE_ENCTYPE_AES_CBC &&
  294. (jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA256 ||
  295. jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA384 ||
  296. jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA512);
  297. valid_aesgcm = jwe->jose.enc_alg &&
  298. jwe->jose.enc_alg->algtype_crypto == LWS_JOSE_ENCTYPE_AES_GCM;
  299. if ((jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_RSASSA_PKCS1_1_5 ||
  300. jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_RSASSA_PKCS1_OAEP)) {
  301. /* RSA + AESCBC */
  302. if (valid_aescbc_hmac)
  303. return lws_jwe_auth_and_decrypt_rsa_aes_cbc_hs(jwe);
  304. /* RSA + AESGCM */
  305. if (valid_aesgcm)
  306. return lws_jwe_auth_and_decrypt_rsa_aes_gcm(jwe);
  307. }
  308. /* AESKW */
  309. if (jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_AES_ECB &&
  310. valid_aescbc_hmac)
  311. return lws_jwe_auth_and_decrypt_aeskw_cbc_hs(jwe);
  312. /* ECDH-ES + AESKW */
  313. if (jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_ECDHES &&
  314. valid_aescbc_hmac)
  315. return lws_jwe_auth_and_decrypt_ecdh_cbc_hs(jwe,
  316. temp, temp_len);
  317. lwsl_err("%s: unknown cipher alg combo %s / %s\n", __func__,
  318. jwe->jose.alg->alg, jwe->jose.enc_alg ?
  319. jwe->jose.enc_alg->alg : "NULL");
  320. return -1;
  321. }
  322. int
  323. lws_jwe_encrypt(struct lws_jwe *jwe, char *temp, int *temp_len)
  324. {
  325. int valid_aescbc_hmac, valid_aesgcm, ot = *temp_len, ret = -1;
  326. if (jwe->jose.recipients >= (int)LWS_ARRAY_SIZE(jwe->jose.recipient)) {
  327. lwsl_err("%s: max recipients reached\n", __func__);
  328. return -1;
  329. }
  330. valid_aesgcm = jwe->jose.enc_alg &&
  331. jwe->jose.enc_alg->algtype_crypto == LWS_JOSE_ENCTYPE_AES_GCM;
  332. if (lws_jwe_parse_jose(&jwe->jose, jwe->jws.map.buf[LJWS_JOSE],
  333. jwe->jws.map.len[LJWS_JOSE], temp, temp_len) < 0) {
  334. lwsl_err("%s: JOSE parse failed\n", __func__);
  335. goto bail;
  336. }
  337. temp += ot - *temp_len;
  338. valid_aescbc_hmac = jwe->jose.enc_alg &&
  339. jwe->jose.enc_alg->algtype_crypto == LWS_JOSE_ENCTYPE_AES_CBC &&
  340. (jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA256 ||
  341. jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA384 ||
  342. jwe->jose.enc_alg->hmac_type == LWS_GENHMAC_TYPE_SHA512);
  343. if ((jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_RSASSA_PKCS1_1_5 ||
  344. jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_RSASSA_PKCS1_OAEP)) {
  345. /* RSA + AESCBC */
  346. if (valid_aescbc_hmac) {
  347. ret = lws_jwe_encrypt_rsa_aes_cbc_hs(jwe, temp, temp_len);
  348. goto bail;
  349. }
  350. /* RSA + AESGCM */
  351. if (valid_aesgcm) {
  352. ret = lws_jwe_encrypt_rsa_aes_gcm(jwe, temp, temp_len);
  353. goto bail;
  354. }
  355. }
  356. /* AESKW */
  357. if (jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_AES_ECB &&
  358. valid_aescbc_hmac) {
  359. ret = lws_jwe_encrypt_aeskw_cbc_hs(jwe, temp, temp_len);
  360. goto bail;
  361. }
  362. /* ECDH-ES + AESKW */
  363. if (jwe->jose.alg->algtype_signing == LWS_JOSE_ENCTYPE_ECDHES &&
  364. valid_aescbc_hmac) {
  365. ret = lws_jwe_encrypt_ecdh_cbc_hs(jwe, temp, temp_len);
  366. goto bail;
  367. }
  368. lwsl_err("%s: unknown cipher alg combo %s / %s\n", __func__,
  369. jwe->jose.alg->alg, jwe->jose.enc_alg ?
  370. jwe->jose.enc_alg->alg : "NULL");
  371. bail:
  372. if (ret)
  373. memset(&jwe->jose.recipient[jwe->jose.recipients], 0,
  374. sizeof(jwe->jose.recipient[0]));
  375. else
  376. jwe->jose.recipients++;
  377. return ret;
  378. }
  379. /*
  380. * JWE Compact Serialization consists of
  381. *
  382. * BASE64URL(UTF8(JWE Protected Header)) || '.' ||
  383. * BASE64URL(JWE Encrypted Key) || '.' ||
  384. * BASE64URL(JWE Initialization Vector) || '.' ||
  385. * BASE64URL(JWE Ciphertext) || '.' ||
  386. * BASE64URL(JWE Authentication Tag)
  387. *
  388. *
  389. * In the JWE Compact Serialization, no JWE Shared Unprotected Header or
  390. * JWE Per-Recipient Unprotected Header are used. In this case, the
  391. * JOSE Header and the JWE Protected Header are the same.
  392. *
  393. * Therefore:
  394. *
  395. * - Everything needed in the header part must go in the protected header
  396. * (it's the only part emitted). We expect the caller did this.
  397. *
  398. * - You can't emit Compact representation if there are multiple recipients
  399. */
  400. int
  401. lws_jwe_render_compact(struct lws_jwe *jwe, char *out, size_t out_len)
  402. {
  403. size_t orig = out_len;
  404. int n;
  405. if (jwe->jose.recipients > 1) {
  406. lwsl_notice("%s: can't issue compact representation for"
  407. " multiple recipients (%d)\n", __func__,
  408. jwe->jose.recipients);
  409. return -1;
  410. }
  411. n = lws_jws_base64_enc(jwe->jws.map.buf[LJWS_JOSE],
  412. jwe->jws.map.len[LJWS_JOSE], out, out_len);
  413. if (n < 0 || (int)out_len == n) {
  414. lwsl_info("%s: unable to encode JOSE\n", __func__);
  415. return -1;
  416. }
  417. out += n;
  418. *out++ = '.';
  419. out_len -= n + 1;
  420. n = lws_jws_base64_enc(jwe->jws.map.buf[LJWE_EKEY],
  421. jwe->jws.map.len[LJWE_EKEY], out, out_len);
  422. if (n < 0 || (int)out_len == n) {
  423. lwsl_info("%s: unable to encode EKEY\n", __func__);
  424. return -1;
  425. }
  426. out += n;
  427. *out++ = '.';
  428. out_len -= n + 1;
  429. n = lws_jws_base64_enc(jwe->jws.map.buf[LJWE_IV],
  430. jwe->jws.map.len[LJWE_IV], out, out_len);
  431. if (n < 0 || (int)out_len == n) {
  432. lwsl_info("%s: unable to encode IV\n", __func__);
  433. return -1;
  434. }
  435. out += n;
  436. *out++ = '.';
  437. out_len -= n + 1;
  438. n = lws_jws_base64_enc(jwe->jws.map.buf[LJWE_CTXT],
  439. jwe->jws.map.len[LJWE_CTXT], out, out_len);
  440. if (n < 0 || (int)out_len == n) {
  441. lwsl_info("%s: unable to encode CTXT\n", __func__);
  442. return -1;
  443. }
  444. out += n;
  445. *out++ = '.';
  446. out_len -= n + 1;
  447. n = lws_jws_base64_enc(jwe->jws.map.buf[LJWE_ATAG],
  448. jwe->jws.map.len[LJWE_ATAG], out, out_len);
  449. if (n < 0 || (int)out_len == n) {
  450. lwsl_info("%s: unable to encode ATAG\n", __func__);
  451. return -1;
  452. }
  453. out += n;
  454. *out++ = '\0';
  455. out_len -= n;
  456. return (int)(orig - out_len);
  457. }
  458. int
  459. lws_jwe_create_packet(struct lws_jwe *jwe, const char *payload, size_t len,
  460. const char *nonce, char *out, size_t out_len,
  461. struct lws_context *context)
  462. {
  463. char *buf, *start, *p, *end, *p1, *end1;
  464. struct lws_jws jws;
  465. int n, m;
  466. lws_jws_init(&jws, &jwe->jwk, context);
  467. /*
  468. * This buffer is local to the function, the actual output is prepared
  469. * into out. Only the plaintext protected header
  470. * (which contains the public key, 512 bytes for 4096b) goes in
  471. * here temporarily.
  472. */
  473. n = LWS_PRE + 2048;
  474. buf = malloc(n);
  475. if (!buf) {
  476. lwsl_notice("%s: malloc %d failed\n", __func__, n);
  477. return -1;
  478. }
  479. p = start = buf + LWS_PRE;
  480. end = buf + n - LWS_PRE - 1;
  481. /*
  482. * temporary JWS protected header plaintext
  483. */
  484. if (!jwe->jose.alg || !jwe->jose.alg->alg)
  485. goto bail;
  486. p += lws_snprintf(p, lws_ptr_diff(end, p), "{\"alg\":\"%s\",\"jwk\":",
  487. jwe->jose.alg->alg);
  488. m = lws_ptr_diff(end, p);
  489. n = lws_jwk_export(&jwe->jwk, 0, p, &m);
  490. if (n < 0) {
  491. lwsl_notice("failed to export jwk\n");
  492. goto bail;
  493. }
  494. p += n;
  495. p += lws_snprintf(p, end - p, ",\"nonce\":\"%s\"}", nonce);
  496. /*
  497. * prepare the signed outer JSON with all the parts in
  498. */
  499. p1 = out;
  500. end1 = out + out_len - 1;
  501. p1 += lws_snprintf(p1, end1 - p1, "{\"protected\":\"");
  502. jws.map_b64.buf[LJWS_JOSE] = p1;
  503. n = lws_jws_base64_enc(start, p - start, p1, end1 - p1);
  504. if (n < 0) {
  505. lwsl_notice("%s: failed to encode protected\n", __func__);
  506. goto bail;
  507. }
  508. jws.map_b64.len[LJWS_JOSE] = n;
  509. p1 += n;
  510. p1 += lws_snprintf(p1, end1 - p1, "\",\"payload\":\"");
  511. jws.map_b64.buf[LJWS_PYLD] = p1;
  512. n = lws_jws_base64_enc(payload, len, p1, end1 - p1);
  513. if (n < 0) {
  514. lwsl_notice("%s: failed to encode payload\n", __func__);
  515. goto bail;
  516. }
  517. jws.map_b64.len[LJWS_PYLD] = n;
  518. p1 += n;
  519. p1 += lws_snprintf(p1, end1 - p1, "\",\"header\":\"");
  520. jws.map_b64.buf[LJWS_UHDR] = p1;
  521. n = lws_jws_base64_enc(payload, len, p1, end1 - p1);
  522. if (n < 0) {
  523. lwsl_notice("%s: failed to encode payload\n", __func__);
  524. goto bail;
  525. }
  526. jws.map_b64.len[LJWS_UHDR] = n;
  527. p1 += n;
  528. p1 += lws_snprintf(p1, end1 - p1, "\",\"signature\":\"");
  529. /*
  530. * taking the b64 protected header and the b64 payload, sign them
  531. * and place the signature into the packet
  532. */
  533. n = lws_jws_sign_from_b64(&jwe->jose, &jws, p1, end1 - p1);
  534. if (n < 0) {
  535. lwsl_notice("sig gen failed\n");
  536. goto bail;
  537. }
  538. jws.map_b64.buf[LJWS_SIG] = p1;
  539. jws.map_b64.len[LJWS_SIG] = n;
  540. p1 += n;
  541. p1 += lws_snprintf(p1, end1 - p1, "\"}");
  542. free(buf);
  543. return lws_ptr_diff(p1, out);
  544. bail:
  545. lws_jws_destroy(&jws);
  546. free(buf);
  547. return -1;
  548. }
  549. static const char *protected_en[] = {
  550. "encrypted_key", "aad", "iv", "ciphertext", "tag"
  551. };
  552. static int protected_idx[] = {
  553. LJWE_EKEY, LJWE_AAD, LJWE_IV, LJWE_CTXT, LJWE_ATAG
  554. };
  555. /*
  556. * The complete JWE may look something like this:
  557. *
  558. * {
  559. * "protected":
  560. * "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
  561. * "unprotected":
  562. * {"jku":"https://server.example.com/keys.jwks"},
  563. * "recipients":[
  564. * {"header":
  565. * {"alg":"RSA1_5","kid":"2011-04-29"},
  566. * "encrypted_key":
  567. * "UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-
  568. * kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKx
  569. * GHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3
  570. * YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPh
  571. * cCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPg
  572. * wCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A"},
  573. * {"header":
  574. * {"alg":"A128KW","kid":"7"},
  575. * "encrypted_key":
  576. * "6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ"}],
  577. * "iv":
  578. * "AxY8DCtDaGlsbGljb3RoZQ",
  579. * "ciphertext":
  580. * "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",
  581. * "tag":
  582. * "Mz-VPPyU4RlcuYv1IwIvzw"
  583. * }
  584. *
  585. * The flattened JWE ends up like this
  586. *
  587. * {
  588. * "protected": "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",
  589. * "unprotected": {"jku":"https://server.example.com/keys.jwks"},
  590. * "header": {"alg":"A128KW","kid":"7"},
  591. * "encrypted_key": "6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ",
  592. * "iv": "AxY8DCtDaGlsbGljb3RoZQ",
  593. * "ciphertext": "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",
  594. * "tag": "Mz-VPPyU4RlcuYv1IwIvzw"
  595. * }
  596. *
  597. * {
  598. * "protected":"<integrity-protected header contents>",
  599. * "unprotected":<non-integrity-protected header contents>,
  600. * "header":<more non-integrity-protected header contents>,
  601. * "encrypted_key":"<encrypted key contents>",
  602. * "aad":"<additional authenticated data contents>",
  603. * "iv":"<initialization vector contents>",
  604. * "ciphertext":"<ciphertext contents>",
  605. * "tag":"<authentication tag contents>"
  606. * }
  607. */
  608. int
  609. lws_jwe_render_flattened(struct lws_jwe *jwe, char *out, size_t out_len)
  610. {
  611. char buf[3072], *p1, *end1, protected[128];
  612. int m, n, jlen, plen;
  613. jlen = lws_jose_render(&jwe->jose, jwe->jws.jwk, buf, sizeof(buf));
  614. if (jlen < 0) {
  615. lwsl_err("%s: lws_jose_render failed\n", __func__);
  616. return -1;
  617. }
  618. /*
  619. * prepare the JWE JSON with all the parts in
  620. */
  621. p1 = out;
  622. end1 = out + out_len - 1;
  623. /*
  624. * The protected header is b64url encoding of the JOSE header part
  625. */
  626. plen = lws_snprintf(protected, sizeof(protected),
  627. "{\"alg\":\"%s\",\"enc\":\"%s\"}",
  628. jwe->jose.alg->alg, jwe->jose.enc_alg->alg);
  629. p1 += lws_snprintf(p1, end1 - p1, "{\"protected\":\"");
  630. jwe->jws.map_b64.buf[LJWS_JOSE] = p1;
  631. n = lws_jws_base64_enc(protected, plen, p1, end1 - p1);
  632. if (n < 0) {
  633. lwsl_notice("%s: failed to encode protected\n", __func__);
  634. goto bail;
  635. }
  636. jwe->jws.map_b64.len[LJWS_JOSE] = n;
  637. p1 += n;
  638. /* unprotected not supported atm */
  639. p1 += lws_snprintf(p1, end1 - p1, "\",\n\"header\":");
  640. lws_strnncpy(p1, buf, jlen, end1 - p1);
  641. p1 += strlen(p1);
  642. for (m = 0; m < (int)LWS_ARRAY_SIZE(protected_en); m++)
  643. if (jwe->jws.map.buf[protected_idx[m]]) {
  644. p1 += lws_snprintf(p1, end1 - p1, ",\n\"%s\":\"",
  645. protected_en[m]);
  646. //jwe->jws.map_b64.buf[protected_idx[m]] = p1;
  647. n = lws_jws_base64_enc(jwe->jws.map.buf[protected_idx[m]],
  648. jwe->jws.map.len[protected_idx[m]],
  649. p1, end1 - p1);
  650. if (n < 0) {
  651. lwsl_notice("%s: failed to encode %s\n",
  652. __func__, protected_en[m]);
  653. goto bail;
  654. }
  655. //jwe->jws.map_b64.len[protected_idx[m]] = n;
  656. p1 += n;
  657. p1 += lws_snprintf(p1, end1 - p1, "\"");
  658. }
  659. p1 += lws_snprintf(p1, end1 - p1, "\n}\n");
  660. return lws_ptr_diff(p1, out);
  661. bail:
  662. lws_jws_destroy(&jwe->jws);
  663. return -1;
  664. }