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