xref: /openbsd/usr.bin/ssh/ssh-sk.c (revision 5411e769)
1 /* $OpenBSD: ssh-sk.c,v 1.41 2024/08/15 00:51:51 djm Exp $ */
2 /*
3  * Copyright (c) 2019 Google LLC
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /* #define DEBUG_SK 1 */
19 
20 #include <dlfcn.h>
21 #include <stddef.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <stdio.h>
25 
26 #ifdef WITH_OPENSSL
27 #include <openssl/objects.h>
28 #include <openssl/ec.h>
29 #include <openssl/evp.h>
30 #endif /* WITH_OPENSSL */
31 
32 #include "log.h"
33 #include "misc.h"
34 #include "sshbuf.h"
35 #include "sshkey.h"
36 #include "ssherr.h"
37 #include "digest.h"
38 
39 #include "ssh-sk.h"
40 #include "sk-api.h"
41 #include "crypto_api.h"
42 
43 struct sshsk_provider {
44 	char *path;
45 	void *dlhandle;
46 
47 	/* Return the version of the middleware API */
48 	uint32_t (*sk_api_version)(void);
49 
50 	/* Enroll a U2F key (private key generation) */
51 	int (*sk_enroll)(int alg, const uint8_t *challenge,
52 	    size_t challenge_len, const char *application, uint8_t flags,
53 	    const char *pin, struct sk_option **opts,
54 	    struct sk_enroll_response **enroll_response);
55 
56 	/* Sign a challenge */
57 	int (*sk_sign)(int alg, const uint8_t *message, size_t message_len,
58 	    const char *application,
59 	    const uint8_t *key_handle, size_t key_handle_len,
60 	    uint8_t flags, const char *pin, struct sk_option **opts,
61 	    struct sk_sign_response **sign_response);
62 
63 	/* Enumerate resident keys */
64 	int (*sk_load_resident_keys)(const char *pin, struct sk_option **opts,
65 	    struct sk_resident_key ***rks, size_t *nrks);
66 };
67 
68 /* Built-in version */
69 int ssh_sk_enroll(int alg, const uint8_t *challenge,
70     size_t challenge_len, const char *application, uint8_t flags,
71     const char *pin, struct sk_option **opts,
72     struct sk_enroll_response **enroll_response);
73 int ssh_sk_sign(int alg, const uint8_t *message, size_t message_len,
74     const char *application,
75     const uint8_t *key_handle, size_t key_handle_len,
76     uint8_t flags, const char *pin, struct sk_option **opts,
77     struct sk_sign_response **sign_response);
78 int ssh_sk_load_resident_keys(const char *pin, struct sk_option **opts,
79     struct sk_resident_key ***rks, size_t *nrks);
80 
81 static void
sshsk_free(struct sshsk_provider * p)82 sshsk_free(struct sshsk_provider *p)
83 {
84 	if (p == NULL)
85 		return;
86 	free(p->path);
87 	if (p->dlhandle != NULL)
88 		dlclose(p->dlhandle);
89 	free(p);
90 }
91 
92 static struct sshsk_provider *
sshsk_open(const char * path)93 sshsk_open(const char *path)
94 {
95 	struct sshsk_provider *ret = NULL;
96 	uint32_t version;
97 
98 	if (path == NULL || *path == '\0') {
99 		error("No FIDO SecurityKeyProvider specified");
100 		return NULL;
101 	}
102 	if ((ret = calloc(1, sizeof(*ret))) == NULL) {
103 		error_f("calloc failed");
104 		return NULL;
105 	}
106 	if ((ret->path = strdup(path)) == NULL) {
107 		error_f("strdup failed");
108 		goto fail;
109 	}
110 	/* Skip the rest if we're using the linked in middleware */
111 	if (strcasecmp(ret->path, "internal") == 0) {
112 		ret->sk_enroll = ssh_sk_enroll;
113 		ret->sk_sign = ssh_sk_sign;
114 		ret->sk_load_resident_keys = ssh_sk_load_resident_keys;
115 		return ret;
116 	}
117 	if (lib_contains_symbol(path, "sk_api_version") != 0) {
118 		error("provider %s is not an OpenSSH FIDO library", path);
119 		goto fail;
120 	}
121 	if ((ret->dlhandle = dlopen(path, RTLD_NOW)) == NULL) {
122 		error("Provider \"%s\" dlopen failed: %s", path, dlerror());
123 		goto fail;
124 	}
125 	if ((ret->sk_api_version = dlsym(ret->dlhandle,
126 	    "sk_api_version")) == NULL) {
127 		fatal("Provider \"%s\" dlsym(sk_api_version) failed: %s",
128 		    path, dlerror());
129 	}
130 	version = ret->sk_api_version();
131 	debug_f("provider %s implements version 0x%08lx", ret->path,
132 	    (u_long)version);
133 	if ((version & SSH_SK_VERSION_MAJOR_MASK) != SSH_SK_VERSION_MAJOR) {
134 		error("Provider \"%s\" implements unsupported "
135 		    "version 0x%08lx (supported: 0x%08lx)",
136 		    path, (u_long)version, (u_long)SSH_SK_VERSION_MAJOR);
137 		goto fail;
138 	}
139 	if ((ret->sk_enroll = dlsym(ret->dlhandle, "sk_enroll")) == NULL) {
140 		error("Provider %s dlsym(sk_enroll) failed: %s",
141 		    path, dlerror());
142 		goto fail;
143 	}
144 	if ((ret->sk_sign = dlsym(ret->dlhandle, "sk_sign")) == NULL) {
145 		error("Provider \"%s\" dlsym(sk_sign) failed: %s",
146 		    path, dlerror());
147 		goto fail;
148 	}
149 	if ((ret->sk_load_resident_keys = dlsym(ret->dlhandle,
150 	    "sk_load_resident_keys")) == NULL) {
151 		error("Provider \"%s\" dlsym(sk_load_resident_keys) "
152 		    "failed: %s", path, dlerror());
153 		goto fail;
154 	}
155 	/* success */
156 	return ret;
157 fail:
158 	sshsk_free(ret);
159 	return NULL;
160 }
161 
162 static void
sshsk_free_enroll_response(struct sk_enroll_response * r)163 sshsk_free_enroll_response(struct sk_enroll_response *r)
164 {
165 	if (r == NULL)
166 		return;
167 	freezero(r->key_handle, r->key_handle_len);
168 	freezero(r->public_key, r->public_key_len);
169 	freezero(r->signature, r->signature_len);
170 	freezero(r->attestation_cert, r->attestation_cert_len);
171 	freezero(r->authdata, r->authdata_len);
172 	freezero(r, sizeof(*r));
173 }
174 
175 static void
sshsk_free_sign_response(struct sk_sign_response * r)176 sshsk_free_sign_response(struct sk_sign_response *r)
177 {
178 	if (r == NULL)
179 		return;
180 	freezero(r->sig_r, r->sig_r_len);
181 	freezero(r->sig_s, r->sig_s_len);
182 	freezero(r, sizeof(*r));
183 }
184 
185 #ifdef WITH_OPENSSL
186 /* Assemble key from response */
187 static int
sshsk_ecdsa_assemble(struct sk_enroll_response * resp,struct sshkey ** keyp)188 sshsk_ecdsa_assemble(struct sk_enroll_response *resp, struct sshkey **keyp)
189 {
190 	struct sshkey *key = NULL;
191 	struct sshbuf *b = NULL;
192 	EC_KEY *ecdsa = NULL;
193 	EC_POINT *q = NULL;
194 	const EC_GROUP *g = NULL;
195 	int r;
196 
197 	*keyp = NULL;
198 	if ((key = sshkey_new(KEY_ECDSA_SK)) == NULL) {
199 		error_f("sshkey_new failed");
200 		r = SSH_ERR_ALLOC_FAIL;
201 		goto out;
202 	}
203 	key->ecdsa_nid = NID_X9_62_prime256v1;
204 	if ((ecdsa = EC_KEY_new_by_curve_name(key->ecdsa_nid)) == NULL ||
205 	    (g = EC_KEY_get0_group(ecdsa)) == NULL ||
206 	    (q = EC_POINT_new(g)) == NULL ||
207 	    (b = sshbuf_new()) == NULL) {
208 		error_f("allocation failed");
209 		r = SSH_ERR_ALLOC_FAIL;
210 		goto out;
211 	}
212 	if ((r = sshbuf_put_string(b,
213 	    resp->public_key, resp->public_key_len)) != 0) {
214 		error_fr(r, "sshbuf_put_string");
215 		goto out;
216 	}
217 	if ((r = sshbuf_get_ec(b, q, g)) != 0) {
218 		error_fr(r, "parse");
219 		r = SSH_ERR_INVALID_FORMAT;
220 		goto out;
221 	}
222 	if (sshkey_ec_validate_public(g, q) != 0) {
223 		error("Authenticator returned invalid ECDSA key");
224 		r = SSH_ERR_KEY_INVALID_EC_VALUE;
225 		goto out;
226 	}
227 	if (EC_KEY_set_public_key(ecdsa, q) != 1) {
228 		/* XXX assume it is a allocation error */
229 		error_f("allocation failed");
230 		r = SSH_ERR_ALLOC_FAIL;
231 		goto out;
232 	}
233 	if ((key->pkey = EVP_PKEY_new()) == NULL) {
234 		error_f("allocation failed");
235 		r = SSH_ERR_ALLOC_FAIL;
236 		goto out;
237 	}
238 	if (EVP_PKEY_set1_EC_KEY(key->pkey, ecdsa) != 1) {
239 		error_f("Assigning EC_KEY failed");
240 		r = SSH_ERR_LIBCRYPTO_ERROR;
241 		goto out;
242 	}
243 	/* success */
244 	*keyp = key;
245 	key = NULL; /* transferred */
246 	r = 0;
247  out:
248 	sshkey_free(key);
249 	sshbuf_free(b);
250 	EC_KEY_free(ecdsa);
251 	EC_POINT_free(q);
252 	return r;
253 }
254 #endif /* WITH_OPENSSL */
255 
256 static int
sshsk_ed25519_assemble(struct sk_enroll_response * resp,struct sshkey ** keyp)257 sshsk_ed25519_assemble(struct sk_enroll_response *resp, struct sshkey **keyp)
258 {
259 	struct sshkey *key = NULL;
260 	int r;
261 
262 	*keyp = NULL;
263 	if (resp->public_key_len != ED25519_PK_SZ) {
264 		error_f("invalid size: %zu", resp->public_key_len);
265 		r = SSH_ERR_INVALID_FORMAT;
266 		goto out;
267 	}
268 	if ((key = sshkey_new(KEY_ED25519_SK)) == NULL) {
269 		error_f("sshkey_new failed");
270 		r = SSH_ERR_ALLOC_FAIL;
271 		goto out;
272 	}
273 	if ((key->ed25519_pk = malloc(ED25519_PK_SZ)) == NULL) {
274 		error_f("malloc failed");
275 		r = SSH_ERR_ALLOC_FAIL;
276 		goto out;
277 	}
278 	memcpy(key->ed25519_pk, resp->public_key, ED25519_PK_SZ);
279 	/* success */
280 	*keyp = key;
281 	key = NULL; /* transferred */
282 	r = 0;
283  out:
284 	sshkey_free(key);
285 	return r;
286 }
287 
288 static int
sshsk_key_from_response(int alg,const char * application,uint8_t flags,struct sk_enroll_response * resp,struct sshkey ** keyp)289 sshsk_key_from_response(int alg, const char *application, uint8_t flags,
290     struct sk_enroll_response *resp, struct sshkey **keyp)
291 {
292 	struct sshkey *key = NULL;
293 	int r = SSH_ERR_INTERNAL_ERROR;
294 
295 	*keyp = NULL;
296 
297 	/* Check response validity */
298 	if (resp->public_key == NULL || resp->key_handle == NULL) {
299 		error_f("sk_enroll response invalid");
300 		r = SSH_ERR_INVALID_FORMAT;
301 		goto out;
302 	}
303 	switch (alg) {
304 #ifdef WITH_OPENSSL
305 	case SSH_SK_ECDSA:
306 		if ((r = sshsk_ecdsa_assemble(resp, &key)) != 0)
307 			goto out;
308 		break;
309 #endif /* WITH_OPENSSL */
310 	case SSH_SK_ED25519:
311 		if ((r = sshsk_ed25519_assemble(resp, &key)) != 0)
312 			goto out;
313 		break;
314 	default:
315 		error_f("unsupported algorithm %d", alg);
316 		r = SSH_ERR_INVALID_ARGUMENT;
317 		goto out;
318 	}
319 	key->sk_flags = flags;
320 	if ((key->sk_key_handle = sshbuf_new()) == NULL ||
321 	    (key->sk_reserved = sshbuf_new()) == NULL) {
322 		error_f("allocation failed");
323 		r = SSH_ERR_ALLOC_FAIL;
324 		goto out;
325 	}
326 	if ((key->sk_application = strdup(application)) == NULL) {
327 		error_f("strdup application failed");
328 		r = SSH_ERR_ALLOC_FAIL;
329 		goto out;
330 	}
331 	if ((r = sshbuf_put(key->sk_key_handle, resp->key_handle,
332 	    resp->key_handle_len)) != 0) {
333 		error_fr(r, "put key handle");
334 		goto out;
335 	}
336 	/* success */
337 	r = 0;
338 	*keyp = key;
339 	key = NULL;
340  out:
341 	sshkey_free(key);
342 	return r;
343 }
344 
345 static int
skerr_to_ssherr(int skerr)346 skerr_to_ssherr(int skerr)
347 {
348 	switch (skerr) {
349 	case SSH_SK_ERR_UNSUPPORTED:
350 		return SSH_ERR_FEATURE_UNSUPPORTED;
351 	case SSH_SK_ERR_PIN_REQUIRED:
352 		return SSH_ERR_KEY_WRONG_PASSPHRASE;
353 	case SSH_SK_ERR_DEVICE_NOT_FOUND:
354 		return SSH_ERR_DEVICE_NOT_FOUND;
355 	case SSH_SK_ERR_CREDENTIAL_EXISTS:
356 		return SSH_ERR_KEY_BAD_PERMISSIONS;
357 	case SSH_SK_ERR_GENERAL:
358 	default:
359 		return SSH_ERR_INVALID_FORMAT;
360 	}
361 }
362 
363 static void
sshsk_free_options(struct sk_option ** opts)364 sshsk_free_options(struct sk_option **opts)
365 {
366 	size_t i;
367 
368 	if (opts == NULL)
369 		return;
370 	for (i = 0; opts[i] != NULL; i++) {
371 		free(opts[i]->name);
372 		free(opts[i]->value);
373 		free(opts[i]);
374 	}
375 	free(opts);
376 }
377 
378 static int
sshsk_add_option(struct sk_option *** optsp,size_t * noptsp,const char * name,const char * value,uint8_t required)379 sshsk_add_option(struct sk_option ***optsp, size_t *noptsp,
380     const char *name, const char *value, uint8_t required)
381 {
382 	struct sk_option **opts = *optsp;
383 	size_t nopts = *noptsp;
384 
385 	if ((opts = recallocarray(opts, nopts, nopts + 2, /* extra for NULL */
386 	    sizeof(*opts))) == NULL) {
387 		error_f("array alloc failed");
388 		return SSH_ERR_ALLOC_FAIL;
389 	}
390 	*optsp = opts;
391 	*noptsp = nopts + 1;
392 	if ((opts[nopts] = calloc(1, sizeof(**opts))) == NULL) {
393 		error_f("alloc failed");
394 		return SSH_ERR_ALLOC_FAIL;
395 	}
396 	if ((opts[nopts]->name = strdup(name)) == NULL ||
397 	    (opts[nopts]->value = strdup(value)) == NULL) {
398 		error_f("alloc failed");
399 		return SSH_ERR_ALLOC_FAIL;
400 	}
401 	opts[nopts]->required = required;
402 	return 0;
403 }
404 
405 static int
make_options(const char * device,const char * user_id,struct sk_option *** optsp)406 make_options(const char *device, const char *user_id,
407     struct sk_option ***optsp)
408 {
409 	struct sk_option **opts = NULL;
410 	size_t nopts = 0;
411 	int r, ret = SSH_ERR_INTERNAL_ERROR;
412 
413 	if (device != NULL &&
414 	    (r = sshsk_add_option(&opts, &nopts, "device", device, 0)) != 0) {
415 		ret = r;
416 		goto out;
417 	}
418 	if (user_id != NULL &&
419 	    (r = sshsk_add_option(&opts, &nopts, "user", user_id, 0)) != 0) {
420 		ret = r;
421 		goto out;
422 	}
423 	/* success */
424 	*optsp = opts;
425 	opts = NULL;
426 	nopts = 0;
427 	ret = 0;
428  out:
429 	sshsk_free_options(opts);
430 	return ret;
431 }
432 
433 
434 static int
fill_attestation_blob(const struct sk_enroll_response * resp,struct sshbuf * attest)435 fill_attestation_blob(const struct sk_enroll_response *resp,
436     struct sshbuf *attest)
437 {
438 	int r;
439 
440 	if (attest == NULL)
441 		return 0; /* nothing to do */
442 	if ((r = sshbuf_put_cstring(attest, "ssh-sk-attest-v01")) != 0 ||
443 	    (r = sshbuf_put_string(attest,
444 	    resp->attestation_cert, resp->attestation_cert_len)) != 0 ||
445 	    (r = sshbuf_put_string(attest,
446 	    resp->signature, resp->signature_len)) != 0 ||
447 	    (r = sshbuf_put_string(attest,
448 	    resp->authdata, resp->authdata_len)) != 0 ||
449 	    (r = sshbuf_put_u32(attest, 0)) != 0 || /* resvd flags */
450 	    (r = sshbuf_put_string(attest, NULL, 0)) != 0 /* resvd */) {
451 		error_fr(r, "compose");
452 		return r;
453 	}
454 	/* success */
455 	return 0;
456 }
457 
458 int
sshsk_enroll(int type,const char * provider_path,const char * device,const char * application,const char * userid,uint8_t flags,const char * pin,struct sshbuf * challenge_buf,struct sshkey ** keyp,struct sshbuf * attest)459 sshsk_enroll(int type, const char *provider_path, const char *device,
460     const char *application, const char *userid, uint8_t flags,
461     const char *pin, struct sshbuf *challenge_buf,
462     struct sshkey **keyp, struct sshbuf *attest)
463 {
464 	struct sshsk_provider *skp = NULL;
465 	struct sshkey *key = NULL;
466 	u_char randchall[32];
467 	const u_char *challenge;
468 	size_t challenge_len;
469 	struct sk_enroll_response *resp = NULL;
470 	struct sk_option **opts = NULL;
471 	int r = SSH_ERR_INTERNAL_ERROR;
472 	int alg;
473 
474 	debug_f("provider \"%s\", device \"%s\", application \"%s\", "
475 	    "userid \"%s\", flags 0x%02x, challenge len %zu%s",
476 	    provider_path, device, application, userid, flags,
477 	    challenge_buf == NULL ? 0 : sshbuf_len(challenge_buf),
478 	    (pin != NULL && *pin != '\0') ? " with-pin" : "");
479 
480 	*keyp = NULL;
481 	if (attest)
482 		sshbuf_reset(attest);
483 
484 	if ((r = make_options(device, userid, &opts)) != 0)
485 		goto out;
486 
487 	switch (type) {
488 #ifdef WITH_OPENSSL
489 	case KEY_ECDSA_SK:
490 		alg = SSH_SK_ECDSA;
491 		break;
492 #endif /* WITH_OPENSSL */
493 	case KEY_ED25519_SK:
494 		alg = SSH_SK_ED25519;
495 		break;
496 	default:
497 		error_f("unsupported key type");
498 		r = SSH_ERR_INVALID_ARGUMENT;
499 		goto out;
500 	}
501 	if (provider_path == NULL) {
502 		error_f("missing provider");
503 		r = SSH_ERR_INVALID_ARGUMENT;
504 		goto out;
505 	}
506 	if (application == NULL || *application == '\0') {
507 		error_f("missing application");
508 		r = SSH_ERR_INVALID_ARGUMENT;
509 		goto out;
510 	}
511 	if (challenge_buf == NULL) {
512 		debug_f("using random challenge");
513 		arc4random_buf(randchall, sizeof(randchall));
514 		challenge = randchall;
515 		challenge_len = sizeof(randchall);
516 	} else if (sshbuf_len(challenge_buf) == 0) {
517 		error("Missing enrollment challenge");
518 		r = SSH_ERR_INVALID_ARGUMENT;
519 		goto out;
520 	} else {
521 		challenge = sshbuf_ptr(challenge_buf);
522 		challenge_len = sshbuf_len(challenge_buf);
523 		debug3_f("using explicit challenge len=%zd", challenge_len);
524 	}
525 	if ((skp = sshsk_open(provider_path)) == NULL) {
526 		r = SSH_ERR_INVALID_FORMAT; /* XXX sshsk_open return code? */
527 		goto out;
528 	}
529 	/* XXX validate flags? */
530 	/* enroll key */
531 	if ((r = skp->sk_enroll(alg, challenge, challenge_len, application,
532 	    flags, pin, opts, &resp)) != 0) {
533 		debug_f("provider \"%s\" failure %d", provider_path, r);
534 		r = skerr_to_ssherr(r);
535 		goto out;
536 	}
537 
538 	if ((r = sshsk_key_from_response(alg, application, resp->flags,
539 	    resp, &key)) != 0)
540 		goto out;
541 
542 	/* Optionally fill in the attestation information */
543 	if ((r = fill_attestation_blob(resp, attest)) != 0)
544 		goto out;
545 
546 	/* success */
547 	*keyp = key;
548 	key = NULL; /* transferred */
549 	r = 0;
550  out:
551 	sshsk_free_options(opts);
552 	sshsk_free(skp);
553 	sshkey_free(key);
554 	sshsk_free_enroll_response(resp);
555 	explicit_bzero(randchall, sizeof(randchall));
556 	return r;
557 }
558 
559 #ifdef WITH_OPENSSL
560 static int
sshsk_ecdsa_sig(struct sk_sign_response * resp,struct sshbuf * sig)561 sshsk_ecdsa_sig(struct sk_sign_response *resp, struct sshbuf *sig)
562 {
563 	struct sshbuf *inner_sig = NULL;
564 	int r = SSH_ERR_INTERNAL_ERROR;
565 
566 	/* Check response validity */
567 	if (resp->sig_r == NULL || resp->sig_s == NULL) {
568 		error_f("sk_sign response invalid");
569 		r = SSH_ERR_INVALID_FORMAT;
570 		goto out;
571 	}
572 	if ((inner_sig = sshbuf_new()) == NULL) {
573 		r = SSH_ERR_ALLOC_FAIL;
574 		goto out;
575 	}
576 	/* Prepare and append inner signature object */
577 	if ((r = sshbuf_put_bignum2_bytes(inner_sig,
578 	    resp->sig_r, resp->sig_r_len)) != 0 ||
579 	    (r = sshbuf_put_bignum2_bytes(inner_sig,
580 	    resp->sig_s, resp->sig_s_len)) != 0) {
581 		error_fr(r, "compose inner");
582 		goto out;
583 	}
584 	if ((r = sshbuf_put_stringb(sig, inner_sig)) != 0 ||
585 	    (r = sshbuf_put_u8(sig, resp->flags)) != 0 ||
586 	    (r = sshbuf_put_u32(sig, resp->counter)) != 0) {
587 		error_fr(r, "compose");
588 		goto out;
589 	}
590 #ifdef DEBUG_SK
591 	fprintf(stderr, "%s: sig_r:\n", __func__);
592 	sshbuf_dump_data(resp->sig_r, resp->sig_r_len, stderr);
593 	fprintf(stderr, "%s: sig_s:\n", __func__);
594 	sshbuf_dump_data(resp->sig_s, resp->sig_s_len, stderr);
595 	fprintf(stderr, "%s: inner:\n", __func__);
596 	sshbuf_dump(inner_sig, stderr);
597 #endif
598 	r = 0;
599  out:
600 	sshbuf_free(inner_sig);
601 	return r;
602 }
603 #endif /* WITH_OPENSSL */
604 
605 static int
sshsk_ed25519_sig(struct sk_sign_response * resp,struct sshbuf * sig)606 sshsk_ed25519_sig(struct sk_sign_response *resp, struct sshbuf *sig)
607 {
608 	int r = SSH_ERR_INTERNAL_ERROR;
609 
610 	/* Check response validity */
611 	if (resp->sig_r == NULL) {
612 		error_f("sk_sign response invalid");
613 		r = SSH_ERR_INVALID_FORMAT;
614 		goto out;
615 	}
616 	if ((r = sshbuf_put_string(sig,
617 	    resp->sig_r, resp->sig_r_len)) != 0 ||
618 	    (r = sshbuf_put_u8(sig, resp->flags)) != 0 ||
619 	    (r = sshbuf_put_u32(sig, resp->counter)) != 0) {
620 		error_fr(r, "compose");
621 		goto out;
622 	}
623 #ifdef DEBUG_SK
624 	fprintf(stderr, "%s: sig_r:\n", __func__);
625 	sshbuf_dump_data(resp->sig_r, resp->sig_r_len, stderr);
626 #endif
627 	r = 0;
628  out:
629 	return r;
630 }
631 
632 int
sshsk_sign(const char * provider_path,struct sshkey * key,u_char ** sigp,size_t * lenp,const u_char * data,size_t datalen,u_int compat,const char * pin)633 sshsk_sign(const char *provider_path, struct sshkey *key,
634     u_char **sigp, size_t *lenp, const u_char *data, size_t datalen,
635     u_int compat, const char *pin)
636 {
637 	struct sshsk_provider *skp = NULL;
638 	int r = SSH_ERR_INTERNAL_ERROR;
639 	int type, alg;
640 	struct sk_sign_response *resp = NULL;
641 	struct sshbuf *inner_sig = NULL, *sig = NULL;
642 	struct sk_option **opts = NULL;
643 
644 	debug_f("provider \"%s\", key %s, flags 0x%02x%s",
645 	    provider_path, sshkey_type(key), key->sk_flags,
646 	    (pin != NULL && *pin != '\0') ? " with-pin" : "");
647 
648 	if (sigp != NULL)
649 		*sigp = NULL;
650 	if (lenp != NULL)
651 		*lenp = 0;
652 	type = sshkey_type_plain(key->type);
653 	switch (type) {
654 #ifdef WITH_OPENSSL
655 	case KEY_ECDSA_SK:
656 		alg = SSH_SK_ECDSA;
657 		break;
658 #endif /* WITH_OPENSSL */
659 	case KEY_ED25519_SK:
660 		alg = SSH_SK_ED25519;
661 		break;
662 	default:
663 		return SSH_ERR_INVALID_ARGUMENT;
664 	}
665 	if (provider_path == NULL ||
666 	    key->sk_key_handle == NULL ||
667 	    key->sk_application == NULL || *key->sk_application == '\0') {
668 		r = SSH_ERR_INVALID_ARGUMENT;
669 		goto out;
670 	}
671 	if ((skp = sshsk_open(provider_path)) == NULL) {
672 		r = SSH_ERR_INVALID_FORMAT; /* XXX sshsk_open return code? */
673 		goto out;
674 	}
675 #ifdef DEBUG_SK
676 	fprintf(stderr, "%s: sk_flags = 0x%02x, sk_application = \"%s\"\n",
677 	    __func__, key->sk_flags, key->sk_application);
678 	fprintf(stderr, "%s: sk_key_handle:\n", __func__);
679 	sshbuf_dump(key->sk_key_handle, stderr);
680 #endif
681 	if ((r = skp->sk_sign(alg, data, datalen, key->sk_application,
682 	    sshbuf_ptr(key->sk_key_handle), sshbuf_len(key->sk_key_handle),
683 	    key->sk_flags, pin, opts, &resp)) != 0) {
684 		debug_f("sk_sign failed with code %d", r);
685 		r = skerr_to_ssherr(r);
686 		goto out;
687 	}
688 	/* Assemble signature */
689 	if ((sig = sshbuf_new()) == NULL) {
690 		r = SSH_ERR_ALLOC_FAIL;
691 		goto out;
692 	}
693 	if ((r = sshbuf_put_cstring(sig, sshkey_ssh_name_plain(key))) != 0) {
694 		error_fr(r, "compose outer");
695 		goto out;
696 	}
697 	switch (type) {
698 #ifdef WITH_OPENSSL
699 	case KEY_ECDSA_SK:
700 		if ((r = sshsk_ecdsa_sig(resp, sig)) != 0)
701 			goto out;
702 		break;
703 #endif /* WITH_OPENSSL */
704 	case KEY_ED25519_SK:
705 		if ((r = sshsk_ed25519_sig(resp, sig)) != 0)
706 			goto out;
707 		break;
708 	}
709 #ifdef DEBUG_SK
710 	fprintf(stderr, "%s: sig_flags = 0x%02x, sig_counter = %u\n",
711 	    __func__, resp->flags, resp->counter);
712 	fprintf(stderr, "%s: data to sign:\n", __func__);
713 	sshbuf_dump_data(data, datalen, stderr);
714 	fprintf(stderr, "%s: sigbuf:\n", __func__);
715 	sshbuf_dump(sig, stderr);
716 #endif
717 	if (sigp != NULL) {
718 		if ((*sigp = malloc(sshbuf_len(sig))) == NULL) {
719 			r = SSH_ERR_ALLOC_FAIL;
720 			goto out;
721 		}
722 		memcpy(*sigp, sshbuf_ptr(sig), sshbuf_len(sig));
723 	}
724 	if (lenp != NULL)
725 		*lenp = sshbuf_len(sig);
726 	/* success */
727 	r = 0;
728  out:
729 	sshsk_free_options(opts);
730 	sshsk_free(skp);
731 	sshsk_free_sign_response(resp);
732 	sshbuf_free(sig);
733 	sshbuf_free(inner_sig);
734 	return r;
735 }
736 
737 static void
sshsk_free_sk_resident_keys(struct sk_resident_key ** rks,size_t nrks)738 sshsk_free_sk_resident_keys(struct sk_resident_key **rks, size_t nrks)
739 {
740 	size_t i;
741 
742 	if (nrks == 0 || rks == NULL)
743 		return;
744 	for (i = 0; i < nrks; i++) {
745 		free(rks[i]->application);
746 		freezero(rks[i]->user_id, rks[i]->user_id_len);
747 		freezero(rks[i]->key.key_handle, rks[i]->key.key_handle_len);
748 		freezero(rks[i]->key.public_key, rks[i]->key.public_key_len);
749 		freezero(rks[i]->key.signature, rks[i]->key.signature_len);
750 		freezero(rks[i]->key.attestation_cert,
751 		    rks[i]->key.attestation_cert_len);
752 		freezero(rks[i], sizeof(**rks));
753 	}
754 	free(rks);
755 }
756 
757 static void
sshsk_free_resident_key(struct sshsk_resident_key * srk)758 sshsk_free_resident_key(struct sshsk_resident_key *srk)
759 {
760 	if (srk == NULL)
761 		return;
762 	sshkey_free(srk->key);
763 	freezero(srk->user_id, srk->user_id_len);
764 	free(srk);
765 }
766 
767 
768 void
sshsk_free_resident_keys(struct sshsk_resident_key ** srks,size_t nsrks)769 sshsk_free_resident_keys(struct sshsk_resident_key **srks, size_t nsrks)
770 {
771 	size_t i;
772 
773 	if (srks == NULL || nsrks == 0)
774 		return;
775 
776 	for (i = 0; i < nsrks; i++)
777 		sshsk_free_resident_key(srks[i]);
778 	free(srks);
779 }
780 
781 int
sshsk_load_resident(const char * provider_path,const char * device,const char * pin,u_int flags,struct sshsk_resident_key *** srksp,size_t * nsrksp)782 sshsk_load_resident(const char *provider_path, const char *device,
783     const char *pin, u_int flags, struct sshsk_resident_key ***srksp,
784     size_t *nsrksp)
785 {
786 	struct sshsk_provider *skp = NULL;
787 	int r = SSH_ERR_INTERNAL_ERROR;
788 	struct sk_resident_key **rks = NULL;
789 	size_t i, nrks = 0, nsrks = 0;
790 	struct sshkey *key = NULL;
791 	struct sshsk_resident_key *srk = NULL, **srks = NULL, **tmp;
792 	uint8_t sk_flags;
793 	struct sk_option **opts = NULL;
794 
795 	debug_f("provider \"%s\"%s", provider_path,
796 	    (pin != NULL && *pin != '\0') ? ", have-pin": "");
797 
798 	if (srksp == NULL || nsrksp == NULL)
799 		return SSH_ERR_INVALID_ARGUMENT;
800 	*srksp = NULL;
801 	*nsrksp = 0;
802 
803 	if ((r = make_options(device, NULL, &opts)) != 0)
804 		goto out;
805 	if ((skp = sshsk_open(provider_path)) == NULL) {
806 		r = SSH_ERR_INVALID_FORMAT; /* XXX sshsk_open return code? */
807 		goto out;
808 	}
809 	if ((r = skp->sk_load_resident_keys(pin, opts, &rks, &nrks)) != 0) {
810 		error("Provider \"%s\" returned failure %d", provider_path, r);
811 		r = skerr_to_ssherr(r);
812 		goto out;
813 	}
814 	for (i = 0; i < nrks; i++) {
815 		debug3_f("rk %zu: slot %zu, alg %d, app \"%s\", uidlen %zu",
816 		    i, rks[i]->slot, rks[i]->alg, rks[i]->application,
817 		    rks[i]->user_id_len);
818 		/* XXX need better filter here */
819 		if (strncmp(rks[i]->application, "ssh:", 4) != 0)
820 			continue;
821 		switch (rks[i]->alg) {
822 		case SSH_SK_ECDSA:
823 		case SSH_SK_ED25519:
824 			break;
825 		default:
826 			continue;
827 		}
828 		sk_flags = SSH_SK_USER_PRESENCE_REQD|SSH_SK_RESIDENT_KEY;
829 		if ((rks[i]->flags & SSH_SK_USER_VERIFICATION_REQD))
830 			sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
831 		if ((r = sshsk_key_from_response(rks[i]->alg,
832 		    rks[i]->application, sk_flags, &rks[i]->key, &key)) != 0)
833 			goto out;
834 		if ((srk = calloc(1, sizeof(*srk))) == NULL) {
835 			error_f("calloc failed");
836 			r = SSH_ERR_ALLOC_FAIL;
837 			goto out;
838 		}
839 		srk->key = key;
840 		key = NULL; /* transferred */
841 		if ((srk->user_id = calloc(1, rks[i]->user_id_len)) == NULL) {
842 			error_f("calloc failed");
843 			r = SSH_ERR_ALLOC_FAIL;
844 			goto out;
845 		}
846 		memcpy(srk->user_id, rks[i]->user_id, rks[i]->user_id_len);
847 		srk->user_id_len = rks[i]->user_id_len;
848 		if ((tmp = recallocarray(srks, nsrks, nsrks + 1,
849 		    sizeof(*tmp))) == NULL) {
850 			error_f("recallocarray failed");
851 			r = SSH_ERR_ALLOC_FAIL;
852 			goto out;
853 		}
854 		srks = tmp;
855 		srks[nsrks++] = srk;
856 		srk = NULL;
857 		/* XXX synthesise comment */
858 	}
859 	/* success */
860 	*srksp = srks;
861 	*nsrksp = nsrks;
862 	srks = NULL;
863 	nsrks = 0;
864 	r = 0;
865  out:
866 	sshsk_free_options(opts);
867 	sshsk_free(skp);
868 	sshsk_free_sk_resident_keys(rks, nrks);
869 	sshkey_free(key);
870 	sshsk_free_resident_key(srk);
871 	sshsk_free_resident_keys(srks, nsrks);
872 	return r;
873 }
874 
875