1 /* $OpenBSD: ssh-keyscan.c,v 1.149 2022/12/26 19:16:03 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>
45 #include "myproposal.h"
57 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
58 Default value is AF_UNSPEC means both IPv4 and IPv6. */
59 int IPv4or6 = AF_UNSPEC;
61 int ssh_port = SSH_DEFAULT_PORT;
65 #define KT_ECDSA (1<<2)
66 #define KT_ED25519 (1<<3)
67 #define KT_XMSS (1<<4)
68 #define KT_ECDSA_SK (1<<5)
69 #define KT_ED25519_SK (1<<6)
72 #define KT_MAX KT_ED25519_SK
75 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
77 int hash_hosts = 0; /* Hash hostname on output */
79 int print_sshfp = 0; /* Print SSHFP records instead of known_hosts */
81 int found_one = 0; /* Successfully found a key */
85 /* The number of seconds after which to give up on a TCP connection */
89 #define MAXCON (maxfd - 10)
91 extern char *__progname;
92 struct pollfd *read_wait;
96 * Keep a connection structure for each file descriptor. The state
97 * associated with file descriptor n is held in fdcon[n].
99 typedef struct Connection {
100 u_char c_status; /* State of connection on this file desc. */
101 #define CS_UNUSED 0 /* File descriptor unused */
102 #define CS_CON 1 /* Waiting to connect/read greeting */
103 #define CS_SIZE 2 /* Waiting to read initial packet size */
104 #define CS_KEYS 3 /* Waiting to read public key packet */
105 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
106 int c_plen; /* Packet length field for ssh packet */
107 int c_len; /* Total bytes which must be read. */
108 int c_off; /* Length of data read so far. */
109 int c_keytype; /* Only one of KT_* */
110 sig_atomic_t c_done; /* SSH2 done */
111 char *c_namebase; /* Address to free for c_name and c_namelist */
112 char *c_name; /* Hostname of connection for errors */
113 char *c_namelist; /* Pointer to other possible addresses */
114 char *c_output_name; /* Hostname of connection for output */
115 char *c_data; /* Data read from this fd */
116 struct ssh *c_ssh; /* SSH-connection */
117 struct timespec c_ts; /* Time at which connection gets aborted */
118 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
121 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
124 static void keyprint(con *c, struct sshkey *key);
129 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
132 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
134 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
137 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
146 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
152 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
153 if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
156 if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
158 #elif defined (HAVE_SETDTABLESIZE)
165 * This is an strsep function that returns a null field for adjacent
166 * separators. This is the same as the 4.4BSD strsep, but different from the
167 * one in the GNU libc.
170 xstrsep(char **str, const char *delim)
178 e = s + strcspn(s, delim);
188 * Get the next non-null token (like GNU strsep). Strsep() will return a
189 * null token for two adjacent separators, so we may have to loop.
192 strnnsep(char **stringp, char *delim)
197 tok = xstrsep(stringp, delim);
198 } while (tok && *tok == '\0');
204 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
208 if ((c = ssh_get_app_data(ssh)) != NULL)
209 keyprint(c, hostkey);
210 /* always abort key exchange */
215 ssh2_capable(int remote_major, int remote_minor)
217 switch (remote_major) {
219 if (remote_minor == 99)
233 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
236 switch (c->c_keytype) {
238 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
239 "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
242 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
243 "rsa-sha2-512-cert-v01@openssh.com,"
244 "rsa-sha2-256-cert-v01@openssh.com,"
245 "ssh-rsa-cert-v01@openssh.com" :
251 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
252 "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
255 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
256 "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
259 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
260 "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
261 "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
262 "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
263 "ecdsa-sha2-nistp256,"
264 "ecdsa-sha2-nistp384,"
265 "ecdsa-sha2-nistp521";
268 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
269 "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
270 "sk-ecdsa-sha2-nistp256@openssh.com";
273 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
274 "sk-ssh-ed25519-cert-v01@openssh.com" :
275 "sk-ssh-ed25519@openssh.com";
278 fatal("unknown key type %d", c->c_keytype);
281 if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
283 fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
287 c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
288 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
289 c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
290 c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
291 c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
292 c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
293 c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
294 # ifdef OPENSSL_HAS_ECC
295 c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
298 c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
299 c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
300 ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
302 * do the key-exchange until an error occurs or until
303 * the key_print_wrapper() callback sets c_done.
305 ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
309 keyprint_one(const char *host, struct sshkey *key)
311 char *hostport = NULL, *hashed = NULL;
312 const char *known_host;
317 export_dns_rr(host, key, stdout, 0);
321 hostport = put_host_port(host, ssh_port);
323 if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
324 fatal("host_hash failed");
325 known_host = hash_hosts ? hashed : hostport;
327 fprintf(stdout, "%s ", known_host);
328 sshkey_write(key, stdout);
335 keyprint(con *c, struct sshkey *key)
337 char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
342 if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
343 keyprint_one(hosts, key);
346 ohosts = hosts = xstrdup(hosts);
347 while ((host = strsep(&hosts, ",")) != NULL)
348 keyprint_one(host, key);
353 tcpconnect(char *host)
355 struct addrinfo hints, *ai, *aitop;
356 char strport[NI_MAXSERV];
359 snprintf(strport, sizeof strport, "%d", ssh_port);
360 memset(&hints, 0, sizeof(hints));
361 hints.ai_family = IPv4or6;
362 hints.ai_socktype = SOCK_STREAM;
363 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
364 error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
367 for (ai = aitop; ai; ai = ai->ai_next) {
368 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
370 error("socket: %s", strerror(errno));
373 if (set_nonblock(s) == -1)
374 fatal_f("set_nonblock(%d)", s);
375 if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
376 errno != EINPROGRESS)
377 error("connect (`%s'): %s", host, strerror(errno));
388 conalloc(const char *iname, const char *oname, int keytype)
390 char *namebase, *name, *namelist;
393 namebase = namelist = xstrdup(iname);
396 name = xstrsep(&namelist, ",");
401 } while ((s = tcpconnect(name)) < 0);
404 fatal("conalloc: fdno %d too high", s);
405 if (fdcon[s].c_status)
406 fatal("conalloc: attempt to reuse fdno %d", s);
408 debug3_f("oname %s kt %d", oname, keytype);
410 fdcon[s].c_status = CS_CON;
411 fdcon[s].c_namebase = namebase;
412 fdcon[s].c_name = name;
413 fdcon[s].c_namelist = namelist;
414 fdcon[s].c_output_name = xstrdup(oname);
415 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
418 fdcon[s].c_keytype = keytype;
419 monotime_ts(&fdcon[s].c_ts);
420 fdcon[s].c_ts.tv_sec += timeout;
421 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
423 read_wait[s].events = POLLIN;
431 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
432 fatal("confree: attempt to free bad fdno %d", s);
433 free(fdcon[s].c_namebase);
434 free(fdcon[s].c_output_name);
435 if (fdcon[s].c_status == CS_KEYS)
436 free(fdcon[s].c_data);
437 fdcon[s].c_status = CS_UNUSED;
438 fdcon[s].c_keytype = 0;
439 if (fdcon[s].c_ssh) {
440 ssh_packet_close(fdcon[s].c_ssh);
441 free(fdcon[s].c_ssh);
442 fdcon[s].c_ssh = NULL;
445 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
446 read_wait[s].fd = -1;
447 read_wait[s].events = 0;
454 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
455 monotime_ts(&fdcon[s].c_ts);
456 fdcon[s].c_ts.tv_sec += timeout;
457 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
466 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
474 int n = 0, remote_major = 0, remote_minor = 0;
476 char remote_version[sizeof buf];
480 /* send client banner */
481 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
482 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
483 if (n < 0 || (size_t)n >= sizeof(buf)) {
484 error("snprintf: buffer too small");
488 if (atomicio(vwrite, s, buf, n) != (size_t)n) {
489 error("write (%s): %s", c->c_name, strerror(errno));
495 * Read the server banner as per RFC4253 section 4.2. The "SSH-"
496 * protocol identification string may be preceeded by an arbitrarily
497 * large banner which we must read and ignore. Loop while reading
498 * newline-terminated lines until we have one starting with "SSH-".
499 * The ID string cannot be longer than 255 characters although the
500 * preceeding banner lines may (in which case they'll be discarded
501 * in multiple iterations of the outer loop).
504 memset(buf, '\0', sizeof(buf));
505 bufsiz = sizeof(buf);
508 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
513 if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
519 error("%s: Connection closed by remote host", c->c_name);
524 error("read (%s): %s", c->c_name, strerror(errno));
530 if (cp >= buf + sizeof(buf)) {
531 error("%s: greeting exceeds allowable length", c->c_name);
535 if (*cp != '\n' && *cp != '\r') {
536 error("%s: bad greeting", c->c_name);
541 if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
542 fatal("ssh_packet_set_connection failed");
543 ssh_packet_set_timeout(c->c_ssh, timeout, 1);
544 ssh_set_app_data(c->c_ssh, c); /* back link */
545 c->c_ssh->compat = 0;
546 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
547 &remote_major, &remote_minor, remote_version) == 3)
548 compat_banner(c->c_ssh, remote_version);
549 if (!ssh2_capable(remote_major, remote_minor)) {
550 debug("%s doesn't support ssh2", c->c_name);
554 fprintf(stderr, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
555 c->c_name, ssh_port, chop(buf));
566 if (c->c_status == CS_CON) {
570 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
572 error("read (%s): %s", c->c_name, strerror(errno));
578 if (c->c_off == c->c_len)
579 switch (c->c_status) {
581 c->c_plen = htonl(c->c_plen);
582 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
584 c->c_data = xmalloc(c->c_len);
585 c->c_status = CS_KEYS;
588 fatal("conread: invalid status %d", c->c_status);
598 struct timespec seltime, now;
603 c = TAILQ_FIRST(&tq);
605 if (c && timespeccmp(&c->c_ts, &now, >))
606 timespecsub(&c->c_ts, &now, &seltime);
608 timespecclear(&seltime);
610 while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
611 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
616 for (i = 0; i < maxfd; i++) {
617 if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
619 else if (read_wait[i].revents & (POLLIN|POLLHUP))
623 c = TAILQ_FIRST(&tq);
624 while (c && timespeccmp(&c->c_ts, &now, <)) {
627 c = TAILQ_NEXT(c, c_link);
633 do_one_host(char *host)
635 char *name = strnnsep(&host, " \t\n");
640 for (j = KT_MIN; j <= KT_MAX; j *= 2) {
641 if (get_keytypes & j) {
642 while (ncon >= MAXCON)
644 conalloc(name, *host ? host : name, j);
653 struct xaddr addr, end_addr;
658 if (addr_pton_cidr(host, &addr, &masklen) != 0) {
659 /* Assume argument is a hostname */
662 /* Argument is a CIDR range */
663 debug("CIDR range %s", host);
665 if (addr_host_to_all1s(&end_addr, masklen) != 0)
668 * Note: we deliberately include the all-zero/ones addresses.
671 if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
673 error("Invalid address %s", host);
676 debug("CIDR expand: address %s", daddr);
678 if (addr_cmp(&addr, &end_addr) == 0)
680 addr_increment(&addr);
686 sshfatal(const char *file, const char *func, int line, int showfunc,
687 LogLevel level, const char *suffix, const char *fmt, ...)
692 sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
701 "usage: %s [-46cDHv] [-f file] [-p port] [-T timeout] [-t type]\n"
702 "\t\t [host | addrlist namelist]\n",
708 main(int argc, char **argv)
710 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
711 int opt, fopt_count = 0, j;
712 char *tname, *cp, *line = NULL;
719 __progname = ssh_get_progname(argv[0]);
723 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
729 while ((opt = getopt(argc, argv, "cDHv46p:T:t:f:")) != -1) {
741 ssh_port = a2port(optarg);
743 fprintf(stderr, "Bad port '%s'\n", optarg);
748 timeout = convtime(optarg);
749 if (timeout == -1 || timeout == 0) {
750 fprintf(stderr, "Bad timeout '%s'\n", optarg);
757 log_level = SYSLOG_LEVEL_DEBUG1;
759 else if (log_level < SYSLOG_LEVEL_DEBUG3)
762 fatal("Too high debugging level.");
765 if (strcmp(optarg, "-") == 0)
767 argv[fopt_count++] = optarg;
771 tname = strtok(optarg, ",");
773 int type = sshkey_type_from_name(tname);
777 get_keytypes |= KT_DSA;
780 get_keytypes |= KT_ECDSA;
783 get_keytypes |= KT_RSA;
786 get_keytypes |= KT_ED25519;
789 get_keytypes |= KT_XMSS;
792 get_keytypes |= KT_ED25519_SK;
795 get_keytypes |= KT_ECDSA_SK;
799 fatal("Unknown key type \"%s\"", tname);
801 tname = strtok(NULL, ",");
814 if (optind == argc && !fopt_count)
817 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
819 maxfd = fdlim_get(1);
821 fatal("%s: fdlim_get: bad value", __progname);
822 if (maxfd > MAXMAXFD)
825 fatal("%s: not enough file descriptors", __progname);
826 if (maxfd > fdlim_get(0))
828 fdcon = xcalloc(maxfd, sizeof(con));
829 read_wait = xcalloc(maxfd, sizeof(struct pollfd));
830 for (j = 0; j < maxfd; j++)
831 read_wait[j].fd = -1;
833 for (j = 0; j < fopt_count; j++) {
836 else if ((fp = fopen(argv[j], "r")) == NULL)
837 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
839 while (getline(&line, &linesize, fp) != -1) {
840 /* Chomp off trailing whitespace and comments */
841 if ((cp = strchr(line, '#')) == NULL)
842 cp = line + strlen(line) - 1;
844 if (*cp == ' ' || *cp == '\t' ||
845 *cp == '\n' || *cp == '#')
851 /* Skip empty lines */
859 fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
865 while (optind < argc)
866 do_host(argv[optind++]);
871 return found_one ? 0 : 1;