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