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