1 /* $OpenBSD: ssh-keyscan.c,v 1.153 2023/06/21 05:06:04 djm 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>
47 #include "myproposal.h"
59 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
60 Default value is AF_UNSPEC means both IPv4 and IPv6. */
61 int IPv4or6 = AF_UNSPEC;
63 int ssh_port = SSH_DEFAULT_PORT;
67 #define KT_ECDSA (1<<2)
68 #define KT_ED25519 (1<<3)
69 #define KT_XMSS (1<<4)
70 #define KT_ECDSA_SK (1<<5)
71 #define KT_ED25519_SK (1<<6)
74 #define KT_MAX KT_ED25519_SK
77 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
79 int hash_hosts = 0; /* Hash hostname on output */
81 int print_sshfp = 0; /* Print SSHFP records instead of known_hosts */
83 int found_one = 0; /* Successfully found a key */
85 int hashalg = -1; /* Hash for SSHFP records or -1 for all */
89 /* The number of seconds after which to give up on a TCP connection */
93 #define MAXCON (maxfd - 10)
95 extern char *__progname;
96 struct pollfd *read_wait;
100 * Keep a connection structure for each file descriptor. The state
101 * associated with file descriptor n is held in fdcon[n].
103 typedef struct Connection {
104 u_char c_status; /* State of connection on this file desc. */
105 #define CS_UNUSED 0 /* File descriptor unused */
106 #define CS_CON 1 /* Waiting to connect/read greeting */
107 #define CS_SIZE 2 /* Waiting to read initial packet size */
108 #define CS_KEYS 3 /* Waiting to read public key packet */
109 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
110 int c_plen; /* Packet length field for ssh packet */
111 int c_len; /* Total bytes which must be read. */
112 int c_off; /* Length of data read so far. */
113 int c_keytype; /* Only one of KT_* */
114 sig_atomic_t c_done; /* SSH2 done */
115 char *c_namebase; /* Address to free for c_name and c_namelist */
116 char *c_name; /* Hostname of connection for errors */
117 char *c_namelist; /* Pointer to other possible addresses */
118 char *c_output_name; /* Hostname of connection for output */
119 char *c_data; /* Data read from this fd */
120 struct ssh *c_ssh; /* SSH-connection */
121 struct timespec c_ts; /* Time at which connection gets aborted */
122 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
125 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
128 static void keyprint(con *c, struct sshkey *key);
133 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
137 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
139 lim = hard ? rlfd.rlim_max : rlfd.rlim_cur;
142 if (lim == RLIM_INFINITY)
148 return (SSH_SYSFDMAX <= 0) ? -1 :
149 ((SSH_SYSFDMAX >= INT_MAX) ? INT_MAX : SSH_SYSFDMAX);
156 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
162 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
163 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
166 if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
168 #elif defined (HAVE_SETDTABLESIZE)
175 * This is an strsep function that returns a null field for adjacent
176 * separators. This is the same as the 4.4BSD strsep, but different from the
177 * one in the GNU libc.
180 xstrsep(char **str, const char *delim)
188 e = s + strcspn(s, delim);
198 * Get the next non-null token (like GNU strsep). Strsep() will return a
199 * null token for two adjacent separators, so we may have to loop.
202 strnnsep(char **stringp, char *delim)
207 tok = xstrsep(stringp, delim);
208 } while (tok && *tok == '\0');
214 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
218 if ((c = ssh_get_app_data(ssh)) != NULL)
219 keyprint(c, hostkey);
220 /* always abort key exchange */
225 ssh2_capable(int remote_major, int remote_minor)
227 switch (remote_major) {
229 if (remote_minor == 99)
243 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
246 switch (c->c_keytype) {
248 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
249 "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
252 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
253 "rsa-sha2-512-cert-v01@openssh.com,"
254 "rsa-sha2-256-cert-v01@openssh.com,"
255 "ssh-rsa-cert-v01@openssh.com" :
261 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
262 "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
265 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
266 "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
269 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
270 "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
271 "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
272 "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
273 "ecdsa-sha2-nistp256,"
274 "ecdsa-sha2-nistp384,"
275 "ecdsa-sha2-nistp521";
278 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
279 "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
280 "sk-ecdsa-sha2-nistp256@openssh.com";
283 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
284 "sk-ssh-ed25519-cert-v01@openssh.com" :
285 "sk-ssh-ed25519@openssh.com";
288 fatal("unknown key type %d", c->c_keytype);
291 if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
293 fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
297 c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
298 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
299 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
300 c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
301 c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
302 c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
303 c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
304 # ifdef OPENSSL_HAS_ECC
305 c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
308 c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
309 c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
310 ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
312 * do the key-exchange until an error occurs or until
313 * the key_print_wrapper() callback sets c_done.
315 ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
319 keyprint_one(const char *host, struct sshkey *key)
321 char *hostport = NULL, *hashed = NULL;
322 const char *known_host;
328 export_dns_rr(host, key, stdout, 0, hashalg);
332 hostport = put_host_port(host, ssh_port);
334 if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
335 fatal("host_hash failed");
336 known_host = hash_hosts ? hashed : hostport;
338 r = fprintf(stdout, "%s ", known_host);
339 if (r >= 0 && sshkey_write(key, stdout) == 0)
340 (void)fputs("\n", stdout);
346 keyprint(con *c, struct sshkey *key)
348 char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
353 if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
354 keyprint_one(hosts, key);
357 ohosts = hosts = xstrdup(hosts);
358 while ((host = strsep(&hosts, ",")) != NULL)
359 keyprint_one(host, key);
364 tcpconnect(char *host)
366 struct addrinfo hints, *ai, *aitop;
367 char strport[NI_MAXSERV];
370 snprintf(strport, sizeof strport, "%d", ssh_port);
371 memset(&hints, 0, sizeof(hints));
372 hints.ai_family = IPv4or6;
373 hints.ai_socktype = SOCK_STREAM;
374 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
375 error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
378 for (ai = aitop; ai; ai = ai->ai_next) {
379 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
381 error("socket: %s", strerror(errno));
384 if (set_nonblock(s) == -1)
385 fatal_f("set_nonblock(%d)", s);
386 if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
387 errno != EINPROGRESS)
388 error("connect (`%s'): %s", host, strerror(errno));
399 conalloc(const char *iname, const char *oname, int keytype)
401 char *namebase, *name, *namelist;
404 namebase = namelist = xstrdup(iname);
407 name = xstrsep(&namelist, ",");
412 } while ((s = tcpconnect(name)) < 0);
415 fatal("conalloc: fdno %d too high", s);
416 if (fdcon[s].c_status)
417 fatal("conalloc: attempt to reuse fdno %d", s);
419 debug3_f("oname %s kt %d", oname, keytype);
421 fdcon[s].c_status = CS_CON;
422 fdcon[s].c_namebase = namebase;
423 fdcon[s].c_name = name;
424 fdcon[s].c_namelist = namelist;
425 fdcon[s].c_output_name = xstrdup(oname);
426 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
429 fdcon[s].c_keytype = keytype;
430 monotime_ts(&fdcon[s].c_ts);
431 fdcon[s].c_ts.tv_sec += timeout;
432 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
434 read_wait[s].events = POLLIN;
442 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
443 fatal("confree: attempt to free bad fdno %d", s);
444 free(fdcon[s].c_namebase);
445 free(fdcon[s].c_output_name);
446 if (fdcon[s].c_status == CS_KEYS)
447 free(fdcon[s].c_data);
448 fdcon[s].c_status = CS_UNUSED;
449 fdcon[s].c_keytype = 0;
450 if (fdcon[s].c_ssh) {
451 ssh_packet_close(fdcon[s].c_ssh);
452 free(fdcon[s].c_ssh);
453 fdcon[s].c_ssh = NULL;
456 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
457 read_wait[s].fd = -1;
458 read_wait[s].events = 0;
465 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
466 monotime_ts(&fdcon[s].c_ts);
467 fdcon[s].c_ts.tv_sec += timeout;
468 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
477 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
485 int n = 0, remote_major = 0, remote_minor = 0;
487 char remote_version[sizeof buf];
491 /* send client banner */
492 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
493 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
494 if (n < 0 || (size_t)n >= sizeof(buf)) {
495 error("snprintf: buffer too small");
499 if (atomicio(vwrite, s, buf, n) != (size_t)n) {
500 error("write (%s): %s", c->c_name, strerror(errno));
506 * Read the server banner as per RFC4253 section 4.2. The "SSH-"
507 * protocol identification string may be preceeded by an arbitrarily
508 * large banner which we must read and ignore. Loop while reading
509 * newline-terminated lines until we have one starting with "SSH-".
510 * The ID string cannot be longer than 255 characters although the
511 * preceeding banner lines may (in which case they'll be discarded
512 * in multiple iterations of the outer loop).
515 memset(buf, '\0', sizeof(buf));
516 bufsiz = sizeof(buf);
519 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
524 if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
530 error("%s: Connection closed by remote host", c->c_name);
535 error("read (%s): %s", c->c_name, strerror(errno));
541 if (cp >= buf + sizeof(buf)) {
542 error("%s: greeting exceeds allowable length", c->c_name);
546 if (*cp != '\n' && *cp != '\r') {
547 error("%s: bad greeting", c->c_name);
552 if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
553 fatal("ssh_packet_set_connection failed");
554 ssh_packet_set_timeout(c->c_ssh, timeout, 1);
555 ssh_set_app_data(c->c_ssh, c); /* back link */
556 c->c_ssh->compat = 0;
557 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
558 &remote_major, &remote_minor, remote_version) == 3)
559 compat_banner(c->c_ssh, remote_version);
560 if (!ssh2_capable(remote_major, remote_minor)) {
561 debug("%s doesn't support ssh2", c->c_name);
565 fprintf(stderr, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
566 c->c_name, ssh_port, chop(buf));
577 if (c->c_status == CS_CON) {
581 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
583 error("read (%s): %s", c->c_name, strerror(errno));
589 if (c->c_off == c->c_len)
590 switch (c->c_status) {
592 c->c_plen = htonl(c->c_plen);
593 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
595 c->c_data = xmalloc(c->c_len);
596 c->c_status = CS_KEYS;
599 fatal("conread: invalid status %d", c->c_status);
609 struct timespec seltime, now;
614 c = TAILQ_FIRST(&tq);
616 if (c && timespeccmp(&c->c_ts, &now, >))
617 timespecsub(&c->c_ts, &now, &seltime);
619 timespecclear(&seltime);
621 while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
622 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
627 for (i = 0; i < maxfd; i++) {
628 if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
630 else if (read_wait[i].revents & (POLLIN|POLLHUP))
634 c = TAILQ_FIRST(&tq);
635 while (c && timespeccmp(&c->c_ts, &now, <)) {
638 c = TAILQ_NEXT(c, c_link);
644 do_one_host(char *host)
646 char *name = strnnsep(&host, " \t\n");
651 for (j = KT_MIN; j <= KT_MAX; j *= 2) {
652 if (get_keytypes & j) {
653 while (ncon >= MAXCON)
655 conalloc(name, *host ? host : name, j);
664 struct xaddr addr, end_addr;
669 if (addr_pton_cidr(host, &addr, &masklen) != 0) {
670 /* Assume argument is a hostname */
673 /* Argument is a CIDR range */
674 debug("CIDR range %s", host);
676 if (addr_host_to_all1s(&end_addr, masklen) != 0)
679 * Note: we deliberately include the all-zero/ones addresses.
682 if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
684 error("Invalid address %s", host);
687 debug("CIDR expand: address %s", daddr);
689 if (addr_cmp(&addr, &end_addr) == 0)
691 addr_increment(&addr);
697 sshfatal(const char *file, const char *func, int line, int showfunc,
698 LogLevel level, const char *suffix, const char *fmt, ...)
703 sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
712 "usage: ssh-keyscan [-46cDHv] [-f file] [-O option] [-p port] [-T timeout]\n"
713 " [-t type] [host | addrlist namelist]\n");
718 main(int argc, char **argv)
720 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
721 int opt, fopt_count = 0, j;
722 char *tname, *cp, *line = NULL;
729 __progname = ssh_get_progname(argv[0]);
733 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
739 while ((opt = getopt(argc, argv, "cDHv46O:p:T:t:f:")) != -1) {
751 ssh_port = a2port(optarg);
753 fprintf(stderr, "Bad port '%s'\n", optarg);
758 timeout = convtime(optarg);
759 if (timeout == -1 || timeout == 0) {
760 fprintf(stderr, "Bad timeout '%s'\n", optarg);
767 log_level = SYSLOG_LEVEL_DEBUG1;
769 else if (log_level < SYSLOG_LEVEL_DEBUG3)
772 fatal("Too high debugging level.");
775 if (strcmp(optarg, "-") == 0)
777 argv[fopt_count++] = optarg;
780 /* Maybe other misc options in the future too */
781 if (strncmp(optarg, "hashalg=", 8) != 0)
782 fatal("Unsupported -O option");
783 if ((hashalg = ssh_digest_alg_by_name(
785 fatal("Unsupported hash algorithm");
789 tname = strtok(optarg, ",");
791 int type = sshkey_type_from_name(tname);
795 get_keytypes |= KT_DSA;
798 get_keytypes |= KT_ECDSA;
801 get_keytypes |= KT_RSA;
804 get_keytypes |= KT_ED25519;
807 get_keytypes |= KT_XMSS;
810 get_keytypes |= KT_ED25519_SK;
813 get_keytypes |= KT_ECDSA_SK;
817 fatal("Unknown key type \"%s\"", tname);
819 tname = strtok(NULL, ",");
832 if (optind == argc && !fopt_count)
835 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
837 maxfd = fdlim_get(1);
839 fatal("%s: fdlim_get: bad value", __progname);
840 if (maxfd > MAXMAXFD)
843 fatal("%s: not enough file descriptors", __progname);
844 if (maxfd > fdlim_get(0))
846 fdcon = xcalloc(maxfd, sizeof(con));
847 read_wait = xcalloc(maxfd, sizeof(struct pollfd));
848 for (j = 0; j < maxfd; j++)
849 read_wait[j].fd = -1;
851 for (j = 0; j < fopt_count; j++) {
854 else if ((fp = fopen(argv[j], "r")) == NULL)
855 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
857 while (getline(&line, &linesize, fp) != -1) {
858 /* Chomp off trailing whitespace and comments */
859 if ((cp = strchr(line, '#')) == NULL)
860 cp = line + strlen(line) - 1;
862 if (*cp == ' ' || *cp == '\t' ||
863 *cp == '\n' || *cp == '#')
869 /* Skip empty lines */
877 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
883 while (optind < argc)
884 do_host(argv[optind++]);
889 return found_one ? 0 : 1;