• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * libwebsockets - small server side websockets and web server implementation
3  *
4  * Copyright (C) 2010 - 2019 Andy Green <andy@warmcat.com>
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 
25 #include "private-lib-core.h"
26 #include "private-lib-jose.h"
27 
28 #if !defined(LWS_PLAT_OPTEE) && !defined(OPTEE_DEV_KIT)
29 #include <fcntl.h>
30 #endif
31 
32 static const char * const kty_names[] = {
33 	"unknown",	/* LWS_GENCRYPTO_KTY_UNKNOWN */
34 	"oct",		/* LWS_GENCRYPTO_KTY_OCT */
35 	"RSA",		/* LWS_GENCRYPTO_KTY_RSA */
36 	"EC"		/* LWS_GENCRYPTO_KTY_EC */
37 };
38 
39 /*
40  * These are the entire legal token set for names in jwk.
41  *
42  * The first version is used to parse a detached single jwk that don't have any
43  * parent JSON context.  The second version is used to parse full jwk objects
44  * that has a "keys": [ ] array containing the keys.
45  */
46 
47 static const char * const jwk_tok[] = {
48 	"keys[]",			/* dummy */
49 	"e", "n", "d", "p", "q", "dp", "dq", "qi", /* RSA */
50 	"kty",				/* generic */
51 	"k",				/* symmetric key data */
52 	"crv", "x", "y",		/* EC (also "D") */
53 	"kid",				/* generic */
54 	"use"				/* mutually exclusive with "key_ops" */,
55 	"key_ops"			/* mutually exclusive with "use" */,
56 	"x5c",				/* generic */
57 	"alg"				/* generic */
58 }, * const jwk_outer_tok[] = {
59 	"keys[]",
60 	"keys[].e", "keys[].n", "keys[].d", "keys[].p", "keys[].q", "keys[].dp",
61 	"keys[].dq", "keys[].qi",
62 
63 	"keys[].kty", "keys[].k",		/* generic */
64 	"keys[].crv", "keys[].x", "keys[].y",	/* EC (also "D") */
65 	"keys[].kid", "keys[].use"	/* mutually exclusive with "key_ops" */,
66 	"keys[].key_ops",		/* mutually exclusive with "use" */
67 	"keys[].x5c", "keys[].alg"
68 };
69 
70 /* information about each token declared above */
71 
72 #define F_M	(1 <<  9)	/* Mandatory for key type */
73 #define F_B64	(1 << 10)	/* Base64 coded octets */
74 #define F_B64U	(1 << 11)	/* Base64 Url coded octets */
75 #define F_META	(1 << 12)	/* JWK key metainformation */
76 #define F_RSA	(1 << 13)	/* RSA key */
77 #define F_EC	(1 << 14)	/* Elliptic curve key */
78 #define F_OCT	(1 << 15)	/* octet key */
79 
80 static unsigned short tok_map[] = {
81 	F_RSA | F_EC | F_OCT | F_META |		 0xff,
82 	F_RSA |				F_B64U | F_M | LWS_GENCRYPTO_RSA_KEYEL_E,
83 	F_RSA |				F_B64U | F_M | LWS_GENCRYPTO_RSA_KEYEL_N,
84 	F_RSA | F_EC |			F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_D,
85 	F_RSA |				F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_P,
86 	F_RSA |				F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_Q,
87 	F_RSA |				F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_DP,
88 	F_RSA |				F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_DQ,
89 	F_RSA |				F_B64U |       LWS_GENCRYPTO_RSA_KEYEL_QI,
90 
91 	F_RSA | F_EC | F_OCT | F_META |		 F_M | JWK_META_KTY,
92 		       F_OCT |		F_B64U | F_M | LWS_GENCRYPTO_OCT_KEYEL_K,
93 
94 		F_EC |				 F_M | LWS_GENCRYPTO_EC_KEYEL_CRV,
95 		F_EC |			F_B64U | F_M | LWS_GENCRYPTO_EC_KEYEL_X,
96 		F_EC |			F_B64U | F_M | LWS_GENCRYPTO_EC_KEYEL_Y,
97 
98 	F_RSA | F_EC | F_OCT | F_META |		       JWK_META_KID,
99 	F_RSA | F_EC | F_OCT | F_META |		       JWK_META_USE,
100 
101 	F_RSA | F_EC | F_OCT | F_META |		       JWK_META_KEY_OPS,
102 	F_RSA | F_EC | F_OCT | F_META | F_B64 |	       JWK_META_X5C,
103 	F_RSA | F_EC | F_OCT | F_META |		       JWK_META_ALG,
104 };
105 
106 static const char *meta_names[] = {
107 	"kty", "kid", "use", "key_ops", "x5c", "alg"
108 };
109 
110 struct lexico {
111 	const char *name;
112 	int idx;
113 	char meta;
114 } lexico_ec[] =  {
115 	{ "alg",	JWK_META_ALG,			1 },
116 	{ "crv",	LWS_GENCRYPTO_EC_KEYEL_CRV,	0 },
117 	{ "d",		LWS_GENCRYPTO_EC_KEYEL_D,	2 | 0 },
118 	{ "key_ops",	JWK_META_KEY_OPS,		1 },
119 	{ "kid",	JWK_META_KID,			1 },
120 	{ "kty",	JWK_META_KTY,			1 },
121 	{ "use",	JWK_META_USE,			1 },
122 	{ "x",		LWS_GENCRYPTO_EC_KEYEL_X,	0 },
123 	{ "x5c",	JWK_META_X5C,			1 },
124 	{ "y",		LWS_GENCRYPTO_EC_KEYEL_Y,	0 }
125 }, lexico_oct[] =  {
126 	{ "alg",	JWK_META_ALG,			1 },
127 	{ "k",		LWS_GENCRYPTO_OCT_KEYEL_K,	0 },
128 	{ "key_ops",	JWK_META_KEY_OPS,		1 },
129 	{ "kid",	JWK_META_KID,			1 },
130 	{ "kty",	JWK_META_KTY,			1 },
131 	{ "use",	JWK_META_USE,			1 },
132 	{ "x5c",	JWK_META_X5C,			1 }
133 }, lexico_rsa[] =  {
134 	{ "alg",	JWK_META_ALG,			1 },
135 	{ "d",		LWS_GENCRYPTO_RSA_KEYEL_D,	2 | 0 },
136 	{ "dp",		LWS_GENCRYPTO_RSA_KEYEL_DP,	2 | 0 },
137 	{ "dq",		LWS_GENCRYPTO_RSA_KEYEL_DQ,	2 | 0 },
138 	{ "e",		LWS_GENCRYPTO_RSA_KEYEL_E,	0 },
139 	{ "key_ops",	JWK_META_KEY_OPS,		1 },
140 	{ "kid",	JWK_META_KID,			1 },
141 	{ "kty",	JWK_META_KTY,			1 },
142 	{ "n",		LWS_GENCRYPTO_RSA_KEYEL_N,	0 },
143 	{ "p",		LWS_GENCRYPTO_RSA_KEYEL_P,	2 | 0 },
144 	{ "q",		LWS_GENCRYPTO_RSA_KEYEL_Q,	2 | 0 },
145 	{ "qi",		LWS_GENCRYPTO_RSA_KEYEL_QI,	2 | 0 },
146 	{ "use",	JWK_META_USE,			1 },
147 	{ "x5c",	JWK_META_X5C,			1 }
148 };
149 
150 static const char meta_b64[] = { 0, 0, 0, 0, 1, 0 };
151 
152 static const char *oct_names[] = {
153 	"k"
154 };
155 static const char oct_b64[] = { 1 };
156 
157 static const char *rsa_names[] = {
158 	"e", "n", "d", "p", "q", "dp", "dq", "qi"
159 };
160 static const char rsa_b64[] = { 1, 1, 1, 1, 1, 1, 1, 1 };
161 
162 static const char *ec_names[] = {
163 	"crv", "x", "d", "y",
164 };
165 static const char ec_b64[] = { 0, 1, 1, 1 };
166 
167 int
lws_jwk_dump(struct lws_jwk * jwk)168 lws_jwk_dump(struct lws_jwk *jwk)
169 {
170 	const char **enames, *b64;
171 	int elems;
172 	int n;
173 
174 	(void)enames;
175 	(void)meta_names;
176 
177 	switch (jwk->kty) {
178 	default:
179 	case LWS_GENCRYPTO_KTY_UNKNOWN:
180 		lwsl_err("%s: jwk %p: unknown type\n", __func__, jwk);
181 
182 		return 1;
183 	case LWS_GENCRYPTO_KTY_OCT:
184 		elems = LWS_GENCRYPTO_OCT_KEYEL_COUNT;
185 		enames = oct_names;
186 		b64 = oct_b64;
187 		break;
188 	case LWS_GENCRYPTO_KTY_RSA:
189 		elems = LWS_GENCRYPTO_RSA_KEYEL_COUNT;
190 		enames = rsa_names;
191 		b64 = rsa_b64;
192 		break;
193 	case LWS_GENCRYPTO_KTY_EC:
194 		elems = LWS_GENCRYPTO_EC_KEYEL_COUNT;
195 		enames = ec_names;
196 		b64 = ec_b64;
197 		break;
198 	}
199 
200 	lwsl_info("%s: jwk %p\n", __func__, jwk);
201 
202 	for (n = 0; n < LWS_COUNT_JWK_ELEMENTS; n++) {
203 		if (jwk->meta[n].buf && meta_b64[n]) {
204 			lwsl_info("  meta: %s\n", meta_names[n]);
205 			lwsl_hexdump_info(jwk->meta[n].buf, jwk->meta[n].len);
206 		}
207 		if (jwk->meta[n].buf && !meta_b64[n])
208 			lwsl_info("  meta: %s: '%s'\n", meta_names[n],
209 					jwk->meta[n].buf);
210 	}
211 
212 	for (n = 0; n < elems; n++) {
213 		if (jwk->e[n].buf && b64[n]) {
214 			lwsl_info("  e: %s\n", enames[n]);
215 			lwsl_hexdump_info(jwk->e[n].buf, jwk->e[n].len);
216 		}
217 		if (jwk->e[n].buf && !b64[n])
218 			lwsl_info("  e: %s: '%s'\n", enames[n], jwk->e[n].buf);
219 	}
220 
221 	return 0;
222 }
223 
224 static int
_lws_jwk_set_el_jwk(struct lws_gencrypto_keyelem * e,char * in,int len)225 _lws_jwk_set_el_jwk(struct lws_gencrypto_keyelem *e, char *in, int len)
226 {
227 	e->buf = lws_malloc(len + 1, "jwk");
228 	if (!e->buf)
229 		return -1;
230 
231 	memcpy(e->buf, in, len);
232 	e->buf[len] = '\0';
233 	e->len = len;
234 
235 	return 0;
236 }
237 
238 static int
_lws_jwk_set_el_jwk_b64(struct lws_gencrypto_keyelem * e,char * in,int len)239 _lws_jwk_set_el_jwk_b64(struct lws_gencrypto_keyelem *e, char *in, int len)
240 {
241 	int dec_size = lws_base64_size(len), n;
242 
243 	e->buf = lws_malloc(dec_size, "jwk");
244 	if (!e->buf)
245 		return -1;
246 
247 	/* same decoder accepts both url or original styles */
248 
249 	n = lws_b64_decode_string_len(in, len, (char *)e->buf, dec_size - 1);
250 	if (n < 0)
251 		return -1;
252 	e->len = n;
253 
254 	return 0;
255 }
256 
257 static int
_lws_jwk_set_el_jwk_b64u(struct lws_gencrypto_keyelem * e,char * in,int len)258 _lws_jwk_set_el_jwk_b64u(struct lws_gencrypto_keyelem *e, char *in, int len)
259 {
260 	int dec_size = lws_base64_size(len), n;
261 
262 	e->buf = lws_malloc(dec_size, "jwk");
263 	if (!e->buf)
264 		return -1;
265 
266 	/* same decoder accepts both url or original styles */
267 
268 	n = lws_b64_decode_string_len(in, len, (char *)e->buf, dec_size - 1);
269 	if (n < 0)
270 		return -1;
271 	e->len = n;
272 
273 	return 0;
274 }
275 
276 void
lws_jwk_destroy_elements(struct lws_gencrypto_keyelem * el,int m)277 lws_jwk_destroy_elements(struct lws_gencrypto_keyelem *el, int m)
278 {
279 	int n;
280 
281 	for (n = 0; n < m; n++)
282 		if (el[n].buf) {
283 			/* wipe all key material when it goes out of scope */
284 			lws_explicit_bzero(el[n].buf, el[n].len);
285 			lws_free_set_NULL(el[n].buf);
286 			el[n].len = 0;
287 		}
288 }
289 
290 void
lws_jwk_destroy(struct lws_jwk * jwk)291 lws_jwk_destroy(struct lws_jwk *jwk)
292 {
293 	lws_jwk_destroy_elements(jwk->e, LWS_ARRAY_SIZE(jwk->e));
294 	lws_jwk_destroy_elements(jwk->meta, LWS_ARRAY_SIZE(jwk->meta));
295 }
296 
297 static signed char
cb_jwk(struct lejp_ctx * ctx,char reason)298 cb_jwk(struct lejp_ctx *ctx, char reason)
299 {
300 	struct lws_jwk_parse_state *jps = (struct lws_jwk_parse_state *)ctx->user;
301 	struct lws_jwk *jwk = jps->jwk;
302 	unsigned int idx, poss, n;
303 	char dotstar[64];
304 
305 	if (reason == LEJPCB_VAL_STR_START)
306 		jps->pos = 0;
307 
308 	if (reason == LEJPCB_OBJECT_START && ctx->path_match == 0 + 1)
309 		/*
310 		 * new keys[] member is starting
311 		 *
312 		 * Until we see some JSON names, it could be anything...
313 		 * there is no requirement for kty to be given first and eg,
314 		 * ACME specifies the keys must be ordered in lexographic
315 		 * order - where kty is not first.
316 		 */
317 		jps->possible = F_RSA | F_EC | F_OCT;
318 
319 	if (reason == LEJPCB_OBJECT_END && ctx->path_match == 0 + 1) {
320 		/* we completed parsing a key */
321 		if (jps->per_key_cb && jps->possible) {
322 			if (jps->per_key_cb(jps->jwk, jps->user)) {
323 
324 				lwsl_notice("%s: user cb halts import\n",
325 					    __func__);
326 
327 				return -2;
328 			}
329 
330 			/* clear it down */
331 			lws_jwk_destroy(jps->jwk);
332 			jps->possible = 0;
333 		}
334 	}
335 
336 	if (reason == LEJPCB_COMPLETE) {
337 
338 		/*
339 		 * Now we saw the whole jwk and know the key type, let'jwk insist
340 		 * that as a whole, it must be consistent and complete.
341 		 *
342 		 * The tracking of ->possible bits from even before we know the
343 		 * kty already makes certain we cannot have key element members
344 		 * defined that are inconsistent with the key type.
345 		 */
346 
347 		for (n = 0; n < LWS_ARRAY_SIZE(tok_map); n++)
348 			/*
349 			 * All mandataory elements for the key type
350 			 * must be present
351 			 */
352 			if ((tok_map[n] & jps->possible) && (
353 			    ((tok_map[n] & (F_M | F_META)) == (F_M | F_META) &&
354 			     !jwk->meta[tok_map[n] & 0xff].buf) ||
355 			    ((tok_map[n] & (F_M | F_META)) == F_M &&
356 			     !jwk->e[tok_map[n] & 0xff].buf))) {
357 				lwsl_notice("%s: missing %s\n", __func__,
358 					    jwk_tok[n]);
359 					return -3;
360 				}
361 
362 		/*
363 		 * When the key may be public or public + private, ensure the
364 		 * intra-key members related to that are consistent.
365 		 *
366 		 * Only RSA keys need extra care, since EC keys are already
367 		 * confirmed by making CRV, X and Y mandatory and only D
368 		 * (the singular private part) optional.  For RSA, N and E are
369 		 * also already known to be present using mandatory checking.
370 		 */
371 
372 		/*
373 		 * If a private key, it must have all D, P and Q.  Public key
374 		 * must have none of them.
375 		 */
376 		if (jwk->kty == LWS_GENCRYPTO_KTY_RSA &&
377 		    !(((!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_D].buf) &&
378 		      (!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_P].buf) &&
379 		      (!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_Q].buf)) ||
380 		      (jwk->e[LWS_GENCRYPTO_RSA_KEYEL_D].buf &&
381 		       jwk->e[LWS_GENCRYPTO_RSA_KEYEL_P].buf &&
382 		       jwk->e[LWS_GENCRYPTO_RSA_KEYEL_Q].buf))
383 		      ) {
384 			lwsl_notice("%s: RSA requires D, P and Q for private\n",
385 				    __func__);
386 			return -3;
387 		}
388 
389 		/*
390 		 * If the precomputed private key terms appear, they must all
391 		 * appear together.
392 		 */
393 		if (jwk->kty == LWS_GENCRYPTO_KTY_RSA &&
394 		    !(((!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_DP].buf) &&
395 		      (!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_DQ].buf) &&
396 		      (!jwk->e[LWS_GENCRYPTO_RSA_KEYEL_QI].buf)) ||
397 		      (jwk->e[LWS_GENCRYPTO_RSA_KEYEL_DP].buf &&
398 		       jwk->e[LWS_GENCRYPTO_RSA_KEYEL_DQ].buf &&
399 		       jwk->e[LWS_GENCRYPTO_RSA_KEYEL_QI].buf))
400 		      ) {
401 			lwsl_notice("%s: RSA DP, DQ, QI must all appear "
402 				    "or none\n", __func__);
403 			return -3;
404 		}
405 
406 		/*
407 		 * The precomputed private key terms must not appear without
408 		 * the private key itself also appearing.
409 		 */
410 		if (jwk->kty == LWS_GENCRYPTO_KTY_RSA &&
411 		    !jwk->e[LWS_GENCRYPTO_RSA_KEYEL_D].buf &&
412 		     jwk->e[LWS_GENCRYPTO_RSA_KEYEL_DQ].buf) {
413 			lwsl_notice("%s: RSA DP, DQ, QI can appear only with "
414 				    "private key\n", __func__);
415 			return -3;
416 		}
417 
418 		if ((jwk->kty == LWS_GENCRYPTO_KTY_RSA ||
419 		     jwk->kty == LWS_GENCRYPTO_KTY_EC) &&
420 		    jwk->e[LWS_GENCRYPTO_RSA_KEYEL_D].buf)
421 		jwk->private_key = 1;
422 	}
423 
424 	if (!(reason & LEJP_FLAG_CB_IS_VALUE) || !ctx->path_match)
425 		return 0;
426 
427 	if (ctx->path_match == 0 + 1)
428 		return 0;
429 
430 	idx = tok_map[ctx->path_match - 1];
431 	if ((idx & 0xff) == 0xff)
432 		return 0;
433 
434 	switch (idx) {
435 	/* note: kty is not necessarily first... we have to keep track of
436 	 * what could match given which element names have already been
437 	 * seen.  Once kty comes, we confirm it'jwk still possible (ie, it'jwk
438 	 * not trying to tell us that it'jwk RSA now when we saw a "crv"
439 	 * earlier) and then reduce the possibilities to just the one that
440 	 * kty told. */
441 	case F_RSA | F_EC | F_OCT | F_META | F_M | JWK_META_KTY:
442 
443 		if (ctx->npos == 3 && !strncmp(ctx->buf, "oct", 3)) {
444 			if (!(jps->possible & F_OCT))
445 				goto elements_mismatch;
446 			jwk->kty = LWS_GENCRYPTO_KTY_OCT;
447 			jps->possible = F_OCT;
448 			goto cont;
449 		}
450 		if (ctx->npos == 3 && !strncmp(ctx->buf, "RSA", 3)) {
451 			if (!(jps->possible & F_RSA))
452 				goto elements_mismatch;
453 			jwk->kty = LWS_GENCRYPTO_KTY_RSA;
454 			jps->possible = F_RSA;
455 			goto cont;
456 		}
457 		if (ctx->npos == 2 && !strncmp(ctx->buf, "EC", 2)) {
458 			if (!(jps->possible & F_EC))
459 				goto elements_mismatch;
460 			jwk->kty = LWS_GENCRYPTO_KTY_EC;
461 			jps->possible = F_EC;
462 			goto cont;
463 		}
464 		lws_strnncpy(dotstar, ctx->buf, ctx->npos, sizeof(dotstar));
465 		lwsl_err("%s: Unknown KTY '%s'\n", __func__, dotstar);
466 		return -1;
467 
468 	default:
469 cont:
470 		if (jps->pos + ctx->npos >= (int)sizeof(jps->b64))
471 			goto bail;
472 
473 		memcpy(jps->b64 + jps->pos, ctx->buf, ctx->npos);
474 		jps->pos += ctx->npos;
475 
476 		if (reason == LEJPCB_VAL_STR_CHUNK)
477 			return 0;
478 
479 		/* chunking has been collated */
480 
481 		poss = idx & (F_RSA | F_EC | F_OCT);
482 		jps->possible &= poss;
483 		if (!jps->possible)
484 			goto elements_mismatch;
485 
486 		if (idx & F_META) {
487 			if (_lws_jwk_set_el_jwk(&jwk->meta[idx & 0x7f],
488 						jps->b64, jps->pos) < 0)
489 				goto bail;
490 
491 			break;
492 		}
493 
494 		if (idx & F_B64U) {
495 			/* key data... do the base64 decode as needed */
496 			if (_lws_jwk_set_el_jwk_b64u(&jwk->e[idx & 0x7f],
497 						     jps->b64, jps->pos) < 0)
498 				goto bail;
499 
500 			if (jwk->e[idx & 0x7f].len >
501 					LWS_JWE_LIMIT_KEY_ELEMENT_BYTES) {
502 				lwsl_notice("%s: oversize keydata\n", __func__);
503 				goto bail;
504 			}
505 
506 			return 0;
507 		}
508 
509 		if (idx & F_B64) {
510 
511 			/* cert data... do non-urlcoded base64 decode */
512 			if (_lws_jwk_set_el_jwk_b64(&jwk->e[idx & 0x7f],
513 						    jps->b64, jps->pos) < 0)
514 				goto bail;
515 			return 0;
516 		}
517 
518 			if (_lws_jwk_set_el_jwk(&jwk->e[idx & 0x7f],
519 						jps->b64, jps->pos) < 0)
520 				goto bail;
521 		break;
522 	}
523 
524 	return 0;
525 
526 elements_mismatch:
527 	lwsl_err("%s: jwk elements mismatch\n", __func__);
528 
529 bail:
530 	lwsl_err("%s: element failed\n", __func__);
531 
532 	return -1;
533 }
534 
535 void
lws_jwk_init_jps(struct lejp_ctx * jctx,struct lws_jwk_parse_state * jps,struct lws_jwk * jwk,lws_jwk_key_import_callback cb,void * user)536 lws_jwk_init_jps(struct lejp_ctx *jctx, struct lws_jwk_parse_state *jps,
537 		 struct lws_jwk *jwk, lws_jwk_key_import_callback cb,
538 		 void *user)
539 {
540 	if (jwk)
541 		memset(jwk, 0, sizeof(*jwk));
542 
543 	jps->jwk = jwk;
544 	jps->possible = F_RSA | F_EC | F_OCT;
545 	jps->per_key_cb = cb;
546 	jps->user = user;
547 	jps->pos = 0;
548 
549 	lejp_construct(jctx, cb_jwk, jps, cb ? jwk_outer_tok: jwk_tok,
550 		       LWS_ARRAY_SIZE(jwk_tok));
551 }
552 
553 int
lws_jwk_dup_oct(struct lws_jwk * jwk,const void * key,int len)554 lws_jwk_dup_oct(struct lws_jwk *jwk, const void *key, int len)
555 {
556 	jwk->e[LWS_GENCRYPTO_KTY_OCT].buf = lws_malloc(len, __func__);
557 	if (!jwk->e[LWS_GENCRYPTO_KTY_OCT].buf)
558 		return -1;
559 
560 	jwk->kty = LWS_GENCRYPTO_KTY_OCT;
561 	jwk->e[LWS_GENCRYPTO_OCT_KEYEL_K].len = len;
562 
563 	memcpy(jwk->e[LWS_GENCRYPTO_KTY_OCT].buf, key, len);
564 
565 	return 0;
566 }
567 
568 int
lws_jwk_generate(struct lws_context * context,struct lws_jwk * jwk,enum lws_gencrypto_kty kty,int bits,const char * curve)569 lws_jwk_generate(struct lws_context *context, struct lws_jwk *jwk,
570 	         enum lws_gencrypto_kty kty, int bits, const char *curve)
571 {
572 	size_t sn;
573 	int n;
574 
575 	memset(jwk, 0, sizeof(*jwk));
576 
577 	jwk->kty = kty;
578 	jwk->private_key = 1;
579 
580 	switch (kty) {
581 	case LWS_GENCRYPTO_KTY_RSA:
582 	{
583 		struct lws_genrsa_ctx ctx;
584 
585 		lwsl_notice("%s: generating %d bit RSA key\n", __func__, bits);
586 		n = lws_genrsa_new_keypair(context, &ctx, LGRSAM_PKCS1_1_5,
587 					    jwk->e, bits);
588 		lws_genrsa_destroy(&ctx);
589 		if (n) {
590 			lwsl_err("%s: problem generating RSA key\n", __func__);
591 			return 1;
592 		}
593 	}
594 		break;
595 	case LWS_GENCRYPTO_KTY_OCT:
596 		sn = lws_gencrypto_bits_to_bytes(bits);
597 		jwk->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf = lws_malloc(sn, "oct");
598 		jwk->e[LWS_GENCRYPTO_OCT_KEYEL_K].len = sn;
599 		if (lws_get_random(context,
600 			     jwk->e[LWS_GENCRYPTO_OCT_KEYEL_K].buf, sn) != sn) {
601 			lwsl_err("%s: problem getting random\n", __func__);
602 			return 1;
603 		}
604 		break;
605 	case LWS_GENCRYPTO_KTY_EC:
606 	{
607 		struct lws_genec_ctx ctx;
608 
609 		if (!curve) {
610 			lwsl_err("%s: must have a named curve\n", __func__);
611 
612 			return 1;
613 		}
614 
615 		if (lws_genecdsa_create(&ctx, context, NULL))
616 			return 1;
617 
618 		lwsl_notice("%s: generating ECDSA key on curve %s\n", __func__,
619 				curve);
620 
621 		n = lws_genecdsa_new_keypair(&ctx, curve, jwk->e);
622 		lws_genec_destroy(&ctx);
623 		if (n) {
624 			lwsl_err("%s: problem generating ECDSA key\n", __func__);
625 			return 1;
626 		}
627 	}
628 		break;
629 
630 	case LWS_GENCRYPTO_KTY_UNKNOWN:
631 	default:
632 		lwsl_err("%s: unknown kty\n", __func__);
633 		return 1;
634 	}
635 
636 	return 0;
637 }
638 
639 int
lws_jwk_import(struct lws_jwk * jwk,lws_jwk_key_import_callback cb,void * user,const char * in,size_t len)640 lws_jwk_import(struct lws_jwk *jwk, lws_jwk_key_import_callback cb, void *user,
641 	       const char *in, size_t len)
642 {
643 	struct lejp_ctx jctx;
644 	struct lws_jwk_parse_state jps;
645 	int m;
646 
647 	lws_jwk_init_jps(&jctx, &jps, jwk, cb, user);
648 
649 	m = (int)(signed char)lejp_parse(&jctx, (uint8_t *)in, len);
650 	lejp_destruct(&jctx);
651 
652 	if (m < 0) {
653 		lwsl_notice("%s: parse got %d\n", __func__, m);
654 		lws_jwk_destroy(jwk);
655 		return -1;
656 	}
657 
658 	switch (jwk->kty) {
659 	case LWS_GENCRYPTO_KTY_UNKNOWN:
660 		lwsl_notice("%s: missing or unknown kyt\n", __func__);
661 		lws_jwk_destroy(jwk);
662 		return -1;
663 	default:
664 		break;
665 	}
666 
667 	return 0;
668 }
669 
670 
671 int
lws_jwk_export(struct lws_jwk * jwk,int flags,char * p,int * len)672 lws_jwk_export(struct lws_jwk *jwk, int flags, char *p, int *len)
673 {
674 	char *start = p, *end = &p[*len - 1];
675 	int n, m, limit, first = 1, asym = 0;
676 	struct lexico *l;
677 
678 	/* RFC7638 lexicographic order requires
679 	 *  RSA: e -> kty -> n
680 	 *  oct: k -> kty
681 	 *
682 	 * ie, meta and key data elements appear interleaved in name alpha order
683 	 */
684 
685 	p += lws_snprintf(p, end - p, "{");
686 
687 	switch (jwk->kty) {
688 	case LWS_GENCRYPTO_KTY_OCT:
689 		l = lexico_oct;
690 		limit = LWS_ARRAY_SIZE(lexico_oct);
691 		break;
692 	case LWS_GENCRYPTO_KTY_RSA:
693 		l = lexico_rsa;
694 		limit = LWS_ARRAY_SIZE(lexico_rsa);
695 		asym = 1;
696 		break;
697 	case LWS_GENCRYPTO_KTY_EC:
698 		l = lexico_ec;
699 		limit = LWS_ARRAY_SIZE(lexico_ec);
700 		asym = 1;
701 		break;
702 	default:
703 		return -1;
704 	}
705 
706 	for (n = 0; n < limit; n++) {
707 		const char *q, *q_end;
708 		char tok[12];
709 		int pos = 0, f = 1;
710 
711 		if ((l->meta & 1) && (jwk->meta[l->idx].buf ||
712 				      l->idx == (int)JWK_META_KTY)) {
713 
714 			switch (l->idx) {
715 			case JWK_META_KTY:
716 				if (!first)
717 					*p++ = ',';
718 				first = 0;
719 				p += lws_snprintf(p, end - p, "\"%s\":\"%s\"",
720 						  l->name, kty_names[jwk->kty]);
721 				break;
722 			case JWK_META_KEY_OPS:
723 				if (!first)
724 					*p++ = ',';
725 				first = 0;
726 				q = (const char *)jwk->meta[l->idx].buf;
727 				q_end = q + jwk->meta[l->idx].len;
728 
729 				p += lws_snprintf(p, end - p,
730 						  "\"%s\":[", l->name);
731 				/*
732 				 * For the public version, usages that
733 				 * require the private part must be
734 				 * snipped
735 				 */
736 
737 				while (q < q_end) {
738 					if (*q != ' ' && pos < (int)sizeof(tok) - 1) {
739 						tok[pos++] = *q++;
740 						if (q != q_end)
741 							continue;
742 					}
743 					tok[pos] = '\0';
744 					pos = 0;
745 					if ((flags & LWSJWKF_EXPORT_PRIVATE) ||
746 					    !asym || (strcmp(tok, "sign") &&
747 						      strcmp(tok, "encrypt"))) {
748 						if (!f)
749 							*p++ = ',';
750 						f = 0;
751 						p += lws_snprintf(p, end - p,
752 							"\"%s\"", tok);
753 					}
754 					q++;
755 				}
756 
757 				*p++ = ']';
758 
759 				break;
760 
761 			default:
762 				/* both sig and enc require asym private key */
763 				if (!(flags & LWSJWKF_EXPORT_PRIVATE) &&
764 				    asym && l->idx == (int)JWK_META_USE)
765 					break;
766 				if (!first)
767 					*p++ = ',';
768 				first = 0;
769 				p += lws_snprintf(p, end - p, "\"%s\":\"",
770 						  l->name);
771 				lws_strnncpy(p, (const char *)jwk->meta[l->idx].buf,
772 					     jwk->meta[l->idx].len, end - p);
773 				p += strlen(p);
774 				p += lws_snprintf(p, end - p, "\"");
775 				break;
776 			}
777 		}
778 
779 		if ((!(l->meta & 1)) && jwk->e[l->idx].buf &&
780 		    ((flags & LWSJWKF_EXPORT_PRIVATE) || !(l->meta & 2))) {
781 			if (!first)
782 				*p++ = ',';
783 			first = 0;
784 
785 			p += lws_snprintf(p, end - p, "\"%s\":\"", l->name);
786 
787 			if (jwk->kty == LWS_GENCRYPTO_KTY_EC &&
788 			    l->idx == (int)LWS_GENCRYPTO_EC_KEYEL_CRV) {
789 				lws_strnncpy(p,
790 					     (const char *)jwk->e[l->idx].buf,
791 					     jwk->e[l->idx].len, end - p);
792 				m = strlen(p);
793 			} else
794 				m = lws_jws_base64_enc(
795 					(const char *)jwk->e[l->idx].buf,
796 					jwk->e[l->idx].len, p, end - p - 4);
797 			if (m < 0) {
798 				lwsl_notice("%s: enc failed\n", __func__);
799 				return -1;
800 			}
801 			p += m;
802 			p += lws_snprintf(p, end - p, "\"");
803 		}
804 
805 		l++;
806 	}
807 
808 	p += lws_snprintf(p, end - p,
809 			  (flags & LWSJWKF_EXPORT_NOCRLF) ? "}" : "}\n");
810 
811 	*len -= p - start;
812 
813 	return p - start;
814 }
815 
816 int
lws_jwk_rfc7638_fingerprint(struct lws_jwk * jwk,char * digest32)817 lws_jwk_rfc7638_fingerprint(struct lws_jwk *jwk, char *digest32)
818 {
819 	struct lws_genhash_ctx hash_ctx;
820 	int tmpsize = 2536, n;
821 	char *tmp;
822 
823 	tmp = lws_malloc(tmpsize, "rfc7638 tmp");
824 
825 	n = lws_jwk_export(jwk, LWSJWKF_EXPORT_NOCRLF, tmp, &tmpsize);
826 	if (n < 0)
827 		goto bail;
828 
829 	if (lws_genhash_init(&hash_ctx, LWS_GENHASH_TYPE_SHA256))
830 		goto bail;
831 
832 	if (lws_genhash_update(&hash_ctx, tmp, n)) {
833 		lws_genhash_destroy(&hash_ctx, NULL);
834 
835 		goto bail;
836 	}
837 	lws_free(tmp);
838 
839 	if (lws_genhash_destroy(&hash_ctx, digest32))
840 		return -1;
841 
842 	return 0;
843 
844 bail:
845 	lws_free(tmp);
846 
847 	return -1;
848 }
849 
850 int
lws_jwk_strdup_meta(struct lws_jwk * jwk,enum enum_jwk_meta_tok idx,const char * in,int len)851 lws_jwk_strdup_meta(struct lws_jwk *jwk, enum enum_jwk_meta_tok idx,
852 		    const char *in, int len)
853 {
854 	jwk->meta[idx].buf = lws_malloc(len, __func__);
855 	if (!jwk->meta[idx].buf)
856 		return 1;
857 	jwk->meta[idx].len = len;
858 	memcpy(jwk->meta[idx].buf, in, len);
859 
860 	return 0;
861 }
862 
863 int
lws_jwk_load(struct lws_jwk * jwk,const char * filename,lws_jwk_key_import_callback cb,void * user)864 lws_jwk_load(struct lws_jwk *jwk, const char *filename,
865 	     lws_jwk_key_import_callback cb, void *user)
866 {
867 	int buflen = 4096;
868 	char *buf = lws_malloc(buflen, "jwk-load");
869 	int n;
870 
871 	if (!buf)
872 		return -1;
873 
874 	n = lws_plat_read_file(filename, buf, buflen);
875 	if (n < 0)
876 		goto bail;
877 
878 	n = lws_jwk_import(jwk, cb, user, buf, n);
879 	lws_free(buf);
880 
881 	return n;
882 bail:
883 	lws_free(buf);
884 
885 	return -1;
886 }
887 
888 int
lws_jwk_save(struct lws_jwk * jwk,const char * filename)889 lws_jwk_save(struct lws_jwk *jwk, const char *filename)
890 {
891 	int buflen = 4096;
892 	char *buf = lws_malloc(buflen, "jwk-save");
893 	int n, m;
894 
895 	if (!buf)
896 		return -1;
897 
898 	n = lws_jwk_export(jwk, LWSJWKF_EXPORT_PRIVATE, buf, &buflen);
899 	if (n < 0)
900 		goto bail;
901 
902 	m = lws_plat_write_file(filename, buf, n);
903 
904 	lws_free(buf);
905 	if (m)
906 		return -1;
907 
908 	return 0;
909 
910 bail:
911 	lws_free(buf);
912 
913 	return -1;
914 }
915