1 /* $OpenBSD: clientloop.c,v 1.213 2009/07/05 19:28:33 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 * The main loop for the interactive session (client side).
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 *
14 *
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 *
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
40 *
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
43 * are met:
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60 */
61
62
63 #include <sys/param.h>
64 #include <sys/ioctl.h>
65 #include <sys/stat.h>
66 #include <sys/socket.h>
67 #include <sys/time.h>
68 #include <sys/queue.h>
69
70 #include <ctype.h>
71 #include <errno.h>
72 #include <paths.h>
73 #include <signal.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <termios.h>
78 #include <pwd.h>
79 #include <unistd.h>
80
81 #include "xmalloc.h"
82 #include "ssh.h"
83 #include "ssh1.h"
84 #include "ssh2.h"
85 #include "packet.h"
86 #include "buffer.h"
87 #include "compat.h"
88 #include "channels.h"
89 #include "dispatch.h"
90 #include "key.h"
91 #include "cipher.h"
92 #include "kex.h"
93 #include "log.h"
94 #include "readconf.h"
95 #include "clientloop.h"
96 #include "sshconnect.h"
97 #include "authfd.h"
98 #include "atomicio.h"
99 #include "sshpty.h"
100 #include "misc.h"
101 #include "match.h"
102 #include "msg.h"
103 #include "roaming.h"
104
105 __RCSID("$MirOS: src/usr.bin/ssh/clientloop.c,v 1.17 2009/10/04 14:29:03 tg Exp $");
106
107 /* import options */
108 extern Options options;
109
110 /* Flag indicating that stdin should be redirected from /dev/null. */
111 extern int stdin_null_flag;
112
113 /* Flag indicating that no shell has been requested */
114 extern int no_shell_flag;
115
116 /* Control socket */
117 extern int muxserver_sock;
118
119 /*
120 * Name of the host we are connecting to. This is the name given on the
121 * command line, or the Hostname specified for the user-supplied name in a
122 * configuration file.
123 */
124 extern char *host;
125
126 /*
127 * Flag to indicate that we have received a window change signal which has
128 * not yet been processed. This will cause a message indicating the new
129 * window size to be sent to the server a little later. This is volatile
130 * because this is updated in a signal handler.
131 */
132 static volatile sig_atomic_t received_window_change_signal = 0;
133 static volatile sig_atomic_t received_signal = 0;
134
135 /* Flag indicating whether the user's terminal is in non-blocking mode. */
136 static int in_non_blocking_mode = 0;
137
138 /* Common data for the client loop code. */
139 static volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
140 static int escape_char1; /* Escape character. (proto1 only) */
141 static int escape_pending1; /* Last character was an escape (proto1 only) */
142 static int last_was_cr; /* Last character was a newline. */
143 static int exit_status; /* Used to store the command exit status. */
144 static int stdin_eof; /* EOF has been encountered on stderr. */
145 static Buffer stdin_buffer; /* Buffer for stdin data. */
146 static Buffer stdout_buffer; /* Buffer for stdout data. */
147 static Buffer stderr_buffer; /* Buffer for stderr data. */
148 static u_int buffer_high;/* Soft max buffer size. */
149 static int connection_in; /* Connection to server (input). */
150 static int connection_out; /* Connection to server (output). */
151 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
152 static int session_closed = 0; /* In SSH2: login session closed. */
153
154 static void client_init_dispatch(void);
155 int session_ident = -1;
156
157 /* Track escape per proto2 channel */
158 struct escape_filter_ctx {
159 int escape_pending;
160 int escape_char;
161 };
162
163 /* Context for channel confirmation replies */
164 struct channel_reply_ctx {
165 const char *request_type;
166 int id, do_close;
167 };
168
169 /* Global request success/failure callbacks */
170 struct global_confirm {
171 TAILQ_ENTRY(global_confirm) entry;
172 global_confirm_cb *cb;
173 void *ctx;
174 int ref_count;
175 };
176 TAILQ_HEAD(global_confirms, global_confirm);
177 static struct global_confirms global_confirms =
178 TAILQ_HEAD_INITIALIZER(global_confirms);
179
180 /*XXX*/
181 extern Kex *xxx_kex;
182
183 void ssh_process_session2_setup(int, int, int, Buffer *);
184
185 /* Restores stdin to blocking mode. */
186
187 static void
leave_non_blocking(void)188 leave_non_blocking(void)
189 {
190 if (in_non_blocking_mode) {
191 unset_nonblock(fileno(stdin));
192 in_non_blocking_mode = 0;
193 }
194 }
195
196 /* Puts stdin terminal in non-blocking mode. */
197
198 static void
enter_non_blocking(void)199 enter_non_blocking(void)
200 {
201 in_non_blocking_mode = 1;
202 set_nonblock(fileno(stdin));
203 }
204
205 /*
206 * Signal handler for the window change signal (SIGWINCH). This just sets a
207 * flag indicating that the window has changed.
208 */
209 /*ARGSUSED */
210 static void
window_change_handler(int sig)211 window_change_handler(int sig)
212 {
213 received_window_change_signal = 1;
214 signal(SIGWINCH, window_change_handler);
215 }
216
217 /*
218 * Signal handler for signals that cause the program to terminate. These
219 * signals must be trapped to restore terminal modes.
220 */
221 /*ARGSUSED */
222 static void
signal_handler(int sig)223 signal_handler(int sig)
224 {
225 received_signal = sig;
226 quit_pending = 1;
227 }
228
229 /*
230 * Returns current time in seconds from Jan 1, 1970 with the maximum
231 * available resolution.
232 */
233
234 static double
get_current_time(void)235 get_current_time(void)
236 {
237 struct timeval tv;
238 gettimeofday(&tv, NULL);
239 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
240 }
241
242 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
243 void
client_x11_get_proto(const char * display,const char * xauth_path,u_int trusted,char ** _proto,char ** _data)244 client_x11_get_proto(const char *display, const char *xauth_path,
245 u_int trusted, char **_proto, char **_data)
246 {
247 char cmd[1024];
248 char line[512];
249 char xdisplay[512];
250 static char proto[512], data[512];
251 FILE *f;
252 int got_data = 0, generated = 0, do_unlink = 0, i;
253 char *xauthdir, *xauthfile;
254 struct stat st;
255
256 xauthdir = xauthfile = NULL;
257 *_proto = proto;
258 *_data = data;
259 proto[0] = data[0] = '\0';
260
261 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
262 debug("No xauth program.");
263 } else {
264 if (display == NULL) {
265 debug("x11_get_proto: DISPLAY not set");
266 return;
267 }
268 /*
269 * Handle FamilyLocal case where $DISPLAY does
270 * not match an authorisation entry. For this we
271 * just try "xauth list unix:displaynum.screennum".
272 * XXX: "localhost" match to determine FamilyLocal
273 * is not perfect.
274 */
275 if (strncmp(display, "localhost:", 10) == 0) {
276 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
277 display + 10);
278 display = xdisplay;
279 }
280 if (trusted == 0) {
281 xauthdir = xmalloc(MAXPATHLEN);
282 xauthfile = xmalloc(MAXPATHLEN);
283 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
284 if (mkdtemp(xauthdir) != NULL) {
285 do_unlink = 1;
286 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
287 xauthdir);
288 snprintf(cmd, sizeof(cmd),
289 "%s -f %s generate %s " SSH_X11_PROTO
290 " untrusted timeout 1200 2>" _PATH_DEVNULL,
291 xauth_path, xauthfile, display);
292 debug2("x11_get_proto: %s", cmd);
293 if (system(cmd) == 0)
294 generated = 1;
295 }
296 }
297
298 /*
299 * When in untrusted mode, we read the cookie only if it was
300 * successfully generated as an untrusted one in the step
301 * above.
302 */
303 if (trusted || generated) {
304 snprintf(cmd, sizeof(cmd),
305 "%s %s%s list %s 2>" _PATH_DEVNULL,
306 xauth_path,
307 generated ? "-f " : "" ,
308 generated ? xauthfile : "",
309 display);
310 debug2("x11_get_proto: %s", cmd);
311 f = popen(cmd, "r");
312 if (f && fgets(line, sizeof(line), f) &&
313 sscanf(line, "%*s %511s %511s", proto, data) == 2)
314 got_data = 1;
315 if (f)
316 pclose(f);
317 } else
318 error("Warning: untrusted X11 forwarding setup failed: "
319 "xauth key data not generated");
320 }
321
322 if (do_unlink) {
323 unlink(xauthfile);
324 rmdir(xauthdir);
325 }
326 if (xauthdir)
327 xfree(xauthdir);
328 if (xauthfile)
329 xfree(xauthfile);
330
331 /*
332 * If we didn't get authentication data, just make up some
333 * data. The forwarding code will check the validity of the
334 * response anyway, and substitute this data. The X11
335 * server, however, will ignore this fake data and use
336 * whatever authentication mechanisms it was using otherwise
337 * for the local connection.
338 */
339 if (!got_data) {
340 u_int32_t rnd = 0;
341
342 logit("Warning: No xauth data; "
343 "using fake authentication data for X11 forwarding.");
344 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
345 for (i = 0; i < 16; i++) {
346 if (i % 4 == 0)
347 rnd = arc4random();
348 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
349 rnd & 0xff);
350 rnd >>= 8;
351 }
352 }
353 }
354
355 /*
356 * This is called when the interactive is entered. This checks if there is
357 * an EOF coming on stdin. We must check this explicitly, as select() does
358 * not appear to wake up when redirecting from /dev/null.
359 */
360
361 static void
client_check_initial_eof_on_stdin(void)362 client_check_initial_eof_on_stdin(void)
363 {
364 int len;
365 char buf[1];
366
367 /*
368 * If standard input is to be "redirected from /dev/null", we simply
369 * mark that we have seen an EOF and send an EOF message to the
370 * server. Otherwise, we try to read a single character; it appears
371 * that for some files, such /dev/null, select() never wakes up for
372 * read for this descriptor, which means that we never get EOF. This
373 * way we will get the EOF if stdin comes from /dev/null or similar.
374 */
375 if (stdin_null_flag) {
376 /* Fake EOF on stdin. */
377 debug("Sending eof.");
378 stdin_eof = 1;
379 packet_start(SSH_CMSG_EOF);
380 packet_send();
381 } else {
382 enter_non_blocking();
383
384 /* Check for immediate EOF on stdin. */
385 len = read(fileno(stdin), buf, 1);
386 if (len == 0) {
387 /*
388 * EOF. Record that we have seen it and send
389 * EOF to server.
390 */
391 debug("Sending eof.");
392 stdin_eof = 1;
393 packet_start(SSH_CMSG_EOF);
394 packet_send();
395 } else if (len > 0) {
396 /*
397 * Got data. We must store the data in the buffer,
398 * and also process it as an escape character if
399 * appropriate.
400 */
401 if ((u_char) buf[0] == escape_char1)
402 escape_pending1 = 1;
403 else
404 buffer_append(&stdin_buffer, buf, 1);
405 }
406 leave_non_blocking();
407 }
408 }
409
410
411 /*
412 * Make packets from buffered stdin data, and buffer them for sending to the
413 * connection.
414 */
415
416 static void
client_make_packets_from_stdin_data(void)417 client_make_packets_from_stdin_data(void)
418 {
419 u_int len;
420
421 /* Send buffered stdin data to the server. */
422 while (buffer_len(&stdin_buffer) > 0 &&
423 packet_not_very_much_data_to_write()) {
424 len = buffer_len(&stdin_buffer);
425 /* Keep the packets at reasonable size. */
426 if (len > packet_get_maxsize())
427 len = packet_get_maxsize();
428 packet_start(SSH_CMSG_STDIN_DATA);
429 packet_put_string(buffer_ptr(&stdin_buffer), len);
430 packet_send();
431 buffer_consume(&stdin_buffer, len);
432 /* If we have a pending EOF, send it now. */
433 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
434 packet_start(SSH_CMSG_EOF);
435 packet_send();
436 }
437 }
438 }
439
440 /*
441 * Checks if the client window has changed, and sends a packet about it to
442 * the server if so. The actual change is detected elsewhere (by a software
443 * interrupt on Unix); this just checks the flag and sends a message if
444 * appropriate.
445 */
446
447 static void
client_check_window_change(void)448 client_check_window_change(void)
449 {
450 struct winsize ws;
451
452 if (! received_window_change_signal)
453 return;
454 /** XXX race */
455 received_window_change_signal = 0;
456
457 debug2("client_check_window_change: changed");
458
459 if (compat20) {
460 channel_send_window_changes();
461 } else {
462 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
463 return;
464 packet_start(SSH_CMSG_WINDOW_SIZE);
465 packet_put_int((u_int)ws.ws_row);
466 packet_put_int((u_int)ws.ws_col);
467 packet_put_int((u_int)ws.ws_xpixel);
468 packet_put_int((u_int)ws.ws_ypixel);
469 packet_send();
470 }
471 }
472
473 static void
client_global_request_reply(int type,u_int32_t seq,void * ctxt)474 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
475 {
476 struct global_confirm *gc;
477
478 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
479 return;
480 if (gc->cb != NULL)
481 gc->cb(type, seq, gc->ctx);
482 if (--gc->ref_count <= 0) {
483 TAILQ_REMOVE(&global_confirms, gc, entry);
484 bzero(gc, sizeof(*gc));
485 xfree(gc);
486 }
487
488 packet_set_alive_timeouts(0);
489 }
490
491 static void
server_alive_check(void)492 server_alive_check(void)
493 {
494 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
495 logit("Timeout, server not responding.");
496 cleanup_exit(255);
497 }
498 packet_start(SSH2_MSG_GLOBAL_REQUEST);
499 packet_put_cstring("keepalive@openssh.com");
500 packet_put_char(1); /* boolean: want reply */
501 packet_send();
502 /* Insert an empty placeholder to maintain ordering */
503 client_register_global_confirm(NULL, NULL);
504 }
505
506 /*
507 * Waits until the client can do something (some data becomes available on
508 * one of the file descriptors).
509 */
510 static void
client_wait_until_can_do_something(fd_set ** readsetp,fd_set ** writesetp,int * maxfdp,u_int * nallocp,int rekeying)511 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
512 int *maxfdp, u_int *nallocp, int rekeying)
513 {
514 struct timeval tv, *tvp;
515 int ret;
516
517 /* Add any selections by the channel mechanism. */
518 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
519
520 if (!compat20) {
521 /* Read from the connection, unless our buffers are full. */
522 if (buffer_len(&stdout_buffer) < buffer_high &&
523 buffer_len(&stderr_buffer) < buffer_high &&
524 channel_not_very_much_buffered_data())
525 FD_SET(connection_in, *readsetp);
526 /*
527 * Read from stdin, unless we have seen EOF or have very much
528 * buffered data to send to the server.
529 */
530 if (!stdin_eof && packet_not_very_much_data_to_write())
531 FD_SET(fileno(stdin), *readsetp);
532
533 /* Select stdout/stderr if have data in buffer. */
534 if (buffer_len(&stdout_buffer) > 0)
535 FD_SET(fileno(stdout), *writesetp);
536 if (buffer_len(&stderr_buffer) > 0)
537 FD_SET(fileno(stderr), *writesetp);
538 } else {
539 /* channel_prepare_select could have closed the last channel */
540 if (session_closed && !channel_still_open() &&
541 !packet_have_data_to_write()) {
542 /* clear mask since we did not call select() */
543 memset(*readsetp, 0, *nallocp);
544 memset(*writesetp, 0, *nallocp);
545 return;
546 } else {
547 FD_SET(connection_in, *readsetp);
548 }
549 }
550
551 /* Select server connection if have data to write to the server. */
552 if (packet_have_data_to_write())
553 FD_SET(connection_out, *writesetp);
554
555 if (muxserver_sock != -1)
556 FD_SET(muxserver_sock, *readsetp);
557
558 /*
559 * Wait for something to happen. This will suspend the process until
560 * some selected descriptor can be read, written, or has some other
561 * event pending.
562 */
563
564 if (options.server_alive_interval == 0 || !compat20)
565 tvp = NULL;
566 else {
567 tv.tv_sec = options.server_alive_interval;
568 tv.tv_usec = 0;
569 tvp = &tv;
570 }
571 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
572 if (ret < 0) {
573 char buf[100];
574
575 /*
576 * We have to clear the select masks, because we return.
577 * We have to return, because the mainloop checks for the flags
578 * set by the signal handlers.
579 */
580 memset(*readsetp, 0, *nallocp);
581 memset(*writesetp, 0, *nallocp);
582
583 if (errno == EINTR)
584 return;
585 /* Note: we might still have data in the buffers. */
586 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
587 buffer_append(&stderr_buffer, buf, strlen(buf));
588 quit_pending = 1;
589 } else if (ret == 0)
590 server_alive_check();
591 }
592
593 static void
client_suspend_self(Buffer * bin,Buffer * bout,Buffer * berr)594 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
595 {
596 /* Flush stdout and stderr buffers. */
597 if (buffer_len(bout) > 0)
598 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
599 buffer_len(bout));
600 if (buffer_len(berr) > 0)
601 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
602 buffer_len(berr));
603
604 leave_raw_mode();
605
606 /*
607 * Free (and clear) the buffer to reduce the amount of data that gets
608 * written to swap.
609 */
610 buffer_free(bin);
611 buffer_free(bout);
612 buffer_free(berr);
613
614 /* Send the suspend signal to the program itself. */
615 kill(getpid(), SIGTSTP);
616
617 /* Reset window sizes in case they have changed */
618 received_window_change_signal = 1;
619
620 /* OK, we have been continued by the user. Reinitialize buffers. */
621 buffer_init(bin);
622 buffer_init(bout);
623 buffer_init(berr);
624
625 enter_raw_mode();
626 }
627
628 static void
client_process_net_input(fd_set * readset)629 client_process_net_input(fd_set *readset)
630 {
631 int len, cont = 0;
632 char buf[8192];
633
634 /*
635 * Read input from the server, and add any such data to the buffer of
636 * the packet subsystem.
637 */
638 if (FD_ISSET(connection_in, readset)) {
639 /* Read as much as possible. */
640 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
641 if (len == 0 && cont == 0) {
642 /*
643 * Received EOF. The remote host has closed the
644 * connection.
645 */
646 snprintf(buf, sizeof buf,
647 "Connection to %.300s closed by remote host.\r\n",
648 host);
649 buffer_append(&stderr_buffer, buf, strlen(buf));
650 quit_pending = 1;
651 return;
652 }
653 /*
654 * There is a kernel bug on Solaris that causes select to
655 * sometimes wake up even though there is no data available.
656 */
657 if (len < 0 && (errno == EAGAIN || errno == EINTR))
658 len = 0;
659
660 if (len < 0) {
661 /*
662 * An error has encountered. Perhaps there is a
663 * network problem.
664 */
665 snprintf(buf, sizeof buf,
666 "Read from remote host %.300s: %.100s\r\n",
667 host, strerror(errno));
668 buffer_append(&stderr_buffer, buf, strlen(buf));
669 quit_pending = 1;
670 return;
671 }
672 packet_process_incoming(buf, len);
673 }
674 }
675
676 static void
client_status_confirm(int type,Channel * c,void * ctx)677 client_status_confirm(int type, Channel *c, void *ctx)
678 {
679 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
680 char errmsg[256];
681 int tochan;
682
683 /* XXX supress on mux _client_ quietmode */
684 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
685 c->ctl_fd != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
686
687 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
688 debug2("%s request accepted on channel %d",
689 cr->request_type, c->self);
690 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
691 if (tochan) {
692 snprintf(errmsg, sizeof(errmsg),
693 "%s request failed\r\n", cr->request_type);
694 } else {
695 snprintf(errmsg, sizeof(errmsg),
696 "%s request failed on channel %d",
697 cr->request_type, c->self);
698 }
699 /* If error occurred on primary session channel, then exit */
700 if (cr->do_close && c->self == session_ident)
701 fatal("%s", errmsg);
702 /* If error occurred on mux client, append to their stderr */
703 if (tochan)
704 buffer_append(&c->extended, errmsg, strlen(errmsg));
705 else
706 error("%s", errmsg);
707 if (cr->do_close) {
708 chan_read_failed(c);
709 chan_write_failed(c);
710 }
711 }
712 xfree(cr);
713 }
714
715 static void
client_abandon_status_confirm(Channel * c,void * ctx)716 client_abandon_status_confirm(Channel *c, void *ctx)
717 {
718 xfree(ctx);
719 }
720
721 static void
client_expect_confirm(int id,const char * request,int do_close)722 client_expect_confirm(int id, const char *request, int do_close)
723 {
724 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
725
726 cr->request_type = request;
727 cr->do_close = do_close;
728
729 channel_register_status_confirm(id, client_status_confirm,
730 client_abandon_status_confirm, cr);
731 }
732
733 void
client_register_global_confirm(global_confirm_cb * cb,void * ctx)734 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
735 {
736 struct global_confirm *gc, *last_gc;
737
738 /* Coalesce identical callbacks */
739 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
740 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
741 if (++last_gc->ref_count >= INT_MAX)
742 fatal("%s: last_gc->ref_count = %d",
743 __func__, last_gc->ref_count);
744 return;
745 }
746
747 gc = xmalloc(sizeof(*gc));
748 gc->cb = cb;
749 gc->ctx = ctx;
750 gc->ref_count = 1;
751 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
752 }
753
754 static void
process_cmdline(void)755 process_cmdline(void)
756 {
757 void (*handler)(int);
758 char *s, *cmd, *cancel_host;
759 int delete = 0;
760 int local = 0, remote = 0, dynamic = 0;
761 int cancel_port;
762 Forward fwd;
763
764 bzero(&fwd, sizeof(fwd));
765 fwd.listen_host = fwd.connect_host = NULL;
766
767 leave_raw_mode();
768 handler = signal(SIGINT, SIG_IGN);
769 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
770 if (s == NULL)
771 goto out;
772 while (isspace(*s))
773 s++;
774 if (*s == '-')
775 s++; /* Skip cmdline '-', if any */
776 if (*s == '\0')
777 goto out;
778
779 if (*s == 'h' || *s == 'H' || *s == '?') {
780 logit("Commands:");
781 logit(" -L[bind_address:]port:host:hostport "
782 "Request local forward");
783 logit(" -R[bind_address:]port:host:hostport "
784 "Request remote forward");
785 logit(" -D[bind_address:]port "
786 "Request dynamic forward");
787 logit(" -KR[bind_address:]port "
788 "Cancel remote forward");
789 if (!options.permit_local_command)
790 goto out;
791 logit(" !args "
792 "Execute local command");
793 goto out;
794 }
795
796 if (*s == '!' && options.permit_local_command) {
797 s++;
798 ssh_local_cmd(s);
799 goto out;
800 }
801
802 if (*s == 'K') {
803 delete = 1;
804 s++;
805 }
806 if (*s == 'L')
807 local = 1;
808 else if (*s == 'R')
809 remote = 1;
810 else if (*s == 'D')
811 dynamic = 1;
812 else {
813 logit("Invalid command.");
814 goto out;
815 }
816
817 if ((local || dynamic) && delete) {
818 logit("Not supported.");
819 goto out;
820 }
821 if (remote && delete && !compat20) {
822 logit("Not supported for SSH protocol version 1.");
823 goto out;
824 }
825
826 while (isspace(*++s))
827 ;
828
829 if (delete) {
830 cancel_port = 0;
831 cancel_host = hpdelim(&s); /* may be NULL */
832 if (s != NULL) {
833 cancel_port = a2port(s);
834 cancel_host = cleanhostname(cancel_host);
835 } else {
836 cancel_port = a2port(cancel_host);
837 cancel_host = NULL;
838 }
839 if (cancel_port <= 0) {
840 logit("Bad forwarding close port");
841 goto out;
842 }
843 channel_request_rforward_cancel(cancel_host, cancel_port);
844 } else {
845 if (!parse_forward(&fwd, s, dynamic, remote)) {
846 logit("Bad forwarding specification.");
847 goto out;
848 }
849 if (local || dynamic) {
850 if (channel_setup_local_fwd_listener(fwd.listen_host,
851 fwd.listen_port, fwd.connect_host,
852 fwd.connect_port, options.gateway_ports) < 0) {
853 logit("Port forwarding failed.");
854 goto out;
855 }
856 } else {
857 if (channel_request_remote_forwarding(fwd.listen_host,
858 fwd.listen_port, fwd.connect_host,
859 fwd.connect_port) < 0) {
860 logit("Port forwarding failed.");
861 goto out;
862 }
863 }
864
865 logit("Forwarding port.");
866 }
867
868 out:
869 signal(SIGINT, handler);
870 enter_raw_mode();
871 if (cmd)
872 xfree(cmd);
873 if (fwd.listen_host != NULL)
874 xfree(fwd.listen_host);
875 if (fwd.connect_host != NULL)
876 xfree(fwd.connect_host);
877 }
878
879 /*
880 * Process the characters one by one, call with c==NULL for proto1 case.
881 */
882 static int
process_escapes(Channel * c,Buffer * bin,Buffer * bout,Buffer * berr,char * buf,int len)883 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
884 char *buf, int len)
885 {
886 char string[1024];
887 pid_t pid;
888 int bytes = 0;
889 u_int i;
890 u_char ch;
891 char *s;
892 int *escape_pendingp, escape_char;
893 struct escape_filter_ctx *efc;
894
895 if (c == NULL) {
896 escape_pendingp = &escape_pending1;
897 escape_char = escape_char1;
898 } else {
899 if (c->filter_ctx == NULL)
900 return 0;
901 efc = (struct escape_filter_ctx *)c->filter_ctx;
902 escape_pendingp = &efc->escape_pending;
903 escape_char = efc->escape_char;
904 }
905
906 if (len <= 0)
907 return (0);
908
909 for (i = 0; i < (u_int)len; i++) {
910 /* Get one character at a time. */
911 ch = buf[i];
912
913 if (*escape_pendingp) {
914 /* We have previously seen an escape character. */
915 /* Clear the flag now. */
916 *escape_pendingp = 0;
917
918 /* Process the escaped character. */
919 switch (ch) {
920 case '.':
921 /* Terminate the connection. */
922 snprintf(string, sizeof string, "%c.\r\n",
923 escape_char);
924 buffer_append(berr, string, strlen(string));
925
926 if (c && c->ctl_fd != -1) {
927 chan_read_failed(c);
928 chan_write_failed(c);
929 return 0;
930 } else
931 quit_pending = 1;
932 return -1;
933
934 case 'Z' - 64:
935 /* XXX support this for mux clients */
936 if (c && c->ctl_fd != -1) {
937 noescape:
938 snprintf(string, sizeof string,
939 "%c%c escape not available to "
940 "multiplexed sessions\r\n",
941 escape_char, ch);
942 buffer_append(berr, string,
943 strlen(string));
944 continue;
945 }
946 /* Suspend the program. Inform the user */
947 snprintf(string, sizeof string,
948 "%c^Z [suspend ssh]\r\n", escape_char);
949 buffer_append(berr, string, strlen(string));
950
951 /* Restore terminal modes and suspend. */
952 client_suspend_self(bin, bout, berr);
953
954 /* We have been continued. */
955 continue;
956
957 case 'B':
958 if (compat20) {
959 snprintf(string, sizeof string,
960 "%cB\r\n", escape_char);
961 buffer_append(berr, string,
962 strlen(string));
963 channel_request_start(session_ident,
964 "break", 0);
965 packet_put_int(1000);
966 packet_send();
967 }
968 continue;
969
970 case 'R':
971 if (compat20) {
972 if (datafellows & SSH_BUG_NOREKEY)
973 logit("Server does not "
974 "support re-keying");
975 else
976 need_rekeying = 1;
977 }
978 continue;
979
980 case '&':
981 if (c && c->ctl_fd != -1)
982 goto noescape;
983 /*
984 * Detach the program (continue to serve
985 * connections, but put in background and no
986 * more new connections).
987 */
988 /* Restore tty modes. */
989 leave_raw_mode();
990
991 /* Stop listening for new connections. */
992 channel_stop_listening();
993
994 snprintf(string, sizeof string,
995 "%c& [backgrounded]\n", escape_char);
996 buffer_append(berr, string, strlen(string));
997
998 /* Fork into background. */
999 pid = fork();
1000 if (pid < 0) {
1001 error("fork: %.100s", strerror(errno));
1002 continue;
1003 }
1004 if (pid != 0) { /* This is the parent. */
1005 /* The parent just exits. */
1006 exit(0);
1007 }
1008 /* The child continues serving connections. */
1009 if (compat20) {
1010 buffer_append(bin, "\004", 1);
1011 /* fake EOF on stdin */
1012 return -1;
1013 } else if (!stdin_eof) {
1014 /*
1015 * Sending SSH_CMSG_EOF alone does not
1016 * always appear to be enough. So we
1017 * try to send an EOF character first.
1018 */
1019 packet_start(SSH_CMSG_STDIN_DATA);
1020 packet_put_string("\004", 1);
1021 packet_send();
1022 /* Close stdin. */
1023 stdin_eof = 1;
1024 if (buffer_len(bin) == 0) {
1025 packet_start(SSH_CMSG_EOF);
1026 packet_send();
1027 }
1028 }
1029 continue;
1030
1031 case '?':
1032 if (c && c->ctl_fd != -1) {
1033 snprintf(string, sizeof string,
1034 "%c?\r\n\
1035 Supported escape sequences:\r\n\
1036 %c. - terminate session\r\n\
1037 %cB - send a BREAK to the remote system\r\n\
1038 %cR - Request rekey (SSH protocol 2 only)\r\n\
1039 %c# - list forwarded connections\r\n\
1040 %c? - this message\r\n\
1041 %c%c - send the escape character by typing it twice\r\n\
1042 (Note that escapes are only recognized immediately after newline.)\r\n",
1043 escape_char, escape_char,
1044 escape_char, escape_char,
1045 escape_char, escape_char,
1046 escape_char, escape_char);
1047 } else {
1048 snprintf(string, sizeof string,
1049 "%c?\r\n\
1050 Supported escape sequences:\r\n\
1051 %c. - terminate connection (and any multiplexed sessions)\r\n\
1052 %cB - send a BREAK to the remote system\r\n\
1053 %cC - open a command line\r\n\
1054 %cR - Request rekey (SSH protocol 2 only)\r\n\
1055 %c^Z - suspend ssh\r\n\
1056 %c# - list forwarded connections\r\n\
1057 %c& - background ssh (when waiting for connections to terminate)\r\n\
1058 %c? - this message\r\n\
1059 %c%c - send the escape character by typing it twice\r\n\
1060 (Note that escapes are only recognized immediately after newline.)\r\n",
1061 escape_char, escape_char,
1062 escape_char, escape_char,
1063 escape_char, escape_char,
1064 escape_char, escape_char,
1065 escape_char, escape_char,
1066 escape_char);
1067 }
1068 buffer_append(berr, string, strlen(string));
1069 continue;
1070
1071 case '#':
1072 snprintf(string, sizeof string, "%c#\r\n",
1073 escape_char);
1074 buffer_append(berr, string, strlen(string));
1075 s = channel_open_message();
1076 buffer_append(berr, s, strlen(s));
1077 xfree(s);
1078 continue;
1079
1080 case 'C':
1081 if (c && c->ctl_fd != -1)
1082 goto noescape;
1083 process_cmdline();
1084 continue;
1085
1086 default:
1087 if (ch != escape_char) {
1088 buffer_put_char(bin, escape_char);
1089 bytes++;
1090 }
1091 /* Escaped characters fall through here */
1092 break;
1093 }
1094 } else {
1095 /*
1096 * The previous character was not an escape char.
1097 * Check if this is an escape.
1098 */
1099 if (last_was_cr && ch == escape_char) {
1100 /*
1101 * It is. Set the flag and continue to
1102 * next character.
1103 */
1104 *escape_pendingp = 1;
1105 continue;
1106 }
1107 }
1108
1109 /*
1110 * Normal character. Record whether it was a newline,
1111 * and append it to the buffer.
1112 */
1113 last_was_cr = (ch == '\r' || ch == '\n');
1114 buffer_put_char(bin, ch);
1115 bytes++;
1116 }
1117 return bytes;
1118 }
1119
1120 static void
client_process_input(fd_set * readset)1121 client_process_input(fd_set *readset)
1122 {
1123 int len;
1124 char buf[8192];
1125
1126 /* Read input from stdin. */
1127 if (FD_ISSET(fileno(stdin), readset)) {
1128 /* Read as much as possible. */
1129 len = read(fileno(stdin), buf, sizeof(buf));
1130 if (len < 0 && (errno == EAGAIN || errno == EINTR))
1131 return; /* we'll try again later */
1132 if (len <= 0) {
1133 /*
1134 * Received EOF or error. They are treated
1135 * similarly, except that an error message is printed
1136 * if it was an error condition.
1137 */
1138 if (len < 0) {
1139 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1140 strerror(errno));
1141 buffer_append(&stderr_buffer, buf, strlen(buf));
1142 }
1143 /* Mark that we have seen EOF. */
1144 stdin_eof = 1;
1145 /*
1146 * Send an EOF message to the server unless there is
1147 * data in the buffer. If there is data in the
1148 * buffer, no message will be sent now. Code
1149 * elsewhere will send the EOF when the buffer
1150 * becomes empty if stdin_eof is set.
1151 */
1152 if (buffer_len(&stdin_buffer) == 0) {
1153 packet_start(SSH_CMSG_EOF);
1154 packet_send();
1155 }
1156 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1157 /*
1158 * Normal successful read, and no escape character.
1159 * Just append the data to buffer.
1160 */
1161 buffer_append(&stdin_buffer, buf, len);
1162 } else {
1163 /*
1164 * Normal, successful read. But we have an escape
1165 * character and have to process the characters one
1166 * by one.
1167 */
1168 if (process_escapes(NULL, &stdin_buffer,
1169 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1170 return;
1171 }
1172 }
1173 }
1174
1175 static void
client_process_output(fd_set * writeset)1176 client_process_output(fd_set *writeset)
1177 {
1178 int len;
1179 char buf[100];
1180
1181 /* Write buffered output to stdout. */
1182 if (FD_ISSET(fileno(stdout), writeset)) {
1183 /* Write as much data as possible. */
1184 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1185 buffer_len(&stdout_buffer));
1186 if (len <= 0) {
1187 if (errno == EINTR || errno == EAGAIN)
1188 len = 0;
1189 else {
1190 /*
1191 * An error or EOF was encountered. Put an
1192 * error message to stderr buffer.
1193 */
1194 snprintf(buf, sizeof buf,
1195 "write stdout: %.50s\r\n", strerror(errno));
1196 buffer_append(&stderr_buffer, buf, strlen(buf));
1197 quit_pending = 1;
1198 return;
1199 }
1200 }
1201 /* Consume printed data from the buffer. */
1202 buffer_consume(&stdout_buffer, len);
1203 }
1204 /* Write buffered output to stderr. */
1205 if (FD_ISSET(fileno(stderr), writeset)) {
1206 /* Write as much data as possible. */
1207 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1208 buffer_len(&stderr_buffer));
1209 if (len <= 0) {
1210 if (errno == EINTR || errno == EAGAIN)
1211 len = 0;
1212 else {
1213 /*
1214 * EOF or error, but can't even print
1215 * error message.
1216 */
1217 quit_pending = 1;
1218 return;
1219 }
1220 }
1221 /* Consume printed characters from the buffer. */
1222 buffer_consume(&stderr_buffer, len);
1223 }
1224 }
1225
1226 /*
1227 * Get packets from the connection input buffer, and process them as long as
1228 * there are packets available.
1229 *
1230 * Any unknown packets received during the actual
1231 * session cause the session to terminate. This is
1232 * intended to make debugging easier since no
1233 * confirmations are sent. Any compatible protocol
1234 * extensions must be negotiated during the
1235 * preparatory phase.
1236 */
1237
1238 static void
client_process_buffered_input_packets(void)1239 client_process_buffered_input_packets(void)
1240 {
1241 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1242 compat20 ? xxx_kex : NULL);
1243 }
1244
1245 /* scan buf[] for '~' before sending data to the peer */
1246
1247 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1248 void *
client_new_escape_filter_ctx(int escape_char)1249 client_new_escape_filter_ctx(int escape_char)
1250 {
1251 struct escape_filter_ctx *ret;
1252
1253 ret = xmalloc(sizeof(*ret));
1254 ret->escape_pending = 0;
1255 ret->escape_char = escape_char;
1256 return (void *)ret;
1257 }
1258
1259 /* Free the escape filter context on channel free */
1260 void
client_filter_cleanup(int cid,void * ctx)1261 client_filter_cleanup(int cid, void *ctx)
1262 {
1263 xfree(ctx);
1264 }
1265
1266 int
client_simple_escape_filter(Channel * c,char * buf,int len)1267 client_simple_escape_filter(Channel *c, char *buf, int len)
1268 {
1269 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1270 return 0;
1271
1272 return process_escapes(c, &c->input, &c->output, &c->extended,
1273 buf, len);
1274 }
1275
1276 static void
client_channel_closed(int id,void * arg)1277 client_channel_closed(int id, void *arg)
1278 {
1279 channel_cancel_cleanup(id);
1280 session_closed = 1;
1281 leave_raw_mode();
1282 }
1283
1284 /*
1285 * Implements the interactive session with the server. This is called after
1286 * the user has been authenticated, and a command has been started on the
1287 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1288 * used as an escape character for terminating or suspending the session.
1289 */
1290
1291 int
client_loop(int have_pty,int escape_char_arg,int ssh2_chan_id)1292 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1293 {
1294 fd_set *readset = NULL, *writeset = NULL;
1295 double start_time, total_time;
1296 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1297 u_int64_t ibytes, obytes;
1298 u_int nalloc = 0;
1299 char buf[100];
1300
1301 debug("Entering interactive session.");
1302
1303 start_time = get_current_time();
1304
1305 /* Initialize variables. */
1306 escape_pending1 = 0;
1307 last_was_cr = 1;
1308 exit_status = -1;
1309 stdin_eof = 0;
1310 buffer_high = 64 * 1024;
1311 connection_in = packet_get_connection_in();
1312 connection_out = packet_get_connection_out();
1313 max_fd = MAX(connection_in, connection_out);
1314 if (muxserver_sock != -1)
1315 max_fd = MAX(max_fd, muxserver_sock);
1316
1317 if (!compat20) {
1318 /* enable nonblocking unless tty */
1319 if (!isatty(fileno(stdin)))
1320 set_nonblock(fileno(stdin));
1321 if (!isatty(fileno(stdout)))
1322 set_nonblock(fileno(stdout));
1323 if (!isatty(fileno(stderr)))
1324 set_nonblock(fileno(stderr));
1325 max_fd = MAX(max_fd, fileno(stdin));
1326 max_fd = MAX(max_fd, fileno(stdout));
1327 max_fd = MAX(max_fd, fileno(stderr));
1328 }
1329 quit_pending = 0;
1330 escape_char1 = escape_char_arg;
1331
1332 /* Initialize buffers. */
1333 buffer_init(&stdin_buffer);
1334 buffer_init(&stdout_buffer);
1335 buffer_init(&stderr_buffer);
1336
1337 client_init_dispatch();
1338
1339 /*
1340 * Set signal handlers, (e.g. to restore non-blocking mode)
1341 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1342 */
1343 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1344 signal(SIGHUP, signal_handler);
1345 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1346 signal(SIGINT, signal_handler);
1347 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1348 signal(SIGQUIT, signal_handler);
1349 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1350 signal(SIGTERM, signal_handler);
1351 signal(SIGWINCH, window_change_handler);
1352
1353 if (have_pty)
1354 enter_raw_mode();
1355
1356 if (compat20) {
1357 session_ident = ssh2_chan_id;
1358 if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1359 channel_register_filter(session_ident,
1360 client_simple_escape_filter, NULL,
1361 client_filter_cleanup,
1362 client_new_escape_filter_ctx(escape_char_arg));
1363 if (session_ident != -1)
1364 channel_register_cleanup(session_ident,
1365 client_channel_closed, 0);
1366 } else {
1367 /* Check if we should immediately send eof on stdin. */
1368 client_check_initial_eof_on_stdin();
1369 }
1370
1371 /* Main loop of the client for the interactive session mode. */
1372 while (!quit_pending) {
1373
1374 /* Process buffered packets sent by the server. */
1375 client_process_buffered_input_packets();
1376
1377 if (compat20 && session_closed && !channel_still_open())
1378 break;
1379
1380 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1381
1382 if (rekeying) {
1383 debug("rekeying in progress");
1384 } else {
1385 /*
1386 * Make packets of buffered stdin data, and buffer
1387 * them for sending to the server.
1388 */
1389 if (!compat20)
1390 client_make_packets_from_stdin_data();
1391
1392 /*
1393 * Make packets from buffered channel data, and
1394 * enqueue them for sending to the server.
1395 */
1396 if (packet_not_very_much_data_to_write())
1397 channel_output_poll();
1398
1399 /*
1400 * Check if the window size has changed, and buffer a
1401 * message about it to the server if so.
1402 */
1403 client_check_window_change();
1404
1405 if (quit_pending)
1406 break;
1407 }
1408 /*
1409 * Wait until we have something to do (something becomes
1410 * available on one of the descriptors).
1411 */
1412 max_fd2 = max_fd;
1413 client_wait_until_can_do_something(&readset, &writeset,
1414 &max_fd2, &nalloc, rekeying);
1415
1416 if (quit_pending)
1417 break;
1418
1419 /* Do channel operations unless rekeying in progress. */
1420 if (!rekeying) {
1421 channel_after_select(readset, writeset);
1422 if (need_rekeying || packet_need_rekeying()) {
1423 debug("need rekeying");
1424 xxx_kex->done = 0;
1425 kex_send_kexinit(xxx_kex);
1426 need_rekeying = 0;
1427 }
1428 }
1429
1430 /* Buffer input from the connection. */
1431 client_process_net_input(readset);
1432
1433 /* Accept control connections. */
1434 if (muxserver_sock != -1 &&FD_ISSET(muxserver_sock, readset)) {
1435 if (muxserver_accept_control())
1436 quit_pending = 1;
1437 }
1438
1439 if (quit_pending)
1440 break;
1441
1442 if (!compat20) {
1443 /* Buffer data from stdin */
1444 client_process_input(readset);
1445 /*
1446 * Process output to stdout and stderr. Output to
1447 * the connection is processed elsewhere (above).
1448 */
1449 client_process_output(writeset);
1450 }
1451
1452 /*
1453 * Send as much buffered packet data as possible to the
1454 * sender.
1455 */
1456 if (FD_ISSET(connection_out, writeset))
1457 packet_write_poll();
1458 }
1459 if (readset)
1460 xfree(readset);
1461 if (writeset)
1462 xfree(writeset);
1463
1464 /* Terminate the session. */
1465
1466 /* Stop watching for window change. */
1467 signal(SIGWINCH, SIG_DFL);
1468
1469 if (compat20) {
1470 packet_start(SSH2_MSG_DISCONNECT);
1471 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1472 packet_put_cstring("disconnected by user");
1473 packet_send();
1474 packet_write_wait();
1475 }
1476
1477 channel_free_all();
1478
1479 if (have_pty)
1480 leave_raw_mode();
1481
1482 /* restore blocking io */
1483 if (!isatty(fileno(stdin)))
1484 unset_nonblock(fileno(stdin));
1485 if (!isatty(fileno(stdout)))
1486 unset_nonblock(fileno(stdout));
1487 if (!isatty(fileno(stderr)))
1488 unset_nonblock(fileno(stderr));
1489
1490 /*
1491 * If there was no shell or command requested, there will be no remote
1492 * exit status to be returned. In that case, clear error code if the
1493 * connection was deliberately terminated at this end.
1494 */
1495 if (no_shell_flag && received_signal == SIGTERM) {
1496 received_signal = 0;
1497 exit_status = 0;
1498 }
1499
1500 if (received_signal)
1501 fatal("Killed by signal %d.", (int) received_signal);
1502
1503 /*
1504 * In interactive mode (with pseudo tty) display a message indicating
1505 * that the connection has been closed.
1506 */
1507 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1508 snprintf(buf, sizeof buf,
1509 "Connection to %.64s closed.\r\n", host);
1510 buffer_append(&stderr_buffer, buf, strlen(buf));
1511 }
1512
1513 /* Output any buffered data for stdout. */
1514 while (buffer_len(&stdout_buffer) > 0) {
1515 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1516 buffer_len(&stdout_buffer));
1517 if (len <= 0) {
1518 error("Write failed flushing stdout buffer.");
1519 break;
1520 }
1521 buffer_consume(&stdout_buffer, len);
1522 }
1523
1524 /* Output any buffered data for stderr. */
1525 while (buffer_len(&stderr_buffer) > 0) {
1526 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1527 buffer_len(&stderr_buffer));
1528 if (len <= 0) {
1529 error("Write failed flushing stderr buffer.");
1530 break;
1531 }
1532 buffer_consume(&stderr_buffer, len);
1533 }
1534
1535 /* Clear and free any buffers. */
1536 memset(buf, 0, sizeof(buf));
1537 buffer_free(&stdin_buffer);
1538 buffer_free(&stdout_buffer);
1539 buffer_free(&stderr_buffer);
1540
1541 /* Report bytes transferred, and transfer rates. */
1542 total_time = get_current_time() - start_time;
1543 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1544 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1545 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1546 obytes, ibytes, total_time);
1547 if (total_time > 0)
1548 verbose("Bytes per second: sent %.1f, received %.1f",
1549 obytes / total_time, ibytes / total_time);
1550 /* Return the exit status of the program. */
1551 debug("Exit status %d", exit_status);
1552 return exit_status;
1553 }
1554
1555 /*********/
1556
1557 static void
client_input_stdout_data(int type,u_int32_t seq,void * ctxt)1558 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1559 {
1560 u_int data_len;
1561 char *data = packet_get_string(&data_len);
1562 packet_check_eom();
1563 buffer_append(&stdout_buffer, data, data_len);
1564 memset(data, 0, data_len);
1565 xfree(data);
1566 }
1567 static void
client_input_stderr_data(int type,u_int32_t seq,void * ctxt)1568 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1569 {
1570 u_int data_len;
1571 char *data = packet_get_string(&data_len);
1572 packet_check_eom();
1573 buffer_append(&stderr_buffer, data, data_len);
1574 memset(data, 0, data_len);
1575 xfree(data);
1576 }
1577 static void
client_input_exit_status(int type,u_int32_t seq,void * ctxt)1578 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1579 {
1580 exit_status = packet_get_int();
1581 packet_check_eom();
1582 /* Acknowledge the exit. */
1583 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1584 packet_send();
1585 /*
1586 * Must wait for packet to be sent since we are
1587 * exiting the loop.
1588 */
1589 packet_write_wait();
1590 /* Flag that we want to exit. */
1591 quit_pending = 1;
1592 }
1593 static void
client_input_agent_open(int type,u_int32_t seq,void * ctxt)1594 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1595 {
1596 Channel *c = NULL;
1597 int remote_id, sock;
1598
1599 /* Read the remote channel number from the message. */
1600 remote_id = packet_get_int();
1601 packet_check_eom();
1602
1603 /*
1604 * Get a connection to the local authentication agent (this may again
1605 * get forwarded).
1606 */
1607 sock = ssh_get_authentication_socket();
1608
1609 /*
1610 * If we could not connect the agent, send an error message back to
1611 * the server. This should never happen unless the agent dies,
1612 * because authentication forwarding is only enabled if we have an
1613 * agent.
1614 */
1615 if (sock >= 0) {
1616 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1617 -1, 0, 0, 0, "authentication agent connection", 1);
1618 c->remote_id = remote_id;
1619 c->force_drain = 1;
1620 }
1621 if (c == NULL) {
1622 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1623 packet_put_int(remote_id);
1624 } else {
1625 /* Send a confirmation to the remote host. */
1626 debug("Forwarding authentication connection.");
1627 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1628 packet_put_int(remote_id);
1629 packet_put_int(c->self);
1630 }
1631 packet_send();
1632 }
1633
1634 static Channel *
client_request_forwarded_tcpip(const char * request_type,int rchan)1635 client_request_forwarded_tcpip(const char *request_type, int rchan)
1636 {
1637 Channel *c = NULL;
1638 char *listen_address, *originator_address;
1639 u_short listen_port, originator_port;
1640
1641 /* Get rest of the packet */
1642 listen_address = packet_get_string(NULL);
1643 listen_port = packet_get_int();
1644 originator_address = packet_get_string(NULL);
1645 originator_port = packet_get_int();
1646 packet_check_eom();
1647
1648 debug("client_request_forwarded_tcpip: listen %s port %d, "
1649 "originator %s port %d", listen_address, listen_port,
1650 originator_address, originator_port);
1651
1652 c = channel_connect_by_listen_address(listen_port,
1653 "forwarded-tcpip", originator_address);
1654
1655 xfree(originator_address);
1656 xfree(listen_address);
1657 return c;
1658 }
1659
1660 static Channel *
client_request_x11(const char * request_type,int rchan)1661 client_request_x11(const char *request_type, int rchan)
1662 {
1663 Channel *c = NULL;
1664 char *originator;
1665 u_short originator_port;
1666 int sock;
1667
1668 if (!options.forward_x11) {
1669 error("Warning: ssh server tried X11 forwarding.");
1670 error("Warning: this is probably a break-in attempt by a "
1671 "malicious server.");
1672 return NULL;
1673 }
1674 originator = packet_get_string(NULL);
1675 if (datafellows & SSH_BUG_X11FWD) {
1676 debug2("buggy server: x11 request w/o originator_port");
1677 originator_port = 0;
1678 } else {
1679 originator_port = packet_get_int();
1680 }
1681 packet_check_eom();
1682 /* XXX check permission */
1683 debug("client_request_x11: request from %s %d", originator,
1684 originator_port);
1685 xfree(originator);
1686 sock = x11_connect_display();
1687 if (sock < 0)
1688 return NULL;
1689 c = channel_new("x11",
1690 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1691 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1692 c->force_drain = 1;
1693 return c;
1694 }
1695
1696 static Channel *
client_request_agent(const char * request_type,int rchan)1697 client_request_agent(const char *request_type, int rchan)
1698 {
1699 Channel *c = NULL;
1700 int sock;
1701
1702 if (!options.forward_agent) {
1703 error("Warning: ssh server tried agent forwarding.");
1704 error("Warning: this is probably a break-in attempt by a "
1705 "malicious server.");
1706 return NULL;
1707 }
1708 sock = ssh_get_authentication_socket();
1709 if (sock < 0)
1710 return NULL;
1711 c = channel_new("authentication agent connection",
1712 SSH_CHANNEL_OPEN, sock, sock, -1,
1713 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1714 "authentication agent connection", 1);
1715 c->force_drain = 1;
1716 return c;
1717 }
1718
1719 int
client_request_tun_fwd(int tun_mode,int local_tun,int remote_tun)1720 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1721 {
1722 Channel *c;
1723 int fd;
1724
1725 if (tun_mode == SSH_TUNMODE_NO)
1726 return 0;
1727
1728 if (!compat20) {
1729 error("Tunnel forwarding is not supported for protocol 1");
1730 return -1;
1731 }
1732
1733 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1734
1735 /* Open local tunnel device */
1736 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1737 error("Tunnel device open failed.");
1738 return -1;
1739 }
1740
1741 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1742 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1743 c->datagram = 1;
1744
1745 packet_start(SSH2_MSG_CHANNEL_OPEN);
1746 packet_put_cstring("tun@openssh.com");
1747 packet_put_int(c->self);
1748 packet_put_int(c->local_window_max);
1749 packet_put_int(c->local_maxpacket);
1750 packet_put_int(tun_mode);
1751 packet_put_int(remote_tun);
1752 packet_send();
1753
1754 return 0;
1755 }
1756
1757 /* XXXX move to generic input handler */
1758 static void
client_input_channel_open(int type,u_int32_t seq,void * ctxt)1759 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1760 {
1761 Channel *c = NULL;
1762 char *ctype;
1763 int rchan;
1764 u_int rmaxpack, rwindow, len;
1765
1766 ctype = packet_get_string(&len);
1767 rchan = packet_get_int();
1768 rwindow = packet_get_int();
1769 rmaxpack = packet_get_int();
1770
1771 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1772 ctype, rchan, rwindow, rmaxpack);
1773
1774 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1775 c = client_request_forwarded_tcpip(ctype, rchan);
1776 } else if (strcmp(ctype, "x11") == 0) {
1777 c = client_request_x11(ctype, rchan);
1778 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1779 c = client_request_agent(ctype, rchan);
1780 }
1781 /* XXX duplicate : */
1782 if (c != NULL) {
1783 debug("confirm %s", ctype);
1784 c->remote_id = rchan;
1785 c->remote_window = rwindow;
1786 c->remote_maxpacket = rmaxpack;
1787 if (c->type != SSH_CHANNEL_CONNECTING) {
1788 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1789 packet_put_int(c->remote_id);
1790 packet_put_int(c->self);
1791 packet_put_int(c->local_window);
1792 packet_put_int(c->local_maxpacket);
1793 packet_send();
1794 }
1795 } else {
1796 debug("failure %s", ctype);
1797 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1798 packet_put_int(rchan);
1799 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1800 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1801 packet_put_cstring("open failed");
1802 packet_put_cstring("");
1803 }
1804 packet_send();
1805 }
1806 xfree(ctype);
1807 }
1808 static void
client_input_channel_req(int type,u_int32_t seq,void * ctxt)1809 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1810 {
1811 Channel *c = NULL;
1812 int exitval, id, reply, success = 0;
1813 char *rtype;
1814
1815 id = packet_get_int();
1816 rtype = packet_get_string(NULL);
1817 reply = packet_get_char();
1818
1819 debug("client_input_channel_req: channel %d rtype %s reply %d",
1820 id, rtype, reply);
1821
1822 if (id == -1) {
1823 error("client_input_channel_req: request for channel -1");
1824 } else if ((c = channel_lookup(id)) == NULL) {
1825 error("client_input_channel_req: channel %d: "
1826 "unknown channel", id);
1827 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1828 packet_check_eom();
1829 chan_rcvd_eow(c);
1830 } else if (strcmp(rtype, "exit-status") == 0) {
1831 exitval = packet_get_int();
1832 if (id == session_ident) {
1833 success = 1;
1834 exit_status = exitval;
1835 } else if (c->ctl_fd == -1) {
1836 error("client_input_channel_req: unexpected channel %d",
1837 session_ident);
1838 } else {
1839 atomicio(vwrite, c->ctl_fd, &exitval, sizeof(exitval));
1840 success = 1;
1841 }
1842 packet_check_eom();
1843 }
1844 if (reply) {
1845 packet_start(success ?
1846 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1847 packet_put_int(c->remote_id);
1848 packet_send();
1849 }
1850 xfree(rtype);
1851 }
1852 static void
client_input_global_request(int type,u_int32_t seq,void * ctxt)1853 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1854 {
1855 char *rtype;
1856 int want_reply;
1857 int success = 0;
1858
1859 rtype = packet_get_string(NULL);
1860 want_reply = packet_get_char();
1861 debug("client_input_global_request: rtype %s want_reply %d",
1862 rtype, want_reply);
1863 if (want_reply) {
1864 packet_start(success ?
1865 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1866 packet_send();
1867 packet_write_wait();
1868 }
1869 xfree(rtype);
1870 }
1871
1872 void
client_session2_setup(int id,int want_tty,int want_subsystem,const char * term,struct termios * tiop,int in_fd,Buffer * cmd,char ** env)1873 client_session2_setup(int id, int want_tty, int want_subsystem,
1874 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1875 {
1876 int len;
1877 Channel *c = NULL;
1878
1879 debug2("%s: id %d", __func__, id);
1880
1881 if ((c = channel_lookup(id)) == NULL)
1882 fatal("client_session2_setup: channel %d: unknown channel", id);
1883
1884 if (want_tty) {
1885 struct winsize ws;
1886
1887 /* Store window size in the packet. */
1888 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
1889 memset(&ws, 0, sizeof(ws));
1890
1891 channel_request_start(id, "pty-req", 1);
1892 client_expect_confirm(id, "PTY allocation", 0);
1893 packet_put_cstring(term != NULL ? term : "");
1894 packet_put_int((u_int)ws.ws_col);
1895 packet_put_int((u_int)ws.ws_row);
1896 packet_put_int((u_int)ws.ws_xpixel);
1897 packet_put_int((u_int)ws.ws_ypixel);
1898 if (tiop == NULL)
1899 tiop = get_saved_tio();
1900 tty_make_modes(-1, tiop);
1901 packet_send();
1902 /* XXX wait for reply */
1903 c->client_tty = 1;
1904 }
1905
1906 /* Transfer any environment variables from client to server */
1907 if (options.num_send_env != 0 && env != NULL) {
1908 int i, j, matched;
1909 char *name, *val;
1910
1911 debug("Sending environment.");
1912 for (i = 0; env[i] != NULL; i++) {
1913 /* Split */
1914 name = xstrdup(env[i]);
1915 if ((val = strchr(name, '=')) == NULL) {
1916 xfree(name);
1917 continue;
1918 }
1919 *val++ = '\0';
1920
1921 matched = 0;
1922 for (j = 0; j < options.num_send_env; j++) {
1923 if (match_pattern(name, options.send_env[j])) {
1924 matched = 1;
1925 break;
1926 }
1927 }
1928 if (!matched) {
1929 debug3("Ignored env %s", name);
1930 xfree(name);
1931 continue;
1932 }
1933
1934 debug("Sending env %s = %s", name, val);
1935 channel_request_start(id, "env", 0);
1936 packet_put_cstring(name);
1937 packet_put_cstring(val);
1938 packet_send();
1939 xfree(name);
1940 }
1941 }
1942
1943 len = buffer_len(cmd);
1944 if (len > 0) {
1945 if (len > 900)
1946 len = 900;
1947 if (want_subsystem) {
1948 debug("Sending subsystem: %.*s",
1949 len, (u_char*)buffer_ptr(cmd));
1950 channel_request_start(id, "subsystem", 1);
1951 client_expect_confirm(id, "subsystem", 1);
1952 } else {
1953 debug("Sending command: %.*s",
1954 len, (u_char*)buffer_ptr(cmd));
1955 channel_request_start(id, "exec", 1);
1956 client_expect_confirm(id, "exec", 1);
1957 }
1958 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
1959 packet_send();
1960 } else {
1961 channel_request_start(id, "shell", 1);
1962 client_expect_confirm(id, "shell", 1);
1963 packet_send();
1964 }
1965 }
1966
1967 static void
client_init_dispatch_20(void)1968 client_init_dispatch_20(void)
1969 {
1970 dispatch_init(&dispatch_protocol_error);
1971
1972 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1973 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1974 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1975 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1976 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1977 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1978 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1979 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1980 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1981 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
1982 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1983 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1984
1985 /* rekeying */
1986 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1987
1988 /* global request reply messages */
1989 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
1990 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1991 }
1992
1993 static void
client_init_dispatch_13(void)1994 client_init_dispatch_13(void)
1995 {
1996 dispatch_init(NULL);
1997 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1998 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1999 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2000 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2001 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2002 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2003 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2004 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2005 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2006
2007 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2008 &client_input_agent_open : &deny_input_open);
2009 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2010 &x11_input_open : &deny_input_open);
2011 }
2012
2013 static void
client_init_dispatch_15(void)2014 client_init_dispatch_15(void)
2015 {
2016 client_init_dispatch_13();
2017 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2018 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2019 }
2020
2021 static void
client_init_dispatch(void)2022 client_init_dispatch(void)
2023 {
2024 if (compat20)
2025 client_init_dispatch_20();
2026 else if (compat13)
2027 client_init_dispatch_13();
2028 else
2029 client_init_dispatch_15();
2030 }
2031
2032 /* client specific fatal cleanup */
2033 void
cleanup_exit(int i)2034 cleanup_exit(int i)
2035 {
2036 leave_raw_mode();
2037 leave_non_blocking();
2038 if (options.control_path != NULL && muxserver_sock != -1)
2039 unlink(options.control_path);
2040 _exit(i);
2041 }
2042