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