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