1/*	$NetBSD: ssh-ecdsa-sk.c,v 1.4 2023/07/26 17:58:16 christos Exp $	*/
2/* $OpenBSD: ssh-ecdsa-sk.c,v 1.18 2023/03/08 04:43:12 guenther Exp $ */
3/*
4 * Copyright (c) 2000 Markus Friedl.  All rights reserved.
5 * Copyright (c) 2010 Damien Miller.  All rights reserved.
6 * Copyright (c) 2019 Google Inc.  All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28#include "includes.h"
29__RCSID("$NetBSD: ssh-ecdsa-sk.c,v 1.4 2023/07/26 17:58:16 christos Exp $");
30
31/* #define DEBUG_SK 1 */
32
33#include <sys/types.h>
34
35#include <openssl/bn.h>
36#include <openssl/ec.h>
37#include <openssl/ecdsa.h>
38#include <openssl/evp.h>
39
40#include <string.h>
41#include <stdio.h> /* needed for DEBUG_SK only */
42
43#include "sshbuf.h"
44#include "ssherr.h"
45#include "digest.h"
46#define SSHKEY_INTERNAL
47#include "sshkey.h"
48
49/* Reuse some ECDSA internals */
50extern struct sshkey_impl_funcs sshkey_ecdsa_funcs;
51
52static void
53ssh_ecdsa_sk_cleanup(struct sshkey *k)
54{
55	sshkey_sk_cleanup(k);
56	sshkey_ecdsa_funcs.cleanup(k);
57}
58
59static int
60ssh_ecdsa_sk_equal(const struct sshkey *a, const struct sshkey *b)
61{
62	if (!sshkey_sk_fields_equal(a, b))
63		return 0;
64	if (!sshkey_ecdsa_funcs.equal(a, b))
65		return 0;
66	return 1;
67}
68
69static int
70ssh_ecdsa_sk_serialize_public(const struct sshkey *key, struct sshbuf *b,
71    enum sshkey_serialize_rep opts)
72{
73	int r;
74
75	if ((r = sshkey_ecdsa_funcs.serialize_public(key, b, opts)) != 0)
76		return r;
77	if ((r = sshkey_serialize_sk(key, b)) != 0)
78		return r;
79
80	return 0;
81}
82
83static int
84ssh_ecdsa_sk_serialize_private(const struct sshkey *key, struct sshbuf *b,
85    enum sshkey_serialize_rep opts)
86{
87	int r;
88
89	if (!sshkey_is_cert(key)) {
90		if ((r = sshkey_ecdsa_funcs.serialize_public(key,
91		    b, opts)) != 0)
92			return r;
93	}
94	if ((r = sshkey_serialize_private_sk(key, b)) != 0)
95		return r;
96
97	return 0;
98}
99
100static int
101ssh_ecdsa_sk_copy_public(const struct sshkey *from, struct sshkey *to)
102{
103	int r;
104
105	if ((r = sshkey_ecdsa_funcs.copy_public(from, to)) != 0)
106		return r;
107	if ((r = sshkey_copy_public_sk(from, to)) != 0)
108		return r;
109	return 0;
110}
111
112static int
113ssh_ecdsa_sk_deserialize_public(const char *ktype, struct sshbuf *b,
114    struct sshkey *key)
115{
116	int r;
117
118	if ((r = sshkey_ecdsa_funcs.deserialize_public(ktype, b, key)) != 0)
119		return r;
120	if ((r = sshkey_deserialize_sk(b, key)) != 0)
121		return r;
122	return 0;
123}
124
125static int
126ssh_ecdsa_sk_deserialize_private(const char *ktype, struct sshbuf *b,
127    struct sshkey *key)
128{
129	int r;
130
131	if (!sshkey_is_cert(key)) {
132		if ((r = sshkey_ecdsa_funcs.deserialize_public(ktype,
133		    b, key)) != 0)
134			return r;
135	}
136	if ((r = sshkey_private_deserialize_sk(b, key)) != 0)
137		return r;
138
139	return 0;
140}
141
142/*
143 * Check FIDO/W3C webauthn signatures clientData field against the expected
144 * format and prepare a hash of it for use in signature verification.
145 *
146 * webauthn signatures do not sign the hash of the message directly, but
147 * instead sign a JSON-like "clientData" wrapper structure that contains the
148 * message hash along with a other information.
149 *
150 * Fortunately this structure has a fixed format so it is possible to verify
151 * that the hash of the signed message is present within the clientData
152 * structure without needing to implement any JSON parsing.
153 */
154static int
155webauthn_check_prepare_hash(const u_char *data, size_t datalen,
156    const char *origin, const struct sshbuf *wrapper,
157    uint8_t flags, const struct sshbuf *extensions,
158    u_char *msghash, size_t msghashlen)
159{
160	int r = SSH_ERR_INTERNAL_ERROR;
161	struct sshbuf *chall = NULL, *m = NULL;
162
163	if ((m = sshbuf_new()) == NULL ||
164	    (chall = sshbuf_from(data, datalen)) == NULL) {
165		r = SSH_ERR_ALLOC_FAIL;
166		goto out;
167	}
168	/*
169	 * Ensure origin contains no quote character and that the flags are
170	 * consistent with what we received
171	 */
172	if (strchr(origin, '\"') != NULL ||
173	    (flags & 0x40) != 0 /* AD */ ||
174	    ((flags & 0x80) == 0 /* ED */) != (sshbuf_len(extensions) == 0)) {
175		r = SSH_ERR_INVALID_FORMAT;
176		goto out;
177	}
178
179	/*
180	 * Prepare the preamble to clientData that we expect, poking the
181	 * challenge and origin into their canonical positions in the
182	 * structure. The crossOrigin flag and any additional extension
183	 * fields present are ignored.
184	 */
185#define WEBAUTHN_0	"{\"type\":\"webauthn.get\",\"challenge\":\""
186#define WEBAUTHN_1	"\",\"origin\":\""
187#define WEBAUTHN_2	"\""
188	if ((r = sshbuf_put(m, WEBAUTHN_0, sizeof(WEBAUTHN_0) - 1)) != 0 ||
189	    (r = sshbuf_dtourlb64(chall, m, 0)) != 0 ||
190	    (r = sshbuf_put(m, WEBAUTHN_1, sizeof(WEBAUTHN_1) - 1)) != 0 ||
191	    (r = sshbuf_put(m, origin, strlen(origin))) != 0 ||
192	    (r = sshbuf_put(m, WEBAUTHN_2, sizeof(WEBAUTHN_2) - 1)) != 0)
193		goto out;
194#ifdef DEBUG_SK
195	fprintf(stderr, "%s: received origin: %s\n", __func__, origin);
196	fprintf(stderr, "%s: received clientData:\n", __func__);
197	sshbuf_dump(wrapper, stderr);
198	fprintf(stderr, "%s: expected clientData premable:\n", __func__);
199	sshbuf_dump(m, stderr);
200#endif
201	/* Check that the supplied clientData has the preamble we expect */
202	if ((r = sshbuf_cmp(wrapper, 0, sshbuf_ptr(m), sshbuf_len(m))) != 0)
203		goto out;
204
205	/* Prepare hash of clientData */
206	if ((r = ssh_digest_buffer(SSH_DIGEST_SHA256, wrapper,
207	    msghash, msghashlen)) != 0)
208		goto out;
209
210	/* success */
211	r = 0;
212 out:
213	sshbuf_free(chall);
214	sshbuf_free(m);
215	return r;
216}
217
218static int
219ssh_ecdsa_sk_verify(const struct sshkey *key,
220    const u_char *sig, size_t siglen,
221    const u_char *data, size_t dlen, const char *alg, u_int compat,
222    struct sshkey_sig_details **detailsp)
223{
224	ECDSA_SIG *esig = NULL;
225	BIGNUM *sig_r = NULL, *sig_s = NULL;
226	u_char sig_flags;
227	u_char msghash[32], apphash[32], sighash[32];
228	u_int sig_counter;
229	int is_webauthn = 0, ret = SSH_ERR_INTERNAL_ERROR;
230	struct sshbuf *b = NULL, *sigbuf = NULL, *original_signed = NULL;
231	struct sshbuf *webauthn_wrapper = NULL, *webauthn_exts = NULL;
232	char *ktype = NULL, *webauthn_origin = NULL;
233	struct sshkey_sig_details *details = NULL;
234#ifdef DEBUG_SK
235	char *tmp = NULL;
236#endif
237
238	if (detailsp != NULL)
239		*detailsp = NULL;
240	if (key == NULL || key->ecdsa == NULL ||
241	    sshkey_type_plain(key->type) != KEY_ECDSA_SK ||
242	    sig == NULL || siglen == 0)
243		return SSH_ERR_INVALID_ARGUMENT;
244
245	if (key->ecdsa_nid != NID_X9_62_prime256v1)
246		return SSH_ERR_INTERNAL_ERROR;
247
248	/* fetch signature */
249	if ((b = sshbuf_from(sig, siglen)) == NULL)
250		return SSH_ERR_ALLOC_FAIL;
251	if ((details = calloc(1, sizeof(*details))) == NULL) {
252		ret = SSH_ERR_ALLOC_FAIL;
253		goto out;
254	}
255	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
256		ret = SSH_ERR_INVALID_FORMAT;
257		goto out;
258	}
259	if (strcmp(ktype, "webauthn-sk-ecdsa-sha2-nistp256@openssh.com") == 0)
260		is_webauthn = 1;
261	else if (strcmp(ktype, "sk-ecdsa-sha2-nistp256@openssh.com") != 0) {
262		ret = SSH_ERR_INVALID_FORMAT;
263		goto out;
264	}
265	if (sshbuf_froms(b, &sigbuf) != 0 ||
266	    sshbuf_get_u8(b, &sig_flags) != 0 ||
267	    sshbuf_get_u32(b, &sig_counter) != 0) {
268		ret = SSH_ERR_INVALID_FORMAT;
269		goto out;
270	}
271	if (is_webauthn) {
272		if (sshbuf_get_cstring(b, &webauthn_origin, NULL) != 0 ||
273		    sshbuf_froms(b, &webauthn_wrapper) != 0 ||
274		    sshbuf_froms(b, &webauthn_exts) != 0) {
275			ret = SSH_ERR_INVALID_FORMAT;
276			goto out;
277		}
278	}
279	if (sshbuf_len(b) != 0) {
280		ret = SSH_ERR_UNEXPECTED_TRAILING_DATA;
281		goto out;
282	}
283
284	/* parse signature */
285	if (sshbuf_get_bignum2(sigbuf, &sig_r) != 0 ||
286	    sshbuf_get_bignum2(sigbuf, &sig_s) != 0) {
287		ret = SSH_ERR_INVALID_FORMAT;
288		goto out;
289	}
290	if (sshbuf_len(sigbuf) != 0) {
291		ret = SSH_ERR_UNEXPECTED_TRAILING_DATA;
292		goto out;
293	}
294
295#ifdef DEBUG_SK
296	fprintf(stderr, "%s: data: (len %zu)\n", __func__, datalen);
297	/* sshbuf_dump_data(data, datalen, stderr); */
298	fprintf(stderr, "%s: sig_r: %s\n", __func__, (tmp = BN_bn2hex(sig_r)));
299	free(tmp);
300	fprintf(stderr, "%s: sig_s: %s\n", __func__, (tmp = BN_bn2hex(sig_s)));
301	free(tmp);
302	fprintf(stderr, "%s: sig_flags = 0x%02x, sig_counter = %u\n",
303	    __func__, sig_flags, sig_counter);
304	if (is_webauthn) {
305		fprintf(stderr, "%s: webauthn origin: %s\n", __func__,
306		    webauthn_origin);
307		fprintf(stderr, "%s: webauthn_wrapper:\n", __func__);
308		sshbuf_dump(webauthn_wrapper, stderr);
309	}
310#endif
311	if ((esig = ECDSA_SIG_new()) == NULL) {
312		ret = SSH_ERR_ALLOC_FAIL;
313		goto out;
314	}
315	if (!ECDSA_SIG_set0(esig, sig_r, sig_s)) {
316		ret = SSH_ERR_LIBCRYPTO_ERROR;
317		goto out;
318	}
319	sig_r = sig_s = NULL; /* transferred */
320
321	/* Reconstruct data that was supposedly signed */
322	if ((original_signed = sshbuf_new()) == NULL) {
323		ret = SSH_ERR_ALLOC_FAIL;
324		goto out;
325	}
326	if (is_webauthn) {
327		if ((ret = webauthn_check_prepare_hash(data, dlen,
328		    webauthn_origin, webauthn_wrapper, sig_flags, webauthn_exts,
329		    msghash, sizeof(msghash))) != 0)
330			goto out;
331	} else if ((ret = ssh_digest_memory(SSH_DIGEST_SHA256, data, dlen,
332	    msghash, sizeof(msghash))) != 0)
333		goto out;
334	/* Application value is hashed before signature */
335	if ((ret = ssh_digest_memory(SSH_DIGEST_SHA256, key->sk_application,
336	    strlen(key->sk_application), apphash, sizeof(apphash))) != 0)
337		goto out;
338#ifdef DEBUG_SK
339	fprintf(stderr, "%s: hashed application:\n", __func__);
340	sshbuf_dump_data(apphash, sizeof(apphash), stderr);
341	fprintf(stderr, "%s: hashed message:\n", __func__);
342	sshbuf_dump_data(msghash, sizeof(msghash), stderr);
343#endif
344	if ((ret = sshbuf_put(original_signed,
345	    apphash, sizeof(apphash))) != 0 ||
346	    (ret = sshbuf_put_u8(original_signed, sig_flags)) != 0 ||
347	    (ret = sshbuf_put_u32(original_signed, sig_counter)) != 0 ||
348	    (ret = sshbuf_putb(original_signed, webauthn_exts)) != 0 ||
349	    (ret = sshbuf_put(original_signed, msghash, sizeof(msghash))) != 0)
350		goto out;
351	/* Signature is over H(original_signed) */
352	if ((ret = ssh_digest_buffer(SSH_DIGEST_SHA256, original_signed,
353	    sighash, sizeof(sighash))) != 0)
354		goto out;
355	details->sk_counter = sig_counter;
356	details->sk_flags = sig_flags;
357#ifdef DEBUG_SK
358	fprintf(stderr, "%s: signed buf:\n", __func__);
359	sshbuf_dump(original_signed, stderr);
360	fprintf(stderr, "%s: signed hash:\n", __func__);
361	sshbuf_dump_data(sighash, sizeof(sighash), stderr);
362#endif
363
364	/* Verify it */
365	switch (ECDSA_do_verify(sighash, sizeof(sighash), esig, key->ecdsa)) {
366	case 1:
367		ret = 0;
368		break;
369	case 0:
370		ret = SSH_ERR_SIGNATURE_INVALID;
371		goto out;
372	default:
373		ret = SSH_ERR_LIBCRYPTO_ERROR;
374		goto out;
375	}
376	/* success */
377	if (detailsp != NULL) {
378		*detailsp = details;
379		details = NULL;
380	}
381 out:
382	explicit_bzero(&sig_flags, sizeof(sig_flags));
383	explicit_bzero(&sig_counter, sizeof(sig_counter));
384	explicit_bzero(msghash, sizeof(msghash));
385	explicit_bzero(sighash, sizeof(msghash));
386	explicit_bzero(apphash, sizeof(apphash));
387	sshkey_sig_details_free(details);
388	sshbuf_free(webauthn_wrapper);
389	sshbuf_free(webauthn_exts);
390	free(webauthn_origin);
391	sshbuf_free(original_signed);
392	sshbuf_free(sigbuf);
393	sshbuf_free(b);
394	ECDSA_SIG_free(esig);
395	BN_clear_free(sig_r);
396	BN_clear_free(sig_s);
397	free(ktype);
398	return ret;
399}
400
401static const struct sshkey_impl_funcs sshkey_ecdsa_sk_funcs = {
402	/* .size = */		NULL,
403	/* .alloc = */		NULL,
404	/* .cleanup = */	ssh_ecdsa_sk_cleanup,
405	/* .equal = */		ssh_ecdsa_sk_equal,
406	/* .ssh_serialize_public = */ ssh_ecdsa_sk_serialize_public,
407	/* .ssh_deserialize_public = */ ssh_ecdsa_sk_deserialize_public,
408	/* .ssh_serialize_private = */ ssh_ecdsa_sk_serialize_private,
409	/* .ssh_deserialize_private = */ ssh_ecdsa_sk_deserialize_private,
410	/* .generate = */	NULL,
411	/* .copy_public = */	ssh_ecdsa_sk_copy_public,
412	/* .sign = */		NULL,
413	/* .verify = */		ssh_ecdsa_sk_verify,
414};
415
416const struct sshkey_impl sshkey_ecdsa_sk_impl = {
417	/* .name = */		"sk-ecdsa-sha2-nistp256@openssh.com",
418	/* .shortname = */	"ECDSA-SK",
419	/* .sigalg = */		NULL,
420	/* .type = */		KEY_ECDSA_SK,
421	/* .nid = */		NID_X9_62_prime256v1,
422	/* .cert = */		0,
423	/* .sigonly = */	0,
424	/* .keybits = */	256,
425	/* .funcs = */		&sshkey_ecdsa_sk_funcs,
426};
427
428const struct sshkey_impl sshkey_ecdsa_sk_cert_impl = {
429	/* .name = */		"sk-ecdsa-sha2-nistp256-cert-v01@openssh.com",
430	/* .shortname = */	"ECDSA-SK-CERT",
431	/* .sigalg = */		NULL,
432	/* .type = */		KEY_ECDSA_SK_CERT,
433	/* .nid = */		NID_X9_62_prime256v1,
434	/* .cert = */		1,
435	/* .sigonly = */	0,
436	/* .keybits = */	256,
437	/* .funcs = */		&sshkey_ecdsa_sk_funcs,
438};
439
440const struct sshkey_impl sshkey_ecdsa_sk_webauthn_impl = {
441	/* .name = */		"webauthn-sk-ecdsa-sha2-nistp256@openssh.com",
442	/* .shortname = */	"ECDSA-SK",
443	/* .sigalg = */		NULL,
444	/* .type = */		KEY_ECDSA_SK,
445	/* .nid = */		NID_X9_62_prime256v1,
446	/* .cert = */		0,
447	/* .sigonly = */	1,
448	/* .keybits = */	256,
449	/* .funcs = */		&sshkey_ecdsa_sk_funcs,
450};
451