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