1 /* $OpenBSD: ssh-keyscan.c,v 1.151 2023/02/10 06:41:53 jmc Exp $ */
3 * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
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.
12 #include <sys/types.h>
13 #include "openbsd-compat/sys-queue.h"
14 #include <sys/resource.h>
15 #ifdef HAVE_SYS_TIME_H
16 # include <sys/time.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
23 #include <openssl/bn.h>
46 #include "myproposal.h"
58 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
59 Default value is AF_UNSPEC means both IPv4 and IPv6. */
60 int IPv4or6 = AF_UNSPEC;
62 int ssh_port = SSH_DEFAULT_PORT;
66 #define KT_ECDSA (1<<2)
67 #define KT_ED25519 (1<<3)
68 #define KT_XMSS (1<<4)
69 #define KT_ECDSA_SK (1<<5)
70 #define KT_ED25519_SK (1<<6)
73 #define KT_MAX KT_ED25519_SK
76 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
78 int hash_hosts = 0; /* Hash hostname on output */
80 int print_sshfp = 0; /* Print SSHFP records instead of known_hosts */
82 int found_one = 0; /* Successfully found a key */
84 int hashalg = -1; /* Hash for SSHFP records or -1 for all */
88 /* The number of seconds after which to give up on a TCP connection */
92 #define MAXCON (maxfd - 10)
94 extern char *__progname;
95 struct pollfd *read_wait;
99 * Keep a connection structure for each file descriptor. The state
100 * associated with file descriptor n is held in fdcon[n].
102 typedef struct Connection {
103 u_char c_status; /* State of connection on this file desc. */
104 #define CS_UNUSED 0 /* File descriptor unused */
105 #define CS_CON 1 /* Waiting to connect/read greeting */
106 #define CS_SIZE 2 /* Waiting to read initial packet size */
107 #define CS_KEYS 3 /* Waiting to read public key packet */
108 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
109 int c_plen; /* Packet length field for ssh packet */
110 int c_len; /* Total bytes which must be read. */
111 int c_off; /* Length of data read so far. */
112 int c_keytype; /* Only one of KT_* */
113 sig_atomic_t c_done; /* SSH2 done */
114 char *c_namebase; /* Address to free for c_name and c_namelist */
115 char *c_name; /* Hostname of connection for errors */
116 char *c_namelist; /* Pointer to other possible addresses */
117 char *c_output_name; /* Hostname of connection for output */
118 char *c_data; /* Data read from this fd */
119 struct ssh *c_ssh; /* SSH-connection */
120 struct timespec c_ts; /* Time at which connection gets aborted */
121 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
124 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
127 static void keyprint(con *c, struct sshkey *key);
132 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
135 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
137 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
140 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
149 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
155 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
156 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
159 if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
161 #elif defined (HAVE_SETDTABLESIZE)
168 * This is an strsep function that returns a null field for adjacent
169 * separators. This is the same as the 4.4BSD strsep, but different from the
170 * one in the GNU libc.
173 xstrsep(char **str, const char *delim)
181 e = s + strcspn(s, delim);
191 * Get the next non-null token (like GNU strsep). Strsep() will return a
192 * null token for two adjacent separators, so we may have to loop.
195 strnnsep(char **stringp, char *delim)
200 tok = xstrsep(stringp, delim);
201 } while (tok && *tok == '\0');
207 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
211 if ((c = ssh_get_app_data(ssh)) != NULL)
212 keyprint(c, hostkey);
213 /* always abort key exchange */
218 ssh2_capable(int remote_major, int remote_minor)
220 switch (remote_major) {
222 if (remote_minor == 99)
236 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
239 switch (c->c_keytype) {
241 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
242 "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
245 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
246 "rsa-sha2-512-cert-v01@openssh.com,"
247 "rsa-sha2-256-cert-v01@openssh.com,"
248 "ssh-rsa-cert-v01@openssh.com" :
254 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
255 "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
258 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
259 "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
262 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
263 "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
264 "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
265 "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
266 "ecdsa-sha2-nistp256,"
267 "ecdsa-sha2-nistp384,"
268 "ecdsa-sha2-nistp521";
271 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
272 "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
273 "sk-ecdsa-sha2-nistp256@openssh.com";
276 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
277 "sk-ssh-ed25519-cert-v01@openssh.com" :
278 "sk-ssh-ed25519@openssh.com";
281 fatal("unknown key type %d", c->c_keytype);
284 if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
286 fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
290 c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
291 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
292 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
293 c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
294 c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
295 c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
296 c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
297 # ifdef OPENSSL_HAS_ECC
298 c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
301 c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
302 c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
303 ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
305 * do the key-exchange until an error occurs or until
306 * the key_print_wrapper() callback sets c_done.
308 ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
312 keyprint_one(const char *host, struct sshkey *key)
314 char *hostport = NULL, *hashed = NULL;
315 const char *known_host;
320 export_dns_rr(host, key, stdout, 0, hashalg);
324 hostport = put_host_port(host, ssh_port);
326 if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
327 fatal("host_hash failed");
328 known_host = hash_hosts ? hashed : hostport;
330 fprintf(stdout, "%s ", known_host);
331 sshkey_write(key, stdout);
338 keyprint(con *c, struct sshkey *key)
340 char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
345 if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
346 keyprint_one(hosts, key);
349 ohosts = hosts = xstrdup(hosts);
350 while ((host = strsep(&hosts, ",")) != NULL)
351 keyprint_one(host, key);
356 tcpconnect(char *host)
358 struct addrinfo hints, *ai, *aitop;
359 char strport[NI_MAXSERV];
362 snprintf(strport, sizeof strport, "%d", ssh_port);
363 memset(&hints, 0, sizeof(hints));
364 hints.ai_family = IPv4or6;
365 hints.ai_socktype = SOCK_STREAM;
366 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
367 error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
370 for (ai = aitop; ai; ai = ai->ai_next) {
371 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
373 error("socket: %s", strerror(errno));
376 if (set_nonblock(s) == -1)
377 fatal_f("set_nonblock(%d)", s);
378 if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
379 errno != EINPROGRESS)
380 error("connect (`%s'): %s", host, strerror(errno));
391 conalloc(const char *iname, const char *oname, int keytype)
393 char *namebase, *name, *namelist;
396 namebase = namelist = xstrdup(iname);
399 name = xstrsep(&namelist, ",");
404 } while ((s = tcpconnect(name)) < 0);
407 fatal("conalloc: fdno %d too high", s);
408 if (fdcon[s].c_status)
409 fatal("conalloc: attempt to reuse fdno %d", s);
411 debug3_f("oname %s kt %d", oname, keytype);
413 fdcon[s].c_status = CS_CON;
414 fdcon[s].c_namebase = namebase;
415 fdcon[s].c_name = name;
416 fdcon[s].c_namelist = namelist;
417 fdcon[s].c_output_name = xstrdup(oname);
418 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
421 fdcon[s].c_keytype = keytype;
422 monotime_ts(&fdcon[s].c_ts);
423 fdcon[s].c_ts.tv_sec += timeout;
424 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
426 read_wait[s].events = POLLIN;
434 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
435 fatal("confree: attempt to free bad fdno %d", s);
436 free(fdcon[s].c_namebase);
437 free(fdcon[s].c_output_name);
438 if (fdcon[s].c_status == CS_KEYS)
439 free(fdcon[s].c_data);
440 fdcon[s].c_status = CS_UNUSED;
441 fdcon[s].c_keytype = 0;
442 if (fdcon[s].c_ssh) {
443 ssh_packet_close(fdcon[s].c_ssh);
444 free(fdcon[s].c_ssh);
445 fdcon[s].c_ssh = NULL;
448 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
449 read_wait[s].fd = -1;
450 read_wait[s].events = 0;
457 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
458 monotime_ts(&fdcon[s].c_ts);
459 fdcon[s].c_ts.tv_sec += timeout;
460 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
469 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
477 int n = 0, remote_major = 0, remote_minor = 0;
479 char remote_version[sizeof buf];
483 /* send client banner */
484 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
485 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
486 if (n < 0 || (size_t)n >= sizeof(buf)) {
487 error("snprintf: buffer too small");
491 if (atomicio(vwrite, s, buf, n) != (size_t)n) {
492 error("write (%s): %s", c->c_name, strerror(errno));
498 * Read the server banner as per RFC4253 section 4.2. The "SSH-"
499 * protocol identification string may be preceeded by an arbitrarily
500 * large banner which we must read and ignore. Loop while reading
501 * newline-terminated lines until we have one starting with "SSH-".
502 * The ID string cannot be longer than 255 characters although the
503 * preceeding banner lines may (in which case they'll be discarded
504 * in multiple iterations of the outer loop).
507 memset(buf, '\0', sizeof(buf));
508 bufsiz = sizeof(buf);
511 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
516 if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
522 error("%s: Connection closed by remote host", c->c_name);
527 error("read (%s): %s", c->c_name, strerror(errno));
533 if (cp >= buf + sizeof(buf)) {
534 error("%s: greeting exceeds allowable length", c->c_name);
538 if (*cp != '\n' && *cp != '\r') {
539 error("%s: bad greeting", c->c_name);
544 if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
545 fatal("ssh_packet_set_connection failed");
546 ssh_packet_set_timeout(c->c_ssh, timeout, 1);
547 ssh_set_app_data(c->c_ssh, c); /* back link */
548 c->c_ssh->compat = 0;
549 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
550 &remote_major, &remote_minor, remote_version) == 3)
551 compat_banner(c->c_ssh, remote_version);
552 if (!ssh2_capable(remote_major, remote_minor)) {
553 debug("%s doesn't support ssh2", c->c_name);
557 fprintf(stderr, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
558 c->c_name, ssh_port, chop(buf));
569 if (c->c_status == CS_CON) {
573 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
575 error("read (%s): %s", c->c_name, strerror(errno));
581 if (c->c_off == c->c_len)
582 switch (c->c_status) {
584 c->c_plen = htonl(c->c_plen);
585 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
587 c->c_data = xmalloc(c->c_len);
588 c->c_status = CS_KEYS;
591 fatal("conread: invalid status %d", c->c_status);
601 struct timespec seltime, now;
606 c = TAILQ_FIRST(&tq);
608 if (c && timespeccmp(&c->c_ts, &now, >))
609 timespecsub(&c->c_ts, &now, &seltime);
611 timespecclear(&seltime);
613 while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
614 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
619 for (i = 0; i < maxfd; i++) {
620 if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
622 else if (read_wait[i].revents & (POLLIN|POLLHUP))
626 c = TAILQ_FIRST(&tq);
627 while (c && timespeccmp(&c->c_ts, &now, <)) {
630 c = TAILQ_NEXT(c, c_link);
636 do_one_host(char *host)
638 char *name = strnnsep(&host, " \t\n");
643 for (j = KT_MIN; j <= KT_MAX; j *= 2) {
644 if (get_keytypes & j) {
645 while (ncon >= MAXCON)
647 conalloc(name, *host ? host : name, j);
656 struct xaddr addr, end_addr;
661 if (addr_pton_cidr(host, &addr, &masklen) != 0) {
662 /* Assume argument is a hostname */
665 /* Argument is a CIDR range */
666 debug("CIDR range %s", host);
668 if (addr_host_to_all1s(&end_addr, masklen) != 0)
671 * Note: we deliberately include the all-zero/ones addresses.
674 if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
676 error("Invalid address %s", host);
679 debug("CIDR expand: address %s", daddr);
681 if (addr_cmp(&addr, &end_addr) == 0)
683 addr_increment(&addr);
689 sshfatal(const char *file, const char *func, int line, int showfunc,
690 LogLevel level, const char *suffix, const char *fmt, ...)
695 sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
704 "usage: ssh-keyscan [-46cDHv] [-f file] [-O option] [-p port] [-T timeout]\n"
705 " [-t type] [host | addrlist namelist]\n");
710 main(int argc, char **argv)
712 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
713 int opt, fopt_count = 0, j;
714 char *tname, *cp, *line = NULL;
721 __progname = ssh_get_progname(argv[0]);
725 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
731 while ((opt = getopt(argc, argv, "cDHv46O:p:T:t:f:")) != -1) {
743 ssh_port = a2port(optarg);
745 fprintf(stderr, "Bad port '%s'\n", optarg);
750 timeout = convtime(optarg);
751 if (timeout == -1 || timeout == 0) {
752 fprintf(stderr, "Bad timeout '%s'\n", optarg);
759 log_level = SYSLOG_LEVEL_DEBUG1;
761 else if (log_level < SYSLOG_LEVEL_DEBUG3)
764 fatal("Too high debugging level.");
767 if (strcmp(optarg, "-") == 0)
769 argv[fopt_count++] = optarg;
772 /* Maybe other misc options in the future too */
773 if (strncmp(optarg, "hashalg=", 8) != 0)
774 fatal("Unsupported -O option");
775 if ((hashalg = ssh_digest_alg_by_name(
777 fatal("Unsupported hash algorithm");
781 tname = strtok(optarg, ",");
783 int type = sshkey_type_from_name(tname);
787 get_keytypes |= KT_DSA;
790 get_keytypes |= KT_ECDSA;
793 get_keytypes |= KT_RSA;
796 get_keytypes |= KT_ED25519;
799 get_keytypes |= KT_XMSS;
802 get_keytypes |= KT_ED25519_SK;
805 get_keytypes |= KT_ECDSA_SK;
809 fatal("Unknown key type \"%s\"", tname);
811 tname = strtok(NULL, ",");
824 if (optind == argc && !fopt_count)
827 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
829 maxfd = fdlim_get(1);
831 fatal("%s: fdlim_get: bad value", __progname);
832 if (maxfd > MAXMAXFD)
835 fatal("%s: not enough file descriptors", __progname);
836 if (maxfd > fdlim_get(0))
838 fdcon = xcalloc(maxfd, sizeof(con));
839 read_wait = xcalloc(maxfd, sizeof(struct pollfd));
840 for (j = 0; j < maxfd; j++)
841 read_wait[j].fd = -1;
843 for (j = 0; j < fopt_count; j++) {
846 else if ((fp = fopen(argv[j], "r")) == NULL)
847 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
849 while (getline(&line, &linesize, fp) != -1) {
850 /* Chomp off trailing whitespace and comments */
851 if ((cp = strchr(line, '#')) == NULL)
852 cp = line + strlen(line) - 1;
854 if (*cp == ' ' || *cp == '\t' ||
855 *cp == '\n' || *cp == '#')
861 /* Skip empty lines */
869 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
875 while (optind < argc)
876 do_host(argv[optind++]);
881 return found_one ? 0 : 1;