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