1 /* $NetBSD: sshconnect.c,v 1.39 2024/07/08 22:33:44 christos Exp $ */
2 /* $OpenBSD: sshconnect.c,v 1.368 2024/04/30 02:10:49 djm Exp $ */
3
4 /*
5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
6 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * All rights reserved
8 * Code to connect to a remote host, and to perform the client side of the
9 * login (authentication) dialog.
10 *
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
16 */
17
18 #include "includes.h"
19 __RCSID("$NetBSD: sshconnect.c,v 1.39 2024/07/08 22:33:44 christos Exp $");
20
21 #include <sys/param.h> /* roundup */
22 #include <sys/types.h>
23 #include <sys/param.h>
24 #include <sys/wait.h>
25 #include <sys/stat.h>
26 #include <sys/socket.h>
27 #include <sys/time.h>
28
29 #include <net/if.h>
30 #include <netinet/in.h>
31 #include <netinet/in_var.h>
32 #include <netinet6/ip6_var.h>
33 #include <rpc/rpc.h>
34
35 #include <ctype.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <netdb.h>
39 #include <limits.h>
40 #include <paths.h>
41 #include <signal.h>
42 #include <pwd.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <stdarg.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include <ifaddrs.h>
49
50 #include "xmalloc.h"
51 #include "ssh.h"
52 #include "sshbuf.h"
53 #include "packet.h"
54 #include "sshkey.h"
55 #include "sshconnect.h"
56 #include "hostfile.h"
57 #include "log.h"
58 #include "match.h"
59 #include "misc.h"
60 #include "readconf.h"
61 #include "atomicio.h"
62 #include "dns.h"
63 #include "monitor_fdpass.h"
64 #include "ssh2.h"
65 #include "version.h"
66 #include "authfile.h"
67 #include "ssherr.h"
68 #include "authfd.h"
69 #include "kex.h"
70
71 struct sshkey *previous_host_key = NULL;
72
73 static int matching_host_key_dns = 0;
74
75 static pid_t proxy_command_pid = 0;
76
77 /* import */
78 extern int debug_flag;
79 extern Options options;
80 extern char *__progname;
81
82 static int show_other_keys(struct hostkeys *, struct sshkey *);
83 static void warn_changed_key(struct sshkey *);
84
85 /* Expand a proxy command */
86 static char *
expand_proxy_command(const char * proxy_command,const char * user,const char * host,const char * host_arg,int port)87 expand_proxy_command(const char *proxy_command, const char *user,
88 const char *host, const char *host_arg, int port)
89 {
90 char *tmp, *ret, strport[NI_MAXSERV];
91 const char *keyalias = options.host_key_alias ?
92 options.host_key_alias : host_arg;
93
94 snprintf(strport, sizeof strport, "%d", port);
95 xasprintf(&tmp, "exec %s", proxy_command);
96 ret = percent_expand(tmp,
97 "h", host,
98 "k", keyalias,
99 "n", host_arg,
100 "p", strport,
101 "r", options.user,
102 (char *)NULL);
103 free(tmp);
104 return ret;
105 }
106
107 /*
108 * Connect to the given ssh server using a proxy command that passes a
109 * a connected fd back to us.
110 */
111 static int
ssh_proxy_fdpass_connect(struct ssh * ssh,const char * host,const char * host_arg,u_short port,const char * proxy_command)112 ssh_proxy_fdpass_connect(struct ssh *ssh, const char *host,
113 const char *host_arg, u_short port, const char *proxy_command)
114 {
115 char *command_string;
116 int sp[2], sock;
117 pid_t pid;
118 const char *shell;
119
120 if ((shell = getenv("SHELL")) == NULL)
121 shell = _PATH_BSHELL;
122
123 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) == -1)
124 fatal("Could not create socketpair to communicate with "
125 "proxy dialer: %.100s", strerror(errno));
126 close(sp[1]);
127
128 command_string = expand_proxy_command(proxy_command, options.user,
129 host, host_arg, port);
130 debug("Executing proxy dialer command: %.500s", command_string);
131
132 /* Fork and execute the proxy command. */
133 if ((pid = fork()) == 0) {
134 char *argv[10];
135
136 close(sp[1]);
137 /* Redirect stdin and stdout. */
138 if (sp[0] != 0) {
139 if (dup2(sp[0], 0) == -1)
140 perror("dup2 stdin");
141 }
142 if (sp[0] != 1) {
143 if (dup2(sp[0], 1) == -1)
144 perror("dup2 stdout");
145 }
146 if (sp[0] >= 2)
147 close(sp[0]);
148
149 /*
150 * Stderr is left for non-ControlPersist connections is so
151 * error messages may be printed on the user's terminal.
152 */
153 if (!debug_flag && options.control_path != NULL &&
154 options.control_persist && stdfd_devnull(0, 0, 1) == -1)
155 error_f("stdfd_devnull failed");
156
157 argv[0] = __UNCONST(shell);
158 argv[1] = __UNCONST("-c");
159 argv[2] = command_string;
160 argv[3] = NULL;
161
162 /*
163 * Execute the proxy command.
164 * Note that we gave up any extra privileges above.
165 */
166 execv(argv[0], argv);
167 perror(argv[0]);
168 exit(1);
169 }
170 /* Parent. */
171 if (pid == -1)
172 fatal("fork failed: %.100s", strerror(errno));
173 close(sp[0]);
174 free(command_string);
175
176 if ((sock = mm_receive_fd(sp[1])) == -1)
177 fatal("proxy dialer did not pass back a connection");
178 close(sp[1]);
179
180 while (waitpid(pid, NULL, 0) == -1)
181 if (errno != EINTR)
182 fatal("Couldn't wait for child: %s", strerror(errno));
183
184 /* Set the connection file descriptors. */
185 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
186 return -1; /* ssh_packet_set_connection logs error */
187
188 return 0;
189 }
190
191 /*
192 * Connect to the given ssh server using a proxy command.
193 */
194 static int
ssh_proxy_connect(struct ssh * ssh,const char * host,const char * host_arg,u_short port,const char * proxy_command)195 ssh_proxy_connect(struct ssh *ssh, const char *host, const char *host_arg,
196 u_short port, const char *proxy_command)
197 {
198 char *command_string;
199 int pin[2], pout[2];
200 pid_t pid;
201 char *shell;
202
203 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
204 shell = __UNCONST(_PATH_BSHELL);
205
206 /* Create pipes for communicating with the proxy. */
207 if (pipe(pin) == -1 || pipe(pout) == -1)
208 fatal("Could not create pipes to communicate with the proxy: %.100s",
209 strerror(errno));
210
211 command_string = expand_proxy_command(proxy_command, options.user,
212 host, host_arg, port);
213 debug("Executing proxy command: %.500s", command_string);
214
215 /* Fork and execute the proxy command. */
216 if ((pid = fork()) == 0) {
217 char *argv[10];
218
219 /* Redirect stdin and stdout. */
220 close(pin[1]);
221 if (pin[0] != 0) {
222 if (dup2(pin[0], 0) == -1)
223 perror("dup2 stdin");
224 close(pin[0]);
225 }
226 close(pout[0]);
227 if (dup2(pout[1], 1) == -1)
228 perror("dup2 stdout");
229 /* Cannot be 1 because pin allocated two descriptors. */
230 close(pout[1]);
231
232 /*
233 * Stderr is left for non-ControlPersist connections is so
234 * error messages may be printed on the user's terminal.
235 */
236 if (!debug_flag && options.control_path != NULL &&
237 options.control_persist && stdfd_devnull(0, 0, 1) == -1)
238 error_f("stdfd_devnull failed");
239
240 argv[0] = shell;
241 argv[1] = __UNCONST("-c");
242 argv[2] = command_string;
243 argv[3] = NULL;
244
245 /*
246 * Execute the proxy command. Note that we gave up any
247 * extra privileges above.
248 */
249 ssh_signal(SIGPIPE, SIG_DFL);
250 execv(argv[0], argv);
251 perror(argv[0]);
252 exit(1);
253 }
254 /* Parent. */
255 if (pid == -1)
256 fatal("fork failed: %.100s", strerror(errno));
257 else
258 proxy_command_pid = pid; /* save pid to clean up later */
259
260 /* Close child side of the descriptors. */
261 close(pin[0]);
262 close(pout[1]);
263
264 /* Free the command name. */
265 free(command_string);
266
267 /* Set the connection file descriptors. */
268 if (ssh_packet_set_connection(ssh, pout[0], pin[1]) == NULL)
269 return -1; /* ssh_packet_set_connection logs error */
270
271 return 0;
272 }
273
274 void
ssh_kill_proxy_command(void)275 ssh_kill_proxy_command(void)
276 {
277 /*
278 * Send SIGHUP to proxy command if used. We don't wait() in
279 * case it hangs and instead rely on init to reap the child
280 */
281 if (proxy_command_pid > 1)
282 kill(proxy_command_pid, SIGHUP);
283 }
284
285 /*
286 * Set TCP receive buffer if requested.
287 * Note: tuning needs to happen after the socket is
288 * created but before the connection happens
289 * so winscale is negotiated properly -cjr
290 */
291 static void
ssh_set_socket_recvbuf(int sock)292 ssh_set_socket_recvbuf(int sock)
293 {
294 void *buf = (void *)&options.tcp_rcv_buf;
295 int sz = sizeof(options.tcp_rcv_buf);
296 int socksize;
297 socklen_t socksizelen = sizeof(int);
298
299 debug("setsockopt Attempting to set SO_RCVBUF to %d",
300 options.tcp_rcv_buf);
301 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, buf, sz) >= 0) {
302 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socksize,
303 &socksizelen);
304 debug("setsockopt SO_RCVBUF: %.100s %d", strerror(errno),
305 socksize);
306 } else {
307 error("Couldn't set socket receive buffer to %d: %.100s",
308 options.tcp_rcv_buf, strerror(errno));
309 }
310 }
311
312 /*
313 * Search a interface address list (returned from getifaddrs(3)) for an
314 * address that matches the desired address family on the specified interface.
315 * Returns 0 and fills in *resultp and *rlenp on success. Returns -1 on failure.
316 */
317 static int
check_ifaddrs(const char * ifname,int af,const struct ifaddrs * ifaddrs,int prefertemp,struct sockaddr_storage * resultp,socklen_t * rlenp)318 check_ifaddrs(const char *ifname, int af, const struct ifaddrs *ifaddrs,
319 int prefertemp, struct sockaddr_storage *resultp, socklen_t *rlenp)
320 {
321 struct sockaddr_in6 *sa6;
322 struct sockaddr_in *sa;
323 struct in6_addr *v6addr;
324 const struct ifaddrs *ifa;
325 int try;
326
327 /*
328 * Prefer temporary addresses according to prefertemp.
329 * Prefer addresses that are not loopback or linklocal, but use them
330 * if nothing else matches.
331 */
332 for (try = 0; try < 3; try++) {
333 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
334 if (ifa->ifa_addr == NULL || ifa->ifa_name == NULL ||
335 (ifa->ifa_flags & IFF_UP) == 0 ||
336 ifa->ifa_addr->sa_family != af ||
337 strcmp(ifa->ifa_name, ifname) != 0)
338 continue;
339 switch (ifa->ifa_addr->sa_family) {
340 case AF_INET:
341 sa = (struct sockaddr_in *)ifa->ifa_addr;
342 if (try < 2 && sa->sin_addr.s_addr ==
343 htonl(INADDR_LOOPBACK))
344 continue;
345 if (*rlenp < sizeof(struct sockaddr_in)) {
346 error_f("v4 addr doesn't fit");
347 return -1;
348 }
349 *rlenp = sizeof(struct sockaddr_in);
350 memcpy(resultp, sa, *rlenp);
351 return 0;
352 case AF_INET6:
353 sa6 = (struct sockaddr_in6 *)ifa->ifa_addr;
354 v6addr = &sa6->sin6_addr;
355 if (try < 2 &&
356 (IN6_IS_ADDR_LINKLOCAL(v6addr) ||
357 IN6_IS_ADDR_LOOPBACK(v6addr)))
358 continue;
359 if (*rlenp < sizeof(struct sockaddr_in6)) {
360 error_f("v6 addr doesn't fit");
361 return -1;
362 }
363
364 /*
365 * For now, ignore scope and
366 * don't allow deprecated addresses. XXX
367 */
368 if (ifa->ifa_addrflags & IN6_IFF_ANYCAST)
369 continue;
370 if (ifa->ifa_addrflags & IN6_IFF_NOTREADY)
371 continue;
372 if (ifa->ifa_addrflags & IN6_IFF_DETACHED)
373 continue;
374 if (ifa->ifa_addrflags & IN6_IFF_DEPRECATED)
375 continue;
376
377 if (prefertemp >= 0 && try < 1) {
378 int istemp = ifa->ifa_addrflags
379 & IN6_IFF_TEMPORARY;
380 if (!!istemp != prefertemp)
381 continue;
382 }
383 *rlenp = sizeof(struct sockaddr_in6);
384 memcpy(resultp, sa6, *rlenp);
385 return 0;
386 }
387 }
388 }
389 return -1;
390 }
391
392 /*
393 * Creates a socket for use as the ssh connection.
394 */
395 static int
ssh_create_socket(struct addrinfo * ai)396 ssh_create_socket(struct addrinfo *ai)
397 {
398 int sock, r;
399 struct sockaddr_storage bindaddr;
400 socklen_t bindaddrlen = 0;
401 struct addrinfo hints, *res = NULL;
402 struct ifaddrs *ifaddrs = NULL;
403 char ntop[NI_MAXHOST];
404
405 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
406 if (sock == -1) {
407 error("socket: %s", strerror(errno));
408 return -1;
409 }
410 (void)fcntl(sock, F_SETFD, FD_CLOEXEC);
411
412 if (options.tcp_rcv_buf > 0)
413 ssh_set_socket_recvbuf(sock);
414
415 /* Use interactive QOS (if specified) until authentication completed */
416 if (options.ip_qos_interactive != INT_MAX)
417 set_sock_tos(sock, options.ip_qos_interactive);
418
419 /* Bind the socket to an alternative local IP address */
420 if (options.bind_address != NULL) {
421 memset(&hints, 0, sizeof(hints));
422 hints.ai_family = ai->ai_family;
423 hints.ai_socktype = ai->ai_socktype;
424 hints.ai_protocol = ai->ai_protocol;
425 hints.ai_flags = AI_PASSIVE;
426 if ((r = getaddrinfo(options.bind_address, NULL,
427 &hints, &res)) != 0) {
428 error("getaddrinfo: %s: %s", options.bind_address,
429 ssh_gai_strerror(r));
430 goto fail;
431 }
432 if (res == NULL) {
433 error("getaddrinfo: no addrs");
434 goto fail;
435 }
436 memcpy(&bindaddr, res->ai_addr, res->ai_addrlen);
437 bindaddrlen = res->ai_addrlen;
438 } else if (options.bind_interface != NULL) {
439 if ((r = getifaddrs(&ifaddrs)) != 0) {
440 error("getifaddrs: %s: %s", options.bind_interface,
441 strerror(errno));
442 goto fail;
443 }
444 bindaddrlen = sizeof(bindaddr);
445 if (check_ifaddrs(options.bind_interface, ai->ai_family,
446 ifaddrs, options.ipv6_prefer_temporary,
447 &bindaddr, &bindaddrlen) != 0) {
448 logit("getifaddrs: %s: no suitable addresses",
449 options.bind_interface);
450 goto fail;
451 }
452 } else {
453 /* Apply user specified temporary address preference */
454 if (ai->ai_family == AF_INET6
455 && options.ipv6_prefer_temporary >= 0) {
456 int temp = options.ipv6_prefer_temporary
457 ? IP6PO_TEMPADDR_PREFER
458 : IP6PO_TEMPADDR_NOTPREFER;
459 if (setsockopt(sock, IPPROTO_IPV6, IPV6_PREFER_TEMPADDR,
460 &temp, sizeof temp) < 0)
461 error("setsockopt(IPV6_PREFER_TEMPADDR: %.100s",
462 strerror(errno));
463 }
464 return sock;
465 }
466
467 if ((r = getnameinfo((struct sockaddr *)&bindaddr, bindaddrlen,
468 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST)) != 0) {
469 error_f("getnameinfo failed: %s", ssh_gai_strerror(r));
470 goto fail;
471 }
472 if (bind(sock, (struct sockaddr *)&bindaddr, bindaddrlen) != 0) {
473 error("bind %s: %s", ntop, strerror(errno));
474 goto fail;
475 }
476 debug_f("bound to %s", ntop);
477 /* success */
478 goto out;
479 fail:
480 close(sock);
481 sock = -1;
482 out:
483 if (res != NULL)
484 freeaddrinfo(res);
485 if (ifaddrs != NULL)
486 freeifaddrs(ifaddrs);
487 return sock;
488 }
489
490 /*
491 * Opens a TCP/IP connection to the remote server on the given host.
492 * The address of the remote host will be returned in hostaddr.
493 * If port is 0, the default port will be used.
494 * Connection_attempts specifies the maximum number of tries (one per
495 * second). If proxy_command is non-NULL, it specifies the command (with %h
496 * and %p substituted for host and port, respectively) to use to contact
497 * the daemon.
498 */
499 static int
ssh_connect_direct(struct ssh * ssh,const char * host,struct addrinfo * aitop,struct sockaddr_storage * hostaddr,u_short port,int connection_attempts,int * timeout_ms,int want_keepalive)500 ssh_connect_direct(struct ssh *ssh, const char *host, struct addrinfo *aitop,
501 struct sockaddr_storage *hostaddr, u_short port, int connection_attempts,
502 int *timeout_ms, int want_keepalive)
503 {
504 int on = 1, saved_timeout_ms = *timeout_ms;
505 int oerrno, sock = -1, attempt;
506 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
507 struct addrinfo *ai;
508
509 debug3_f("entering");
510 memset(ntop, 0, sizeof(ntop));
511 memset(strport, 0, sizeof(strport));
512
513 for (attempt = 0; attempt < connection_attempts; attempt++) {
514 if (attempt > 0) {
515 /* Sleep a moment before retrying. */
516 sleep(1);
517 debug("Trying again...");
518 }
519 /*
520 * Loop through addresses for this host, and try each one in
521 * sequence until the connection succeeds.
522 */
523 for (ai = aitop; ai; ai = ai->ai_next) {
524 if (ai->ai_family != AF_INET &&
525 ai->ai_family != AF_INET6) {
526 errno = EAFNOSUPPORT;
527 continue;
528 }
529 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
530 ntop, sizeof(ntop), strport, sizeof(strport),
531 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
532 oerrno = errno;
533 error_f("getnameinfo failed");
534 errno = oerrno;
535 continue;
536 }
537 if (options.address_family != AF_UNSPEC &&
538 ai->ai_family != options.address_family) {
539 debug2_f("skipping address [%s]:%s: "
540 "wrong address family", ntop, strport);
541 errno = EAFNOSUPPORT;
542 continue;
543 }
544
545 debug("Connecting to %.200s [%.100s] port %s.",
546 host, ntop, strport);
547
548 /* Create a socket for connecting. */
549 sock = ssh_create_socket(ai);
550 if (sock < 0) {
551 /* Any error is already output */
552 errno = 0;
553 continue;
554 }
555
556 *timeout_ms = saved_timeout_ms;
557 if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
558 timeout_ms) >= 0) {
559 /* Successful connection. */
560 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
561 break;
562 } else {
563 oerrno = errno;
564 debug("connect to address %s port %s: %s",
565 ntop, strport, strerror(errno));
566 close(sock);
567 sock = -1;
568 errno = oerrno;
569 }
570 }
571 if (sock != -1)
572 break; /* Successful connection. */
573 }
574
575 /* Return failure if we didn't get a successful connection. */
576 if (sock == -1) {
577 error("ssh: connect to host %s port %s: %s",
578 host, strport, errno == 0 ? "failure" : strerror(errno));
579 return -1;
580 }
581
582 debug("Connection established.");
583
584 /* Set SO_KEEPALIVE if requested. */
585 if (want_keepalive &&
586 setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
587 sizeof(on)) == -1)
588 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
589
590 /* Set the connection. */
591 if (ssh_packet_set_connection(ssh, sock, sock) == NULL)
592 return -1; /* ssh_packet_set_connection logs error */
593
594 return 0;
595 }
596
597 int
ssh_connect(struct ssh * ssh,const char * host,const char * host_arg,struct addrinfo * addrs,struct sockaddr_storage * hostaddr,u_short port,int connection_attempts,int * timeout_ms,int want_keepalive)598 ssh_connect(struct ssh *ssh, const char *host, const char *host_arg,
599 struct addrinfo *addrs, struct sockaddr_storage *hostaddr, u_short port,
600 int connection_attempts, int *timeout_ms, int want_keepalive)
601 {
602 int in, out;
603
604 if (options.proxy_command == NULL) {
605 return ssh_connect_direct(ssh, host, addrs, hostaddr, port,
606 connection_attempts, timeout_ms, want_keepalive);
607 } else if (strcmp(options.proxy_command, "-") == 0) {
608 if ((in = dup(STDIN_FILENO)) == -1 ||
609 (out = dup(STDOUT_FILENO)) == -1) {
610 if (in >= 0)
611 close(in);
612 error_f("dup() in/out failed");
613 return -1; /* ssh_packet_set_connection logs error */
614 }
615 if ((ssh_packet_set_connection(ssh, in, out)) == NULL)
616 return -1; /* ssh_packet_set_connection logs error */
617 return 0;
618 } else if (options.proxy_use_fdpass) {
619 return ssh_proxy_fdpass_connect(ssh, host, host_arg, port,
620 options.proxy_command);
621 }
622 return ssh_proxy_connect(ssh, host, host_arg, port,
623 options.proxy_command);
624 }
625
626 /* defaults to 'no' */
627 static int
confirm(const char * prompt,const char * fingerprint)628 confirm(const char *prompt, const char *fingerprint)
629 {
630 const char *msg, *again = "Please type 'yes' or 'no': ";
631 const char *again_fp = "Please type 'yes', 'no' or the fingerprint: ";
632 char *p, *cp;
633 int ret = -1;
634
635 if (options.batch_mode)
636 return 0;
637 for (msg = prompt;;msg = fingerprint ? again_fp : again) {
638 cp = p = read_passphrase(msg, RP_ECHO);
639 if (p == NULL)
640 return 0;
641 p += strspn(p, " \t"); /* skip leading whitespace */
642 p[strcspn(p, " \t\n")] = '\0'; /* remove trailing whitespace */
643 if (p[0] == '\0' || strcasecmp(p, "no") == 0)
644 ret = 0;
645 else if (strcasecmp(p, "yes") == 0 || (fingerprint != NULL &&
646 strcmp(p, fingerprint) == 0))
647 ret = 1;
648 free(cp);
649 if (ret != -1)
650 return ret;
651 }
652 }
653
654 static int
sockaddr_is_local(struct sockaddr * hostaddr)655 sockaddr_is_local(struct sockaddr *hostaddr)
656 {
657 switch (hostaddr->sa_family) {
658 case AF_INET:
659 return (ntohl(((struct sockaddr_in *)hostaddr)->
660 sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
661 case AF_INET6:
662 return IN6_IS_ADDR_LOOPBACK(
663 &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
664 default:
665 return 0;
666 }
667 }
668
669 /*
670 * Prepare the hostname and ip address strings that are used to lookup
671 * host keys in known_hosts files. These may have a port number appended.
672 */
673 void
get_hostfile_hostname_ipaddr(char * hostname,struct sockaddr * hostaddr,u_short port,char ** hostfile_hostname,char ** hostfile_ipaddr)674 get_hostfile_hostname_ipaddr(char *hostname, struct sockaddr *hostaddr,
675 u_short port, char **hostfile_hostname, char **hostfile_ipaddr)
676 {
677 char ntop[NI_MAXHOST];
678
679 /*
680 * We don't have the remote ip-address for connections
681 * using a proxy command
682 */
683 if (hostfile_ipaddr != NULL) {
684 if (options.proxy_command == NULL) {
685 if (getnameinfo(hostaddr, hostaddr->sa_len,
686 ntop, sizeof(ntop), NULL, 0, NI_NUMERICHOST) != 0)
687 fatal_f("getnameinfo failed");
688 *hostfile_ipaddr = put_host_port(ntop, port);
689 } else {
690 *hostfile_ipaddr = xstrdup("<no hostip for proxy "
691 "command>");
692 }
693 }
694
695 /*
696 * Allow the user to record the key under a different name or
697 * differentiate a non-standard port. This is useful for ssh
698 * tunneling over forwarded connections or if you run multiple
699 * sshd's on different ports on the same machine.
700 */
701 if (hostfile_hostname != NULL) {
702 if (options.host_key_alias != NULL) {
703 *hostfile_hostname = xstrdup(options.host_key_alias);
704 debug("using hostkeyalias: %s", *hostfile_hostname);
705 } else {
706 *hostfile_hostname = put_host_port(hostname, port);
707 }
708 }
709 }
710
711 /* returns non-zero if path appears in hostfiles, or 0 if not. */
712 static int
path_in_hostfiles(const char * path,char ** hostfiles,u_int num_hostfiles)713 path_in_hostfiles(const char *path, char **hostfiles, u_int num_hostfiles)
714 {
715 u_int i;
716
717 for (i = 0; i < num_hostfiles; i++) {
718 if (strcmp(path, hostfiles[i]) == 0)
719 return 1;
720 }
721 return 0;
722 }
723
724 struct find_by_key_ctx {
725 const char *host, *ip;
726 const struct sshkey *key;
727 char **names;
728 u_int nnames;
729 };
730
731 /* Try to replace home directory prefix (per $HOME) with a ~/ sequence */
732 static char *
try_tilde_unexpand(const char * path)733 try_tilde_unexpand(const char *path)
734 {
735 char *home, *ret = NULL;
736 size_t l;
737
738 if (*path != '/')
739 return xstrdup(path);
740 if ((home = getenv("HOME")) == NULL || (l = strlen(home)) == 0)
741 return xstrdup(path);
742 if (strncmp(path, home, l) != 0)
743 return xstrdup(path);
744 /*
745 * ensure we have matched on a path boundary: either the $HOME that
746 * we just compared ends with a '/' or the next character of the path
747 * must be a '/'.
748 */
749 if (home[l - 1] != '/' && path[l] != '/')
750 return xstrdup(path);
751 if (path[l] == '/')
752 l++;
753 xasprintf(&ret, "~/%s", path + l);
754 return ret;
755 }
756
757 /*
758 * Returns non-zero if the key is accepted by HostkeyAlgorithms.
759 * Made slightly less trivial by the multiple RSA signature algorithm names.
760 */
761 int
hostkey_accepted_by_hostkeyalgs(const struct sshkey * key)762 hostkey_accepted_by_hostkeyalgs(const struct sshkey *key)
763 {
764 const char *ktype = sshkey_ssh_name(key);
765 const char *hostkeyalgs = options.hostkeyalgorithms;
766
767 if (key->type == KEY_UNSPEC)
768 return 0;
769 if (key->type == KEY_RSA &&
770 (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
771 match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
772 return 1;
773 if (key->type == KEY_RSA_CERT &&
774 (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com", hostkeyalgs, 0) == 1 ||
775 match_pattern_list("rsa-sha2-256-cert-v01@openssh.com", hostkeyalgs, 0) == 1))
776 return 1;
777 return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
778 }
779
780 static int
hostkeys_find_by_key_cb(struct hostkey_foreach_line * l,void * _ctx)781 hostkeys_find_by_key_cb(struct hostkey_foreach_line *l, void *_ctx)
782 {
783 struct find_by_key_ctx *ctx = (struct find_by_key_ctx *)_ctx;
784 char *path;
785
786 /* we are looking for keys with names that *do not* match */
787 if ((l->match & HKF_MATCH_HOST) != 0)
788 return 0;
789 /* not interested in marker lines */
790 if (l->marker != MRK_NONE)
791 return 0;
792 /* we are only interested in exact key matches */
793 if (l->key == NULL || !sshkey_equal(ctx->key, l->key))
794 return 0;
795 path = try_tilde_unexpand(l->path);
796 debug_f("found matching key in %s:%lu", path, l->linenum);
797 ctx->names = xrecallocarray(ctx->names,
798 ctx->nnames, ctx->nnames + 1, sizeof(*ctx->names));
799 xasprintf(&ctx->names[ctx->nnames], "%s:%lu: %s", path, l->linenum,
800 strncmp(l->hosts, HASH_MAGIC, strlen(HASH_MAGIC)) == 0 ?
801 "[hashed name]" : l->hosts);
802 ctx->nnames++;
803 free(path);
804 return 0;
805 }
806
807 static int
hostkeys_find_by_key_hostfile(const char * file,const char * which,struct find_by_key_ctx * ctx)808 hostkeys_find_by_key_hostfile(const char *file, const char *which,
809 struct find_by_key_ctx *ctx)
810 {
811 int r;
812
813 debug3_f("trying %s hostfile \"%s\"", which, file);
814 if ((r = hostkeys_foreach(file, hostkeys_find_by_key_cb, ctx,
815 ctx->host, ctx->ip, HKF_WANT_PARSE_KEY, 0)) != 0) {
816 if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
817 debug_f("hostkeys file %s does not exist", file);
818 return 0;
819 }
820 error_fr(r, "hostkeys_foreach failed for %s", file);
821 return r;
822 }
823 return 0;
824 }
825
826 /*
827 * Find 'key' in known hosts file(s) that do not match host/ip.
828 * Used to display also-known-as information for previously-unseen hostkeys.
829 */
830 static void
hostkeys_find_by_key(const char * host,const char * ip,const struct sshkey * key,char ** user_hostfiles,u_int num_user_hostfiles,char ** system_hostfiles,u_int num_system_hostfiles,char *** names,u_int * nnames)831 hostkeys_find_by_key(const char *host, const char *ip, const struct sshkey *key,
832 char **user_hostfiles, u_int num_user_hostfiles,
833 char **system_hostfiles, u_int num_system_hostfiles,
834 char ***names, u_int *nnames)
835 {
836 struct find_by_key_ctx ctx = {0, 0, 0, 0, 0};
837 u_int i;
838
839 *names = NULL;
840 *nnames = 0;
841
842 if (key == NULL || sshkey_is_cert(key))
843 return;
844
845 ctx.host = host;
846 ctx.ip = ip;
847 ctx.key = key;
848
849 for (i = 0; i < num_user_hostfiles; i++) {
850 if (hostkeys_find_by_key_hostfile(user_hostfiles[i],
851 "user", &ctx) != 0)
852 goto fail;
853 }
854 for (i = 0; i < num_system_hostfiles; i++) {
855 if (hostkeys_find_by_key_hostfile(system_hostfiles[i],
856 "system", &ctx) != 0)
857 goto fail;
858 }
859 /* success */
860 *names = ctx.names;
861 *nnames = ctx.nnames;
862 ctx.names = NULL;
863 ctx.nnames = 0;
864 return;
865 fail:
866 for (i = 0; i < ctx.nnames; i++)
867 free(ctx.names[i]);
868 free(ctx.names);
869 }
870
871 #define MAX_OTHER_NAMES 8 /* Maximum number of names to list */
872 static char *
other_hostkeys_message(const char * host,const char * ip,const struct sshkey * key,char ** user_hostfiles,u_int num_user_hostfiles,char ** system_hostfiles,u_int num_system_hostfiles)873 other_hostkeys_message(const char *host, const char *ip,
874 const struct sshkey *key,
875 char **user_hostfiles, u_int num_user_hostfiles,
876 char **system_hostfiles, u_int num_system_hostfiles)
877 {
878 char *ret = NULL, **othernames = NULL;
879 u_int i, n, num_othernames = 0;
880
881 hostkeys_find_by_key(host, ip, key,
882 user_hostfiles, num_user_hostfiles,
883 system_hostfiles, num_system_hostfiles,
884 &othernames, &num_othernames);
885 if (num_othernames == 0)
886 return xstrdup("This key is not known by any other names.");
887
888 xasprintf(&ret, "This host key is known by the following other "
889 "names/addresses:");
890
891 n = num_othernames;
892 if (n > MAX_OTHER_NAMES)
893 n = MAX_OTHER_NAMES;
894 for (i = 0; i < n; i++) {
895 xextendf(&ret, "\n", " %s", othernames[i]);
896 }
897 if (n < num_othernames) {
898 xextendf(&ret, "\n", " (%d additional names omitted)",
899 num_othernames - n);
900 }
901 for (i = 0; i < num_othernames; i++)
902 free(othernames[i]);
903 free(othernames);
904 return ret;
905 }
906
907 void
load_hostkeys_command(struct hostkeys * hostkeys,const char * command_template,const char * invocation,const struct ssh_conn_info * cinfo,const struct sshkey * host_key,const char * hostfile_hostname)908 load_hostkeys_command(struct hostkeys *hostkeys, const char *command_template,
909 const char *invocation, const struct ssh_conn_info *cinfo,
910 const struct sshkey *host_key, const char *hostfile_hostname)
911 {
912 int r, i, ac = 0;
913 char *key_fp = NULL, *keytext = NULL, *tmp;
914 char *command = NULL, *tag = NULL, **av = NULL;
915 FILE *f = NULL;
916 pid_t pid;
917 void (*osigchld)(int);
918
919 xasprintf(&tag, "KnownHostsCommand-%s", invocation);
920
921 if (host_key != NULL) {
922 if ((key_fp = sshkey_fingerprint(host_key,
923 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
924 fatal_f("sshkey_fingerprint failed");
925 if ((r = sshkey_to_base64(host_key, &keytext)) != 0)
926 fatal_fr(r, "sshkey_to_base64 failed");
927 }
928 /*
929 * NB. all returns later this function should go via "out" to
930 * ensure the original SIGCHLD handler is restored properly.
931 */
932 osigchld = ssh_signal(SIGCHLD, SIG_DFL);
933
934 /* Turn the command into an argument vector */
935 if (argv_split(command_template, &ac, &av, 0) != 0) {
936 error("%s \"%s\" contains invalid quotes", tag,
937 command_template);
938 goto out;
939 }
940 if (ac == 0) {
941 error("%s \"%s\" yielded no arguments", tag,
942 command_template);
943 goto out;
944 }
945 for (i = 1; i < ac; i++) {
946 tmp = percent_dollar_expand(av[i],
947 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
948 "H", hostfile_hostname,
949 "I", invocation,
950 "t", host_key == NULL ? "NONE" : sshkey_ssh_name(host_key),
951 "f", key_fp == NULL ? "NONE" : key_fp,
952 "K", keytext == NULL ? "NONE" : keytext,
953 (char *)NULL);
954 if (tmp == NULL)
955 fatal_f("percent_expand failed");
956 free(av[i]);
957 av[i] = tmp;
958 }
959 /* Prepare a printable command for logs, etc. */
960 command = argv_assemble(ac, av);
961
962 if ((pid = subprocess(tag, command, ac, av, &f,
963 SSH_SUBPROCESS_STDOUT_CAPTURE|SSH_SUBPROCESS_UNSAFE_PATH|
964 SSH_SUBPROCESS_PRESERVE_ENV, NULL, NULL, NULL)) == 0)
965 goto out;
966
967 load_hostkeys_file(hostkeys, hostfile_hostname, tag, f, 1);
968
969 if (exited_cleanly(pid, tag, command, 0) != 0)
970 fatal("KnownHostsCommand failed");
971
972 out:
973 if (f != NULL)
974 fclose(f);
975 ssh_signal(SIGCHLD, osigchld);
976 for (i = 0; i < ac; i++)
977 free(av[i]);
978 free(av);
979 free(tag);
980 free(command);
981 free(key_fp);
982 free(keytext);
983 }
984
985 /*
986 * check whether the supplied host key is valid, return -1 if the key
987 * is not valid. user_hostfile[0] will not be updated if 'readonly' is true.
988 */
989 #define RDRW 0
990 #define RDONLY 1
991 #define ROQUIET 2
992 static int
check_host_key(char * hostname,const struct ssh_conn_info * cinfo,struct sockaddr * hostaddr,u_short port,struct sshkey * host_key,int readonly,int clobber_port,char ** user_hostfiles,u_int num_user_hostfiles,char ** system_hostfiles,u_int num_system_hostfiles,const char * hostfile_command)993 check_host_key(char *hostname, const struct ssh_conn_info *cinfo,
994 struct sockaddr *hostaddr, u_short port,
995 struct sshkey *host_key, int readonly, int clobber_port,
996 char **user_hostfiles, u_int num_user_hostfiles,
997 char **system_hostfiles, u_int num_system_hostfiles,
998 const char *hostfile_command)
999 {
1000 HostStatus host_status = -1, ip_status = -1;
1001 struct sshkey *raw_key = NULL;
1002 char *ip = NULL, *host = NULL;
1003 char hostline[1000], *hostp, *fp, *ra;
1004 char msg[1024];
1005 const char *type, *fail_reason = NULL;
1006 const struct hostkey_entry *host_found = NULL, *ip_found = NULL;
1007 int len, cancelled_forwarding = 0, confirmed;
1008 int local = sockaddr_is_local(hostaddr);
1009 int r, want_cert = sshkey_is_cert(host_key), host_ip_differ = 0;
1010 int hostkey_trusted = 0; /* Known or explicitly accepted by user */
1011 struct hostkeys *host_hostkeys, *ip_hostkeys;
1012 u_int i;
1013
1014 /*
1015 * Force accepting of the host key for loopback/localhost. The
1016 * problem is that if the home directory is NFS-mounted to multiple
1017 * machines, localhost will refer to a different machine in each of
1018 * them, and the user will get bogus HOST_CHANGED warnings. This
1019 * essentially disables host authentication for localhost; however,
1020 * this is probably not a real problem.
1021 */
1022 if (options.no_host_authentication_for_localhost == 1 && local &&
1023 options.host_key_alias == NULL) {
1024 debug("Forcing accepting of host key for "
1025 "loopback/localhost.");
1026 options.update_hostkeys = 0;
1027 return 0;
1028 }
1029
1030 /*
1031 * Don't ever try to write an invalid name to a known hosts file.
1032 * Note: do this before get_hostfile_hostname_ipaddr() to catch
1033 * '[' or ']' in the name before they are added.
1034 */
1035 if (strcspn(hostname, "@?*#[]|'\'\"\\") != strlen(hostname)) {
1036 debug_f("invalid hostname \"%s\"; will not record: %s",
1037 hostname, fail_reason);
1038 readonly = RDONLY;
1039 }
1040
1041 /*
1042 * Prepare the hostname and address strings used for hostkey lookup.
1043 * In some cases, these will have a port number appended.
1044 */
1045 get_hostfile_hostname_ipaddr(hostname, hostaddr,
1046 clobber_port ? 0 : port, &host, &ip);
1047
1048 /*
1049 * Turn off check_host_ip if the connection is to localhost, via proxy
1050 * command or if we don't have a hostname to compare with
1051 */
1052 if (options.check_host_ip && (local ||
1053 strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
1054 options.check_host_ip = 0;
1055
1056 host_hostkeys = init_hostkeys();
1057 for (i = 0; i < num_user_hostfiles; i++)
1058 load_hostkeys(host_hostkeys, host, user_hostfiles[i], 0);
1059 for (i = 0; i < num_system_hostfiles; i++)
1060 load_hostkeys(host_hostkeys, host, system_hostfiles[i], 0);
1061 if (hostfile_command != NULL && !clobber_port) {
1062 load_hostkeys_command(host_hostkeys, hostfile_command,
1063 "HOSTNAME", cinfo, host_key, host);
1064 }
1065
1066 ip_hostkeys = NULL;
1067 if (!want_cert && options.check_host_ip) {
1068 ip_hostkeys = init_hostkeys();
1069 for (i = 0; i < num_user_hostfiles; i++)
1070 load_hostkeys(ip_hostkeys, ip, user_hostfiles[i], 0);
1071 for (i = 0; i < num_system_hostfiles; i++)
1072 load_hostkeys(ip_hostkeys, ip, system_hostfiles[i], 0);
1073 if (hostfile_command != NULL && !clobber_port) {
1074 load_hostkeys_command(ip_hostkeys, hostfile_command,
1075 "ADDRESS", cinfo, host_key, ip);
1076 }
1077 }
1078
1079 retry:
1080 if (!hostkey_accepted_by_hostkeyalgs(host_key)) {
1081 error("host key %s not permitted by HostkeyAlgorithms",
1082 sshkey_ssh_name(host_key));
1083 goto fail;
1084 }
1085
1086 /* Reload these as they may have changed on cert->key downgrade */
1087 want_cert = sshkey_is_cert(host_key);
1088 type = sshkey_type(host_key);
1089
1090 /*
1091 * Check if the host key is present in the user's list of known
1092 * hosts or in the systemwide list.
1093 */
1094 host_status = check_key_in_hostkeys(host_hostkeys, host_key,
1095 &host_found);
1096
1097 /*
1098 * If there are no hostfiles, or if the hostkey was found via
1099 * KnownHostsCommand, then don't try to touch the disk.
1100 */
1101 if (!readonly && (num_user_hostfiles == 0 ||
1102 (host_found != NULL && host_found->note != 0)))
1103 readonly = RDONLY;
1104
1105 /*
1106 * Also perform check for the ip address, skip the check if we are
1107 * localhost, looking for a certificate, or the hostname was an ip
1108 * address to begin with.
1109 */
1110 if (!want_cert && ip_hostkeys != NULL) {
1111 ip_status = check_key_in_hostkeys(ip_hostkeys, host_key,
1112 &ip_found);
1113 if (host_status == HOST_CHANGED &&
1114 (ip_status != HOST_CHANGED ||
1115 (ip_found != NULL &&
1116 !sshkey_equal(ip_found->key, host_found->key))))
1117 host_ip_differ = 1;
1118 } else
1119 ip_status = host_status;
1120
1121 switch (host_status) {
1122 case HOST_OK:
1123 /* The host is known and the key matches. */
1124 debug("Host '%.200s' is known and matches the %s host %s.",
1125 host, type, want_cert ? "certificate" : "key");
1126 debug("Found %s in %s:%lu", want_cert ? "CA key" : "key",
1127 host_found->file, host_found->line);
1128 if (want_cert) {
1129 if (sshkey_cert_check_host(host_key,
1130 options.host_key_alias == NULL ?
1131 hostname : options.host_key_alias, 0,
1132 options.ca_sign_algorithms, &fail_reason) != 0) {
1133 error("%s", fail_reason);
1134 goto fail;
1135 }
1136 /*
1137 * Do not attempt hostkey update if a certificate was
1138 * successfully matched.
1139 */
1140 if (options.update_hostkeys != 0) {
1141 options.update_hostkeys = 0;
1142 debug3_f("certificate host key in use; "
1143 "disabling UpdateHostkeys");
1144 }
1145 }
1146 /* Turn off UpdateHostkeys if key was in system known_hosts */
1147 if (options.update_hostkeys != 0 &&
1148 (path_in_hostfiles(host_found->file,
1149 system_hostfiles, num_system_hostfiles) ||
1150 (ip_status == HOST_OK && ip_found != NULL &&
1151 path_in_hostfiles(ip_found->file,
1152 system_hostfiles, num_system_hostfiles)))) {
1153 options.update_hostkeys = 0;
1154 debug3_f("host key found in GlobalKnownHostsFile; "
1155 "disabling UpdateHostkeys");
1156 }
1157 if (options.update_hostkeys != 0 && host_found->note) {
1158 options.update_hostkeys = 0;
1159 debug3_f("host key found via KnownHostsCommand; "
1160 "disabling UpdateHostkeys");
1161 }
1162 if (options.check_host_ip && ip_status == HOST_NEW) {
1163 if (readonly || want_cert)
1164 logit("%s host key for IP address "
1165 "'%.128s' not in list of known hosts.",
1166 type, ip);
1167 else if (!add_host_to_hostfile(user_hostfiles[0], ip,
1168 host_key, options.hash_known_hosts))
1169 logit("Failed to add the %s host key for IP "
1170 "address '%.128s' to the list of known "
1171 "hosts (%.500s).", type, ip,
1172 user_hostfiles[0]);
1173 else
1174 logit("Warning: Permanently added the %s host "
1175 "key for IP address '%.128s' to the list "
1176 "of known hosts.", type, ip);
1177 } else if (options.visual_host_key) {
1178 fp = sshkey_fingerprint(host_key,
1179 options.fingerprint_hash, SSH_FP_DEFAULT);
1180 ra = sshkey_fingerprint(host_key,
1181 options.fingerprint_hash, SSH_FP_RANDOMART);
1182 if (fp == NULL || ra == NULL)
1183 fatal_f("sshkey_fingerprint failed");
1184 logit("Host key fingerprint is %s\n%s", fp, ra);
1185 free(ra);
1186 free(fp);
1187 }
1188 hostkey_trusted = 1;
1189 break;
1190 case HOST_NEW:
1191 if (options.host_key_alias == NULL && port != 0 &&
1192 port != SSH_DEFAULT_PORT && !clobber_port) {
1193 debug("checking without port identifier");
1194 if (check_host_key(hostname, cinfo, hostaddr, 0,
1195 host_key, ROQUIET, 1,
1196 user_hostfiles, num_user_hostfiles,
1197 system_hostfiles, num_system_hostfiles,
1198 hostfile_command) == 0) {
1199 debug("found matching key w/out port");
1200 break;
1201 }
1202 }
1203 if (readonly || want_cert)
1204 goto fail;
1205 /* The host is new. */
1206 if (options.strict_host_key_checking ==
1207 SSH_STRICT_HOSTKEY_YES) {
1208 /*
1209 * User has requested strict host key checking. We
1210 * will not add the host key automatically. The only
1211 * alternative left is to abort.
1212 */
1213 error("No %s host key is known for %.200s and you "
1214 "have requested strict checking.", type, host);
1215 goto fail;
1216 } else if (options.strict_host_key_checking ==
1217 SSH_STRICT_HOSTKEY_ASK) {
1218 char *msg1 = NULL, *msg2 = NULL;
1219
1220 xasprintf(&msg1, "The authenticity of host "
1221 "'%.200s (%s)' can't be established", host, ip);
1222
1223 if (show_other_keys(host_hostkeys, host_key)) {
1224 xextendf(&msg1, "\n", "but keys of different "
1225 "type are already known for this host.");
1226 } else
1227 xextendf(&msg1, "", ".");
1228
1229 fp = sshkey_fingerprint(host_key,
1230 options.fingerprint_hash, SSH_FP_DEFAULT);
1231 ra = sshkey_fingerprint(host_key,
1232 options.fingerprint_hash, SSH_FP_RANDOMART);
1233 if (fp == NULL || ra == NULL)
1234 fatal_f("sshkey_fingerprint failed");
1235 xextendf(&msg1, "\n", "%s key fingerprint is %s.",
1236 type, fp);
1237 if (options.visual_host_key)
1238 xextendf(&msg1, "\n", "%s", ra);
1239 if (options.verify_host_key_dns) {
1240 xextendf(&msg1, "\n",
1241 "%s host key fingerprint found in DNS.",
1242 matching_host_key_dns ?
1243 "Matching" : "No matching");
1244 }
1245 /* msg2 informs for other names matching this key */
1246 if ((msg2 = other_hostkeys_message(host, ip, host_key,
1247 user_hostfiles, num_user_hostfiles,
1248 system_hostfiles, num_system_hostfiles)) != NULL)
1249 xextendf(&msg1, "\n", "%s", msg2);
1250
1251 xextendf(&msg1, "\n",
1252 "Are you sure you want to continue connecting "
1253 "(yes/no/[fingerprint])? ");
1254
1255 confirmed = confirm(msg1, fp);
1256 free(ra);
1257 free(fp);
1258 free(msg1);
1259 free(msg2);
1260 if (!confirmed)
1261 goto fail;
1262 hostkey_trusted = 1; /* user explicitly confirmed */
1263 }
1264 /*
1265 * If in "new" or "off" strict mode, add the key automatically
1266 * to the local known_hosts file.
1267 */
1268 if (options.check_host_ip && ip_status == HOST_NEW) {
1269 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1270 hostp = hostline;
1271 if (options.hash_known_hosts) {
1272 /* Add hash of host and IP separately */
1273 r = add_host_to_hostfile(user_hostfiles[0],
1274 host, host_key, options.hash_known_hosts) &&
1275 add_host_to_hostfile(user_hostfiles[0], ip,
1276 host_key, options.hash_known_hosts);
1277 } else {
1278 /* Add unhashed "host,ip" */
1279 r = add_host_to_hostfile(user_hostfiles[0],
1280 hostline, host_key,
1281 options.hash_known_hosts);
1282 }
1283 } else {
1284 r = add_host_to_hostfile(user_hostfiles[0], host,
1285 host_key, options.hash_known_hosts);
1286 hostp = host;
1287 }
1288
1289 if (!r)
1290 logit("Failed to add the host to the list of known "
1291 "hosts (%.500s).", user_hostfiles[0]);
1292 else
1293 logit("Warning: Permanently added '%.200s' (%s) to the "
1294 "list of known hosts.", hostp, type);
1295 break;
1296 case HOST_REVOKED:
1297 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1298 error("@ WARNING: REVOKED HOST KEY DETECTED! @");
1299 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1300 error("The %s host key for %s is marked as revoked.", type, host);
1301 error("This could mean that a stolen key is being used to");
1302 error("impersonate this host.");
1303
1304 /*
1305 * If strict host key checking is in use, the user will have
1306 * to edit the key manually and we can only abort.
1307 */
1308 if (options.strict_host_key_checking !=
1309 SSH_STRICT_HOSTKEY_OFF) {
1310 error("%s host key for %.200s was revoked and you have "
1311 "requested strict checking.", type, host);
1312 goto fail;
1313 }
1314 goto continue_unsafe;
1315
1316 case HOST_CHANGED:
1317 if (want_cert) {
1318 /*
1319 * This is only a debug() since it is valid to have
1320 * CAs with wildcard DNS matches that don't match
1321 * all hosts that one might visit.
1322 */
1323 debug("Host certificate authority does not "
1324 "match %s in %s:%lu", CA_MARKER,
1325 host_found->file, host_found->line);
1326 goto fail;
1327 }
1328 if (readonly == ROQUIET)
1329 goto fail;
1330 if (options.check_host_ip && host_ip_differ) {
1331 const char *key_msg;
1332 if (ip_status == HOST_NEW)
1333 key_msg = "is unknown";
1334 else if (ip_status == HOST_OK)
1335 key_msg = "is unchanged";
1336 else
1337 key_msg = "has a different value";
1338 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1339 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1340 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1341 error("The %s host key for %s has changed,", type, host);
1342 error("and the key for the corresponding IP address %s", ip);
1343 error("%s. This could either mean that", key_msg);
1344 error("DNS SPOOFING is happening or the IP address for the host");
1345 error("and its host key have changed at the same time.");
1346 if (ip_status != HOST_NEW)
1347 error("Offending key for IP in %s:%lu",
1348 ip_found->file, ip_found->line);
1349 }
1350 /* The host key has changed. */
1351 warn_changed_key(host_key);
1352 if (num_user_hostfiles > 0 || num_system_hostfiles > 0) {
1353 error("Add correct host key in %.100s to get rid "
1354 "of this message.", num_user_hostfiles > 0 ?
1355 user_hostfiles[0] : system_hostfiles[0]);
1356 }
1357 error("Offending %s key in %s:%lu",
1358 sshkey_type(host_found->key),
1359 host_found->file, host_found->line);
1360
1361 /*
1362 * If strict host key checking is in use, the user will have
1363 * to edit the key manually and we can only abort.
1364 */
1365 if (options.strict_host_key_checking !=
1366 SSH_STRICT_HOSTKEY_OFF) {
1367 error("Host key for %.200s has changed and you have "
1368 "requested strict checking.", host);
1369 goto fail;
1370 }
1371
1372 continue_unsafe:
1373 /*
1374 * If strict host key checking has not been requested, allow
1375 * the connection but without MITM-able authentication or
1376 * forwarding.
1377 */
1378 if (options.password_authentication) {
1379 error("Password authentication is disabled to avoid "
1380 "man-in-the-middle attacks.");
1381 options.password_authentication = 0;
1382 cancelled_forwarding = 1;
1383 }
1384 if (options.kbd_interactive_authentication) {
1385 error("Keyboard-interactive authentication is disabled"
1386 " to avoid man-in-the-middle attacks.");
1387 options.kbd_interactive_authentication = 0;
1388 cancelled_forwarding = 1;
1389 }
1390 if (options.forward_agent) {
1391 error("Agent forwarding is disabled to avoid "
1392 "man-in-the-middle attacks.");
1393 options.forward_agent = 0;
1394 cancelled_forwarding = 1;
1395 }
1396 if (options.forward_x11) {
1397 error("X11 forwarding is disabled to avoid "
1398 "man-in-the-middle attacks.");
1399 options.forward_x11 = 0;
1400 cancelled_forwarding = 1;
1401 }
1402 if (options.num_local_forwards > 0 ||
1403 options.num_remote_forwards > 0) {
1404 error("Port forwarding is disabled to avoid "
1405 "man-in-the-middle attacks.");
1406 options.num_local_forwards =
1407 options.num_remote_forwards = 0;
1408 cancelled_forwarding = 1;
1409 }
1410 if (options.tun_open != SSH_TUNMODE_NO) {
1411 error("Tunnel forwarding is disabled to avoid "
1412 "man-in-the-middle attacks.");
1413 options.tun_open = SSH_TUNMODE_NO;
1414 cancelled_forwarding = 1;
1415 }
1416 if (options.update_hostkeys != 0) {
1417 error("UpdateHostkeys is disabled because the host "
1418 "key is not trusted.");
1419 options.update_hostkeys = 0;
1420 }
1421 if (options.exit_on_forward_failure && cancelled_forwarding)
1422 fatal("Error: forwarding disabled due to host key "
1423 "check failure");
1424
1425 /*
1426 * XXX Should permit the user to change to use the new id.
1427 * This could be done by converting the host key to an
1428 * identifying sentence, tell that the host identifies itself
1429 * by that sentence, and ask the user if they wish to
1430 * accept the authentication.
1431 */
1432 break;
1433 case HOST_FOUND:
1434 fatal("internal error");
1435 break;
1436 }
1437
1438 if (options.check_host_ip && host_status != HOST_CHANGED &&
1439 ip_status == HOST_CHANGED) {
1440 snprintf(msg, sizeof(msg),
1441 "Warning: the %s host key for '%.200s' "
1442 "differs from the key for the IP address '%.128s'"
1443 "\nOffending key for IP in %s:%lu",
1444 type, host, ip, ip_found->file, ip_found->line);
1445 if (host_status == HOST_OK) {
1446 len = strlen(msg);
1447 snprintf(msg + len, sizeof(msg) - len,
1448 "\nMatching host key in %s:%lu",
1449 host_found->file, host_found->line);
1450 }
1451 if (options.strict_host_key_checking ==
1452 SSH_STRICT_HOSTKEY_ASK) {
1453 strlcat(msg, "\nAre you sure you want "
1454 "to continue connecting (yes/no)? ", sizeof(msg));
1455 if (!confirm(msg, NULL))
1456 goto fail;
1457 } else if (options.strict_host_key_checking !=
1458 SSH_STRICT_HOSTKEY_OFF) {
1459 logit("%s", msg);
1460 error("Exiting, you have requested strict checking.");
1461 goto fail;
1462 } else {
1463 logit("%s", msg);
1464 }
1465 }
1466
1467 if (!hostkey_trusted && options.update_hostkeys) {
1468 debug_f("hostkey not known or explicitly trusted: "
1469 "disabling UpdateHostkeys");
1470 options.update_hostkeys = 0;
1471 }
1472
1473 free(ip);
1474 free(host);
1475 if (host_hostkeys != NULL)
1476 free_hostkeys(host_hostkeys);
1477 if (ip_hostkeys != NULL)
1478 free_hostkeys(ip_hostkeys);
1479 return 0;
1480
1481 fail:
1482 if (want_cert && host_status != HOST_REVOKED) {
1483 /*
1484 * No matching certificate. Downgrade cert to raw key and
1485 * search normally.
1486 */
1487 debug("No matching CA found. Retry with plain key");
1488 if ((r = sshkey_from_private(host_key, &raw_key)) != 0)
1489 fatal_fr(r, "decode key");
1490 if ((r = sshkey_drop_cert(raw_key)) != 0)
1491 fatal_r(r, "Couldn't drop certificate");
1492 host_key = raw_key;
1493 goto retry;
1494 }
1495 sshkey_free(raw_key);
1496 free(ip);
1497 free(host);
1498 if (host_hostkeys != NULL)
1499 free_hostkeys(host_hostkeys);
1500 if (ip_hostkeys != NULL)
1501 free_hostkeys(ip_hostkeys);
1502 return -1;
1503 }
1504
1505 /* returns 0 if key verifies or -1 if key does NOT verify */
1506 int
verify_host_key(char * host,struct sockaddr * hostaddr,struct sshkey * host_key,const struct ssh_conn_info * cinfo)1507 verify_host_key(char *host, struct sockaddr *hostaddr, struct sshkey *host_key,
1508 const struct ssh_conn_info *cinfo)
1509 {
1510 u_int i;
1511 int r = -1, flags = 0;
1512 char valid[64], *fp = NULL, *cafp = NULL;
1513 struct sshkey *plain = NULL;
1514
1515 if ((fp = sshkey_fingerprint(host_key,
1516 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1517 error_fr(r, "fingerprint host key");
1518 r = -1;
1519 goto out;
1520 }
1521
1522 if (sshkey_is_cert(host_key)) {
1523 if ((cafp = sshkey_fingerprint(host_key->cert->signature_key,
1524 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) {
1525 error_fr(r, "fingerprint CA key");
1526 r = -1;
1527 goto out;
1528 }
1529 sshkey_format_cert_validity(host_key->cert,
1530 valid, sizeof(valid));
1531 debug("Server host certificate: %s %s, serial %llu "
1532 "ID \"%s\" CA %s %s valid %s",
1533 sshkey_ssh_name(host_key), fp,
1534 (unsigned long long)host_key->cert->serial,
1535 host_key->cert->key_id,
1536 sshkey_ssh_name(host_key->cert->signature_key), cafp,
1537 valid);
1538 for (i = 0; i < host_key->cert->nprincipals; i++) {
1539 debug2("Server host certificate hostname: %s",
1540 host_key->cert->principals[i]);
1541 }
1542 } else {
1543 debug("Server host key: %s %s", sshkey_ssh_name(host_key), fp);
1544 }
1545
1546 if (sshkey_equal(previous_host_key, host_key)) {
1547 debug2_f("server host key %s %s matches cached key",
1548 sshkey_type(host_key), fp);
1549 r = 0;
1550 goto out;
1551 }
1552
1553 /* Check in RevokedHostKeys file if specified */
1554 if (options.revoked_host_keys != NULL) {
1555 r = sshkey_check_revoked(host_key, options.revoked_host_keys);
1556 switch (r) {
1557 case 0:
1558 break; /* not revoked */
1559 case SSH_ERR_KEY_REVOKED:
1560 error("Host key %s %s revoked by file %s",
1561 sshkey_type(host_key), fp,
1562 options.revoked_host_keys);
1563 r = -1;
1564 goto out;
1565 default:
1566 error_r(r, "Error checking host key %s %s in "
1567 "revoked keys file %s", sshkey_type(host_key),
1568 fp, options.revoked_host_keys);
1569 r = -1;
1570 goto out;
1571 }
1572 }
1573
1574 if (options.verify_host_key_dns) {
1575 /*
1576 * XXX certs are not yet supported for DNS, so downgrade
1577 * them and try the plain key.
1578 */
1579 if ((r = sshkey_from_private(host_key, &plain)) != 0)
1580 goto out;
1581 if (sshkey_is_cert(plain))
1582 sshkey_drop_cert(plain);
1583 if (verify_host_key_dns(host, hostaddr, plain, &flags) == 0) {
1584 if (flags & DNS_VERIFY_FOUND) {
1585 if (options.verify_host_key_dns == 1 &&
1586 flags & DNS_VERIFY_MATCH &&
1587 flags & DNS_VERIFY_SECURE) {
1588 r = 0;
1589 goto out;
1590 }
1591 if (flags & DNS_VERIFY_MATCH) {
1592 matching_host_key_dns = 1;
1593 } else {
1594 warn_changed_key(plain);
1595 error("Update the SSHFP RR in DNS "
1596 "with the new host key to get rid "
1597 "of this message.");
1598 }
1599 }
1600 }
1601 }
1602 r = check_host_key(host, cinfo, hostaddr, options.port, host_key,
1603 RDRW, 0, options.user_hostfiles, options.num_user_hostfiles,
1604 options.system_hostfiles, options.num_system_hostfiles,
1605 options.known_hosts_command);
1606
1607 out:
1608 sshkey_free(plain);
1609 free(fp);
1610 free(cafp);
1611 if (r == 0 && host_key != NULL) {
1612 sshkey_free(previous_host_key);
1613 r = sshkey_from_private(host_key, &previous_host_key);
1614 }
1615
1616 return r;
1617 }
1618
1619 /*
1620 * Starts a dialog with the server, and authenticates the current user on the
1621 * server. This does not need any extra privileges. The basic connection
1622 * to the server must already have been established before this is called.
1623 * If login fails, this function prints an error and never returns.
1624 * This function does not require super-user privileges.
1625 */
1626 void
ssh_login(struct ssh * ssh,Sensitive * sensitive,const char * orighost,struct sockaddr * hostaddr,u_short port,struct passwd * pw,int timeout_ms,const struct ssh_conn_info * cinfo)1627 ssh_login(struct ssh *ssh, Sensitive *sensitive, const char *orighost,
1628 struct sockaddr *hostaddr, u_short port, struct passwd *pw, int timeout_ms,
1629 const struct ssh_conn_info *cinfo)
1630 {
1631 char *host;
1632 char *server_user, *local_user;
1633 int r;
1634
1635 local_user = xstrdup(pw->pw_name);
1636 server_user = options.user ? options.user : local_user;
1637
1638 /* Convert the user-supplied hostname into all lowercase. */
1639 host = xstrdup(orighost);
1640 lowercase(host);
1641
1642 /* Exchange protocol version identification strings with the server. */
1643 if ((r = kex_exchange_identification(ssh, timeout_ms, NULL)) != 0)
1644 sshpkt_fatal(ssh, r, "banner exchange");
1645
1646 /* Put the connection into non-blocking mode. */
1647 ssh_packet_set_nonblocking(ssh);
1648
1649 /* key exchange */
1650 /* authenticate user */
1651 debug("Authenticating to %s:%d as '%s'", host, port, server_user);
1652 ssh_kex2(ssh, host, hostaddr, port, cinfo);
1653 ssh_userauth2(ssh, local_user, server_user, host, sensitive);
1654 free(local_user);
1655 free(host);
1656 }
1657
1658 /* print all known host keys for a given host, but skip keys of given type */
1659 static int
show_other_keys(struct hostkeys * hostkeys,struct sshkey * key)1660 show_other_keys(struct hostkeys *hostkeys, struct sshkey *key)
1661 {
1662 int type[] = {
1663 KEY_RSA,
1664 #ifdef WITH_DSA
1665 KEY_DSA,
1666 #endif
1667 KEY_ECDSA,
1668 KEY_ED25519,
1669 KEY_XMSS,
1670 -1
1671 };
1672 int i, ret = 0;
1673 char *fp, *ra;
1674 const struct hostkey_entry *found;
1675
1676 for (i = 0; type[i] != -1; i++) {
1677 if (type[i] == key->type)
1678 continue;
1679 if (!lookup_key_in_hostkeys_by_type(hostkeys, type[i],
1680 -1, &found))
1681 continue;
1682 fp = sshkey_fingerprint(found->key,
1683 options.fingerprint_hash, SSH_FP_DEFAULT);
1684 ra = sshkey_fingerprint(found->key,
1685 options.fingerprint_hash, SSH_FP_RANDOMART);
1686 if (fp == NULL || ra == NULL)
1687 fatal_f("sshkey_fingerprint fail");
1688 logit("WARNING: %s key found for host %s\n"
1689 "in %s:%lu\n"
1690 "%s key fingerprint %s.",
1691 sshkey_type(found->key),
1692 found->host, found->file, found->line,
1693 sshkey_type(found->key), fp);
1694 if (options.visual_host_key)
1695 logit("%s", ra);
1696 free(ra);
1697 free(fp);
1698 ret = 1;
1699 }
1700 return ret;
1701 }
1702
1703 static void
warn_changed_key(struct sshkey * host_key)1704 warn_changed_key(struct sshkey *host_key)
1705 {
1706 char *fp;
1707
1708 fp = sshkey_fingerprint(host_key, options.fingerprint_hash,
1709 SSH_FP_DEFAULT);
1710 if (fp == NULL)
1711 fatal_f("sshkey_fingerprint fail");
1712
1713 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1714 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1715 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1716 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1717 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1718 error("It is also possible that a host key has just been changed.");
1719 error("The fingerprint for the %s key sent by the remote host is\n%s.",
1720 sshkey_type(host_key), fp);
1721 error("Please contact your system administrator.");
1722
1723 free(fp);
1724 }
1725
1726 /*
1727 * Execute a local command
1728 */
1729 int
ssh_local_cmd(const char * args)1730 ssh_local_cmd(const char *args)
1731 {
1732 const char *shell;
1733 pid_t pid;
1734 int status;
1735 void (*osighand)(int);
1736
1737 if (!options.permit_local_command ||
1738 args == NULL || !*args)
1739 return (1);
1740
1741 if ((shell = getenv("SHELL")) == NULL || *shell == '\0')
1742 shell = _PATH_BSHELL;
1743
1744 osighand = ssh_signal(SIGCHLD, SIG_DFL);
1745 pid = fork();
1746 if (pid == 0) {
1747 ssh_signal(SIGPIPE, SIG_DFL);
1748 debug3("Executing %s -c \"%s\"", shell, args);
1749 execl(shell, shell, "-c", args, (char *)NULL);
1750 error("Couldn't execute %s -c \"%s\": %s",
1751 shell, args, strerror(errno));
1752 _exit(1);
1753 } else if (pid == -1)
1754 fatal("fork failed: %.100s", strerror(errno));
1755 while (waitpid(pid, &status, 0) == -1)
1756 if (errno != EINTR)
1757 fatal("Couldn't wait for child: %s", strerror(errno));
1758 ssh_signal(SIGCHLD, osighand);
1759
1760 if (!WIFEXITED(status))
1761 return (1);
1762
1763 return (WEXITSTATUS(status));
1764 }
1765
1766 void
maybe_add_key_to_agent(const char * authfile,struct sshkey * private,const char * comment,const char * passphrase)1767 maybe_add_key_to_agent(const char *authfile, struct sshkey *private,
1768 const char *comment, const char *passphrase)
1769 {
1770 int auth_sock = -1, r;
1771 const char *skprovider = NULL;
1772
1773 if (options.add_keys_to_agent == 0)
1774 return;
1775
1776 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
1777 debug3("no authentication agent, not adding key");
1778 return;
1779 }
1780
1781 if (options.add_keys_to_agent == 2 &&
1782 !ask_permission("Add key %s (%s) to agent?", authfile, comment)) {
1783 debug3("user denied adding this key");
1784 close(auth_sock);
1785 return;
1786 }
1787 if (sshkey_is_sk(private))
1788 skprovider = options.sk_provider;
1789 if ((r = ssh_add_identity_constrained(auth_sock, private,
1790 comment == NULL ? authfile : comment,
1791 options.add_keys_to_agent_lifespan,
1792 (options.add_keys_to_agent == 3), 0, skprovider, NULL, 0)) == 0)
1793 debug("identity added to agent: %s", authfile);
1794 else
1795 debug("could not add identity to agent: %s (%d)", authfile, r);
1796 close(auth_sock);
1797 }
1798