xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-pkcs11-helper.c (revision 122b5006ee1bd67145794b4cde92f4fe4781a5ec)
1 /*	$NetBSD: ssh-pkcs11-helper.c,v 1.21 2021/09/02 11:26:18 christos Exp $	*/
2 /* $OpenBSD: ssh-pkcs11-helper.c,v 1.25 2021/08/11 05:20:17 djm Exp $ */
3 
4 /*
5  * Copyright (c) 2010 Markus Friedl.  All rights reserved.
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 #include "includes.h"
20 __RCSID("$NetBSD: ssh-pkcs11-helper.c,v 1.21 2021/09/02 11:26:18 christos Exp $");
21 
22 #include <sys/types.h>
23 #include <sys/queue.h>
24 #include <sys/time.h>
25 #include <sys/param.h>
26 
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <poll.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <unistd.h>
33 
34 #include "xmalloc.h"
35 #include "sshbuf.h"
36 #include "log.h"
37 #include "misc.h"
38 #include "sshkey.h"
39 #include "authfd.h"
40 #include "ssh-pkcs11.h"
41 #include "ssherr.h"
42 
43 #ifdef WITH_OPENSSL
44 
45 /* borrows code from sftp-server and ssh-agent */
46 
47 struct pkcs11_keyinfo {
48 	struct sshkey	*key;
49 	char		*providername, *label;
50 	TAILQ_ENTRY(pkcs11_keyinfo) next;
51 };
52 
53 TAILQ_HEAD(, pkcs11_keyinfo) pkcs11_keylist;
54 
55 #define MAX_MSG_LENGTH		10240 /*XXX*/
56 
57 /* input and output queue */
58 struct sshbuf *iqueue;
59 struct sshbuf *oqueue;
60 
61 static void
62 add_key(struct sshkey *k, char *name, char *label)
63 {
64 	struct pkcs11_keyinfo *ki;
65 
66 	ki = xcalloc(1, sizeof(*ki));
67 	ki->providername = xstrdup(name);
68 	ki->key = k;
69 	ki->label = xstrdup(label);
70 	TAILQ_INSERT_TAIL(&pkcs11_keylist, ki, next);
71 }
72 
73 static void
74 del_keys_by_name(char *name)
75 {
76 	struct pkcs11_keyinfo *ki, *nxt;
77 
78 	for (ki = TAILQ_FIRST(&pkcs11_keylist); ki; ki = nxt) {
79 		nxt = TAILQ_NEXT(ki, next);
80 		if (!strcmp(ki->providername, name)) {
81 			TAILQ_REMOVE(&pkcs11_keylist, ki, next);
82 			free(ki->providername);
83 			free(ki->label);
84 			sshkey_free(ki->key);
85 			free(ki);
86 		}
87 	}
88 }
89 
90 /* lookup matching 'private' key */
91 static struct sshkey *
92 lookup_key(struct sshkey *k)
93 {
94 	struct pkcs11_keyinfo *ki;
95 
96 	TAILQ_FOREACH(ki, &pkcs11_keylist, next) {
97 		debug("check %s %s %s", sshkey_type(ki->key),
98 		    ki->providername, ki->label);
99 		if (sshkey_equal(k, ki->key))
100 			return (ki->key);
101 	}
102 	return (NULL);
103 }
104 
105 static void
106 send_msg(struct sshbuf *m)
107 {
108 	int r;
109 
110 	if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
111 		fatal_fr(r, "enqueue");
112 }
113 
114 static void
115 process_add(void)
116 {
117 	char *name, *pin;
118 	struct sshkey **keys = NULL;
119 	int r, i, nkeys;
120 	u_char *blob;
121 	size_t blen;
122 	struct sshbuf *msg;
123 	char **labels = NULL;
124 
125 	if ((msg = sshbuf_new()) == NULL)
126 		fatal_f("sshbuf_new failed");
127 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
128 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
129 		fatal_fr(r, "parse");
130 	if ((nkeys = pkcs11_add_provider(name, pin, &keys, &labels)) > 0) {
131 		if ((r = sshbuf_put_u8(msg,
132 		    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
133 		    (r = sshbuf_put_u32(msg, nkeys)) != 0)
134 			fatal_fr(r, "compose");
135 		for (i = 0; i < nkeys; i++) {
136 			if ((r = sshkey_to_blob(keys[i], &blob, &blen)) != 0) {
137 				debug_fr(r, "encode key");
138 				continue;
139 			}
140 			if ((r = sshbuf_put_string(msg, blob, blen)) != 0 ||
141 			    (r = sshbuf_put_cstring(msg, labels[i])) != 0)
142 				fatal_fr(r, "compose key");
143 			free(blob);
144 			add_key(keys[i], name, labels[i]);
145 			free(labels[i]);
146 		}
147 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0 ||
148 	    (r = sshbuf_put_u32(msg, -nkeys)) != 0)
149 		fatal_fr(r, "compose");
150 	free(labels);
151 	free(keys); /* keys themselves are transferred to pkcs11_keylist */
152 	free(pin);
153 	free(name);
154 	send_msg(msg);
155 	sshbuf_free(msg);
156 }
157 
158 static void
159 process_del(void)
160 {
161 	char *name, *pin;
162 	struct sshbuf *msg;
163 	int r;
164 
165 	if ((msg = sshbuf_new()) == NULL)
166 		fatal_f("sshbuf_new failed");
167 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
168 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
169 		fatal_fr(r, "parse");
170 	del_keys_by_name(name);
171 	if ((r = sshbuf_put_u8(msg, pkcs11_del_provider(name) == 0 ?
172 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
173 		fatal_fr(r, "compose");
174 	free(pin);
175 	free(name);
176 	send_msg(msg);
177 	sshbuf_free(msg);
178 }
179 
180 static void
181 process_sign(void)
182 {
183 	u_char *blob, *data, *signature = NULL;
184 	size_t blen, dlen, slen = 0;
185 	int r, ok = -1;
186 	struct sshkey *key, *found;
187 	struct sshbuf *msg;
188 
189 	/* XXX support SHA2 signature flags */
190 	if ((r = sshbuf_get_string(iqueue, &blob, &blen)) != 0 ||
191 	    (r = sshbuf_get_string(iqueue, &data, &dlen)) != 0 ||
192 	    (r = sshbuf_get_u32(iqueue, NULL)) != 0)
193 		fatal_fr(r, "parse");
194 
195 	if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
196 		fatal_fr(r, "decode key");
197 	else {
198 		if ((found = lookup_key(key)) != NULL) {
199 #ifdef WITH_OPENSSL
200 			int ret;
201 
202 			if (key->type == KEY_RSA) {
203 				slen = RSA_size(key->rsa);
204 				signature = xmalloc(slen);
205 				ret = RSA_private_encrypt(dlen, data, signature,
206 				    found->rsa, RSA_PKCS1_PADDING);
207 				if (ret != -1) {
208 					slen = ret;
209 					ok = 0;
210 				}
211 			} else if (key->type == KEY_ECDSA) {
212 				u_int xslen = ECDSA_size(key->ecdsa);
213 
214 				signature = xmalloc(xslen);
215 				/* "The parameter type is ignored." */
216 				ret = ECDSA_sign(-1, data, dlen, signature,
217 				    &xslen, found->ecdsa);
218 				if (ret != 0)
219 					ok = 0;
220 				else
221 					error_f("ECDSA_sign returned %d", ret);
222 				slen = xslen;
223 			} else
224 				error_f("don't know how to sign with key "
225 				    "type %d", (int)key->type);
226 #endif /* WITH_OPENSSL */
227 		}
228 		sshkey_free(key);
229 	}
230 	if ((msg = sshbuf_new()) == NULL)
231 		fatal_f("sshbuf_new failed");
232 	if (ok == 0) {
233 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
234 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
235 			fatal_fr(r, "compose response");
236 	} else {
237 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_FAILURE)) != 0)
238 			fatal_fr(r, "compose failure response");
239 	}
240 	free(data);
241 	free(blob);
242 	free(signature);
243 	send_msg(msg);
244 	sshbuf_free(msg);
245 }
246 
247 static void
248 process(void)
249 {
250 	u_int msg_len;
251 	u_int buf_len;
252 	u_int consumed;
253 	u_char type;
254 	const u_char *cp;
255 	int r;
256 
257 	buf_len = sshbuf_len(iqueue);
258 	if (buf_len < 5)
259 		return;		/* Incomplete message. */
260 	cp = sshbuf_ptr(iqueue);
261 	msg_len = get_u32(cp);
262 	if (msg_len > MAX_MSG_LENGTH) {
263 		error("bad message len %d", msg_len);
264 		cleanup_exit(11);
265 	}
266 	if (buf_len < msg_len + 4)
267 		return;
268 	if ((r = sshbuf_consume(iqueue, 4)) != 0 ||
269 	    (r = sshbuf_get_u8(iqueue, &type)) != 0)
270 		fatal_fr(r, "parse type/len");
271 	buf_len -= 4;
272 	switch (type) {
273 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
274 		debug("process_add");
275 		process_add();
276 		break;
277 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
278 		debug("process_del");
279 		process_del();
280 		break;
281 	case SSH2_AGENTC_SIGN_REQUEST:
282 		debug("process_sign");
283 		process_sign();
284 		break;
285 	default:
286 		error("Unknown message %d", type);
287 		break;
288 	}
289 	/* discard the remaining bytes from the current packet */
290 	if (buf_len < sshbuf_len(iqueue)) {
291 		error("iqueue grew unexpectedly");
292 		cleanup_exit(255);
293 	}
294 	consumed = buf_len - sshbuf_len(iqueue);
295 	if (msg_len < consumed) {
296 		error("msg_len %d < consumed %d", msg_len, consumed);
297 		cleanup_exit(255);
298 	}
299 	if (msg_len > consumed) {
300 		if ((r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
301 			fatal_fr(r, "consume");
302 	}
303 }
304 
305 void
306 cleanup_exit(int i)
307 {
308 	/* XXX */
309 	_exit(i);
310 }
311 
312 
313 int
314 main(int argc, char **argv)
315 {
316 	int r, ch, in, out, log_stderr = 0;
317 	ssize_t len;
318 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
319 	LogLevel log_level = SYSLOG_LEVEL_ERROR;
320 	char buf[4*4096];
321 	extern char *__progname;
322 	struct pollfd pfd[2];
323 
324 	TAILQ_INIT(&pkcs11_keylist);
325 
326 	log_init(__progname, log_level, log_facility, log_stderr);
327 
328 	while ((ch = getopt(argc, argv, "v")) != -1) {
329 		switch (ch) {
330 		case 'v':
331 			log_stderr = 1;
332 			if (log_level == SYSLOG_LEVEL_ERROR)
333 				log_level = SYSLOG_LEVEL_DEBUG1;
334 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
335 				log_level++;
336 			break;
337 		default:
338 			fprintf(stderr, "usage: %s [-v]\n", __progname);
339 			exit(1);
340 		}
341 	}
342 
343 	log_init(__progname, log_level, log_facility, log_stderr);
344 
345 	pkcs11_init(0);
346 	in = STDIN_FILENO;
347 	out = STDOUT_FILENO;
348 
349 	if ((iqueue = sshbuf_new()) == NULL)
350 		fatal_f("sshbuf_new failed");
351 	if ((oqueue = sshbuf_new()) == NULL)
352 		fatal_f("sshbuf_new failed");
353 
354 	while (1) {
355 		memset(pfd, 0, sizeof(pfd));
356 		pfd[0].fd = in;
357 		pfd[1].fd = out;
358 
359 		/*
360 		 * Ensure that we can read a full buffer and handle
361 		 * the worst-case length packet it can generate,
362 		 * otherwise apply backpressure by stopping reads.
363 		 */
364 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
365 		    (r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
366 			pfd[0].events = POLLIN;
367 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
368 			fatal_fr(r, "reserve");
369 
370 		if (sshbuf_len(oqueue) > 0)
371 			pfd[1].events = POLLOUT;
372 
373 		if ((r = poll(pfd, 2, -1 /* INFTIM */)) <= 0) {
374 			if (r == 0 || errno == EINTR)
375 				continue;
376 			fatal("poll: %s", strerror(errno));
377 		}
378 
379 		/* copy stdin to iqueue */
380 		if ((pfd[0].revents & (POLLIN|POLLERR)) != 0) {
381 			len = read(in, buf, sizeof buf);
382 			if (len == 0) {
383 				debug("read eof");
384 				cleanup_exit(0);
385 			} else if (len < 0) {
386 				error("read: %s", strerror(errno));
387 				cleanup_exit(1);
388 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
389 				fatal_fr(r, "sshbuf_put");
390 		}
391 		/* send oqueue to stdout */
392 		if ((pfd[1].revents & (POLLOUT|POLLHUP)) != 0) {
393 			len = write(out, sshbuf_ptr(oqueue),
394 			    sshbuf_len(oqueue));
395 			if (len < 0) {
396 				error("write: %s", strerror(errno));
397 				cleanup_exit(1);
398 			} else if ((r = sshbuf_consume(oqueue, len)) != 0)
399 				fatal_fr(r, "consume");
400 		}
401 
402 		/*
403 		 * Process requests from client if we can fit the results
404 		 * into the output buffer, otherwise stop processing input
405 		 * and let the output queue drain.
406 		 */
407 		if ((r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
408 			process();
409 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
410 			fatal_fr(r, "reserve");
411 	}
412 }
413 
414 #else /* WITH_OPENSSL */
415 void
416 cleanup_exit(int i)
417 {
418 	_exit(i);
419 }
420 
421 int
422 main(int argc, char **argv)
423 {
424 	fprintf(stderr, "PKCS#11 code is not enabled\n");
425 	return 1;
426 }
427 #endif /* WITH_OPENSSL */
428