xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-pkcs11-helper.c (revision c38e7cc395b1472a774ff828e46123de44c628e9)
1 /*	$NetBSD: ssh-pkcs11-helper.c,v 1.14 2018/04/06 18:59:00 christos Exp $	*/
2 /* $OpenBSD: ssh-pkcs11-helper.c,v 1.14 2018/01/08 15:18:46 markus Exp $ */
3 /*
4  * Copyright (c) 2010 Markus Friedl.  All rights reserved.
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include "includes.h"
19 __RCSID("$NetBSD: ssh-pkcs11-helper.c,v 1.14 2018/04/06 18:59:00 christos Exp $");
20 
21 #include <sys/types.h>
22 #include <sys/queue.h>
23 #include <sys/time.h>
24 #include <sys/param.h>
25 
26 #include <stdarg.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <errno.h>
30 
31 #include "xmalloc.h"
32 #include "sshbuf.h"
33 #include "log.h"
34 #include "misc.h"
35 #include "sshkey.h"
36 #include "authfd.h"
37 #include "ssh-pkcs11.h"
38 #include "ssherr.h"
39 
40 /* borrows code from sftp-server and ssh-agent */
41 
42 struct pkcs11_keyinfo {
43 	struct sshkey	*key;
44 	char		*providername;
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)
58 {
59 	struct pkcs11_keyinfo *ki;
60 
61 	ki = xcalloc(1, sizeof(*ki));
62 	ki->providername = xstrdup(name);
63 	ki->key = k;
64 	TAILQ_INSERT_TAIL(&pkcs11_keylist, ki, next);
65 }
66 
67 static void
68 del_keys_by_name(char *name)
69 {
70 	struct pkcs11_keyinfo *ki, *nxt;
71 
72 	for (ki = TAILQ_FIRST(&pkcs11_keylist); ki; ki = nxt) {
73 		nxt = TAILQ_NEXT(ki, next);
74 		if (!strcmp(ki->providername, name)) {
75 			TAILQ_REMOVE(&pkcs11_keylist, ki, next);
76 			free(ki->providername);
77 			sshkey_free(ki->key);
78 			free(ki);
79 		}
80 	}
81 }
82 
83 /* lookup matching 'private' key */
84 static struct sshkey *
85 lookup_key(struct sshkey *k)
86 {
87 	struct pkcs11_keyinfo *ki;
88 
89 	TAILQ_FOREACH(ki, &pkcs11_keylist, next) {
90 		debug("check %p %s", ki, ki->providername);
91 		if (sshkey_equal(k, ki->key))
92 			return (ki->key);
93 	}
94 	return (NULL);
95 }
96 
97 static void
98 send_msg(struct sshbuf *m)
99 {
100 	int r;
101 
102 	if ((r = sshbuf_put_stringb(oqueue, m)) != 0)
103 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
104 }
105 
106 static void
107 process_add(void)
108 {
109 	char *name, *pin;
110 	struct sshkey **keys;
111 	int r, i, nkeys;
112 	u_char *blob;
113 	size_t blen;
114 	struct sshbuf *msg;
115 
116 	if ((msg = sshbuf_new()) == NULL)
117 		fatal("%s: sshbuf_new failed", __func__);
118 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
119 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
120 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
121 	if ((nkeys = pkcs11_add_provider(name, pin, &keys)) > 0) {
122 		if ((r = sshbuf_put_u8(msg,
123 		    SSH2_AGENT_IDENTITIES_ANSWER)) != 0 ||
124 		    (r = sshbuf_put_u32(msg, nkeys)) != 0)
125 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
126 		for (i = 0; i < nkeys; i++) {
127 			if ((r = sshkey_to_blob(keys[i], &blob, &blen)) != 0) {
128 				debug("%s: sshkey_to_blob: %s",
129 				    __func__, ssh_err(r));
130 				continue;
131 			}
132 			if ((r = sshbuf_put_string(msg, blob, blen)) != 0 ||
133 			    (r = sshbuf_put_cstring(msg, name)) != 0)
134 				fatal("%s: buffer error: %s",
135 				    __func__, ssh_err(r));
136 			free(blob);
137 			add_key(keys[i], name);
138 		}
139 		free(keys);
140 	} else {
141 		if ((r = sshbuf_put_u8(msg, SSH_AGENT_FAILURE)) != 0)
142 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
143 	}
144 	free(pin);
145 	free(name);
146 	send_msg(msg);
147 	sshbuf_free(msg);
148 }
149 
150 static void
151 process_del(void)
152 {
153 	char *name, *pin;
154 	struct sshbuf *msg;
155 	int r;
156 
157 	if ((msg = sshbuf_new()) == NULL)
158 		fatal("%s: sshbuf_new failed", __func__);
159 	if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 ||
160 	    (r = sshbuf_get_cstring(iqueue, &pin, NULL)) != 0)
161 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
162 	del_keys_by_name(name);
163 	if ((r = sshbuf_put_u8(msg, pkcs11_del_provider(name) == 0 ?
164 	    SSH_AGENT_SUCCESS : SSH_AGENT_FAILURE)) != 0)
165 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
166 	free(pin);
167 	free(name);
168 	send_msg(msg);
169 	sshbuf_free(msg);
170 }
171 
172 static void
173 process_sign(void)
174 {
175 	u_char *blob, *data, *signature = NULL;
176 	size_t blen, dlen, slen = 0;
177 	int r, ok = -1;
178 	struct sshkey *key, *found;
179 	struct sshbuf *msg;
180 
181 	/* XXX support SHA2 signature flags */
182 	if ((r = sshbuf_get_string(iqueue, &blob, &blen)) != 0 ||
183 	    (r = sshbuf_get_string(iqueue, &data, &dlen)) != 0 ||
184 	    (r = sshbuf_get_u32(iqueue, NULL)) != 0)
185 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
186 
187 	if ((r = sshkey_from_blob(blob, blen, &key)) != 0)
188 		error("%s: sshkey_from_blob: %s", __func__, ssh_err(r));
189 	else {
190 		if ((found = lookup_key(key)) != NULL) {
191 #ifdef WITH_OPENSSL
192 			int ret;
193 
194 			slen = RSA_size(key->rsa);
195 			signature = xmalloc(slen);
196 			if ((ret = RSA_private_encrypt(dlen, data, signature,
197 			    found->rsa, RSA_PKCS1_PADDING)) != -1) {
198 				slen = ret;
199 				ok = 0;
200 			}
201 #endif /* WITH_OPENSSL */
202 		}
203 		sshkey_free(key);
204 	}
205 	if ((msg = sshbuf_new()) == NULL)
206 		fatal("%s: sshbuf_new failed", __func__);
207 	if (ok == 0) {
208 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_SIGN_RESPONSE)) != 0 ||
209 		    (r = sshbuf_put_string(msg, signature, slen)) != 0)
210 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
211 	} else {
212 		if ((r = sshbuf_put_u8(msg, SSH2_AGENT_FAILURE)) != 0)
213 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
214 	}
215 	free(data);
216 	free(blob);
217 	free(signature);
218 	send_msg(msg);
219 	sshbuf_free(msg);
220 }
221 
222 static void
223 process(void)
224 {
225 	u_int msg_len;
226 	u_int buf_len;
227 	u_int consumed;
228 	u_char type;
229 	const u_char *cp;
230 	int r;
231 
232 	buf_len = sshbuf_len(iqueue);
233 	if (buf_len < 5)
234 		return;		/* Incomplete message. */
235 	cp = sshbuf_ptr(iqueue);
236 	msg_len = get_u32(cp);
237 	if (msg_len > MAX_MSG_LENGTH) {
238 		error("bad message len %d", msg_len);
239 		cleanup_exit(11);
240 	}
241 	if (buf_len < msg_len + 4)
242 		return;
243 	if ((r = sshbuf_consume(iqueue, 4)) != 0 ||
244 	    (r = sshbuf_get_u8(iqueue, &type)) != 0)
245 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
246 	buf_len -= 4;
247 	switch (type) {
248 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
249 		debug("process_add");
250 		process_add();
251 		break;
252 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
253 		debug("process_del");
254 		process_del();
255 		break;
256 	case SSH2_AGENTC_SIGN_REQUEST:
257 		debug("process_sign");
258 		process_sign();
259 		break;
260 	default:
261 		error("Unknown message %d", type);
262 		break;
263 	}
264 	/* discard the remaining bytes from the current packet */
265 	if (buf_len < sshbuf_len(iqueue)) {
266 		error("iqueue grew unexpectedly");
267 		cleanup_exit(255);
268 	}
269 	consumed = buf_len - sshbuf_len(iqueue);
270 	if (msg_len < consumed) {
271 		error("msg_len %d < consumed %d", msg_len, consumed);
272 		cleanup_exit(255);
273 	}
274 	if (msg_len > consumed) {
275 		if ((r = sshbuf_consume(iqueue, msg_len - consumed)) != 0)
276 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
277 	}
278 }
279 
280 void
281 cleanup_exit(int i)
282 {
283 	/* XXX */
284 	_exit(i);
285 }
286 
287 int
288 main(int argc, char **argv)
289 {
290 	fd_set *rset, *wset;
291 	int r, in, out, max, log_stderr = 0;
292 	ssize_t len, olen, set_size;
293 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
294 	LogLevel log_level = SYSLOG_LEVEL_ERROR;
295 	char buf[4*4096];
296 	extern char *__progname;
297 
298 	ssh_malloc_init();	/* must be called before any mallocs */
299 	TAILQ_INIT(&pkcs11_keylist);
300 	pkcs11_init(0);
301 
302 	log_init(__progname, log_level, log_facility, log_stderr);
303 
304 	in = STDIN_FILENO;
305 	out = STDOUT_FILENO;
306 
307 	max = 0;
308 	if (in > max)
309 		max = in;
310 	if (out > max)
311 		max = out;
312 
313 	if ((iqueue = sshbuf_new()) == NULL)
314 		fatal("%s: sshbuf_new failed", __func__);
315 	if ((oqueue = sshbuf_new()) == NULL)
316 		fatal("%s: sshbuf_new failed", __func__);
317 
318 	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
319 	rset = xmalloc(set_size);
320 	wset = xmalloc(set_size);
321 
322 	for (;;) {
323 		memset(rset, 0, set_size);
324 		memset(wset, 0, set_size);
325 
326 		/*
327 		 * Ensure that we can read a full buffer and handle
328 		 * the worst-case length packet it can generate,
329 		 * otherwise apply backpressure by stopping reads.
330 		 */
331 		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
332 		    (r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
333 			FD_SET(in, rset);
334 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
335 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
336 
337 		olen = sshbuf_len(oqueue);
338 		if (olen > 0)
339 			FD_SET(out, wset);
340 
341 		if (select(max+1, rset, wset, NULL, NULL) < 0) {
342 			if (errno == EINTR)
343 				continue;
344 			error("select: %s", strerror(errno));
345 			cleanup_exit(2);
346 		}
347 
348 		/* copy stdin to iqueue */
349 		if (FD_ISSET(in, rset)) {
350 			len = read(in, buf, sizeof buf);
351 			if (len == 0) {
352 				debug("read eof");
353 				cleanup_exit(0);
354 			} else if (len < 0) {
355 				error("read: %s", strerror(errno));
356 				cleanup_exit(1);
357 			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0) {
358 				fatal("%s: buffer error: %s",
359 				    __func__, ssh_err(r));
360 			}
361 		}
362 		/* send oqueue to stdout */
363 		if (FD_ISSET(out, wset)) {
364 			len = write(out, sshbuf_ptr(oqueue), olen);
365 			if (len < 0) {
366 				error("write: %s", strerror(errno));
367 				cleanup_exit(1);
368 			} else if ((r = sshbuf_consume(oqueue, len)) != 0) {
369 				fatal("%s: buffer error: %s",
370 				    __func__, ssh_err(r));
371 			}
372 		}
373 
374 		/*
375 		 * Process requests from client if we can fit the results
376 		 * into the output buffer, otherwise stop processing input
377 		 * and let the output queue drain.
378 		 */
379 		if ((r = sshbuf_check_reserve(oqueue, MAX_MSG_LENGTH)) == 0)
380 			process();
381 		else if (r != SSH_ERR_NO_BUFFER_SPACE)
382 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
383 	}
384 }
385