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