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