1/*	$NetBSD: ssh-sk-client.c,v 1.6 2022/02/23 19:07:20 christos Exp $	*/
2/* $OpenBSD: ssh-sk-client.c,v 1.12 2022/01/14 03:34:00 djm Exp $ */
3/*
4 * Copyright (c) 2019 Google LLC
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18#include "includes.h"
19__RCSID("$NetBSD: ssh-sk-client.c,v 1.6 2022/02/23 19:07:20 christos Exp $");
20
21#include <sys/types.h>
22#include <sys/socket.h>
23#include <sys/wait.h>
24
25#include <fcntl.h>
26#include <limits.h>
27#include <errno.h>
28#include <signal.h>
29#include <stdarg.h>
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#include <unistd.h>
34
35#include "log.h"
36#include "ssherr.h"
37#include "sshbuf.h"
38#include "sshkey.h"
39#include "msg.h"
40#include "digest.h"
41#include "pathnames.h"
42#include "ssh-sk.h"
43#include "misc.h"
44
45/* #define DEBUG_SK 1 */
46
47static int
48start_helper(int *fdp, pid_t *pidp, void (**osigchldp)(int))
49{
50	void (*osigchld)(int);
51	int oerrno, pair[2];
52	pid_t pid;
53	const char *helper, *verbosity = NULL;
54
55	*fdp = -1;
56	*pidp = 0;
57	*osigchldp = SIG_DFL;
58
59	helper = getenv("SSH_SK_HELPER");
60	if (helper == NULL || strlen(helper) == 0)
61		helper = _PATH_SSH_SK_HELPER;
62	if (access(helper, X_OK) != 0) {
63		oerrno = errno;
64		error_f("helper \"%s\" unusable: %s", helper, strerror(errno));
65		errno = oerrno;
66		return SSH_ERR_SYSTEM_ERROR;
67	}
68#ifdef DEBUG_SK
69	verbosity = "-vvv";
70#endif
71
72	/* Start helper */
73	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
74		error("socketpair: %s", strerror(errno));
75		return SSH_ERR_SYSTEM_ERROR;
76	}
77	osigchld = ssh_signal(SIGCHLD, SIG_DFL);
78	if ((pid = fork()) == -1) {
79		oerrno = errno;
80		error("fork: %s", strerror(errno));
81		close(pair[0]);
82		close(pair[1]);
83		ssh_signal(SIGCHLD, osigchld);
84		errno = oerrno;
85		return SSH_ERR_SYSTEM_ERROR;
86	}
87	if (pid == 0) {
88		if ((dup2(pair[1], STDIN_FILENO) == -1) ||
89		    (dup2(pair[1], STDOUT_FILENO) == -1)) {
90			error_f("dup2: %s", strerror(errno));
91			_exit(1);
92		}
93		close(pair[0]);
94		close(pair[1]);
95		closefrom(STDERR_FILENO + 1);
96		debug_f("starting %s %s", helper,
97		    verbosity == NULL ? "" : verbosity);
98		execlp(helper, helper, verbosity, (char *)NULL);
99		error_f("execlp: %s", strerror(errno));
100		_exit(1);
101	}
102	close(pair[1]);
103
104	/* success */
105	debug3_f("started pid=%ld", (long)pid);
106	*fdp = pair[0];
107	*pidp = pid;
108	*osigchldp = osigchld;
109	return 0;
110}
111
112static int
113reap_helper(pid_t pid)
114{
115	int status, oerrno;
116
117	debug3_f("pid=%ld", (long)pid);
118
119	errno = 0;
120	while (waitpid(pid, &status, 0) == -1) {
121		if (errno == EINTR) {
122			errno = 0;
123			continue;
124		}
125		oerrno = errno;
126		error_f("waitpid: %s", strerror(errno));
127		errno = oerrno;
128		return SSH_ERR_SYSTEM_ERROR;
129	}
130	if (!WIFEXITED(status)) {
131		error_f("helper exited abnormally");
132		return SSH_ERR_AGENT_FAILURE;
133	} else if (WEXITSTATUS(status) != 0) {
134		error_f("helper exited with non-zero exit status");
135		return SSH_ERR_AGENT_FAILURE;
136	}
137	return 0;
138}
139
140static int
141client_converse(struct sshbuf *msg, struct sshbuf **respp, u_int type)
142{
143	int oerrno, fd, r2, ll, r = SSH_ERR_INTERNAL_ERROR;
144	u_int rtype, rerr;
145	pid_t pid;
146	u_char version;
147	void (*osigchld)(int);
148	struct sshbuf *req = NULL, *resp = NULL;
149	*respp = NULL;
150
151	if ((r = start_helper(&fd, &pid, &osigchld)) != 0)
152		return r;
153
154	if ((req = sshbuf_new()) == NULL || (resp = sshbuf_new()) == NULL) {
155		r = SSH_ERR_ALLOC_FAIL;
156		goto out;
157	}
158	/* Request preamble: type, log_on_stderr, log_level */
159	ll = log_level_get();
160	if ((r = sshbuf_put_u32(req, type)) != 0 ||
161	    (r = sshbuf_put_u8(req, log_is_on_stderr() != 0)) != 0 ||
162	    (r = sshbuf_put_u32(req, (uint32_t)(ll < 0 ? 0 : ll))) != 0 ||
163	    (r = sshbuf_putb(req, msg)) != 0) {
164		error_fr(r, "compose");
165		goto out;
166	}
167	if ((r = ssh_msg_send(fd, SSH_SK_HELPER_VERSION, req)) != 0) {
168		error_fr(r, "send");
169		goto out;
170	}
171	if ((r = ssh_msg_recv(fd, resp)) != 0) {
172		error_fr(r, "receive");
173		goto out;
174	}
175	if ((r = sshbuf_get_u8(resp, &version)) != 0) {
176		error_fr(r, "parse version");
177		goto out;
178	}
179	if (version != SSH_SK_HELPER_VERSION) {
180		error_f("unsupported version: got %u, expected %u",
181		    version, SSH_SK_HELPER_VERSION);
182		r = SSH_ERR_INVALID_FORMAT;
183		goto out;
184	}
185	if ((r = sshbuf_get_u32(resp, &rtype)) != 0) {
186		error_fr(r, "parse message type");
187		goto out;
188	}
189	if (rtype == SSH_SK_HELPER_ERROR) {
190		if ((r = sshbuf_get_u32(resp, &rerr)) != 0) {
191			error_fr(r, "parse");
192			goto out;
193		}
194		debug_f("helper returned error -%u", rerr);
195		/* OpenSSH error values are negative; encoded as -err on wire */
196		if (rerr == 0 || rerr >= INT_MAX)
197			r = SSH_ERR_INTERNAL_ERROR;
198		else
199			r = -(int)rerr;
200		goto out;
201	} else if (rtype != type) {
202		error_f("helper returned incorrect message type %u, "
203		    "expecting %u", rtype, type);
204		r = SSH_ERR_INTERNAL_ERROR;
205		goto out;
206	}
207	/* success */
208	r = 0;
209 out:
210	oerrno = errno;
211	close(fd);
212	if ((r2 = reap_helper(pid)) != 0) {
213		if (r == 0) {
214			r = r2;
215			oerrno = errno;
216		}
217	}
218	if (r == 0) {
219		*respp = resp;
220		resp = NULL;
221	}
222	sshbuf_free(req);
223	sshbuf_free(resp);
224	ssh_signal(SIGCHLD, osigchld);
225	errno = oerrno;
226	return r;
227
228}
229
230int
231sshsk_sign(const char *provider, struct sshkey *key,
232    u_char **sigp, size_t *lenp, const u_char *data, size_t datalen,
233    u_int compat, const char *pin)
234{
235	int oerrno, r = SSH_ERR_INTERNAL_ERROR;
236	struct sshbuf *kbuf = NULL, *req = NULL, *resp = NULL;
237
238	*sigp = NULL;
239	*lenp = 0;
240
241	if ((kbuf = sshbuf_new()) == NULL ||
242	    (req = sshbuf_new()) == NULL) {
243		r = SSH_ERR_ALLOC_FAIL;
244		goto out;
245	}
246
247	if ((r = sshkey_private_serialize(key, kbuf)) != 0) {
248		error_fr(r, "encode key");
249		goto out;
250	}
251	if ((r = sshbuf_put_stringb(req, kbuf)) != 0 ||
252	    (r = sshbuf_put_cstring(req, provider)) != 0 ||
253	    (r = sshbuf_put_string(req, data, datalen)) != 0 ||
254	    (r = sshbuf_put_cstring(req, NULL)) != 0 || /* alg */
255	    (r = sshbuf_put_u32(req, compat)) != 0 ||
256	    (r = sshbuf_put_cstring(req, pin)) != 0) {
257		error_fr(r, "compose");
258		goto out;
259	}
260
261	if ((r = client_converse(req, &resp, SSH_SK_HELPER_SIGN)) != 0)
262		goto out;
263
264	if ((r = sshbuf_get_string(resp, sigp, lenp)) != 0) {
265		error_fr(r, "parse signature");
266		r = SSH_ERR_INVALID_FORMAT;
267		goto out;
268	}
269	if (sshbuf_len(resp) != 0) {
270		error_f("trailing data in response");
271		r = SSH_ERR_INVALID_FORMAT;
272		goto out;
273	}
274	/* success */
275	r = 0;
276 out:
277	oerrno = errno;
278	if (r != 0) {
279		freezero(*sigp, *lenp);
280		*sigp = NULL;
281		*lenp = 0;
282	}
283	sshbuf_free(kbuf);
284	sshbuf_free(req);
285	sshbuf_free(resp);
286	errno = oerrno;
287	return r;
288}
289
290int
291sshsk_enroll(int type, const char *provider_path, const char *device,
292    const char *application, const char *userid, uint8_t flags,
293    const char *pin, struct sshbuf *challenge_buf,
294    struct sshkey **keyp, struct sshbuf *attest)
295{
296	int oerrno, r = SSH_ERR_INTERNAL_ERROR;
297	struct sshbuf *kbuf = NULL, *abuf = NULL, *req = NULL, *resp = NULL;
298	struct sshkey *key = NULL;
299
300	*keyp = NULL;
301	if (attest != NULL)
302		sshbuf_reset(attest);
303
304	if (type < 0)
305		return SSH_ERR_INVALID_ARGUMENT;
306
307	if ((abuf = sshbuf_new()) == NULL ||
308	    (kbuf = sshbuf_new()) == NULL ||
309	    (req = sshbuf_new()) == NULL) {
310		r = SSH_ERR_ALLOC_FAIL;
311		goto out;
312	}
313
314	if ((r = sshbuf_put_u32(req, (u_int)type)) != 0 ||
315	    (r = sshbuf_put_cstring(req, provider_path)) != 0 ||
316	    (r = sshbuf_put_cstring(req, device)) != 0 ||
317	    (r = sshbuf_put_cstring(req, application)) != 0 ||
318	    (r = sshbuf_put_cstring(req, userid)) != 0 ||
319	    (r = sshbuf_put_u8(req, flags)) != 0 ||
320	    (r = sshbuf_put_cstring(req, pin)) != 0 ||
321	    (r = sshbuf_put_stringb(req, challenge_buf)) != 0) {
322		error_fr(r, "compose");
323		goto out;
324	}
325
326	if ((r = client_converse(req, &resp, SSH_SK_HELPER_ENROLL)) != 0)
327		goto out;
328
329	if ((r = sshbuf_get_stringb(resp, kbuf)) != 0 ||
330	    (r = sshbuf_get_stringb(resp, abuf)) != 0) {
331		error_fr(r, "parse");
332		r = SSH_ERR_INVALID_FORMAT;
333		goto out;
334	}
335	if (sshbuf_len(resp) != 0) {
336		error_f("trailing data in response");
337		r = SSH_ERR_INVALID_FORMAT;
338		goto out;
339	}
340	if ((r = sshkey_private_deserialize(kbuf, &key)) != 0) {
341		error_fr(r, "encode");
342		goto out;
343	}
344	if (attest != NULL && (r = sshbuf_putb(attest, abuf)) != 0) {
345		error_fr(r, "encode attestation information");
346		goto out;
347	}
348
349	/* success */
350	r = 0;
351	*keyp = key;
352	key = NULL;
353 out:
354	oerrno = errno;
355	sshkey_free(key);
356	sshbuf_free(kbuf);
357	sshbuf_free(abuf);
358	sshbuf_free(req);
359	sshbuf_free(resp);
360	errno = oerrno;
361	return r;
362}
363
364static void
365sshsk_free_resident_key(struct sshsk_resident_key *srk)
366{
367	if (srk == NULL)
368		return;
369	sshkey_free(srk->key);
370	freezero(srk->user_id, srk->user_id_len);
371	free(srk);
372}
373
374
375void
376sshsk_free_resident_keys(struct sshsk_resident_key **srks, size_t nsrks)
377{
378	size_t i;
379
380	if (srks == NULL || nsrks == 0)
381		return;
382
383	for (i = 0; i < nsrks; i++)
384		sshsk_free_resident_key(srks[i]);
385	free(srks);
386}
387
388int
389sshsk_load_resident(const char *provider_path, const char *device,
390    const char *pin, u_int flags, struct sshsk_resident_key ***srksp,
391    size_t *nsrksp)
392{
393	int oerrno, r = SSH_ERR_INTERNAL_ERROR;
394	struct sshbuf *kbuf = NULL, *req = NULL, *resp = NULL;
395	struct sshkey *key = NULL;
396	struct sshsk_resident_key *srk = NULL, **srks = NULL, **tmp;
397	u_char *userid = NULL;
398	size_t userid_len = 0, nsrks = 0;
399
400	*srksp = NULL;
401	*nsrksp = 0;
402
403	if ((kbuf = sshbuf_new()) == NULL ||
404	    (req = sshbuf_new()) == NULL) {
405		r = SSH_ERR_ALLOC_FAIL;
406		goto out;
407	}
408
409	if ((r = sshbuf_put_cstring(req, provider_path)) != 0 ||
410	    (r = sshbuf_put_cstring(req, device)) != 0 ||
411	    (r = sshbuf_put_cstring(req, pin)) != 0 ||
412	    (r = sshbuf_put_u32(req, flags)) != 0) {
413		error_fr(r, "compose");
414		goto out;
415	}
416
417	if ((r = client_converse(req, &resp, SSH_SK_HELPER_LOAD_RESIDENT)) != 0)
418		goto out;
419
420	while (sshbuf_len(resp) != 0) {
421		/* key, comment, user_id */
422		if ((r = sshbuf_get_stringb(resp, kbuf)) != 0 ||
423		    (r = sshbuf_get_cstring(resp, NULL, NULL)) != 0 ||
424		    (r = sshbuf_get_string(resp, &userid, &userid_len)) != 0) {
425			error_fr(r, "parse");
426			r = SSH_ERR_INVALID_FORMAT;
427			goto out;
428		}
429		if ((r = sshkey_private_deserialize(kbuf, &key)) != 0) {
430			error_fr(r, "decode key");
431			goto out;
432		}
433		if ((srk = calloc(1, sizeof(*srk))) == NULL) {
434			error_f("calloc failed");
435			goto out;
436		}
437		srk->key = key;
438		key = NULL;
439		srk->user_id = userid;
440		srk->user_id_len = userid_len;
441		userid = NULL;
442		userid_len = 0;
443		if ((tmp = recallocarray(srks, nsrks, nsrks + 1,
444		    sizeof(*srks))) == NULL) {
445			error_f("recallocarray keys failed");
446			goto out;
447		}
448		debug_f("srks[%zu]: %s %s uidlen %zu", nsrks,
449		    sshkey_type(srk->key), srk->key->sk_application,
450		    srk->user_id_len);
451		srks = tmp;
452		srks[nsrks++] = srk;
453		srk = NULL;
454	}
455
456	/* success */
457	r = 0;
458	*srksp = srks;
459	*nsrksp = nsrks;
460	srks = NULL;
461	nsrks = 0;
462 out:
463	oerrno = errno;
464	sshsk_free_resident_key(srk);
465	sshsk_free_resident_keys(srks, nsrks);
466	freezero(userid, userid_len);
467	sshkey_free(key);
468	sshbuf_free(kbuf);
469	sshbuf_free(req);
470	sshbuf_free(resp);
471	errno = oerrno;
472	return r;
473}
474