ssh-pkcs11-client.c revision 1.18
1/*	$NetBSD: ssh-pkcs11-client.c,v 1.18 2023/10/25 20:19:57 christos Exp $	*/
2/* $OpenBSD: ssh-pkcs11-client.c,v 1.18 2023/07/19 14:03:45 djm Exp $ */
3
4/*
5 * Copyright (c) 2010 Markus Friedl.  All rights reserved.
6 * Copyright (c) 2014 Pedro Martelletto. All rights reserved.
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
20#include "includes.h"
21__RCSID("$NetBSD: ssh-pkcs11-client.c,v 1.18 2023/10/25 20:19:57 christos Exp $");
22
23#include <sys/types.h>
24#include <sys/time.h>
25#include <sys/socket.h>
26
27#include <stdarg.h>
28#include <string.h>
29#include <unistd.h>
30#include <errno.h>
31#include <limits.h>
32
33#include <openssl/ecdsa.h>
34#include <openssl/rsa.h>
35
36#include "pathnames.h"
37#include "xmalloc.h"
38#include "sshbuf.h"
39#include "log.h"
40#include "misc.h"
41#include "sshkey.h"
42#include "authfd.h"
43#include "atomicio.h"
44#include "ssh-pkcs11.h"
45#include "ssherr.h"
46
47/* borrows code from sftp-server and ssh-agent */
48
49/*
50 * Maintain a list of ssh-pkcs11-helper subprocesses. These may be looked up
51 * by provider path or their unique EC/RSA METHOD pointers.
52 */
53struct helper {
54	char *path;
55	pid_t pid;
56	int fd;
57	RSA_METHOD *rsa_meth;
58	EC_KEY_METHOD *ec_meth;
59	int (*rsa_finish)(RSA *rsa);
60	void (*ec_finish)(EC_KEY *key);
61	size_t nrsa, nec; /* number of active keys of each type */
62};
63static struct helper **helpers;
64static size_t nhelpers;
65
66static struct helper *
67helper_by_provider(const char *path)
68{
69	size_t i;
70
71	for (i = 0; i < nhelpers; i++) {
72		if (helpers[i] == NULL || helpers[i]->path == NULL ||
73		    helpers[i]->fd == -1)
74			continue;
75		if (strcmp(helpers[i]->path, path) == 0)
76			return helpers[i];
77	}
78	return NULL;
79}
80
81static struct helper *
82helper_by_rsa(const RSA *rsa)
83{
84	size_t i;
85	const RSA_METHOD *meth;
86
87	if ((meth = RSA_get_method(rsa)) == NULL)
88		return NULL;
89	for (i = 0; i < nhelpers; i++) {
90		if (helpers[i] != NULL && helpers[i]->rsa_meth == meth)
91			return helpers[i];
92	}
93	return NULL;
94
95}
96
97static struct helper *
98helper_by_ec(const EC_KEY *ec)
99{
100	size_t i;
101	const EC_KEY_METHOD *meth;
102
103	if ((meth = EC_KEY_get_method(ec)) == NULL)
104		return NULL;
105	for (i = 0; i < nhelpers; i++) {
106		if (helpers[i] != NULL && helpers[i]->ec_meth == meth)
107			return helpers[i];
108	}
109	return NULL;
110
111}
112
113static void
114helper_free(struct helper *helper)
115{
116	size_t i;
117	int found = 0;
118
119	if (helper == NULL)
120		return;
121	if (helper->path == NULL || helper->ec_meth == NULL ||
122	    helper->rsa_meth == NULL)
123		fatal_f("inconsistent helper");
124	debug3_f("free helper for provider %s", helper->path);
125	for (i = 0; i < nhelpers; i++) {
126		if (helpers[i] == helper) {
127			if (found)
128				fatal_f("helper recorded more than once");
129			found = 1;
130		}
131		else if (found)
132			helpers[i - 1] = helpers[i];
133	}
134	if (found) {
135		helpers = xrecallocarray(helpers, nhelpers,
136		    nhelpers - 1, sizeof(*helpers));
137		nhelpers--;
138	}
139	free(helper->path);
140	EC_KEY_METHOD_free(helper->ec_meth);
141	RSA_meth_free(helper->rsa_meth);
142	free(helper);
143}
144
145static void
146helper_terminate(struct helper *helper)
147{
148	if (helper == NULL) {
149		return;
150	} else if (helper->fd == -1) {
151		debug3_f("already terminated");
152	} else {
153		debug3_f("terminating helper for %s; "
154		    "remaining %zu RSA %zu ECDSA",
155		    helper->path, helper->nrsa, helper->nec);
156		close(helper->fd);
157		/* XXX waitpid() */
158		helper->fd = -1;
159		helper->pid = -1;
160	}
161	/*
162	 * Don't delete the helper entry until there are no remaining keys
163	 * that reference it. Otherwise, any signing operation would call
164	 * a free'd METHOD pointer and that would be bad.
165	 */
166	if (helper->nrsa == 0 && helper->nec == 0)
167		helper_free(helper);
168}
169
170static void
171send_msg(int fd, struct sshbuf *m)
172{
173	u_char buf[4];
174	size_t mlen = sshbuf_len(m);
175	int r;
176
177	if (fd == -1)
178		return;
179	POKE_U32(buf, mlen);
180	if (atomicio(vwrite, fd, buf, 4) != 4 ||
181	    atomicio(vwrite, fd, sshbuf_mutable_ptr(m),
182	    sshbuf_len(m)) != sshbuf_len(m))
183		error("write to helper failed");
184	if ((r = sshbuf_consume(m, mlen)) != 0)
185		fatal_fr(r, "consume");
186}
187
188static int
189recv_msg(int fd, struct sshbuf *m)
190{
191	u_int l, len;
192	u_char c, buf[1024];
193	int r;
194
195	sshbuf_reset(m);
196	if (fd == -1)
197		return 0; /* XXX */
198	if ((len = atomicio(read, fd, buf, 4)) != 4) {
199		error("read from helper failed: %u", len);
200		return (0); /* XXX */
201	}
202	len = PEEK_U32(buf);
203	if (len > 256 * 1024)
204		fatal("response too long: %u", len);
205	/* read len bytes into m */
206	while (len > 0) {
207		l = len;
208		if (l > sizeof(buf))
209			l = sizeof(buf);
210		if (atomicio(read, fd, buf, l) != l) {
211			error("response from helper failed.");
212			return (0); /* XXX */
213		}
214		if ((r = sshbuf_put(m, buf, l)) != 0)
215			fatal_fr(r, "sshbuf_put");
216		len -= l;
217	}
218	if ((r = sshbuf_get_u8(m, &c)) != 0)
219		fatal_fr(r, "parse type");
220	return c;
221}
222
223int
224pkcs11_init(int interactive)
225{
226	return 0;
227}
228
229void
230pkcs11_terminate(void)
231{
232	size_t i;
233
234	debug3_f("terminating %zu helpers", nhelpers);
235	for (i = 0; i < nhelpers; i++)
236		helper_terminate(helpers[i]);
237}
238
239static int
240rsa_encrypt(int flen, const u_char *from, u_char *to, RSA *rsa, int padding)
241{
242	struct sshkey *key = NULL;
243	struct sshbuf *msg = NULL;
244	u_char *blob = NULL, *signature = NULL;
245	size_t blen, slen = 0;
246	int r, ret = -1;
247	struct helper *helper;
248
249	if ((helper = helper_by_rsa(rsa)) == NULL || helper->fd == -1)
250		fatal_f("no helper for PKCS11 key");
251	debug3_f("signing with PKCS11 provider %s", helper->path);
252	if (padding != RSA_PKCS1_PADDING)
253		goto fail;
254	key = sshkey_new(KEY_UNSPEC);
255	if (key == NULL) {
256		error_f("sshkey_new failed");
257		goto fail;
258	}
259	key->type = KEY_RSA;
260	RSA_up_ref(rsa);
261	key->rsa = rsa;
262	if ((r = sshkey_to_blob(key, &blob, &blen)) != 0) {
263		error_fr(r, "encode key");
264		goto fail;
265	}
266	if ((msg = sshbuf_new()) == NULL)
267		fatal_f("sshbuf_new failed");
268	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 ||
269	    (r = sshbuf_put_string(msg, blob, blen)) != 0 ||
270	    (r = sshbuf_put_string(msg, from, flen)) != 0 ||
271	    (r = sshbuf_put_u32(msg, 0)) != 0)
272		fatal_fr(r, "compose");
273	send_msg(helper->fd, msg);
274	sshbuf_reset(msg);
275
276	if (recv_msg(helper->fd, msg) == SSH2_AGENT_SIGN_RESPONSE) {
277		if ((r = sshbuf_get_string(msg, &signature, &slen)) != 0)
278			fatal_fr(r, "parse");
279		if (slen <= (size_t)RSA_size(rsa)) {
280			memcpy(to, signature, slen);
281			ret = slen;
282		}
283		free(signature);
284	}
285 fail:
286	free(blob);
287	sshkey_free(key);
288	sshbuf_free(msg);
289	return (ret);
290}
291
292static int
293rsa_finish(RSA *rsa)
294{
295	struct helper *helper;
296
297	if ((helper = helper_by_rsa(rsa)) == NULL)
298		fatal_f("no helper for PKCS11 key");
299	debug3_f("free PKCS11 RSA key for provider %s", helper->path);
300	if (helper->rsa_finish != NULL)
301		helper->rsa_finish(rsa);
302	if (helper->nrsa == 0)
303		fatal_f("RSA refcount error");
304	helper->nrsa--;
305	debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA",
306	    helper->path, helper->nrsa, helper->nec);
307	if (helper->nrsa == 0 && helper->nec == 0)
308		helper_terminate(helper);
309	return 1;
310}
311
312static ECDSA_SIG *
313ecdsa_do_sign(const unsigned char *dgst, int dgst_len, const BIGNUM *inv,
314    const BIGNUM *rp, EC_KEY *ec)
315{
316	struct sshkey *key = NULL;
317	struct sshbuf *msg = NULL;
318	ECDSA_SIG *ret = NULL;
319	const u_char *cp;
320	u_char *blob = NULL, *signature = NULL;
321	size_t blen, slen = 0;
322	int r, nid;
323	struct helper *helper;
324
325	if ((helper = helper_by_ec(ec)) == NULL || helper->fd == -1)
326		fatal_f("no helper for PKCS11 key");
327	debug3_f("signing with PKCS11 provider %s", helper->path);
328	nid = sshkey_ecdsa_key_to_nid(ec);
329	if (nid < 0) {
330		error_f("couldn't get curve nid");
331		goto fail;
332	}
333
334	key = sshkey_new(KEY_UNSPEC);
335	if (key == NULL) {
336		error_f("sshkey_new failed");
337		goto fail;
338	}
339	key->ecdsa = ec;
340	key->ecdsa_nid = nid;
341	key->type = KEY_ECDSA;
342	EC_KEY_up_ref(ec);
343
344	if ((r = sshkey_to_blob(key, &blob, &blen)) != 0) {
345		error_fr(r, "encode key");
346		goto fail;
347	}
348	if ((msg = sshbuf_new()) == NULL)
349		fatal_f("sshbuf_new failed");
350	if ((r = sshbuf_put_u8(msg, SSH2_AGENTC_SIGN_REQUEST)) != 0 ||
351	    (r = sshbuf_put_string(msg, blob, blen)) != 0 ||
352	    (r = sshbuf_put_string(msg, dgst, dgst_len)) != 0 ||
353	    (r = sshbuf_put_u32(msg, 0)) != 0)
354		fatal_fr(r, "compose");
355	send_msg(helper->fd, msg);
356	sshbuf_reset(msg);
357
358	if (recv_msg(helper->fd, msg) == SSH2_AGENT_SIGN_RESPONSE) {
359		if ((r = sshbuf_get_string(msg, &signature, &slen)) != 0)
360			fatal_fr(r, "parse");
361		cp = signature;
362		ret = d2i_ECDSA_SIG(NULL, &cp, slen);
363		free(signature);
364	}
365
366 fail:
367	free(blob);
368	sshkey_free(key);
369	sshbuf_free(msg);
370	return (ret);
371}
372
373static void
374ecdsa_do_finish(EC_KEY *ec)
375{
376	struct helper *helper;
377
378	if ((helper = helper_by_ec(ec)) == NULL)
379		fatal_f("no helper for PKCS11 key");
380	debug3_f("free PKCS11 ECDSA key for provider %s", helper->path);
381	if (helper->ec_finish != NULL)
382		helper->ec_finish(ec);
383	if (helper->nec == 0)
384		fatal_f("ECDSA refcount error");
385	helper->nec--;
386	debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA",
387	    helper->path, helper->nrsa, helper->nec);
388	if (helper->nrsa == 0 && helper->nec == 0)
389		helper_terminate(helper);
390}
391
392/* redirect private key crypto operations to the ssh-pkcs11-helper */
393static void
394wrap_key(struct helper *helper, struct sshkey *k)
395{
396	debug3_f("wrap %s for provider %s", sshkey_type(k), helper->path);
397	if (k->type == KEY_RSA) {
398		RSA_set_method(k->rsa, helper->rsa_meth);
399		if (helper->nrsa++ >= INT_MAX)
400			fatal_f("RSA refcount error");
401	} else if (k->type == KEY_ECDSA) {
402		EC_KEY_set_method(k->ecdsa, helper->ec_meth);
403		if (helper->nec++ >= INT_MAX)
404			fatal_f("EC refcount error");
405	} else
406		fatal_f("unknown key type");
407	k->flags |= SSHKEY_FLAG_EXT;
408	debug3_f("provider %s remaining keys: %zu RSA %zu ECDSA",
409	    helper->path, helper->nrsa, helper->nec);
410}
411
412static int
413pkcs11_start_helper_methods(struct helper *helper)
414{
415	int (*ec_init)(EC_KEY *key);
416	int (*ec_copy)(EC_KEY *dest, const EC_KEY *src);
417	int (*ec_set_group)(EC_KEY *key, const EC_GROUP *grp);
418	int (*ec_set_private)(EC_KEY *key, const BIGNUM *priv_key);
419	int (*ec_set_public)(EC_KEY *key, const EC_POINT *pub_key);
420	int (*ec_sign)(int, const unsigned char *, int, unsigned char *,
421	    unsigned int *, const BIGNUM *, const BIGNUM *, EC_KEY *) = NULL;
422	RSA_METHOD *rsa_meth;
423	EC_KEY_METHOD *ec_meth;
424
425	if ((ec_meth = EC_KEY_METHOD_new(EC_KEY_OpenSSL())) == NULL)
426		return -1;
427	EC_KEY_METHOD_get_sign(ec_meth, &ec_sign, NULL, NULL);
428	EC_KEY_METHOD_set_sign(ec_meth, ec_sign, NULL, ecdsa_do_sign);
429	EC_KEY_METHOD_get_init(ec_meth, &ec_init, &helper->ec_finish,
430	    &ec_copy, &ec_set_group, &ec_set_private, &ec_set_public);
431	EC_KEY_METHOD_set_init(ec_meth, ec_init, ecdsa_do_finish,
432	    ec_copy, ec_set_group, ec_set_private, ec_set_public);
433
434	if ((rsa_meth = RSA_meth_dup(RSA_get_default_method())) == NULL)
435		fatal_f("RSA_meth_dup failed");
436	helper->rsa_finish = RSA_meth_get_finish(rsa_meth);
437	if (!RSA_meth_set1_name(rsa_meth, "ssh-pkcs11-helper") ||
438	    !RSA_meth_set_priv_enc(rsa_meth, rsa_encrypt) ||
439	    !RSA_meth_set_finish(rsa_meth, rsa_finish))
440		fatal_f("failed to prepare method");
441
442	helper->ec_meth = ec_meth;
443	helper->rsa_meth = rsa_meth;
444	return 0;
445}
446
447static struct helper *
448pkcs11_start_helper(const char *path)
449{
450	int pair[2];
451	const char *prog, *verbosity = NULL;
452	struct helper *helper;
453	pid_t pid;
454
455	if (nhelpers >= INT_MAX)
456		fatal_f("too many helpers");
457	debug3_f("start helper for %s", path);
458	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
459		error_f("socketpair: %s", strerror(errno));
460		return NULL;
461	}
462	helper = xcalloc(1, sizeof(*helper));
463	if (pkcs11_start_helper_methods(helper) == -1) {
464		error_f("pkcs11_start_helper_methods failed");
465		goto fail;
466	}
467	if ((pid = fork()) == -1) {
468		error_f("fork: %s", strerror(errno));
469 fail:
470		close(pair[0]);
471		close(pair[1]);
472		RSA_meth_free(helper->rsa_meth);
473		EC_KEY_METHOD_free(helper->ec_meth);
474		free(helper);
475		return NULL;
476	} else if (pid == 0) {
477		if ((dup2(pair[1], STDIN_FILENO) == -1) ||
478		    (dup2(pair[1], STDOUT_FILENO) == -1)) {
479			fprintf(stderr, "dup2: %s\n", strerror(errno));
480			_exit(1);
481		}
482		close(pair[0]);
483		close(pair[1]);
484		prog = getenv("SSH_PKCS11_HELPER");
485		if (prog == NULL || strlen(prog) == 0)
486			prog = _PATH_SSH_PKCS11_HELPER;
487		if (log_level_get() >= SYSLOG_LEVEL_DEBUG1)
488			verbosity = "-vvv";
489		debug_f("starting %s %s", prog,
490		    verbosity == NULL ? "" : verbosity);
491		execlp(prog, prog, verbosity, (char *)NULL);
492		fprintf(stderr, "exec: %s: %s\n", prog, strerror(errno));
493		_exit(1);
494	}
495	close(pair[1]);
496	helper->fd = pair[0];
497	helper->path = xstrdup(path);
498	helper->pid = pid;
499	debug3_f("helper %zu for \"%s\" on fd %d pid %ld", nhelpers,
500	    helper->path, helper->fd, (long)helper->pid);
501	helpers = xrecallocarray(helpers, nhelpers,
502	    nhelpers + 1, sizeof(*helpers));
503	helpers[nhelpers++] = helper;
504	return helper;
505}
506
507int
508pkcs11_add_provider(char *name, char *pin, struct sshkey ***keysp,
509    char ***labelsp)
510{
511	struct sshkey *k;
512	int r, type;
513	u_char *blob;
514	char *label;
515	size_t blen;
516	u_int nkeys, i;
517	struct sshbuf *msg;
518	struct helper *helper;
519
520	if ((helper = helper_by_provider(name)) == NULL &&
521	    (helper = pkcs11_start_helper(name)) == NULL)
522		return -1;
523
524	if ((msg = sshbuf_new()) == NULL)
525		fatal_f("sshbuf_new failed");
526	if ((r = sshbuf_put_u8(msg, SSH_AGENTC_ADD_SMARTCARD_KEY)) != 0 ||
527	    (r = sshbuf_put_cstring(msg, name)) != 0 ||
528	    (r = sshbuf_put_cstring(msg, pin)) != 0)
529		fatal_fr(r, "compose");
530	send_msg(helper->fd, msg);
531	sshbuf_reset(msg);
532
533	type = recv_msg(helper->fd, msg);
534	if (type == SSH2_AGENT_IDENTITIES_ANSWER) {
535		if ((r = sshbuf_get_u32(msg, &nkeys)) != 0)
536			fatal_fr(r, "parse nkeys");
537		*keysp = xcalloc(nkeys, sizeof(struct sshkey *));
538		if (labelsp)
539			*labelsp = xcalloc(nkeys, sizeof(char *));
540		for (i = 0; i < nkeys; i++) {
541			/* XXX clean up properly instead of fatal() */
542			if ((r = sshbuf_get_string(msg, &blob, &blen)) != 0 ||
543			    (r = sshbuf_get_cstring(msg, &label, NULL)) != 0)
544				fatal_fr(r, "parse key");
545			if ((r = sshkey_from_blob(blob, blen, &k)) != 0)
546				fatal_fr(r, "decode key");
547			wrap_key(helper, k);
548			(*keysp)[i] = k;
549			if (labelsp)
550				(*labelsp)[i] = label;
551			else
552				free(label);
553			free(blob);
554		}
555	} else if (type == SSH2_AGENT_FAILURE) {
556		if ((r = sshbuf_get_u32(msg, &nkeys)) != 0)
557			nkeys = -1;
558	} else {
559		nkeys = -1;
560	}
561	sshbuf_free(msg);
562	return (nkeys);
563}
564
565int
566pkcs11_del_provider(char *name)
567{
568	struct helper *helper;
569
570	/*
571	 * ssh-agent deletes keys before calling this, so the helper entry
572	 * should be gone before we get here.
573	 */
574	debug3_f("delete %s", name);
575	if ((helper = helper_by_provider(name)) != NULL)
576		helper_terminate(helper);
577	return 0;
578}
579