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