1 /* $OpenBSD: ssh-keyscan.c,v 1.146 2022/08/19 04:02:46 dtucker 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"
56 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
57 Default value is AF_UNSPEC means both IPv4 and IPv6. */
58 int IPv4or6
= AF_UNSPEC
;
60 int ssh_port
= SSH_DEFAULT_PORT
;
64 #define KT_ECDSA (1<<2)
65 #define KT_ED25519 (1<<3)
66 #define KT_XMSS (1<<4)
67 #define KT_ECDSA_SK (1<<5)
68 #define KT_ED25519_SK (1<<6)
71 #define KT_MAX KT_ED25519_SK
74 int get_keytypes
= KT_RSA
|KT_ECDSA
|KT_ED25519
|KT_ECDSA_SK
|KT_ED25519_SK
;
76 int hash_hosts
= 0; /* Hash hostname on output */
78 int print_sshfp
= 0; /* Print SSHFP records instead of known_hosts */
80 int found_one
= 0; /* Successfully found a key */
84 /* The number of seconds after which to give up on a TCP connection */
88 #define MAXCON (maxfd - 10)
90 extern char *__progname
;
91 struct pollfd
*read_wait
;
95 * Keep a connection structure for each file descriptor. The state
96 * associated with file descriptor n is held in fdcon[n].
98 typedef struct Connection
{
99 u_char c_status
; /* State of connection on this file desc. */
100 #define CS_UNUSED 0 /* File descriptor unused */
101 #define CS_CON 1 /* Waiting to connect/read greeting */
102 #define CS_SIZE 2 /* Waiting to read initial packet size */
103 #define CS_KEYS 3 /* Waiting to read public key packet */
104 int c_fd
; /* Quick lookup: c->c_fd == c - fdcon */
105 int c_plen
; /* Packet length field for ssh packet */
106 int c_len
; /* Total bytes which must be read. */
107 int c_off
; /* Length of data read so far. */
108 int c_keytype
; /* Only one of KT_* */
109 sig_atomic_t c_done
; /* SSH2 done */
110 char *c_namebase
; /* Address to free for c_name and c_namelist */
111 char *c_name
; /* Hostname of connection for errors */
112 char *c_namelist
; /* Pointer to other possible addresses */
113 char *c_output_name
; /* Hostname of connection for output */
114 char *c_data
; /* Data read from this fd */
115 struct ssh
*c_ssh
; /* SSH-connection */
116 struct timespec c_ts
; /* Time at which connection gets aborted */
117 TAILQ_ENTRY(Connection
) c_link
; /* List of connections in timeout order. */
120 TAILQ_HEAD(conlist
, Connection
) tq
; /* Timeout Queue */
123 static void keyprint(con
*c
, struct sshkey
*key
);
128 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
131 if (getrlimit(RLIMIT_NOFILE
, &rlfd
) == -1)
133 if ((hard
? rlfd
.rlim_max
: rlfd
.rlim_cur
) == RLIM_INFINITY
)
136 return hard
? rlfd
.rlim_max
: rlfd
.rlim_cur
;
145 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
151 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
152 if (getrlimit(RLIMIT_NOFILE
, &rlfd
) == -1)
155 if (setrlimit(RLIMIT_NOFILE
, &rlfd
) == -1)
157 #elif defined (HAVE_SETDTABLESIZE)
164 * This is an strsep function that returns a null field for adjacent
165 * separators. This is the same as the 4.4BSD strsep, but different from the
166 * one in the GNU libc.
169 xstrsep(char **str
, const char *delim
)
177 e
= s
+ strcspn(s
, delim
);
187 * Get the next non-null token (like GNU strsep). Strsep() will return a
188 * null token for two adjacent separators, so we may have to loop.
191 strnnsep(char **stringp
, char *delim
)
196 tok
= xstrsep(stringp
, delim
);
197 } while (tok
&& *tok
== '\0');
203 key_print_wrapper(struct sshkey
*hostkey
, struct ssh
*ssh
)
207 if ((c
= ssh_get_app_data(ssh
)) != NULL
)
208 keyprint(c
, hostkey
);
209 /* always abort key exchange */
214 ssh2_capable(int remote_major
, int remote_minor
)
216 switch (remote_major
) {
218 if (remote_minor
== 99)
232 char *myproposal
[PROPOSAL_MAX
] = { KEX_CLIENT
};
235 switch (c
->c_keytype
) {
237 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
238 "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
241 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
242 "rsa-sha2-512-cert-v01@openssh.com,"
243 "rsa-sha2-256-cert-v01@openssh.com,"
244 "ssh-rsa-cert-v01@openssh.com" :
250 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
251 "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
254 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
255 "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
258 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
259 "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
260 "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
261 "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
262 "ecdsa-sha2-nistp256,"
263 "ecdsa-sha2-nistp384,"
264 "ecdsa-sha2-nistp521";
267 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
268 "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
269 "sk-ecdsa-sha2-nistp256@openssh.com";
272 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = get_cert
?
273 "sk-ssh-ed25519-cert-v01@openssh.com" :
274 "sk-ssh-ed25519@openssh.com";
277 fatal("unknown key type %d", c
->c_keytype
);
280 if ((r
= kex_setup(c
->c_ssh
, myproposal
)) != 0) {
282 fprintf(stderr
, "kex_setup: %s\n", ssh_err(r
));
286 c
->c_ssh
->kex
->kex
[KEX_DH_GRP1_SHA1
] = kex_gen_client
;
287 c
->c_ssh
->kex
->kex
[KEX_DH_GRP14_SHA1
] = kex_gen_client
;
288 c
->c_ssh
->kex
->kex
[KEX_DH_GRP14_SHA256
] = kex_gen_client
;
289 c
->c_ssh
->kex
->kex
[KEX_DH_GRP16_SHA512
] = kex_gen_client
;
290 c
->c_ssh
->kex
->kex
[KEX_DH_GRP18_SHA512
] = kex_gen_client
;
291 c
->c_ssh
->kex
->kex
[KEX_DH_GEX_SHA1
] = kexgex_client
;
292 c
->c_ssh
->kex
->kex
[KEX_DH_GEX_SHA256
] = kexgex_client
;
293 # ifdef OPENSSL_HAS_ECC
294 c
->c_ssh
->kex
->kex
[KEX_ECDH_SHA2
] = kex_gen_client
;
297 c
->c_ssh
->kex
->kex
[KEX_C25519_SHA256
] = kex_gen_client
;
298 c
->c_ssh
->kex
->kex
[KEX_KEM_SNTRUP761X25519_SHA512
] = kex_gen_client
;
299 ssh_set_verify_host_key_callback(c
->c_ssh
, key_print_wrapper
);
301 * do the key-exchange until an error occurs or until
302 * the key_print_wrapper() callback sets c_done.
304 ssh_dispatch_run(c
->c_ssh
, DISPATCH_BLOCK
, &c
->c_done
);
308 keyprint_one(const char *host
, struct sshkey
*key
)
310 char *hostport
= NULL
, *hashed
= NULL
;
311 const char *known_host
;
316 export_dns_rr(host
, key
, stdout
, 0);
320 hostport
= put_host_port(host
, ssh_port
);
322 if (hash_hosts
&& (hashed
= host_hash(hostport
, NULL
, 0)) == NULL
)
323 fatal("host_hash failed");
324 known_host
= hash_hosts
? hashed
: hostport
;
326 fprintf(stdout
, "%s ", known_host
);
327 sshkey_write(key
, stdout
);
334 keyprint(con
*c
, struct sshkey
*key
)
336 char *hosts
= c
->c_output_name
? c
->c_output_name
: c
->c_name
;
341 if (get_cert
|| (!hash_hosts
&& ssh_port
== SSH_DEFAULT_PORT
)) {
342 keyprint_one(hosts
, key
);
345 ohosts
= hosts
= xstrdup(hosts
);
346 while ((host
= strsep(&hosts
, ",")) != NULL
)
347 keyprint_one(host
, key
);
352 tcpconnect(char *host
)
354 struct addrinfo hints
, *ai
, *aitop
;
355 char strport
[NI_MAXSERV
];
358 snprintf(strport
, sizeof strport
, "%d", ssh_port
);
359 memset(&hints
, 0, sizeof(hints
));
360 hints
.ai_family
= IPv4or6
;
361 hints
.ai_socktype
= SOCK_STREAM
;
362 if ((gaierr
= getaddrinfo(host
, strport
, &hints
, &aitop
)) != 0) {
363 error("getaddrinfo %s: %s", host
, ssh_gai_strerror(gaierr
));
366 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
367 s
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
369 error("socket: %s", strerror(errno
));
372 if (set_nonblock(s
) == -1)
373 fatal_f("set_nonblock(%d)", s
);
374 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) == -1 &&
375 errno
!= EINPROGRESS
)
376 error("connect (`%s'): %s", host
, strerror(errno
));
387 conalloc(char *iname
, char *oname
, int keytype
)
389 char *namebase
, *name
, *namelist
;
392 namebase
= namelist
= xstrdup(iname
);
395 name
= xstrsep(&namelist
, ",");
400 } while ((s
= tcpconnect(name
)) < 0);
403 fatal("conalloc: fdno %d too high", s
);
404 if (fdcon
[s
].c_status
)
405 fatal("conalloc: attempt to reuse fdno %d", s
);
407 debug3_f("oname %s kt %d", oname
, keytype
);
409 fdcon
[s
].c_status
= CS_CON
;
410 fdcon
[s
].c_namebase
= namebase
;
411 fdcon
[s
].c_name
= name
;
412 fdcon
[s
].c_namelist
= namelist
;
413 fdcon
[s
].c_output_name
= xstrdup(oname
);
414 fdcon
[s
].c_data
= (char *) &fdcon
[s
].c_plen
;
417 fdcon
[s
].c_keytype
= keytype
;
418 monotime_ts(&fdcon
[s
].c_ts
);
419 fdcon
[s
].c_ts
.tv_sec
+= timeout
;
420 TAILQ_INSERT_TAIL(&tq
, &fdcon
[s
], c_link
);
422 read_wait
[s
].events
= POLLIN
;
430 if (s
>= maxfd
|| fdcon
[s
].c_status
== CS_UNUSED
)
431 fatal("confree: attempt to free bad fdno %d", s
);
432 free(fdcon
[s
].c_namebase
);
433 free(fdcon
[s
].c_output_name
);
434 if (fdcon
[s
].c_status
== CS_KEYS
)
435 free(fdcon
[s
].c_data
);
436 fdcon
[s
].c_status
= CS_UNUSED
;
437 fdcon
[s
].c_keytype
= 0;
438 if (fdcon
[s
].c_ssh
) {
439 ssh_packet_close(fdcon
[s
].c_ssh
);
440 free(fdcon
[s
].c_ssh
);
441 fdcon
[s
].c_ssh
= NULL
;
444 TAILQ_REMOVE(&tq
, &fdcon
[s
], c_link
);
445 read_wait
[s
].fd
= -1;
446 read_wait
[s
].events
= 0;
453 TAILQ_REMOVE(&tq
, &fdcon
[s
], c_link
);
454 monotime_ts(&fdcon
[s
].c_ts
);
455 fdcon
[s
].c_ts
.tv_sec
+= timeout
;
456 TAILQ_INSERT_TAIL(&tq
, &fdcon
[s
], c_link
);
465 ret
= conalloc(c
->c_namelist
, c
->c_output_name
, c
->c_keytype
);
473 int n
= 0, remote_major
= 0, remote_minor
= 0;
475 char remote_version
[sizeof buf
];
479 /* send client banner */
480 n
= snprintf(buf
, sizeof buf
, "SSH-%d.%d-OpenSSH-keyscan\r\n",
481 PROTOCOL_MAJOR_2
, PROTOCOL_MINOR_2
);
482 if (n
< 0 || (size_t)n
>= sizeof(buf
)) {
483 error("snprintf: buffer too small");
487 if (atomicio(vwrite
, s
, buf
, n
) != (size_t)n
) {
488 error("write (%s): %s", c
->c_name
, strerror(errno
));
494 * Read the server banner as per RFC4253 section 4.2. The "SSH-"
495 * protocol identification string may be preceeded by an arbitarily
496 * large banner which we must read and ignore. Loop while reading
497 * newline-terminated lines until we have one starting with "SSH-".
498 * The ID string cannot be longer than 255 characters although the
499 * preceeding banner lines may (in which case they'll be discarded
500 * in multiple iterations of the outer loop).
503 memset(buf
, '\0', sizeof(buf
));
504 bufsiz
= sizeof(buf
);
507 (n
= atomicio(read
, s
, cp
, 1)) == 1 && *cp
!= '\n') {
512 if (n
!= 1 || strncmp(buf
, "SSH-", 4) == 0)
518 error("%s: Connection closed by remote host", c
->c_name
);
523 error("read (%s): %s", c
->c_name
, strerror(errno
));
529 if (cp
>= buf
+ sizeof(buf
)) {
530 error("%s: greeting exceeds allowable length", c
->c_name
);
534 if (*cp
!= '\n' && *cp
!= '\r') {
535 error("%s: bad greeting", c
->c_name
);
540 if ((c
->c_ssh
= ssh_packet_set_connection(NULL
, s
, s
)) == NULL
)
541 fatal("ssh_packet_set_connection failed");
542 ssh_packet_set_timeout(c
->c_ssh
, timeout
, 1);
543 ssh_set_app_data(c
->c_ssh
, c
); /* back link */
544 c
->c_ssh
->compat
= 0;
545 if (sscanf(buf
, "SSH-%d.%d-%[^\n]\n",
546 &remote_major
, &remote_minor
, remote_version
) == 3)
547 compat_banner(c
->c_ssh
, remote_version
);
548 if (!ssh2_capable(remote_major
, remote_minor
)) {
549 debug("%s doesn't support ssh2", c
->c_name
);
553 fprintf(stderr
, "%c %s:%d %s\n", print_sshfp
? ';' : '#',
554 c
->c_name
, ssh_port
, chop(buf
));
565 if (c
->c_status
== CS_CON
) {
569 n
= atomicio(read
, s
, c
->c_data
+ c
->c_off
, c
->c_len
- c
->c_off
);
571 error("read (%s): %s", c
->c_name
, strerror(errno
));
577 if (c
->c_off
== c
->c_len
)
578 switch (c
->c_status
) {
580 c
->c_plen
= htonl(c
->c_plen
);
581 c
->c_len
= c
->c_plen
+ 8 - (c
->c_plen
& 7);
583 c
->c_data
= xmalloc(c
->c_len
);
584 c
->c_status
= CS_KEYS
;
587 fatal("conread: invalid status %d", c
->c_status
);
597 struct timespec seltime
, now
;
602 c
= TAILQ_FIRST(&tq
);
604 if (c
&& timespeccmp(&c
->c_ts
, &now
, >))
605 timespecsub(&c
->c_ts
, &now
, &seltime
);
607 timespecclear(&seltime
);
609 while (ppoll(read_wait
, maxfd
, &seltime
, NULL
) == -1) {
610 if (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
)
615 for (i
= 0; i
< maxfd
; i
++) {
616 if (read_wait
[i
].revents
& (POLLHUP
|POLLERR
|POLLNVAL
))
618 else if (read_wait
[i
].revents
& (POLLIN
|POLLHUP
))
622 c
= TAILQ_FIRST(&tq
);
623 while (c
&& timespeccmp(&c
->c_ts
, &now
, <)) {
626 c
= TAILQ_NEXT(c
, c_link
);
634 char *name
= strnnsep(&host
, " \t\n");
639 for (j
= KT_MIN
; j
<= KT_MAX
; j
*= 2) {
640 if (get_keytypes
& j
) {
641 while (ncon
>= MAXCON
)
643 conalloc(name
, *host
? host
: name
, j
);
649 sshfatal(const char *file
, const char *func
, int line
, int showfunc
,
650 LogLevel level
, const char *suffix
, const char *fmt
, ...)
655 sshlogv(file
, func
, line
, showfunc
, level
, suffix
, fmt
, args
);
664 "usage: %s [-46cDHv] [-f file] [-p port] [-T timeout] [-t type]\n"
665 "\t\t [host | addrlist namelist]\n",
671 main(int argc
, char **argv
)
673 int debug_flag
= 0, log_level
= SYSLOG_LEVEL_INFO
;
674 int opt
, fopt_count
= 0, j
;
675 char *tname
, *cp
, *line
= NULL
;
682 __progname
= ssh_get_progname(argv
[0]);
686 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
692 while ((opt
= getopt(argc
, argv
, "cDHv46p:T:t:f:")) != -1) {
704 ssh_port
= a2port(optarg
);
706 fprintf(stderr
, "Bad port '%s'\n", optarg
);
711 timeout
= convtime(optarg
);
712 if (timeout
== -1 || timeout
== 0) {
713 fprintf(stderr
, "Bad timeout '%s'\n", optarg
);
720 log_level
= SYSLOG_LEVEL_DEBUG1
;
722 else if (log_level
< SYSLOG_LEVEL_DEBUG3
)
725 fatal("Too high debugging level.");
728 if (strcmp(optarg
, "-") == 0)
730 argv
[fopt_count
++] = optarg
;
734 tname
= strtok(optarg
, ",");
736 int type
= sshkey_type_from_name(tname
);
740 get_keytypes
|= KT_DSA
;
743 get_keytypes
|= KT_ECDSA
;
746 get_keytypes
|= KT_RSA
;
749 get_keytypes
|= KT_ED25519
;
752 get_keytypes
|= KT_XMSS
;
755 get_keytypes
|= KT_ED25519_SK
;
758 get_keytypes
|= KT_ECDSA_SK
;
762 fatal("Unknown key type \"%s\"", tname
);
764 tname
= strtok(NULL
, ",");
778 if (optind
== argc
&& !fopt_count
)
781 log_init("ssh-keyscan", log_level
, SYSLOG_FACILITY_USER
, 1);
783 maxfd
= fdlim_get(1);
785 fatal("%s: fdlim_get: bad value", __progname
);
786 if (maxfd
> MAXMAXFD
)
789 fatal("%s: not enough file descriptors", __progname
);
790 if (maxfd
> fdlim_get(0))
792 fdcon
= xcalloc(maxfd
, sizeof(con
));
793 read_wait
= xcalloc(maxfd
, sizeof(struct pollfd
));
794 for (j
= 0; j
< maxfd
; j
++)
795 read_wait
[j
].fd
= -1;
797 for (j
= 0; j
< fopt_count
; j
++) {
800 else if ((fp
= fopen(argv
[j
], "r")) == NULL
)
801 fatal("%s: %s: %s", __progname
, argv
[j
], strerror(errno
));
803 while (getline(&line
, &linesize
, fp
) != -1) {
804 /* Chomp off trailing whitespace and comments */
805 if ((cp
= strchr(line
, '#')) == NULL
)
806 cp
= line
+ strlen(line
) - 1;
808 if (*cp
== ' ' || *cp
== '\t' ||
809 *cp
== '\n' || *cp
== '#')
815 /* Skip empty lines */
823 fatal("%s: %s: %s", __progname
, argv
[j
], strerror(errno
));
829 while (optind
< argc
)
830 do_host(argv
[optind
++]);
835 return found_one
? 0 : 1;