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