xref: /openbsd/usr.bin/ssh/ssh-pkcs11-helper.c (revision fc61954a)
1 /* $OpenBSD: ssh-pkcs11-helper.c,v 1.12 2016/02/15 09:47:49 dtucker 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 <stdarg.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 
27 #include "xmalloc.h"
28 #include "buffer.h"
29 #include "log.h"
30 #include "misc.h"
31 #include "key.h"
32 #include "authfd.h"
33 #include "ssh-pkcs11.h"
34 
35 /* borrows code from sftp-server and ssh-agent */
36 
37 struct pkcs11_keyinfo {
38 	Key		*key;
39 	char		*providername;
40 	TAILQ_ENTRY(pkcs11_keyinfo) next;
41 };
42 
43 TAILQ_HEAD(, pkcs11_keyinfo) pkcs11_keylist;
44 
45 #define MAX_MSG_LENGTH		10240 /*XXX*/
46 
47 /* helper */
48 #define get_int()			buffer_get_int(&iqueue);
49 #define get_string(lenp)		buffer_get_string(&iqueue, lenp);
50 
51 /* input and output queue */
52 Buffer iqueue;
53 Buffer oqueue;
54 
55 static void
56 add_key(Key *k, char *name)
57 {
58 	struct pkcs11_keyinfo *ki;
59 
60 	ki = xcalloc(1, sizeof(*ki));
61 	ki->providername = xstrdup(name);
62 	ki->key = k;
63 	TAILQ_INSERT_TAIL(&pkcs11_keylist, ki, next);
64 }
65 
66 static void
67 del_keys_by_name(char *name)
68 {
69 	struct pkcs11_keyinfo *ki, *nxt;
70 
71 	for (ki = TAILQ_FIRST(&pkcs11_keylist); ki; ki = nxt) {
72 		nxt = TAILQ_NEXT(ki, next);
73 		if (!strcmp(ki->providername, name)) {
74 			TAILQ_REMOVE(&pkcs11_keylist, ki, next);
75 			free(ki->providername);
76 			key_free(ki->key);
77 			free(ki);
78 		}
79 	}
80 }
81 
82 /* lookup matching 'private' key */
83 static Key *
84 lookup_key(Key *k)
85 {
86 	struct pkcs11_keyinfo *ki;
87 
88 	TAILQ_FOREACH(ki, &pkcs11_keylist, next) {
89 		debug("check %p %s", ki, ki->providername);
90 		if (key_equal(k, ki->key))
91 			return (ki->key);
92 	}
93 	return (NULL);
94 }
95 
96 static void
97 send_msg(Buffer *m)
98 {
99 	int mlen = buffer_len(m);
100 
101 	buffer_put_int(&oqueue, mlen);
102 	buffer_append(&oqueue, buffer_ptr(m), mlen);
103 	buffer_consume(m, mlen);
104 }
105 
106 static void
107 process_add(void)
108 {
109 	char *name, *pin;
110 	Key **keys;
111 	int i, nkeys;
112 	u_char *blob;
113 	u_int blen;
114 	Buffer msg;
115 
116 	buffer_init(&msg);
117 	name = get_string(NULL);
118 	pin = get_string(NULL);
119 	if ((nkeys = pkcs11_add_provider(name, pin, &keys)) > 0) {
120 		buffer_put_char(&msg, SSH2_AGENT_IDENTITIES_ANSWER);
121 		buffer_put_int(&msg, nkeys);
122 		for (i = 0; i < nkeys; i++) {
123 			if (key_to_blob(keys[i], &blob, &blen) == 0)
124 				continue;
125 			buffer_put_string(&msg, blob, blen);
126 			buffer_put_cstring(&msg, name);
127 			free(blob);
128 			add_key(keys[i], name);
129 		}
130 		free(keys);
131 	} else {
132 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
133 	}
134 	free(pin);
135 	free(name);
136 	send_msg(&msg);
137 	buffer_free(&msg);
138 }
139 
140 static void
141 process_del(void)
142 {
143 	char *name, *pin;
144 	Buffer msg;
145 
146 	buffer_init(&msg);
147 	name = get_string(NULL);
148 	pin = get_string(NULL);
149 	del_keys_by_name(name);
150 	if (pkcs11_del_provider(name) == 0)
151 		 buffer_put_char(&msg, SSH_AGENT_SUCCESS);
152 	else
153 		 buffer_put_char(&msg, SSH_AGENT_FAILURE);
154 	free(pin);
155 	free(name);
156 	send_msg(&msg);
157 	buffer_free(&msg);
158 }
159 
160 static void
161 process_sign(void)
162 {
163 	u_char *blob, *data, *signature = NULL;
164 	u_int blen, dlen, slen = 0;
165 	int ok = -1;
166 	Key *key, *found;
167 	Buffer msg;
168 
169 	blob = get_string(&blen);
170 	data = get_string(&dlen);
171 	(void)get_int(); /* XXX ignore flags */
172 
173 	if ((key = key_from_blob(blob, blen)) != NULL) {
174 		if ((found = lookup_key(key)) != NULL) {
175 #ifdef WITH_OPENSSL
176 			int ret;
177 
178 			slen = RSA_size(key->rsa);
179 			signature = xmalloc(slen);
180 			if ((ret = RSA_private_encrypt(dlen, data, signature,
181 			    found->rsa, RSA_PKCS1_PADDING)) != -1) {
182 				slen = ret;
183 				ok = 0;
184 			}
185 #endif /* WITH_OPENSSL */
186 		}
187 		key_free(key);
188 	}
189 	buffer_init(&msg);
190 	if (ok == 0) {
191 		buffer_put_char(&msg, SSH2_AGENT_SIGN_RESPONSE);
192 		buffer_put_string(&msg, signature, slen);
193 	} else {
194 		buffer_put_char(&msg, SSH_AGENT_FAILURE);
195 	}
196 	free(data);
197 	free(blob);
198 	free(signature);
199 	send_msg(&msg);
200 	buffer_free(&msg);
201 }
202 
203 static void
204 process(void)
205 {
206 	u_int msg_len;
207 	u_int buf_len;
208 	u_int consumed;
209 	u_int type;
210 	u_char *cp;
211 
212 	buf_len = buffer_len(&iqueue);
213 	if (buf_len < 5)
214 		return;		/* Incomplete message. */
215 	cp = buffer_ptr(&iqueue);
216 	msg_len = get_u32(cp);
217 	if (msg_len > MAX_MSG_LENGTH) {
218 		error("bad message len %d", msg_len);
219 		cleanup_exit(11);
220 	}
221 	if (buf_len < msg_len + 4)
222 		return;
223 	buffer_consume(&iqueue, 4);
224 	buf_len -= 4;
225 	type = buffer_get_char(&iqueue);
226 	switch (type) {
227 	case SSH_AGENTC_ADD_SMARTCARD_KEY:
228 		debug("process_add");
229 		process_add();
230 		break;
231 	case SSH_AGENTC_REMOVE_SMARTCARD_KEY:
232 		debug("process_del");
233 		process_del();
234 		break;
235 	case SSH2_AGENTC_SIGN_REQUEST:
236 		debug("process_sign");
237 		process_sign();
238 		break;
239 	default:
240 		error("Unknown message %d", type);
241 		break;
242 	}
243 	/* discard the remaining bytes from the current packet */
244 	if (buf_len < buffer_len(&iqueue)) {
245 		error("iqueue grew unexpectedly");
246 		cleanup_exit(255);
247 	}
248 	consumed = buf_len - buffer_len(&iqueue);
249 	if (msg_len < consumed) {
250 		error("msg_len %d < consumed %d", msg_len, consumed);
251 		cleanup_exit(255);
252 	}
253 	if (msg_len > consumed)
254 		buffer_consume(&iqueue, msg_len - consumed);
255 }
256 
257 void
258 cleanup_exit(int i)
259 {
260 	/* XXX */
261 	_exit(i);
262 }
263 
264 int
265 main(int argc, char **argv)
266 {
267 	fd_set *rset, *wset;
268 	int in, out, max, log_stderr = 0;
269 	ssize_t len, olen, set_size;
270 	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
271 	LogLevel log_level = SYSLOG_LEVEL_ERROR;
272 	char buf[4*4096];
273 	extern char *__progname;
274 
275 	ssh_malloc_init();	/* must be called before any mallocs */
276 	TAILQ_INIT(&pkcs11_keylist);
277 	pkcs11_init(0);
278 
279 	log_init(__progname, log_level, log_facility, log_stderr);
280 
281 	in = STDIN_FILENO;
282 	out = STDOUT_FILENO;
283 
284 	max = 0;
285 	if (in > max)
286 		max = in;
287 	if (out > max)
288 		max = out;
289 
290 	buffer_init(&iqueue);
291 	buffer_init(&oqueue);
292 
293 	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
294 	rset = xmalloc(set_size);
295 	wset = xmalloc(set_size);
296 
297 	for (;;) {
298 		memset(rset, 0, set_size);
299 		memset(wset, 0, set_size);
300 
301 		/*
302 		 * Ensure that we can read a full buffer and handle
303 		 * the worst-case length packet it can generate,
304 		 * otherwise apply backpressure by stopping reads.
305 		 */
306 		if (buffer_check_alloc(&iqueue, sizeof(buf)) &&
307 		    buffer_check_alloc(&oqueue, MAX_MSG_LENGTH))
308 			FD_SET(in, rset);
309 
310 		olen = buffer_len(&oqueue);
311 		if (olen > 0)
312 			FD_SET(out, wset);
313 
314 		if (select(max+1, rset, wset, NULL, NULL) < 0) {
315 			if (errno == EINTR)
316 				continue;
317 			error("select: %s", strerror(errno));
318 			cleanup_exit(2);
319 		}
320 
321 		/* copy stdin to iqueue */
322 		if (FD_ISSET(in, rset)) {
323 			len = read(in, buf, sizeof buf);
324 			if (len == 0) {
325 				debug("read eof");
326 				cleanup_exit(0);
327 			} else if (len < 0) {
328 				error("read: %s", strerror(errno));
329 				cleanup_exit(1);
330 			} else {
331 				buffer_append(&iqueue, buf, len);
332 			}
333 		}
334 		/* send oqueue to stdout */
335 		if (FD_ISSET(out, wset)) {
336 			len = write(out, buffer_ptr(&oqueue), olen);
337 			if (len < 0) {
338 				error("write: %s", strerror(errno));
339 				cleanup_exit(1);
340 			} else {
341 				buffer_consume(&oqueue, len);
342 			}
343 		}
344 
345 		/*
346 		 * Process requests from client if we can fit the results
347 		 * into the output buffer, otherwise stop processing input
348 		 * and let the output queue drain.
349 		 */
350 		if (buffer_check_alloc(&oqueue, MAX_MSG_LENGTH))
351 			process();
352 	}
353 }
354