File: key2jwk.c

package info (click to toggle)
libjwt3 3.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,920 kB
  • sloc: ansic: 10,119; xml: 253; javascript: 187; sh: 45; makefile: 14; ruby: 11
file content (508 lines) | stat: -rw-r--r-- 13,055 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/* Copyright (C) 2024-2025 maClara, LLC <info@maclara-llc.com>
   This file is part of the JWT C Library

   SPDX-License-Identifier:  MPL-2.0
   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* XXX BIG FAT WARNING: There's not much error checking here. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <getopt.h>
#include <unistd.h>

#include <openssl/pem.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/bn.h>
#include <openssl/core_names.h>
#include <openssl/err.h>
#include <openssl/rand.h>

#include <jwt.h>

#include "jwt-util.h"

/* We make use of some LibJWT internals. Soon, this code will move into LibJWT
 * so it can be used to important PEM/DER keys into a JWK keyring. Until then,
 * we hack around it here. */
#include "jwt-private.h"

static int ec_count, rsa_count, eddsa_count, rsa_pss_count, hmac_count;

static void print_openssl_errors_and_exit()
{
	ERR_print_errors_fp(stderr);
	exit(EXIT_FAILURE);
}

static int with_kid = 1;
static int do_not_assume_hmac = 0;

static const char *uuidv4(void)
{
	uint8_t uuid_bytes[16];
	static char uuid[37];

	// Generate 16 random bytes
	if (RAND_bytes(uuid_bytes, sizeof(uuid_bytes)) != 1) {
		fprintf(stderr, "Error: Failed to generate random bytes.\n");
		return NULL;
	}

	// Set the version to 4 (0100 in binary)
	uuid_bytes[6] = (uuid_bytes[6] & 0x0F) | 0x40;

	// Set the variant to RFC 4122 (10xx in binary)
	uuid_bytes[8] = (uuid_bytes[8] & 0x3F) | 0x80;

	// Format the UUID as a string
	snprintf(uuid, sizeof(uuid),
		"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
		uuid_bytes[0], uuid_bytes[1], uuid_bytes[2], uuid_bytes[3],
		uuid_bytes[4], uuid_bytes[5], uuid_bytes[6], uuid_bytes[7],
		uuid_bytes[8], uuid_bytes[9], uuid_bytes[10], uuid_bytes[11],
		uuid_bytes[12], uuid_bytes[13], uuid_bytes[14], uuid_bytes[15]);

	return uuid;
}

/* Set the alg and crv for an EC key */
static void ec_alg_type(EVP_PKEY *pkey, char crv[32], char alg[32])
{
	char __named_crv[32];
	char *__alg = NULL, *__crv = NULL;
	size_t bits;

	crv[0] = alg[0] = '\0';

	EVP_PKEY_get_size_t_param(pkey, OSSL_PKEY_PARAM_BITS,
				  &bits);

	EVP_PKEY_get_group_name(pkey, __named_crv, sizeof(__named_crv), NULL);

	switch (bits) {
	case 256:
		if (!strcmp(__named_crv, "secp256k1")) {
			__alg = "ES256K";
			__crv = "secp256k1";
		} else {
			__alg = "ES256";
			__crv = "P-256";
		}
		break;

	case 384:
		__alg = "ES384";
		__crv = "P-384";
		break;

	case 521:
		__alg = "ES512";
		__crv = "P-521";
		break;
	}

	if (!__alg || !__crv) {
		fprintf(stderr, "EC: Unknown curve %s with %d bits\n",
			__named_crv, (int)bits);
		return;
	}

	strcpy(crv, __crv);
	strcpy(alg, __alg);
}

/* Retrieves and b64url-encodes a single OSSL BIGNUM param and adds it to
 * the JSON object as a string. */
static void get_one_bn(EVP_PKEY *pkey, const char *ossl_param,
		       jwt_json_t *jwk, const char *name)
{
	/* Get param */
	BIGNUM *bn = NULL;
	if (!EVP_PKEY_get_bn_param(pkey, ossl_param, &bn) || bn == NULL)
		return;

	/* Extract data */
	int len = BN_num_bytes(bn);
	unsigned char *bin = OPENSSL_malloc(len);
	if (bin == NULL) {
		BN_free(bn);
		return;
	}
	BN_bn2bin(bn, bin);
	BN_free(bn);

	/* Encode */
	char *b64;
	jwt_base64uri_encode(&b64, (char *)bin, len);
	OPENSSL_free(bin);
	jwt_json_obj_set(jwk, name, jwt_json_create_str(b64));
	jwt_freemem(b64);
}

/* Retrieves and b64url-encodes a single OSSL octet param and adds it to
 * the JSON object as a string. */
static void get_one_octet(EVP_PKEY *pkey, const char *ossl_param,
                          jwt_json_t *jwk, const char *name)
{
	unsigned char buf[256];
	size_t len = 0;
	if (!EVP_PKEY_get_octet_string_param(pkey, ossl_param, buf,
					     sizeof(buf), &len) || len == 0)
		return;
        char *b64;
	jwt_base64uri_encode(&b64, (char *)buf, len);
	OPENSSL_cleanse(buf, len);
	jwt_json_obj_set(jwk, name, jwt_json_create_str(b64));
        jwt_freemem(b64);
}

/* For ECC Keys (ES256, ES384, ES512) */
static void process_ec_key(EVP_PKEY *pkey, int priv, jwt_json_t *jwk)
{
	char alg_type[32], crv[32];

	ec_alg_type(pkey, crv, alg_type);

	jwt_json_obj_set(jwk, "alg", jwt_json_create_str(alg_type));
	jwt_json_obj_set(jwk, "crv", jwt_json_create_str(crv));

	get_one_bn(pkey, OSSL_PKEY_PARAM_EC_PUB_X, jwk, "x");
	get_one_bn(pkey, OSSL_PKEY_PARAM_EC_PUB_Y, jwk, "y");
	if (priv)
		get_one_bn(pkey, OSSL_PKEY_PARAM_PRIV_KEY, jwk, "d");
}

/* For EdDSA keys */
static void process_eddsa_key(EVP_PKEY *pkey, int priv, jwt_json_t *jwk)
{
	if (priv)
		get_one_octet(pkey, OSSL_PKEY_PARAM_PRIV_KEY, jwk, "d");
	else
		get_one_octet(pkey, OSSL_PKEY_PARAM_PUB_KEY, jwk, "x");
}

/* For RSA keys (RS256, RS384, RS512). Also works for RSA-PSS
 * (PS256, PS384, PS512) */
static void process_rsa_key(EVP_PKEY *pkey, int priv, jwt_json_t *jwk)
{
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_N, jwk, "n");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_E, jwk, "e");

	if (!priv)
		return;

	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_D, jwk, "d");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_FACTOR1, jwk, "p");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_FACTOR2, jwk, "q");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_EXPONENT1, jwk, "dp");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_EXPONENT2, jwk, "dq");
	get_one_bn(pkey, OSSL_PKEY_PARAM_RSA_COEFFICIENT1, jwk, "qi");
}

static void process_hmac_key(jwt_json_t *jwk, const unsigned char *key, size_t len)
{
	char *b64;

	jwt_json_obj_set(jwk, "kty", jwt_json_create_str("oct"));

	jwt_base64uri_encode(&b64, (char *)key, len);
	jwt_json_obj_set(jwk, "k", jwt_json_create_str(b64));
	jwt_freemem(b64);

	if (len >= 32 && len < 48)
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("HS256"));
	else if (len >= 48 && len < 64)
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("HS384"));
	else if (len >= 64)
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("HS512"));

	hmac_count++;
}

static jwt_json_t *parse_one_file(const char *file)
{
	int priv = 0;
	FILE *fp;
	EVP_PKEY *pkey;
	jwt_json_t *jwk, *ops;
	size_t len = 0;
	unsigned char file_buf[BUFSIZ];

	fp = fopen(file, "r");
	if (!fp) {
		perror("Error opening file");
		exit(EXIT_FAILURE);
	}

	/* Try public key first */
	pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
	if (pkey == NULL) {
		/* Retry with private key type */
		rewind(fp);
		pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
		priv = 1;
	}

	if (pkey == NULL) {
		/* Check length to see if it can be HMAC */
		fseek(fp, 0, SEEK_END);
		len = ftell(fp);
		if (do_not_assume_hmac || len < 32 || len > sizeof(file_buf)) {
			fprintf(stderr, "Error parsing key file\n");
			print_openssl_errors_and_exit();
		}

		rewind(fp);
		len = fread(file_buf, 1, len, fp);
		priv = 1;
	}

	fclose(fp);

	/* Setup json object */
	jwk = jwt_json_create();
	if (!priv) {
		/* Key use */
		jwt_json_obj_set(jwk, "use", jwt_json_create_str("sig"));
	} else {
		/* Key ops */
		ops = jwt_json_create_arr();
		jwt_json_arr_append(ops, jwt_json_create_str("sign"));
		jwt_json_obj_set(jwk, "key_ops", ops);
	}

	/* Use uuidv4 for "kid" */
	if (with_kid)
		jwt_json_obj_set(jwk, "kid", jwt_json_create_str(uuidv4()));

	if (len) {
		process_hmac_key(jwk, file_buf, len);
		OPENSSL_cleanse(file_buf, len);
		return jwk;
	}

	/* Process per key type params */
	switch (EVP_PKEY_get_base_id(pkey)) {
	case EVP_PKEY_RSA:
		jwt_json_obj_set(jwk, "kty", jwt_json_create_str("RSA"));
		process_rsa_key(pkey, priv, jwk);
		rsa_count++;
		break;

	case EVP_PKEY_EC:
		jwt_json_obj_set(jwk, "kty", jwt_json_create_str("EC"));
		process_ec_key(pkey, priv, jwk);
		ec_count++;
		break;

	case EVP_PKEY_ED25519:
		jwt_json_obj_set(jwk, "kty", jwt_json_create_str("OKP"));
		jwt_json_obj_set(jwk, "crv", jwt_json_create_str("Ed25519"));
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("EdDSA"));
		process_eddsa_key(pkey, priv, jwk);
		eddsa_count++;
		break;

	case EVP_PKEY_ED448:
		jwt_json_obj_set(jwk, "kty", jwt_json_create_str("OKP"));
		jwt_json_obj_set(jwk, "crv", jwt_json_create_str("Ed448"));
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("EdDSA"));
		process_eddsa_key(pkey, priv, jwk);
		eddsa_count++;
		break;

	case EVP_PKEY_RSA_PSS:
		/* XXX We need a way to designate this for PS alg only ???
		 * For now, default to PS256. */
		jwt_json_obj_set(jwk, "kty", jwt_json_create_str("RSA"));
		jwt_json_obj_set(jwk, "alg", jwt_json_create_str("PS256"));
		process_rsa_key(pkey, priv, jwk);
		rsa_pss_count++;
		break;

	default:
		fprintf(stderr, "Skipped unknown key type: %s\n", file);
	}

	EVP_PKEY_free(pkey);

	return jwk;
}

_Noreturn static void usage(const char *error, int exit_state)
{
	if (error)
		fprintf(stderr, "ERROR: %s\n\n", error);

	fprintf(stderr, "\
Usage: %s [OPTIONS] <FILE> [FILE]...\n\
\n\
Parse PEM/DER file(s) into JSON Web Key format.\n\
\n\
  -h, --help            This help information\n\
  -q, --quiet           No output other than JWKS file\n\
  -l, --list            List supported algorithms and exit\n\
  -k, --disable-kid     Disable generating \"kid\" attribute\n\
  -m, --disable-hmac    Disable fallback to HMAC\n\
  -o, --output=FILE     File to write JWKS to\n\
\n\
This program will parse PEM/DER key files (public and private) into JSON Web\n\
Keys and output a JWK Set. Note that HMAC keys are \"guessed\" based on them\n\
not being parsed by OpenSSL. This may cause some issues. You can disable\n\
this with the -m option.\n\
\n\
You can use '-' as the argument to the -o option to write to stdout.\n\
\n\
RSA keys will not have an algorithm set as they are valid for RS256, RS384,\n\
and RS512. RSA keys must be at least 1024 bits.\n\
\n\
RSA-PSS keys will be set to PS256, otherwise they will look no different\n\
than an RSA key.\n\
\n\
All keys will get a generated randomized uuidv4 \"kid\" attribute unless you\n\
use the -k option..\n", get_progname());

	exit(exit_state);
}

int main(int argc, char **argv)
{
	jwt_json_t *jwk_set, *jwk_array, *jwk;
	time_t now;
	char *time_str;
	char comment[256];
	jwt_alg_t alg;
	int quiet = 0;
	char *jwk_str;
	FILE *outfp = NULL;
	FILE *msg = stdout;
	int i, oc;

	char *optstr = "hlqo:km";
	struct option opttbl[] = {
		{ "help",		no_argument,		NULL, 'h' },
		{ "list",		no_argument,		NULL, 'l' },
		{ "quiet",		no_argument,		NULL, 'q' },
		{ "output",		required_argument,	NULL, 'o' },
		{ "disable-kid",	no_argument,		NULL, 'k' },
		{ "disable-hmac",	no_argument,		NULL, 'm' },
		{ NULL, 0, 0, 0 },
	};

	while ((oc = getopt_long(argc, argv, optstr, opttbl, NULL)) != -1) {
		switch (oc) {
		case 'h':
			usage(NULL, EXIT_SUCCESS);

		case 'l':
			printf("Algorithms supported:\n");
			for (alg = JWT_ALG_NONE; alg < JWT_ALG_INVAL; alg++)
				printf("    %s\n", jwt_alg_str(alg));
			exit(EXIT_SUCCESS);
			break;

		case 'q':
			quiet = 1;
			break;

		case 'k':
			with_kid = 0;
			break;

		case 'm':
			do_not_assume_hmac = 1;
			break;

		case 'o':
			if (optarg[0] == '-') {
				outfp = stdout;
				msg = stderr;
			} else {
				outfp = fopen(optarg, "wx");
				if (outfp == NULL)
					perror(optarg);
			}
			break;
		default: /* '?' */
			usage("Unknown option", EXIT_FAILURE);
			break;
		}
	}

	argc -= optind;
	argv += optind;

	if (argc == 0)
		usage("No key(s) given", EXIT_FAILURE);

	if (outfp == NULL)
		usage("The --output argument is required", EXIT_FAILURE);


	if (!quiet)
		fprintf(msg, "Parsing %d files (", argc);

	jwk_array = jwt_json_create_arr();

	for (i = 0; i < argc; i++) {
		jwk = parse_one_file(argv[i]);
		jwt_json_arr_append(jwk_array, jwk);
		if (!quiet)
			fprintf(msg, ".");
	}
	if (!quiet) {
		fprintf(msg, ") done\n");

		fprintf(msg, "Parse results:\n");
		if (ec_count)
			fprintf(msg, "  EC     : %d\n", ec_count);
		if (rsa_count)
			fprintf(msg, "  RSA    : %d\n", rsa_count);
		if (rsa_pss_count)
			fprintf(msg, "  RSA-PSS: %d\n", rsa_pss_count);
		if (eddsa_count)
			fprintf(msg, "  EdDSA  : %d\n", eddsa_count);
		if (hmac_count)
			fprintf(msg, "  HMAC   : %d\n", hmac_count);
		fprintf(msg, "\n");

		fprintf(msg, "Generating JWKS...\n");
	}

	jwk_set = jwt_json_create();
	snprintf(comment, sizeof(comment), "Generated by LibJWT %s",
		 JWT_VERSION_STRING);
	comment[sizeof(comment) - 1] = '\0';
	jwt_json_obj_set(jwk_set, "libjwt.io:comment", jwt_json_create_str(comment));

	now = time(NULL);
	time_str = ctime(&now);
	time_str[strlen(time_str) - 1] = '\0';
	jwt_json_obj_set(jwk_set, "libjwt.io:date", jwt_json_create_str(time_str));

#ifdef _WIN32
	DWORD hostnamesize = sizeof(comment);
	GetComputerNameA(comment, &hostnamesize);
#else
	gethostname(comment, sizeof(comment));
#endif
	comment[sizeof(comment) - 1] = '\0';
	jwt_json_obj_set(jwk_set, "libjwt.io:hostname",
			 jwt_json_create_str(comment));

	jwt_json_obj_set(jwk_set, "keys", jwk_array);

	jwk_str = jwt_json_serialize(jwk_set, JWT_JSON_INDENT(2));
	fprintf(outfp, "%s\n", jwk_str);

	jwt_freemem(jwk_str);

	exit(EXIT_SUCCESS);
}