xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-pkcs11-helper.c (revision 53d1339bf7f9c7367b35a9e1ebe693f9b047a47b)
1 /*	$NetBSD: ssh-pkcs11-helper.c,v 1.20 2021/03/05 17:47:16 christos Exp $	*/
2 /* $OpenBSD: ssh-pkcs11-helper.c,v 1.24 2020/10/18 11:32:02 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.20 2021/03/05 17:47:16 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 %p %s %s", ki, ki->providername, ki->label);
98 		if (sshkey_equal(k, ki->key))
99 			return (ki->key);
100 	}
101 	return (NULL);
102 }
103 
104 static void
105 send_msg(struct sshbuf *m)
106 {
107 	int r;
108 
109 	if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
110 		fatal_fr(r, "enqueue");
111 }
112 
113 static void
114 process_add(void)
115 {
116 	char *name, *pin;
117 	struct sshkey **keys = NULL;
118 	int r, i, nkeys;
119 	u_char *blob;
120 	size_t blen;
121 	struct sshbuf *msg;
122 	char **labels = NULL;
123 
124 	if ((msg = sshbuf_new()) == NULL)
125 		fatal_f("sshbuf_new failed");
126 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
127 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
128 		fatal_fr(r, "parse");
129 	if ((nkeys = pkcs11_add_provider(name, pin, &keys, &labels)) > 0) {
130 		if ((r = sshbuf_put_u8(msg,
131 		    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
132 		    (r = sshbuf_put_u32(msg, nkeys)) != 0)
133 			fatal_fr(r, "compose");
134 		for (i = 0; i < nkeys; i++) {
135 			if ((r = sshkey_to_blob(keys[i], &blob, &blen)) != 0) {
136 				debug_fr(r, "encode key");
137 				continue;
138 			}
139 			if ((r = sshbuf_put_string(msg, blob, blen)) != 0 ||
140 			    (r = sshbuf_put_cstring(msg, labels[i])) != 0)
141 				fatal_fr(r, "compose key");
142 			free(blob);
143 			add_key(keys[i], name, labels[i]);
144 			free(labels[i]);
145 		}
146 	} else if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0 ||
147 	    (r = sshbuf_put_u32(msg, -nkeys)) != 0)
148 		fatal_fr(r, "compose");
149 	free(labels);
150 	free(keys); /* keys themselves are transferred to pkcs11_keylist */
151 	free(pin);
152 	free(name);
153 	send_msg(msg);
154 	sshbuf_free(msg);
155 }
156 
157 static void
158 process_del(void)
159 {
160 	char *name, *pin;
161 	struct sshbuf *msg;
162 	int r;
163 
164 	if ((msg = sshbuf_new()) == NULL)
165 		fatal_f("sshbuf_new failed");
166 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
167 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
168 		fatal_fr(r, "parse");
169 	del_keys_by_name(name);
170 	if ((r = sshbuf_put_u8(msg, pkcs11_del_provider(name) == 0 ?
171 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
172 		fatal_fr(r, "compose");
173 	free(pin);
174 	free(name);
175 	send_msg(msg);
176 	sshbuf_free(msg);
177 }
178 
179 static void
180 process_sign(void)
181 {
182 	u_char *blob, *data, *signature = NULL;
183 	size_t blen, dlen, slen = 0;
184 	int r, ok = -1;
185 	struct sshkey *key, *found;
186 	struct sshbuf *msg;
187 
188 	/* XXX support SHA2 signature flags */
189 	if ((r = sshbuf_get_string(iqueue, &blob, &blen)) != 0 ||
190 	    (r = sshbuf_get_string(iqueue, &data, &dlen)) != 0 ||
191 	    (r = sshbuf_get_u32(iqueue, NULL)) != 0)
192 		fatal_fr(r, "parse");
193 
194 	if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
195 		fatal_fr(r, "decode key");
196 	else {
197 		if ((found = lookup_key(key)) != NULL) {
198 #ifdef WITH_OPENSSL
199 			int ret;
200 
201 			if (key->type == KEY_RSA) {
202 				slen = RSA_size(key->rsa);
203 				signature = xmalloc(slen);
204 				ret = RSA_private_encrypt(dlen, data, signature,
205 				    found->rsa, RSA_PKCS1_PADDING);
206 				if (ret != -1) {
207 					slen = ret;
208 					ok = 0;
209 				}
210 			} else if (key->type == KEY_ECDSA) {
211 				u_int xslen = ECDSA_size(key->ecdsa);
212 
213 				signature = xmalloc(xslen);
214 				/* "The parameter type is ignored." */
215 				ret = ECDSA_sign(-1, data, dlen, signature,
216 				    &xslen, found->ecdsa);
217 				if (ret != 0)
218 					ok = 0;
219 				else
220 					error_f("ECDSA_sign returned %d", ret);
221 				slen = xslen;
222 			} else
223 				error_f("don't know how to sign with key "
224 				    "type %d", (int)key->type);
225 #endif /* WITH_OPENSSL */
226 		}
227 		sshkey_free(key);
228 	}
229 	if ((msg = sshbuf_new()) == NULL)
230 		fatal_f("sshbuf_new failed");
231 	if (ok == 0) {
232 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
233 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
234 			fatal_fr(r, "compose response");
235 	} else {
236 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_FAILURE)) != 0)
237 			fatal_fr(r, "compose failure response");
238 	}
239 	free(data);
240 	free(blob);
241 	free(signature);
242 	send_msg(msg);
243 	sshbuf_free(msg);
244 }
245 
246 static void
247 process(void)
248 {
249 	u_int msg_len;
250 	u_int buf_len;
251 	u_int consumed;
252 	u_char type;
253 	const u_char *cp;
254 	int r;
255 
256 	buf_len = sshbuf_len(iqueue);
257 	if (buf_len < 5)
258 		return;		/* Incomplete message. */
259 	cp = sshbuf_ptr(iqueue);
260 	msg_len = get_u32(cp);
261 	if (msg_len > MAX_MSG_LENGTH) {
262 		error("bad message len %d", msg_len);
263 		cleanup_exit(11);
264 	}
265 	if (buf_len < msg_len + 4)
266 		return;
267 	if ((r = sshbuf_consume(iqueue, 4)) != 0 ||
268 	    (r = sshbuf_get_u8(iqueue, &type)) != 0)
269 		fatal_fr(r, "parse type/len");
270 	buf_len -= 4;
271 	switch (type) {
272 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
273 		debug("process_add");
274 		process_add();
275 		break;
276 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
277 		debug("process_del");
278 		process_del();
279 		break;
280 	case SSH2_AGENTC_SIGN_REQUEST:
281 		debug("process_sign");
282 		process_sign();
283 		break;
284 	default:
285 		error("Unknown message %d", type);
286 		break;
287 	}
288 	/* discard the remaining bytes from the current packet */
289 	if (buf_len < sshbuf_len(iqueue)) {
290 		error("iqueue grew unexpectedly");
291 		cleanup_exit(255);
292 	}
293 	consumed = buf_len - sshbuf_len(iqueue);
294 	if (msg_len < consumed) {
295 		error("msg_len %d < consumed %d", msg_len, consumed);
296 		cleanup_exit(255);
297 	}
298 	if (msg_len > consumed) {
299 		if ((r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
300 			fatal_fr(r, "consume");
301 	}
302 }
303 
304 void
305 cleanup_exit(int i)
306 {
307 	/* XXX */
308 	_exit(i);
309 }
310 
311 
312 int
313 main(int argc, char **argv)
314 {
315 	int r, ch, in, out, log_stderr = 0;
316 	ssize_t len;
317 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
318 	LogLevel log_level = SYSLOG_LEVEL_ERROR;
319 	char buf[4*4096];
320 	extern char *__progname;
321 	struct pollfd pfd[2];
322 
323 	TAILQ_INIT(&pkcs11_keylist);
324 
325 	log_init(__progname, log_level, log_facility, log_stderr);
326 
327 	while ((ch = getopt(argc, argv, "v")) != -1) {
328 		switch (ch) {
329 		case 'v':
330 			log_stderr = 1;
331 			if (log_level == SYSLOG_LEVEL_ERROR)
332 				log_level = SYSLOG_LEVEL_DEBUG1;
333 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
334 				log_level++;
335 			break;
336 		default:
337 			fprintf(stderr, "usage: %s [-v]\n", __progname);
338 			exit(1);
339 		}
340 	}
341 
342 	log_init(__progname, log_level, log_facility, log_stderr);
343 
344 	pkcs11_init(0);
345 	in = STDIN_FILENO;
346 	out = STDOUT_FILENO;
347 
348 	if ((iqueue = sshbuf_new()) == NULL)
349 		fatal_f("sshbuf_new failed");
350 	if ((oqueue = sshbuf_new()) == NULL)
351 		fatal_f("sshbuf_new failed");
352 
353 	while (1) {
354 		memset(pfd, 0, sizeof(pfd));
355 		pfd[0].fd = in;
356 		pfd[1].fd = out;
357 
358 		/*
359 		 * Ensure that we can read a full buffer and handle
360 		 * the worst-case length packet it can generate,
361 		 * otherwise apply backpressure by stopping reads.
362 		 */
363 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
364 		    (r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
365 			pfd[0].events = POLLIN;
366 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
367 			fatal_fr(r, "reserve");
368 
369 		if (sshbuf_len(oqueue) > 0)
370 			pfd[1].events = POLLOUT;
371 
372 		if ((r = poll(pfd, 2, -1 /* INFTIM */)) <= 0) {
373 			if (r == 0 || errno == EINTR)
374 				continue;
375 			fatal("poll: %s", strerror(errno));
376 		}
377 
378 		/* copy stdin to iqueue */
379 		if ((pfd[0].revents & (POLLIN|POLLERR)) != 0) {
380 			len = read(in, buf, sizeof buf);
381 			if (len == 0) {
382 				debug("read eof");
383 				cleanup_exit(0);
384 			} else if (len < 0) {
385 				error("read: %s", strerror(errno));
386 				cleanup_exit(1);
387 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0)
388 				fatal_fr(r, "sshbuf_put");
389 		}
390 		/* send oqueue to stdout */
391 		if ((pfd[1].revents & (POLLOUT|POLLHUP)) != 0) {
392 			len = write(out, sshbuf_ptr(oqueue),
393 			    sshbuf_len(oqueue));
394 			if (len < 0) {
395 				error("write: %s", strerror(errno));
396 				cleanup_exit(1);
397 			} else if ((r = sshbuf_consume(oqueue, len)) != 0)
398 				fatal_fr(r, "consume");
399 		}
400 
401 		/*
402 		 * Process requests from client if we can fit the results
403 		 * into the output buffer, otherwise stop processing input
404 		 * and let the output queue drain.
405 		 */
406 		if ((r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
407 			process();
408 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
409 			fatal_fr(r, "reserve");
410 	}
411 }
412 
413 #else /* WITH_OPENSSL */
414 void
415 cleanup_exit(int i)
416 {
417 	_exit(i);
418 }
419 
420 int
421 main(int argc, char **argv)
422 {
423 	fprintf(stderr, "PKCS#11 code is not enabled\n");
424 	return 1;
425 }
426 #endif /* WITH_OPENSSL */
427