]> andersk Git - openssh.git/blob - sshconnect.c
- stevesk@cvs.openbsd.org 2006/07/25 02:59:21
[openssh.git] / sshconnect.c
1 /* $OpenBSD: sshconnect.c,v 1.195 2006/07/25 02:59:21 stevesk 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 <netinet/in.h>
27
28 #include <ctype.h>
29 #include <errno.h>
30 #include <netdb.h>
31 #ifdef HAVE_PATHS_H
32 #include <paths.h>
33 #endif
34 #include <pwd.h>
35 #include <string.h>
36 #include <unistd.h>
37
38 #include "ssh.h"
39 #include "xmalloc.h"
40 #include "rsa.h"
41 #include "buffer.h"
42 #include "packet.h"
43 #include "uidswap.h"
44 #include "compat.h"
45 #include "key.h"
46 #include "sshconnect.h"
47 #include "hostfile.h"
48 #include "log.h"
49 #include "readconf.h"
50 #include "atomicio.h"
51 #include "misc.h"
52 #include "dns.h"
53 #include "version.h"
54
55 char *client_version_string = NULL;
56 char *server_version_string = NULL;
57
58 static int matching_host_key_dns = 0;
59
60 /* import */
61 extern Options options;
62 extern char *__progname;
63 extern uid_t original_real_uid;
64 extern uid_t original_effective_uid;
65 extern pid_t proxy_command_pid;
66
67 #ifndef INET6_ADDRSTRLEN                /* for non IPv6 machines */
68 #define INET6_ADDRSTRLEN 46
69 #endif
70
71 static int show_other_keys(const char *, Key *);
72 static void warn_changed_key(Key *);
73
74 /*
75  * Connect to the given ssh server using a proxy command.
76  */
77 static int
78 ssh_proxy_connect(const char *host, u_short port, const char *proxy_command)
79 {
80         char *command_string, *tmp;
81         int pin[2], pout[2];
82         pid_t pid;
83         char strport[NI_MAXSERV];
84
85         /* Convert the port number into a string. */
86         snprintf(strport, sizeof strport, "%hu", port);
87
88         /*
89          * Build the final command string in the buffer by making the
90          * appropriate substitutions to the given proxy command.
91          *
92          * Use "exec" to avoid "sh -c" processes on some platforms
93          * (e.g. Solaris)
94          */
95         xasprintf(&tmp, "exec %s", proxy_command);
96         command_string = percent_expand(tmp, "h", host,
97             "p", strport, (char *)NULL);
98         xfree(tmp);
99
100         /* Create pipes for communicating with the proxy. */
101         if (pipe(pin) < 0 || pipe(pout) < 0)
102                 fatal("Could not create pipes to communicate with the proxy: %.100s",
103                     strerror(errno));
104
105         debug("Executing proxy command: %.500s", command_string);
106
107         /* Fork and execute the proxy command. */
108         if ((pid = fork()) == 0) {
109                 char *argv[10];
110
111                 /* Child.  Permanently give up superuser privileges. */
112                 permanently_drop_suid(original_real_uid);
113
114                 /* Redirect stdin and stdout. */
115                 close(pin[1]);
116                 if (pin[0] != 0) {
117                         if (dup2(pin[0], 0) < 0)
118                                 perror("dup2 stdin");
119                         close(pin[0]);
120                 }
121                 close(pout[0]);
122                 if (dup2(pout[1], 1) < 0)
123                         perror("dup2 stdout");
124                 /* Cannot be 1 because pin allocated two descriptors. */
125                 close(pout[1]);
126
127                 /* Stderr is left as it is so that error messages get
128                    printed on the user's terminal. */
129                 argv[0] = _PATH_BSHELL;
130                 argv[1] = "-c";
131                 argv[2] = command_string;
132                 argv[3] = NULL;
133
134                 /* Execute the proxy command.  Note that we gave up any
135                    extra privileges above. */
136                 execv(argv[0], argv);
137                 perror(argv[0]);
138                 exit(1);
139         }
140         /* Parent. */
141         if (pid < 0)
142                 fatal("fork failed: %.100s", strerror(errno));
143         else
144                 proxy_command_pid = pid; /* save pid to clean up later */
145
146         /* Close child side of the descriptors. */
147         close(pin[0]);
148         close(pout[1]);
149
150         /* Free the command name. */
151         xfree(command_string);
152
153         /* Set the connection file descriptors. */
154         packet_set_connection(pout[0], pin[1]);
155
156         /* Indicate OK return */
157         return 0;
158 }
159
160 /*
161  * Creates a (possibly privileged) socket for use as the ssh connection.
162  */
163 static int
164 ssh_create_socket(int privileged, struct addrinfo *ai)
165 {
166         int sock, gaierr;
167         struct addrinfo hints, *res;
168
169         /*
170          * If we are running as root and want to connect to a privileged
171          * port, bind our own socket to a privileged port.
172          */
173         if (privileged) {
174                 int p = IPPORT_RESERVED - 1;
175                 PRIV_START;
176                 sock = rresvport_af(&p, ai->ai_family);
177                 PRIV_END;
178                 if (sock < 0)
179                         error("rresvport: af=%d %.100s", ai->ai_family,
180                             strerror(errno));
181                 else
182                         debug("Allocated local port %d.", p);
183                 return sock;
184         }
185         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
186         if (sock < 0)
187                 error("socket: %.100s", strerror(errno));
188
189         /* Bind the socket to an alternative local IP address */
190         if (options.bind_address == NULL)
191                 return sock;
192
193         memset(&hints, 0, sizeof(hints));
194         hints.ai_family = ai->ai_family;
195         hints.ai_socktype = ai->ai_socktype;
196         hints.ai_protocol = ai->ai_protocol;
197         hints.ai_flags = AI_PASSIVE;
198         gaierr = getaddrinfo(options.bind_address, "0", &hints, &res);
199         if (gaierr) {
200                 error("getaddrinfo: %s: %s", options.bind_address,
201                     gai_strerror(gaierr));
202                 close(sock);
203                 return -1;
204         }
205         if (bind(sock, res->ai_addr, res->ai_addrlen) < 0) {
206                 error("bind: %s: %s", options.bind_address, strerror(errno));
207                 close(sock);
208                 freeaddrinfo(res);
209                 return -1;
210         }
211         freeaddrinfo(res);
212         return sock;
213 }
214
215 static int
216 timeout_connect(int sockfd, const struct sockaddr *serv_addr,
217     socklen_t addrlen, int timeout)
218 {
219         fd_set *fdset;
220         struct timeval tv;
221         socklen_t optlen;
222         int optval, rc, result = -1;
223
224         if (timeout <= 0)
225                 return (connect(sockfd, serv_addr, addrlen));
226
227         set_nonblock(sockfd);
228         rc = connect(sockfd, serv_addr, addrlen);
229         if (rc == 0) {
230                 unset_nonblock(sockfd);
231                 return (0);
232         }
233         if (errno != EINPROGRESS)
234                 return (-1);
235
236         fdset = (fd_set *)xcalloc(howmany(sockfd + 1, NFDBITS),
237             sizeof(fd_mask));
238         FD_SET(sockfd, fdset);
239         tv.tv_sec = timeout;
240         tv.tv_usec = 0;
241
242         for (;;) {
243                 rc = select(sockfd + 1, NULL, fdset, NULL, &tv);
244                 if (rc != -1 || errno != EINTR)
245                         break;
246         }
247
248         switch (rc) {
249         case 0:
250                 /* Timed out */
251                 errno = ETIMEDOUT;
252                 break;
253         case -1:
254                 /* Select error */
255                 debug("select: %s", strerror(errno));
256                 break;
257         case 1:
258                 /* Completed or failed */
259                 optval = 0;
260                 optlen = sizeof(optval);
261                 if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &optval,
262                     &optlen) == -1) {
263                         debug("getsockopt: %s", strerror(errno));
264                         break;
265                 }
266                 if (optval != 0) {
267                         errno = optval;
268                         break;
269                 }
270                 result = 0;
271                 unset_nonblock(sockfd);
272                 break;
273         default:
274                 /* Should not occur */
275                 fatal("Bogus return (%d) from select()", rc);
276         }
277
278         xfree(fdset);
279         return (result);
280 }
281
282 /*
283  * Opens a TCP/IP connection to the remote server on the given host.
284  * The address of the remote host will be returned in hostaddr.
285  * If port is 0, the default port will be used.  If needpriv is true,
286  * a privileged port will be allocated to make the connection.
287  * This requires super-user privileges if needpriv is true.
288  * Connection_attempts specifies the maximum number of tries (one per
289  * second).  If proxy_command is non-NULL, it specifies the command (with %h
290  * and %p substituted for host and port, respectively) to use to contact
291  * the daemon.
292  */
293 int
294 ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
295     u_short port, int family, int connection_attempts,
296     int needpriv, const char *proxy_command)
297 {
298         int gaierr;
299         int on = 1;
300         int sock = -1, attempt;
301         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
302         struct addrinfo hints, *ai, *aitop;
303
304         debug2("ssh_connect: needpriv %d", needpriv);
305
306         /* If a proxy command is given, connect using it. */
307         if (proxy_command != NULL)
308                 return ssh_proxy_connect(host, port, proxy_command);
309
310         /* No proxy command. */
311
312         memset(&hints, 0, sizeof(hints));
313         hints.ai_family = family;
314         hints.ai_socktype = SOCK_STREAM;
315         snprintf(strport, sizeof strport, "%u", port);
316         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
317                 fatal("%s: %.100s: %s", __progname, host,
318                     gai_strerror(gaierr));
319
320         for (attempt = 0; attempt < connection_attempts; attempt++) {
321                 if (attempt > 0)
322                         debug("Trying again...");
323
324                 /*
325                  * Loop through addresses for this host, and try each one in
326                  * sequence until the connection succeeds.
327                  */
328                 for (ai = aitop; ai; ai = ai->ai_next) {
329                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
330                                 continue;
331                         if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
332                             ntop, sizeof(ntop), strport, sizeof(strport),
333                             NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
334                                 error("ssh_connect: getnameinfo failed");
335                                 continue;
336                         }
337                         debug("Connecting to %.200s [%.100s] port %s.",
338                                 host, ntop, strport);
339
340                         /* Create a socket for connecting. */
341                         sock = ssh_create_socket(needpriv, ai);
342                         if (sock < 0)
343                                 /* Any error is already output */
344                                 continue;
345
346                         if (timeout_connect(sock, ai->ai_addr, ai->ai_addrlen,
347                             options.connection_timeout) >= 0) {
348                                 /* Successful connection. */
349                                 memcpy(hostaddr, ai->ai_addr, ai->ai_addrlen);
350                                 break;
351                         } else {
352                                 debug("connect to address %s port %s: %s",
353                                     ntop, strport, strerror(errno));
354                                 close(sock);
355                                 sock = -1;
356                         }
357                 }
358                 if (sock != -1)
359                         break;  /* Successful connection. */
360
361                 /* Sleep a moment before retrying. */
362                 sleep(1);
363         }
364
365         freeaddrinfo(aitop);
366
367         /* Return failure if we didn't get a successful connection. */
368         if (sock == -1) {
369                 error("ssh: connect to host %s port %s: %s",
370                     host, strport, strerror(errno));
371                 return (-1);
372         }
373
374         debug("Connection established.");
375
376         /* Set SO_KEEPALIVE if requested. */
377         if (options.tcp_keep_alive &&
378             setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
379             sizeof(on)) < 0)
380                 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
381
382         /* Set the connection. */
383         packet_set_connection(sock, sock);
384
385         return 0;
386 }
387
388 /*
389  * Waits for the server identification string, and sends our own
390  * identification string.
391  */
392 static void
393 ssh_exchange_identification(void)
394 {
395         char buf[256], remote_version[256];     /* must be same size! */
396         int remote_major, remote_minor, mismatch;
397         int connection_in = packet_get_connection_in();
398         int connection_out = packet_get_connection_out();
399         int minor1 = PROTOCOL_MINOR_1;
400         u_int i, n;
401
402         /* Read other side's version identification. */
403         for (n = 0;;) {
404                 for (i = 0; i < sizeof(buf) - 1; i++) {
405                         size_t len = atomicio(read, connection_in, &buf[i], 1);
406
407                         if (len != 1 && errno == EPIPE)
408                                 fatal("ssh_exchange_identification: Connection closed by remote host");
409                         else if (len != 1)
410                                 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
411                         if (buf[i] == '\r') {
412                                 buf[i] = '\n';
413                                 buf[i + 1] = 0;
414                                 continue;               /**XXX wait for \n */
415                         }
416                         if (buf[i] == '\n') {
417                                 buf[i + 1] = 0;
418                                 break;
419                         }
420                         if (++n > 65536)
421                                 fatal("ssh_exchange_identification: No banner received");
422                 }
423                 buf[sizeof(buf) - 1] = 0;
424                 if (strncmp(buf, "SSH-", 4) == 0)
425                         break;
426                 debug("ssh_exchange_identification: %s", buf);
427         }
428         server_version_string = xstrdup(buf);
429
430         /*
431          * Check that the versions match.  In future this might accept
432          * several versions and set appropriate flags to handle them.
433          */
434         if (sscanf(server_version_string, "SSH-%d.%d-%[^\n]\n",
435             &remote_major, &remote_minor, remote_version) != 3)
436                 fatal("Bad remote protocol version identification: '%.100s'", buf);
437         debug("Remote protocol version %d.%d, remote software version %.100s",
438             remote_major, remote_minor, remote_version);
439
440         compat_datafellows(remote_version);
441         mismatch = 0;
442
443         switch (remote_major) {
444         case 1:
445                 if (remote_minor == 99 &&
446                     (options.protocol & SSH_PROTO_2) &&
447                     !(options.protocol & SSH_PROTO_1_PREFERRED)) {
448                         enable_compat20();
449                         break;
450                 }
451                 if (!(options.protocol & SSH_PROTO_1)) {
452                         mismatch = 1;
453                         break;
454                 }
455                 if (remote_minor < 3) {
456                         fatal("Remote machine has too old SSH software version.");
457                 } else if (remote_minor == 3 || remote_minor == 4) {
458                         /* We speak 1.3, too. */
459                         enable_compat13();
460                         minor1 = 3;
461                         if (options.forward_agent) {
462                                 logit("Agent forwarding disabled for protocol 1.3");
463                                 options.forward_agent = 0;
464                         }
465                 }
466                 break;
467         case 2:
468                 if (options.protocol & SSH_PROTO_2) {
469                         enable_compat20();
470                         break;
471                 }
472                 /* FALLTHROUGH */
473         default:
474                 mismatch = 1;
475                 break;
476         }
477         if (mismatch)
478                 fatal("Protocol major versions differ: %d vs. %d",
479                     (options.protocol & SSH_PROTO_2) ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
480                     remote_major);
481         /* Send our own protocol version identification. */
482         snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
483             compat20 ? PROTOCOL_MAJOR_2 : PROTOCOL_MAJOR_1,
484             compat20 ? PROTOCOL_MINOR_2 : minor1,
485             SSH_VERSION);
486         if (atomicio(vwrite, connection_out, buf, strlen(buf)) != strlen(buf))
487                 fatal("write: %.100s", strerror(errno));
488         client_version_string = xstrdup(buf);
489         chop(client_version_string);
490         chop(server_version_string);
491         debug("Local version string %.100s", client_version_string);
492 }
493
494 /* defaults to 'no' */
495 static int
496 confirm(const char *prompt)
497 {
498         const char *msg, *again = "Please type 'yes' or 'no': ";
499         char *p;
500         int ret = -1;
501
502         if (options.batch_mode)
503                 return 0;
504         for (msg = prompt;;msg = again) {
505                 p = read_passphrase(msg, RP_ECHO);
506                 if (p == NULL ||
507                     (p[0] == '\0') || (p[0] == '\n') ||
508                     strncasecmp(p, "no", 2) == 0)
509                         ret = 0;
510                 if (p && strncasecmp(p, "yes", 3) == 0)
511                         ret = 1;
512                 if (p)
513                         xfree(p);
514                 if (ret != -1)
515                         return ret;
516         }
517 }
518
519 /*
520  * check whether the supplied host key is valid, return -1 if the key
521  * is not valid. the user_hostfile will not be updated if 'readonly' is true.
522  */
523 static int
524 check_host_key(char *hostname, struct sockaddr *hostaddr, Key *host_key,
525     int readonly, const char *user_hostfile, const char *system_hostfile)
526 {
527         Key *file_key;
528         const char *type = key_type(host_key);
529         char *ip = NULL, *host = NULL;
530         char hostline[1000], *hostp, *fp;
531         HostStatus host_status;
532         HostStatus ip_status;
533         int r, local = 0, host_ip_differ = 0;
534         int salen;
535         char ntop[NI_MAXHOST];
536         char msg[1024];
537         int len, host_line, ip_line;
538         const char *host_file = NULL, *ip_file = NULL;
539
540         /*
541          * Force accepting of the host key for loopback/localhost. The
542          * problem is that if the home directory is NFS-mounted to multiple
543          * machines, localhost will refer to a different machine in each of
544          * them, and the user will get bogus HOST_CHANGED warnings.  This
545          * essentially disables host authentication for localhost; however,
546          * this is probably not a real problem.
547          */
548         /**  hostaddr == 0! */
549         switch (hostaddr->sa_family) {
550         case AF_INET:
551                 local = (ntohl(((struct sockaddr_in *)hostaddr)->
552                     sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
553                 salen = sizeof(struct sockaddr_in);
554                 break;
555         case AF_INET6:
556                 local = IN6_IS_ADDR_LOOPBACK(
557                     &(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
558                 salen = sizeof(struct sockaddr_in6);
559                 break;
560         default:
561                 local = 0;
562                 salen = sizeof(struct sockaddr_storage);
563                 break;
564         }
565         if (options.no_host_authentication_for_localhost == 1 && local &&
566             options.host_key_alias == NULL) {
567                 debug("Forcing accepting of host key for "
568                     "loopback/localhost.");
569                 return 0;
570         }
571
572         /*
573          * We don't have the remote ip-address for connections
574          * using a proxy command
575          */
576         if (options.proxy_command == NULL) {
577                 if (getnameinfo(hostaddr, salen, ntop, sizeof(ntop),
578                     NULL, 0, NI_NUMERICHOST) != 0)
579                         fatal("check_host_key: getnameinfo failed");
580                 ip = put_host_port(ntop, options.port);
581         } else {
582                 ip = xstrdup("<no hostip for proxy command>");
583         }
584         /*
585          * Turn off check_host_ip if the connection is to localhost, via proxy
586          * command or if we don't have a hostname to compare with
587          */
588         if (options.check_host_ip && (local ||
589             strcmp(hostname, ip) == 0 || options.proxy_command != NULL))
590                 options.check_host_ip = 0;
591
592         /*
593          * Allow the user to record the key under a different name or
594          * differentiate a non-standard port.  This is useful for ssh
595          * tunneling over forwarded connections or if you run multiple
596          * sshd's on different ports on the same machine.
597          */
598         if (options.host_key_alias != NULL) {
599                 host = xstrdup(options.host_key_alias);
600                 debug("using hostkeyalias: %s", host);
601         } else {
602                 host = put_host_port(hostname, options.port);
603         }
604
605         /*
606          * Store the host key from the known host file in here so that we can
607          * compare it with the key for the IP address.
608          */
609         file_key = key_new(host_key->type);
610
611         /*
612          * Check if the host key is present in the user's list of known
613          * hosts or in the systemwide list.
614          */
615         host_file = user_hostfile;
616         host_status = check_host_in_hostfile(host_file, host, host_key,
617             file_key, &host_line);
618         if (host_status == HOST_NEW) {
619                 host_file = system_hostfile;
620                 host_status = check_host_in_hostfile(host_file, host, host_key,
621                     file_key, &host_line);
622         }
623         /*
624          * Also perform check for the ip address, skip the check if we are
625          * localhost or the hostname was an ip address to begin with
626          */
627         if (options.check_host_ip) {
628                 Key *ip_key = key_new(host_key->type);
629
630                 ip_file = user_hostfile;
631                 ip_status = check_host_in_hostfile(ip_file, ip, host_key,
632                     ip_key, &ip_line);
633                 if (ip_status == HOST_NEW) {
634                         ip_file = system_hostfile;
635                         ip_status = check_host_in_hostfile(ip_file, ip,
636                             host_key, ip_key, &ip_line);
637                 }
638                 if (host_status == HOST_CHANGED &&
639                     (ip_status != HOST_CHANGED || !key_equal(ip_key, file_key)))
640                         host_ip_differ = 1;
641
642                 key_free(ip_key);
643         } else
644                 ip_status = host_status;
645
646         key_free(file_key);
647
648         switch (host_status) {
649         case HOST_OK:
650                 /* The host is known and the key matches. */
651                 debug("Host '%.200s' is known and matches the %s host key.",
652                     host, type);
653                 debug("Found key in %s:%d", host_file, host_line);
654                 if (options.check_host_ip && ip_status == HOST_NEW) {
655                         if (readonly)
656                                 logit("%s host key for IP address "
657                                     "'%.128s' not in list of known hosts.",
658                                     type, ip);
659                         else if (!add_host_to_hostfile(user_hostfile, ip,
660                             host_key, options.hash_known_hosts))
661                                 logit("Failed to add the %s host key for IP "
662                                     "address '%.128s' to the list of known "
663                                     "hosts (%.30s).", type, ip, user_hostfile);
664                         else
665                                 logit("Warning: Permanently added the %s host "
666                                     "key for IP address '%.128s' to the list "
667                                     "of known hosts.", type, ip);
668                 }
669                 break;
670         case HOST_NEW:
671                 if (readonly)
672                         goto fail;
673                 /* The host is new. */
674                 if (options.strict_host_key_checking == 1) {
675                         /*
676                          * User has requested strict host key checking.  We
677                          * will not add the host key automatically.  The only
678                          * alternative left is to abort.
679                          */
680                         error("No %s host key is known for %.200s and you "
681                             "have requested strict checking.", type, host);
682                         goto fail;
683                 } else if (options.strict_host_key_checking == 2) {
684                         char msg1[1024], msg2[1024];
685
686                         if (show_other_keys(host, host_key))
687                                 snprintf(msg1, sizeof(msg1),
688                                     "\nbut keys of different type are already"
689                                     " known for this host.");
690                         else
691                                 snprintf(msg1, sizeof(msg1), ".");
692                         /* The default */
693                         fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
694                         msg2[0] = '\0';
695                         if (options.verify_host_key_dns) {
696                                 if (matching_host_key_dns)
697                                         snprintf(msg2, sizeof(msg2),
698                                             "Matching host key fingerprint"
699                                             " found in DNS.\n");
700                                 else
701                                         snprintf(msg2, sizeof(msg2),
702                                             "No matching host key fingerprint"
703                                             " found in DNS.\n");
704                         }
705                         snprintf(msg, sizeof(msg),
706                             "The authenticity of host '%.200s (%s)' can't be "
707                             "established%s\n"
708                             "%s key fingerprint is %s.\n%s"
709                             "Are you sure you want to continue connecting "
710                             "(yes/no)? ",
711                             host, ip, msg1, type, fp, msg2);
712                         xfree(fp);
713                         if (!confirm(msg))
714                                 goto fail;
715                 }
716                 /*
717                  * If not in strict mode, add the key automatically to the
718                  * local known_hosts file.
719                  */
720                 if (options.check_host_ip && ip_status == HOST_NEW) {
721                         snprintf(hostline, sizeof(hostline), "%s,%s",
722                             host, ip);
723                         hostp = hostline;
724                         if (options.hash_known_hosts) {
725                                 /* Add hash of host and IP separately */
726                                 r = add_host_to_hostfile(user_hostfile, host,
727                                     host_key, options.hash_known_hosts) &&
728                                     add_host_to_hostfile(user_hostfile, ip,
729                                     host_key, options.hash_known_hosts);
730                         } else {
731                                 /* Add unhashed "host,ip" */
732                                 r = add_host_to_hostfile(user_hostfile,
733                                     hostline, host_key,
734                                     options.hash_known_hosts);
735                         }
736                 } else {
737                         r = add_host_to_hostfile(user_hostfile, host, host_key,
738                             options.hash_known_hosts);
739                         hostp = host;
740                 }
741
742                 if (!r)
743                         logit("Failed to add the host to the list of known "
744                             "hosts (%.500s).", user_hostfile);
745                 else
746                         logit("Warning: Permanently added '%.200s' (%s) to the "
747                             "list of known hosts.", hostp, type);
748                 break;
749         case HOST_CHANGED:
750                 if (options.check_host_ip && host_ip_differ) {
751                         char *key_msg;
752                         if (ip_status == HOST_NEW)
753                                 key_msg = "is unknown";
754                         else if (ip_status == HOST_OK)
755                                 key_msg = "is unchanged";
756                         else
757                                 key_msg = "has a different value";
758                         error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
759                         error("@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @");
760                         error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
761                         error("The %s host key for %s has changed,", type, host);
762                         error("and the key for the according IP address %s", ip);
763                         error("%s. This could either mean that", key_msg);
764                         error("DNS SPOOFING is happening or the IP address for the host");
765                         error("and its host key have changed at the same time.");
766                         if (ip_status != HOST_NEW)
767                                 error("Offending key for IP in %s:%d", ip_file, ip_line);
768                 }
769                 /* The host key has changed. */
770                 warn_changed_key(host_key);
771                 error("Add correct host key in %.100s to get rid of this message.",
772                     user_hostfile);
773                 error("Offending key in %s:%d", host_file, host_line);
774
775                 /*
776                  * If strict host key checking is in use, the user will have
777                  * to edit the key manually and we can only abort.
778                  */
779                 if (options.strict_host_key_checking) {
780                         error("%s host key for %.200s has changed and you have "
781                             "requested strict checking.", type, host);
782                         goto fail;
783                 }
784
785                 /*
786                  * If strict host key checking has not been requested, allow
787                  * the connection but without MITM-able authentication or
788                  * forwarding.
789                  */
790                 if (options.password_authentication) {
791                         error("Password authentication is disabled to avoid "
792                             "man-in-the-middle attacks.");
793                         options.password_authentication = 0;
794                 }
795                 if (options.kbd_interactive_authentication) {
796                         error("Keyboard-interactive authentication is disabled"
797                             " to avoid man-in-the-middle attacks.");
798                         options.kbd_interactive_authentication = 0;
799                         options.challenge_response_authentication = 0;
800                 }
801                 if (options.challenge_response_authentication) {
802                         error("Challenge/response authentication is disabled"
803                             " to avoid man-in-the-middle attacks.");
804                         options.challenge_response_authentication = 0;
805                 }
806                 if (options.forward_agent) {
807                         error("Agent forwarding is disabled to avoid "
808                             "man-in-the-middle attacks.");
809                         options.forward_agent = 0;
810                 }
811                 if (options.forward_x11) {
812                         error("X11 forwarding is disabled to avoid "
813                             "man-in-the-middle attacks.");
814                         options.forward_x11 = 0;
815                 }
816                 if (options.num_local_forwards > 0 ||
817                     options.num_remote_forwards > 0) {
818                         error("Port forwarding is disabled to avoid "
819                             "man-in-the-middle attacks.");
820                         options.num_local_forwards =
821                             options.num_remote_forwards = 0;
822                 }
823                 if (options.tun_open != SSH_TUNMODE_NO) {
824                         error("Tunnel forwarding is disabled to avoid "
825                             "man-in-the-middle attacks.");
826                         options.tun_open = SSH_TUNMODE_NO;
827                 }
828                 /*
829                  * XXX Should permit the user to change to use the new id.
830                  * This could be done by converting the host key to an
831                  * identifying sentence, tell that the host identifies itself
832                  * by that sentence, and ask the user if he/she whishes to
833                  * accept the authentication.
834                  */
835                 break;
836         case HOST_FOUND:
837                 fatal("internal error");
838                 break;
839         }
840
841         if (options.check_host_ip && host_status != HOST_CHANGED &&
842             ip_status == HOST_CHANGED) {
843                 snprintf(msg, sizeof(msg),
844                     "Warning: the %s host key for '%.200s' "
845                     "differs from the key for the IP address '%.128s'"
846                     "\nOffending key for IP in %s:%d",
847                     type, host, ip, ip_file, ip_line);
848                 if (host_status == HOST_OK) {
849                         len = strlen(msg);
850                         snprintf(msg + len, sizeof(msg) - len,
851                             "\nMatching host key in %s:%d",
852                             host_file, host_line);
853                 }
854                 if (options.strict_host_key_checking == 1) {
855                         logit("%s", msg);
856                         error("Exiting, you have requested strict checking.");
857                         goto fail;
858                 } else if (options.strict_host_key_checking == 2) {
859                         strlcat(msg, "\nAre you sure you want "
860                             "to continue connecting (yes/no)? ", sizeof(msg));
861                         if (!confirm(msg))
862                                 goto fail;
863                 } else {
864                         logit("%s", msg);
865                 }
866         }
867
868         xfree(ip);
869         xfree(host);
870         return 0;
871
872 fail:
873         xfree(ip);
874         xfree(host);
875         return -1;
876 }
877
878 /* returns 0 if key verifies or -1 if key does NOT verify */
879 int
880 verify_host_key(char *host, struct sockaddr *hostaddr, Key *host_key)
881 {
882         struct stat st;
883         int flags = 0;
884
885         if (options.verify_host_key_dns &&
886             verify_host_key_dns(host, hostaddr, host_key, &flags) == 0) {
887
888                 if (flags & DNS_VERIFY_FOUND) {
889
890                         if (options.verify_host_key_dns == 1 &&
891                             flags & DNS_VERIFY_MATCH &&
892                             flags & DNS_VERIFY_SECURE)
893                                 return 0;
894
895                         if (flags & DNS_VERIFY_MATCH) {
896                                 matching_host_key_dns = 1;
897                         } else {
898                                 warn_changed_key(host_key);
899                                 error("Update the SSHFP RR in DNS with the new "
900                                     "host key to get rid of this message.");
901                         }
902                 }
903         }
904
905         /* return ok if the key can be found in an old keyfile */
906         if (stat(options.system_hostfile2, &st) == 0 ||
907             stat(options.user_hostfile2, &st) == 0) {
908                 if (check_host_key(host, hostaddr, host_key, /*readonly*/ 1,
909                     options.user_hostfile2, options.system_hostfile2) == 0)
910                         return 0;
911         }
912         return check_host_key(host, hostaddr, host_key, /*readonly*/ 0,
913             options.user_hostfile, options.system_hostfile);
914 }
915
916 /*
917  * Starts a dialog with the server, and authenticates the current user on the
918  * server.  This does not need any extra privileges.  The basic connection
919  * to the server must already have been established before this is called.
920  * If login fails, this function prints an error and never returns.
921  * This function does not require super-user privileges.
922  */
923 void
924 ssh_login(Sensitive *sensitive, const char *orighost,
925     struct sockaddr *hostaddr, struct passwd *pw)
926 {
927         char *host, *cp;
928         char *server_user, *local_user;
929
930         local_user = xstrdup(pw->pw_name);
931         server_user = options.user ? options.user : local_user;
932
933         /* Convert the user-supplied hostname into all lowercase. */
934         host = xstrdup(orighost);
935         for (cp = host; *cp; cp++)
936                 if (isupper(*cp))
937                         *cp = (char)tolower(*cp);
938
939         /* Exchange protocol version identification strings with the server. */
940         ssh_exchange_identification();
941
942         /* Put the connection into non-blocking mode. */
943         packet_set_nonblocking();
944
945         /* key exchange */
946         /* authenticate user */
947         if (compat20) {
948                 ssh_kex2(host, hostaddr);
949                 ssh_userauth2(local_user, server_user, host, sensitive);
950         } else {
951                 ssh_kex(host, hostaddr);
952                 ssh_userauth1(local_user, server_user, host, sensitive);
953         }
954         xfree(local_user);
955 }
956
957 void
958 ssh_put_password(char *password)
959 {
960         int size;
961         char *padded;
962
963         if (datafellows & SSH_BUG_PASSWORDPAD) {
964                 packet_put_cstring(password);
965                 return;
966         }
967         size = roundup(strlen(password) + 1, 32);
968         padded = xcalloc(1, size);
969         strlcpy(padded, password, size);
970         packet_put_string(padded, size);
971         memset(padded, 0, size);
972         xfree(padded);
973 }
974
975 static int
976 show_key_from_file(const char *file, const char *host, int keytype)
977 {
978         Key *found;
979         char *fp;
980         int line, ret;
981
982         found = key_new(keytype);
983         if ((ret = lookup_key_in_hostfile_by_type(file, host,
984             keytype, found, &line))) {
985                 fp = key_fingerprint(found, SSH_FP_MD5, SSH_FP_HEX);
986                 logit("WARNING: %s key found for host %s\n"
987                     "in %s:%d\n"
988                     "%s key fingerprint %s.",
989                     key_type(found), host, file, line,
990                     key_type(found), fp);
991                 xfree(fp);
992         }
993         key_free(found);
994         return (ret);
995 }
996
997 /* print all known host keys for a given host, but skip keys of given type */
998 static int
999 show_other_keys(const char *host, Key *key)
1000 {
1001         int type[] = { KEY_RSA1, KEY_RSA, KEY_DSA, -1};
1002         int i, found = 0;
1003
1004         for (i = 0; type[i] != -1; i++) {
1005                 if (type[i] == key->type)
1006                         continue;
1007                 if (type[i] != KEY_RSA1 &&
1008                     show_key_from_file(options.user_hostfile2, host, type[i])) {
1009                         found = 1;
1010                         continue;
1011                 }
1012                 if (type[i] != KEY_RSA1 &&
1013                     show_key_from_file(options.system_hostfile2, host, type[i])) {
1014                         found = 1;
1015                         continue;
1016                 }
1017                 if (show_key_from_file(options.user_hostfile, host, type[i])) {
1018                         found = 1;
1019                         continue;
1020                 }
1021                 if (show_key_from_file(options.system_hostfile, host, type[i])) {
1022                         found = 1;
1023                         continue;
1024                 }
1025                 debug2("no key of type %d for host %s", type[i], host);
1026         }
1027         return (found);
1028 }
1029
1030 static void
1031 warn_changed_key(Key *host_key)
1032 {
1033         char *fp;
1034         const char *type = key_type(host_key);
1035
1036         fp = key_fingerprint(host_key, SSH_FP_MD5, SSH_FP_HEX);
1037
1038         error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1039         error("@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1040         error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1041         error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1042         error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1043         error("It is also possible that the %s host key has just been changed.", type);
1044         error("The fingerprint for the %s key sent by the remote host is\n%s.",
1045             type, fp);
1046         error("Please contact your system administrator.");
1047
1048         xfree(fp);
1049 }
1050
1051 /*
1052  * Execute a local command
1053  */
1054 int
1055 ssh_local_cmd(const char *args)
1056 {
1057         char *shell;
1058         pid_t pid;
1059         int status;
1060
1061         if (!options.permit_local_command ||
1062             args == NULL || !*args)
1063                 return (1);
1064
1065         if ((shell = getenv("SHELL")) == NULL)
1066                 shell = _PATH_BSHELL;
1067
1068         pid = fork();
1069         if (pid == 0) {
1070                 debug3("Executing %s -c \"%s\"", shell, args);
1071                 execl(shell, shell, "-c", args, (char *)NULL);
1072                 error("Couldn't execute %s -c \"%s\": %s",
1073                     shell, args, strerror(errno));
1074                 _exit(1);
1075         } else if (pid == -1)
1076                 fatal("fork failed: %.100s", strerror(errno));
1077         while (waitpid(pid, &status, 0) == -1)
1078                 if (errno != EINTR)
1079                         fatal("Couldn't wait for child: %s", strerror(errno));
1080
1081         if (!WIFEXITED(status))
1082                 return (1);
1083
1084         return (WEXITSTATUS(status));
1085 }
This page took 0.185015 seconds and 5 git commands to generate.