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