1/* $OpenBSD: ssh-keyscan.c,v 1.85 2011/03/15 10:36:02 okan Exp $ */
2/*
3 * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
4 *
5 * Modification and redistribution in source and binary forms is
6 * permitted provided that due credit is given to the author and the
7 * OpenBSD project by leaving this copyright notice intact.
8 */
9
10#include "includes.h"
11
12#include "openbsd-compat/sys-queue.h"
13#include <sys/resource.h>
14#ifdef HAVE_SYS_TIME_H
15# include <sys/time.h>
16#endif
17
18#include <netinet/in.h>
19#include <arpa/inet.h>
20
21#include <openssl/bn.h>
22
23#include <netdb.h>
24#include <errno.h>
25#include <setjmp.h>
26#include <stdarg.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <signal.h>
30#include <string.h>
31#include <unistd.h>
32
33#include "xmalloc.h"
34#include "ssh.h"
35#include "ssh1.h"
36#include "buffer.h"
37#include "key.h"
38#include "cipher.h"
39#include "kex.h"
40#include "compat.h"
41#include "myproposal.h"
42#include "packet.h"
43#include "dispatch.h"
44#include "log.h"
45#include "atomicio.h"
46#include "misc.h"
47#include "hostfile.h"
48
49/* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
50   Default value is AF_UNSPEC means both IPv4 and IPv6. */
51int IPv4or6 = AF_UNSPEC;
52
53int ssh_port = SSH_DEFAULT_PORT;
54
55#define KT_RSA1		1
56#define KT_DSA		2
57#define KT_RSA		4
58#define KT_ECDSA	8
59
60int get_keytypes = KT_RSA;	/* Get only RSA keys by default */
61
62int hash_hosts = 0;		/* Hash hostname on output */
63
64#define MAXMAXFD 256
65
66/* The number of seconds after which to give up on a TCP connection */
67int timeout = 5;
68
69int maxfd;
70#define MAXCON (maxfd - 10)
71
72extern char *__progname;
73fd_set *read_wait;
74size_t read_wait_nfdset;
75int ncon;
76int nonfatal_fatal = 0;
77jmp_buf kexjmp;
78Key *kexjmp_key;
79
80/*
81 * Keep a connection structure for each file descriptor.  The state
82 * associated with file descriptor n is held in fdcon[n].
83 */
84typedef struct Connection {
85	u_char c_status;	/* State of connection on this file desc. */
86#define CS_UNUSED 0		/* File descriptor unused */
87#define CS_CON 1		/* Waiting to connect/read greeting */
88#define CS_SIZE 2		/* Waiting to read initial packet size */
89#define CS_KEYS 3		/* Waiting to read public key packet */
90	int c_fd;		/* Quick lookup: c->c_fd == c - fdcon */
91	int c_plen;		/* Packet length field for ssh packet */
92	int c_len;		/* Total bytes which must be read. */
93	int c_off;		/* Length of data read so far. */
94	int c_keytype;		/* Only one of KT_RSA1, KT_DSA, or KT_RSA */
95	char *c_namebase;	/* Address to free for c_name and c_namelist */
96	char *c_name;		/* Hostname of connection for errors */
97	char *c_namelist;	/* Pointer to other possible addresses */
98	char *c_output_name;	/* Hostname of connection for output */
99	char *c_data;		/* Data read from this fd */
100	Kex *c_kex;		/* The key-exchange struct for ssh2 */
101	struct timeval c_tv;	/* Time at which connection gets aborted */
102	TAILQ_ENTRY(Connection) c_link;	/* List of connections in timeout order. */
103} con;
104
105TAILQ_HEAD(conlist, Connection) tq;	/* Timeout Queue */
106con *fdcon;
107
108static int
109fdlim_get(int hard)
110{
111#if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
112	struct rlimit rlfd;
113
114	if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
115		return (-1);
116	if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
117		return SSH_SYSFDMAX;
118	else
119		return hard ? rlfd.rlim_max : rlfd.rlim_cur;
120#else
121	return SSH_SYSFDMAX;
122#endif
123}
124
125static int
126fdlim_set(int lim)
127{
128#if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
129	struct rlimit rlfd;
130#endif
131
132	if (lim <= 0)
133		return (-1);
134#if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
135	if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
136		return (-1);
137	rlfd.rlim_cur = lim;
138	if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
139		return (-1);
140#elif defined (HAVE_SETDTABLESIZE)
141	setdtablesize(lim);
142#endif
143	return (0);
144}
145
146/*
147 * This is an strsep function that returns a null field for adjacent
148 * separators.  This is the same as the 4.4BSD strsep, but different from the
149 * one in the GNU libc.
150 */
151static char *
152xstrsep(char **str, const char *delim)
153{
154	char *s, *e;
155
156	if (!**str)
157		return (NULL);
158
159	s = *str;
160	e = s + strcspn(s, delim);
161
162	if (*e != '\0')
163		*e++ = '\0';
164	*str = e;
165
166	return (s);
167}
168
169/*
170 * Get the next non-null token (like GNU strsep).  Strsep() will return a
171 * null token for two adjacent separators, so we may have to loop.
172 */
173static char *
174strnnsep(char **stringp, char *delim)
175{
176	char *tok;
177
178	do {
179		tok = xstrsep(stringp, delim);
180	} while (tok && *tok == '\0');
181	return (tok);
182}
183
184static Key *
185keygrab_ssh1(con *c)
186{
187	static Key *rsa;
188	static Buffer msg;
189
190	if (rsa == NULL) {
191		buffer_init(&msg);
192		rsa = key_new(KEY_RSA1);
193	}
194	buffer_append(&msg, c->c_data, c->c_plen);
195	buffer_consume(&msg, 8 - (c->c_plen & 7));	/* padding */
196	if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
197		error("%s: invalid packet type", c->c_name);
198		buffer_clear(&msg);
199		return NULL;
200	}
201	buffer_consume(&msg, 8);		/* cookie */
202
203	/* server key */
204	(void) buffer_get_int(&msg);
205	buffer_get_bignum(&msg, rsa->rsa->e);
206	buffer_get_bignum(&msg, rsa->rsa->n);
207
208	/* host key */
209	(void) buffer_get_int(&msg);
210	buffer_get_bignum(&msg, rsa->rsa->e);
211	buffer_get_bignum(&msg, rsa->rsa->n);
212
213	buffer_clear(&msg);
214
215	return (rsa);
216}
217
218static int
219hostjump(Key *hostkey)
220{
221	kexjmp_key = hostkey;
222	longjmp(kexjmp, 1);
223}
224
225static int
226ssh2_capable(int remote_major, int remote_minor)
227{
228	switch (remote_major) {
229	case 1:
230		if (remote_minor == 99)
231			return 1;
232		break;
233	case 2:
234		return 1;
235	default:
236		break;
237	}
238	return 0;
239}
240
241static Key *
242keygrab_ssh2(con *c)
243{
244	int j;
245
246	packet_set_connection(c->c_fd, c->c_fd);
247	enable_compat20();
248	myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = c->c_keytype == KT_DSA?
249	    "ssh-dss" : (c->c_keytype == KT_RSA ? "ssh-rsa" :
250	    "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521");
251	c->c_kex = kex_setup(myproposal);
252	c->c_kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
253	c->c_kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
254	c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
255	c->c_kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
256	c->c_kex->kex[KEX_ECDH_SHA2] = kexecdh_client;
257	c->c_kex->verify_host_key = hostjump;
258
259	if (!(j = setjmp(kexjmp))) {
260		nonfatal_fatal = 1;
261		dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex);
262		fprintf(stderr, "Impossible! dispatch_run() returned!\n");
263		exit(1);
264	}
265	nonfatal_fatal = 0;
266	xfree(c->c_kex);
267	c->c_kex = NULL;
268	packet_close();
269
270	return j < 0? NULL : kexjmp_key;
271}
272
273static void
274keyprint(con *c, Key *key)
275{
276	char *host = c->c_output_name ? c->c_output_name : c->c_name;
277
278	if (!key)
279		return;
280	if (hash_hosts && (host = host_hash(host, NULL, 0)) == NULL)
281		fatal("host_hash failed");
282
283	fprintf(stdout, "%s ", host);
284	key_write(key, stdout);
285	fputs("\n", stdout);
286}
287
288static int
289tcpconnect(char *host)
290{
291	struct addrinfo hints, *ai, *aitop;
292	char strport[NI_MAXSERV];
293	int gaierr, s = -1;
294
295	snprintf(strport, sizeof strport, "%d", ssh_port);
296	memset(&hints, 0, sizeof(hints));
297	hints.ai_family = IPv4or6;
298	hints.ai_socktype = SOCK_STREAM;
299	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
300		fatal("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
301	for (ai = aitop; ai; ai = ai->ai_next) {
302		s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
303		if (s < 0) {
304			error("socket: %s", strerror(errno));
305			continue;
306		}
307		if (set_nonblock(s) == -1)
308			fatal("%s: set_nonblock(%d)", __func__, s);
309		if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
310		    errno != EINPROGRESS)
311			error("connect (`%s'): %s", host, strerror(errno));
312		else
313			break;
314		close(s);
315		s = -1;
316	}
317	freeaddrinfo(aitop);
318	return s;
319}
320
321static int
322conalloc(char *iname, char *oname, int keytype)
323{
324	char *namebase, *name, *namelist;
325	int s;
326
327	namebase = namelist = xstrdup(iname);
328
329	do {
330		name = xstrsep(&namelist, ",");
331		if (!name) {
332			xfree(namebase);
333			return (-1);
334		}
335	} while ((s = tcpconnect(name)) < 0);
336
337	if (s >= maxfd)
338		fatal("conalloc: fdno %d too high", s);
339	if (fdcon[s].c_status)
340		fatal("conalloc: attempt to reuse fdno %d", s);
341
342	fdcon[s].c_fd = s;
343	fdcon[s].c_status = CS_CON;
344	fdcon[s].c_namebase = namebase;
345	fdcon[s].c_name = name;
346	fdcon[s].c_namelist = namelist;
347	fdcon[s].c_output_name = xstrdup(oname);
348	fdcon[s].c_data = (char *) &fdcon[s].c_plen;
349	fdcon[s].c_len = 4;
350	fdcon[s].c_off = 0;
351	fdcon[s].c_keytype = keytype;
352	gettimeofday(&fdcon[s].c_tv, NULL);
353	fdcon[s].c_tv.tv_sec += timeout;
354	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
355	FD_SET(s, read_wait);
356	ncon++;
357	return (s);
358}
359
360static void
361confree(int s)
362{
363	if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
364		fatal("confree: attempt to free bad fdno %d", s);
365	close(s);
366	xfree(fdcon[s].c_namebase);
367	xfree(fdcon[s].c_output_name);
368	if (fdcon[s].c_status == CS_KEYS)
369		xfree(fdcon[s].c_data);
370	fdcon[s].c_status = CS_UNUSED;
371	fdcon[s].c_keytype = 0;
372	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
373	FD_CLR(s, read_wait);
374	ncon--;
375}
376
377static void
378contouch(int s)
379{
380	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
381	gettimeofday(&fdcon[s].c_tv, NULL);
382	fdcon[s].c_tv.tv_sec += timeout;
383	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
384}
385
386static int
387conrecycle(int s)
388{
389	con *c = &fdcon[s];
390	int ret;
391
392	ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
393	confree(s);
394	return (ret);
395}
396
397static void
398congreet(int s)
399{
400	int n = 0, remote_major = 0, remote_minor = 0;
401	char buf[256], *cp;
402	char remote_version[sizeof buf];
403	size_t bufsiz;
404	con *c = &fdcon[s];
405
406	for (;;) {
407		memset(buf, '\0', sizeof(buf));
408		bufsiz = sizeof(buf);
409		cp = buf;
410		while (bufsiz-- &&
411		    (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
412			if (*cp == '\r')
413				*cp = '\n';
414			cp++;
415		}
416		if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
417			break;
418	}
419	if (n == 0) {
420		switch (errno) {
421		case EPIPE:
422			error("%s: Connection closed by remote host", c->c_name);
423			break;
424		case ECONNREFUSED:
425			break;
426		default:
427			error("read (%s): %s", c->c_name, strerror(errno));
428			break;
429		}
430		conrecycle(s);
431		return;
432	}
433	if (*cp != '\n' && *cp != '\r') {
434		error("%s: bad greeting", c->c_name);
435		confree(s);
436		return;
437	}
438	*cp = '\0';
439	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
440	    &remote_major, &remote_minor, remote_version) == 3)
441		compat_datafellows(remote_version);
442	else
443		datafellows = 0;
444	if (c->c_keytype != KT_RSA1) {
445		if (!ssh2_capable(remote_major, remote_minor)) {
446			debug("%s doesn't support ssh2", c->c_name);
447			confree(s);
448			return;
449		}
450	} else if (remote_major != 1) {
451		debug("%s doesn't support ssh1", c->c_name);
452		confree(s);
453		return;
454	}
455	fprintf(stderr, "# %s %s\n", c->c_name, chop(buf));
456	n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
457	    c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
458	    c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
459	if (n < 0 || (size_t)n >= sizeof(buf)) {
460		error("snprintf: buffer too small");
461		confree(s);
462		return;
463	}
464	if (atomicio(vwrite, s, buf, n) != (size_t)n) {
465		error("write (%s): %s", c->c_name, strerror(errno));
466		confree(s);
467		return;
468	}
469	if (c->c_keytype != KT_RSA1) {
470		keyprint(c, keygrab_ssh2(c));
471		confree(s);
472		return;
473	}
474	c->c_status = CS_SIZE;
475	contouch(s);
476}
477
478static void
479conread(int s)
480{
481	con *c = &fdcon[s];
482	size_t n;
483
484	if (c->c_status == CS_CON) {
485		congreet(s);
486		return;
487	}
488	n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
489	if (n == 0) {
490		error("read (%s): %s", c->c_name, strerror(errno));
491		confree(s);
492		return;
493	}
494	c->c_off += n;
495
496	if (c->c_off == c->c_len)
497		switch (c->c_status) {
498		case CS_SIZE:
499			c->c_plen = htonl(c->c_plen);
500			c->c_len = c->c_plen + 8 - (c->c_plen & 7);
501			c->c_off = 0;
502			c->c_data = xmalloc(c->c_len);
503			c->c_status = CS_KEYS;
504			break;
505		case CS_KEYS:
506			keyprint(c, keygrab_ssh1(c));
507			confree(s);
508			return;
509		default:
510			fatal("conread: invalid status %d", c->c_status);
511			break;
512		}
513
514	contouch(s);
515}
516
517static void
518conloop(void)
519{
520	struct timeval seltime, now;
521	fd_set *r, *e;
522	con *c;
523	int i;
524
525	gettimeofday(&now, NULL);
526	c = TAILQ_FIRST(&tq);
527
528	if (c && (c->c_tv.tv_sec > now.tv_sec ||
529	    (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
530		seltime = c->c_tv;
531		seltime.tv_sec -= now.tv_sec;
532		seltime.tv_usec -= now.tv_usec;
533		if (seltime.tv_usec < 0) {
534			seltime.tv_usec += 1000000;
535			seltime.tv_sec--;
536		}
537	} else
538		timerclear(&seltime);
539
540	r = xcalloc(read_wait_nfdset, sizeof(fd_mask));
541	e = xcalloc(read_wait_nfdset, sizeof(fd_mask));
542	memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask));
543	memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask));
544
545	while (select(maxfd, r, NULL, e, &seltime) == -1 &&
546	    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
547		;
548
549	for (i = 0; i < maxfd; i++) {
550		if (FD_ISSET(i, e)) {
551			error("%s: exception!", fdcon[i].c_name);
552			confree(i);
553		} else if (FD_ISSET(i, r))
554			conread(i);
555	}
556	xfree(r);
557	xfree(e);
558
559	c = TAILQ_FIRST(&tq);
560	while (c && (c->c_tv.tv_sec < now.tv_sec ||
561	    (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
562		int s = c->c_fd;
563
564		c = TAILQ_NEXT(c, c_link);
565		conrecycle(s);
566	}
567}
568
569static void
570do_host(char *host)
571{
572	char *name = strnnsep(&host, " \t\n");
573	int j;
574
575	if (name == NULL)
576		return;
577	for (j = KT_RSA1; j <= KT_ECDSA; j *= 2) {
578		if (get_keytypes & j) {
579			while (ncon >= MAXCON)
580				conloop();
581			conalloc(name, *host ? host : name, j);
582		}
583	}
584}
585
586void
587fatal(const char *fmt,...)
588{
589	va_list args;
590
591	va_start(args, fmt);
592	do_log(SYSLOG_LEVEL_FATAL, fmt, args);
593	va_end(args);
594	if (nonfatal_fatal)
595		longjmp(kexjmp, -1);
596	else
597		exit(255);
598}
599
600static void
601usage(void)
602{
603	fprintf(stderr,
604	    "usage: %s [-46Hv] [-f file] [-p port] [-T timeout] [-t type]\n"
605	    "\t\t   [host | addrlist namelist] ...\n",
606	    __progname);
607	exit(1);
608}
609
610int
611main(int argc, char **argv)
612{
613	int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
614	int opt, fopt_count = 0, j;
615	char *tname, *cp, line[NI_MAXHOST];
616	FILE *fp;
617	u_long linenum;
618
619	extern int optind;
620	extern char *optarg;
621
622	__progname = ssh_get_progname(argv[0]);
623	seed_rng();
624	TAILQ_INIT(&tq);
625
626	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
627	sanitise_stdfd();
628
629	if (argc <= 1)
630		usage();
631
632	while ((opt = getopt(argc, argv, "Hv46p:T:t:f:")) != -1) {
633		switch (opt) {
634		case 'H':
635			hash_hosts = 1;
636			break;
637		case 'p':
638			ssh_port = a2port(optarg);
639			if (ssh_port <= 0) {
640				fprintf(stderr, "Bad port '%s'\n", optarg);
641				exit(1);
642			}
643			break;
644		case 'T':
645			timeout = convtime(optarg);
646			if (timeout == -1 || timeout == 0) {
647				fprintf(stderr, "Bad timeout '%s'\n", optarg);
648				usage();
649			}
650			break;
651		case 'v':
652			if (!debug_flag) {
653				debug_flag = 1;
654				log_level = SYSLOG_LEVEL_DEBUG1;
655			}
656			else if (log_level < SYSLOG_LEVEL_DEBUG3)
657				log_level++;
658			else
659				fatal("Too high debugging level.");
660			break;
661		case 'f':
662			if (strcmp(optarg, "-") == 0)
663				optarg = NULL;
664			argv[fopt_count++] = optarg;
665			break;
666		case 't':
667			get_keytypes = 0;
668			tname = strtok(optarg, ",");
669			while (tname) {
670				int type = key_type_from_name(tname);
671				switch (type) {
672				case KEY_RSA1:
673					get_keytypes |= KT_RSA1;
674					break;
675				case KEY_DSA:
676					get_keytypes |= KT_DSA;
677					break;
678				case KEY_ECDSA:
679					get_keytypes |= KT_ECDSA;
680					break;
681				case KEY_RSA:
682					get_keytypes |= KT_RSA;
683					break;
684				case KEY_UNSPEC:
685					fatal("unknown key type %s", tname);
686				}
687				tname = strtok(NULL, ",");
688			}
689			break;
690		case '4':
691			IPv4or6 = AF_INET;
692			break;
693		case '6':
694			IPv4or6 = AF_INET6;
695			break;
696		case '?':
697		default:
698			usage();
699		}
700	}
701	if (optind == argc && !fopt_count)
702		usage();
703
704	log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
705
706	maxfd = fdlim_get(1);
707	if (maxfd < 0)
708		fatal("%s: fdlim_get: bad value", __progname);
709	if (maxfd > MAXMAXFD)
710		maxfd = MAXMAXFD;
711	if (MAXCON <= 0)
712		fatal("%s: not enough file descriptors", __progname);
713	if (maxfd > fdlim_get(0))
714		fdlim_set(maxfd);
715	fdcon = xcalloc(maxfd, sizeof(con));
716
717	read_wait_nfdset = howmany(maxfd, NFDBITS);
718	read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask));
719
720	for (j = 0; j < fopt_count; j++) {
721		if (argv[j] == NULL)
722			fp = stdin;
723		else if ((fp = fopen(argv[j], "r")) == NULL)
724			fatal("%s: %s: %s", __progname, argv[j],
725			    strerror(errno));
726		linenum = 0;
727
728		while (read_keyfile_line(fp,
729		    argv[j] == NULL ? "(stdin)" : argv[j], line, sizeof(line),
730		    &linenum) != -1) {
731			/* Chomp off trailing whitespace and comments */
732			if ((cp = strchr(line, '#')) == NULL)
733				cp = line + strlen(line) - 1;
734			while (cp >= line) {
735				if (*cp == ' ' || *cp == '\t' ||
736				    *cp == '\n' || *cp == '#')
737					*cp-- = '\0';
738				else
739					break;
740			}
741
742			/* Skip empty lines */
743			if (*line == '\0')
744				continue;
745
746			do_host(line);
747		}
748
749		if (ferror(fp))
750			fatal("%s: %s: %s", __progname, argv[j],
751			    strerror(errno));
752
753		fclose(fp);
754	}
755
756	while (optind < argc)
757		do_host(argv[optind++]);
758
759	while (ncon > 0)
760		conloop();
761
762	return (0);
763}
764