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