1 /* $OpenBSD: serverloop.c,v 1.157 2009/02/12 03:16:01 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Server main loop for handling the interactive session.
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".
14 * SSH2 support by Markus Friedl.
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
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.
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.
40 #include <sys/types.h>
41 #include <sys/param.h>
43 #include <sys/socket.h>
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
48 #include <netinet/in.h>
59 #include "openbsd-compat/sys-queue.h"
78 #include "auth-options.h"
79 #include "serverloop.h"
82 extern ServerOptions options;
86 extern Authctxt *the_authctxt;
87 extern int use_privsep;
89 static Buffer stdin_buffer; /* Buffer for stdin data. */
90 static Buffer stdout_buffer; /* Buffer for stdout data. */
91 static Buffer stderr_buffer; /* Buffer for stderr data. */
92 static int fdin; /* Descriptor for stdin (for writing) */
93 static int fdout; /* Descriptor for stdout (for reading);
94 May be same number as fdin. */
95 static int fderr; /* Descriptor for stderr. May be -1. */
96 static u_long stdin_bytes = 0; /* Number of bytes written to stdin. */
97 static u_long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
98 static u_long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
99 static u_long fdout_bytes = 0; /* Number of stdout bytes read from program. */
100 static int stdin_eof = 0; /* EOF message received from client. */
101 static int fdout_eof = 0; /* EOF encountered reading from fdout. */
102 static int fderr_eof = 0; /* EOF encountered readung from fderr. */
103 static int fdin_is_tty = 0; /* fdin points to a tty. */
104 static int connection_in; /* Connection to client (input). */
105 static int connection_out; /* Connection to client (output). */
106 static int connection_closed = 0; /* Connection to client closed. */
107 static u_int buffer_high; /* "Soft" max buffer size. */
108 static int no_more_sessions = 0; /* Disallow further sessions. */
111 * This SIGCHLD kludge is used to detect when the child exits. The server
112 * will exit after that, as soon as forwarded connections have terminated.
115 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
117 /* Cleanup on signals (!use_privsep case only) */
118 static volatile sig_atomic_t received_sigterm = 0;
121 static void server_init_dispatch(void);
124 * Returns current time in seconds from Jan 1, 1970 with the maximum
125 * available resolution.
129 get_current_time(void)
132 gettimeofday(&tv, NULL);
133 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
138 * we write to this pipe if a SIGCHLD is caught in order to avoid
139 * the race between select() and child_terminated
141 static int notify_pipe[2];
145 if (pipe(notify_pipe) < 0) {
146 error("pipe(notify_pipe) failed %s", strerror(errno));
147 } else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
148 (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
149 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
150 close(notify_pipe[0]);
151 close(notify_pipe[1]);
153 set_nonblock(notify_pipe[0]);
154 set_nonblock(notify_pipe[1]);
157 notify_pipe[0] = -1; /* read end */
158 notify_pipe[1] = -1; /* write end */
163 if (notify_pipe[1] != -1)
164 write(notify_pipe[1], "", 1);
167 notify_prepare(fd_set *readset)
169 if (notify_pipe[0] != -1)
170 FD_SET(notify_pipe[0], readset);
173 notify_done(fd_set *readset)
177 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
178 while (read(notify_pipe[0], &c, 1) != -1)
179 debug2("notify_done: reading");
184 sigchld_handler(int sig)
186 int save_errno = errno;
187 child_terminated = 1;
189 mysignal(SIGCHLD, sigchld_handler);
197 sigterm_handler(int sig)
199 received_sigterm = sig;
203 * Make packets from buffered stderr data, and buffer it for sending
207 make_packets_from_stderr_data(void)
211 /* Send buffered stderr data to the client. */
212 while (buffer_len(&stderr_buffer) > 0 &&
213 packet_not_very_much_data_to_write()) {
214 len = buffer_len(&stderr_buffer);
215 if (packet_is_interactive()) {
219 /* Keep the packets at reasonable size. */
220 if (len > packet_get_maxsize())
221 len = packet_get_maxsize();
223 packet_start(SSH_SMSG_STDERR_DATA);
224 packet_put_string(buffer_ptr(&stderr_buffer), len);
226 buffer_consume(&stderr_buffer, len);
232 * Make packets from buffered stdout data, and buffer it for sending to the
236 make_packets_from_stdout_data(void)
240 /* Send buffered stdout data to the client. */
241 while (buffer_len(&stdout_buffer) > 0 &&
242 packet_not_very_much_data_to_write()) {
243 len = buffer_len(&stdout_buffer);
244 if (packet_is_interactive()) {
248 /* Keep the packets at reasonable size. */
249 if (len > packet_get_maxsize())
250 len = packet_get_maxsize();
252 packet_start(SSH_SMSG_STDOUT_DATA);
253 packet_put_string(buffer_ptr(&stdout_buffer), len);
255 buffer_consume(&stdout_buffer, len);
261 client_alive_check(void)
265 /* timeout, check to see how many we have had */
266 if (++keep_alive_timeouts > options.client_alive_count_max) {
267 logit("Timeout, client not responding.");
272 * send a bogus global/channel request with "wantreply",
273 * we should get back a failure
275 if ((channel_id = channel_find_open()) == -1) {
276 packet_start(SSH2_MSG_GLOBAL_REQUEST);
277 packet_put_cstring("keepalive@openssh.com");
278 packet_put_char(1); /* boolean: want reply */
280 channel_request_start(channel_id, "keepalive@openssh.com", 1);
286 * Sleep in select() until we can do something. This will initialize the
287 * select masks. Upon return, the masks will indicate which descriptors
288 * have data or can accept data. Optionally, a maximum time can be specified
289 * for the duration of the wait (0 = infinite).
292 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
293 u_int *nallocp, u_int max_time_milliseconds)
295 struct timeval tv, *tvp;
297 int client_alive_scheduled = 0;
298 int program_alive_scheduled = 0;
301 * if using client_alive, set the max timeout accordingly,
302 * and indicate that this particular timeout was for client
303 * alive by setting the client_alive_scheduled flag.
305 * this could be randomized somewhat to make traffic
306 * analysis more difficult, but we're not doing it yet.
309 max_time_milliseconds == 0 && options.client_alive_interval) {
310 client_alive_scheduled = 1;
311 max_time_milliseconds = options.client_alive_interval * 1000;
314 /* Allocate and update select() masks for channel descriptors. */
315 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
319 /* wrong: bad condition XXX */
320 if (channel_not_very_much_buffered_data())
322 FD_SET(connection_in, *readsetp);
325 * Read packets from the client unless we have too much
326 * buffered stdin or channel data.
328 if (buffer_len(&stdin_buffer) < buffer_high &&
329 channel_not_very_much_buffered_data())
330 FD_SET(connection_in, *readsetp);
332 * If there is not too much data already buffered going to
333 * the client, try to get some more data from the program.
335 if (packet_not_very_much_data_to_write()) {
336 program_alive_scheduled = child_terminated;
338 FD_SET(fdout, *readsetp);
340 FD_SET(fderr, *readsetp);
343 * If we have buffered data, try to write some of that data
346 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
347 FD_SET(fdin, *writesetp);
349 notify_prepare(*readsetp);
352 * If we have buffered packet data going to the client, mark that
355 if (packet_have_data_to_write())
356 FD_SET(connection_out, *writesetp);
359 * If child has terminated and there is enough buffer space to read
360 * from it, then read as much as is available and exit.
362 if (child_terminated && packet_not_very_much_data_to_write())
363 if (max_time_milliseconds == 0 || client_alive_scheduled)
364 max_time_milliseconds = 100;
366 if (max_time_milliseconds == 0)
369 tv.tv_sec = max_time_milliseconds / 1000;
370 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
374 /* Wait for something to happen, or the timeout to expire. */
375 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
378 memset(*readsetp, 0, *nallocp);
379 memset(*writesetp, 0, *nallocp);
381 error("select: %.100s", strerror(errno));
383 if (ret == 0 && client_alive_scheduled)
384 client_alive_check();
385 if (!compat20 && program_alive_scheduled && fdin_is_tty) {
387 FD_SET(fdout, *readsetp);
389 FD_SET(fderr, *readsetp);
393 notify_done(*readsetp);
397 * Processes input from the client and the program. Input data is stored
398 * in buffers and processed later.
401 process_input(fd_set *readset)
406 /* Read and buffer any input data from the client. */
407 if (FD_ISSET(connection_in, readset)) {
408 len = read(connection_in, buf, sizeof(buf));
410 verbose("Connection closed by %.100s",
411 get_remote_ipaddr());
412 connection_closed = 1;
416 } else if (len < 0) {
417 if (errno != EINTR && errno != EAGAIN &&
418 errno != EWOULDBLOCK) {
419 verbose("Read error from remote host "
421 get_remote_ipaddr(), strerror(errno));
425 /* Buffer any received data. */
426 packet_process_incoming(buf, len);
433 /* Read and buffer any available stdout data from the program. */
434 if (!fdout_eof && FD_ISSET(fdout, readset)) {
436 len = read(fdout, buf, sizeof(buf));
437 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
438 errno == EWOULDBLOCK) && !child_terminated))) {
441 } else if (len <= 0) {
443 } else if ((!isatty(fdout) && len <= 0) ||
444 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
448 buffer_append(&stdout_buffer, buf, len);
450 debug ("FD out now: %ld", fdout_bytes);
453 /* Read and buffer any available stderr data from the program. */
454 if (!fderr_eof && FD_ISSET(fderr, readset)) {
456 len = read(fderr, buf, sizeof(buf));
457 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
458 errno == EWOULDBLOCK) && !child_terminated))) {
461 } else if (len <= 0) {
463 } else if ((!isatty(fderr) && len <= 0) ||
464 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
468 buffer_append(&stderr_buffer, buf, len);
474 * Sends data from internal buffers to client program stdin.
477 process_output(fd_set *writeset)
484 /* Write buffered data to program stdin. */
485 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
486 data = buffer_ptr(&stdin_buffer);
487 dlen = buffer_len(&stdin_buffer);
488 len = write(fdin, data, dlen);
490 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
492 } else if (len <= 0) {
496 shutdown(fdin, SHUT_WR); /* We will no longer send. */
499 /* Successful write. */
500 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
501 tcgetattr(fdin, &tio) == 0 &&
502 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
504 * Simulate echo to reduce the impact of
507 packet_send_ignore(len);
510 /* Consume the data from the buffer. */
511 buffer_consume(&stdin_buffer, len);
512 /* Update the count of bytes written to the program. */
516 /* Send any buffered packet data to the client. */
517 if (FD_ISSET(connection_out, writeset))
518 stdin_bytes += packet_write_poll();
522 * Wait until all buffered output has been sent to the client.
523 * This is used when the program terminates.
528 /* Send any buffered stdout data to the client. */
529 if (buffer_len(&stdout_buffer) > 0) {
530 packet_start(SSH_SMSG_STDOUT_DATA);
531 packet_put_string(buffer_ptr(&stdout_buffer),
532 buffer_len(&stdout_buffer));
534 /* Update the count of sent bytes. */
535 stdout_bytes += buffer_len(&stdout_buffer);
537 /* Send any buffered stderr data to the client. */
538 if (buffer_len(&stderr_buffer) > 0) {
539 packet_start(SSH_SMSG_STDERR_DATA);
540 packet_put_string(buffer_ptr(&stderr_buffer),
541 buffer_len(&stderr_buffer));
543 /* Update the count of sent bytes. */
544 stderr_bytes += buffer_len(&stderr_buffer);
546 /* Wait until all buffered data has been written to the client. */
551 process_buffered_input_packets(void)
553 dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
557 * Performs the interactive session. This handles data transmission between
558 * the client and the program. Note that the notion of stdin, stdout, and
559 * stderr in this function is sort of reversed: this function writes to
560 * stdin (of the child program), and reads from stdout and stderr (of the
564 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
566 fd_set *readset = NULL, *writeset = NULL;
569 int wait_status; /* Status returned by wait(). */
570 pid_t wait_pid; /* pid returned by wait(). */
571 int waiting_termination = 0; /* Have displayed waiting close message. */
572 u_int max_time_milliseconds;
573 u_int previous_stdout_buffer_bytes;
574 u_int stdout_buffer_bytes;
577 debug("Entering interactive session.");
579 /* Initialize the SIGCHLD kludge. */
580 child_terminated = 0;
581 mysignal(SIGCHLD, sigchld_handler);
584 signal(SIGTERM, sigterm_handler);
585 signal(SIGINT, sigterm_handler);
586 signal(SIGQUIT, sigterm_handler);
589 /* Initialize our global variables. */
597 /* we don't have stderr for interactive terminal sessions, see below */
601 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
604 connection_in = packet_get_connection_in();
605 connection_out = packet_get_connection_out();
609 previous_stdout_buffer_bytes = 0;
611 /* Set approximate I/O buffer size. */
612 if (packet_is_interactive())
615 buffer_high = 64 * 1024;
618 /* Initialize max_fd to the maximum of the known file descriptors. */
619 max_fd = MAX(connection_in, connection_out);
620 max_fd = MAX(max_fd, fdin);
621 max_fd = MAX(max_fd, fdout);
623 max_fd = MAX(max_fd, fderr);
626 /* Initialize Initialize buffers. */
627 buffer_init(&stdin_buffer);
628 buffer_init(&stdout_buffer);
629 buffer_init(&stderr_buffer);
632 * If we have no separate fderr (which is the case when we have a pty
633 * - there we cannot make difference between data sent to stdout and
634 * stderr), indicate that we have seen an EOF from stderr. This way
635 * we don't need to check the descriptor everywhere.
640 server_init_dispatch();
642 /* Main loop of the server for the interactive session mode. */
645 /* Process buffered packets from the client. */
646 process_buffered_input_packets();
649 * If we have received eof, and there is no more pending
650 * input data, cause a real eof by closing fdin.
652 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
656 shutdown(fdin, SHUT_WR); /* We will no longer send. */
659 /* Make packets from buffered stderr data to send to the client. */
660 make_packets_from_stderr_data();
663 * Make packets from buffered stdout data to send to the
664 * client. If there is very little to send, this arranges to
665 * not send them now, but to wait a short while to see if we
666 * are getting more data. This is necessary, as some systems
667 * wake up readers from a pty after each separate character.
669 max_time_milliseconds = 0;
670 stdout_buffer_bytes = buffer_len(&stdout_buffer);
671 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
672 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
673 /* try again after a while */
674 max_time_milliseconds = 10;
677 make_packets_from_stdout_data();
679 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
681 /* Send channel data to the client. */
682 if (packet_not_very_much_data_to_write())
683 channel_output_poll();
686 * Bail out of the loop if the program has closed its output
687 * descriptors, and we have no more data to send to the
688 * client, and there is no pending buffered data.
690 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
691 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
692 if (!channel_still_open())
694 if (!waiting_termination) {
695 const char *s = "Waiting for forwarded connections to terminate...\r\n";
697 waiting_termination = 1;
698 buffer_append(&stderr_buffer, s, strlen(s));
700 /* Display list of open channels. */
701 cp = channel_open_message();
702 buffer_append(&stderr_buffer, cp, strlen(cp));
706 max_fd = MAX(connection_in, connection_out);
707 max_fd = MAX(max_fd, fdin);
708 max_fd = MAX(max_fd, fdout);
709 max_fd = MAX(max_fd, fderr);
710 max_fd = MAX(max_fd, notify_pipe[0]);
712 /* Sleep in select() until we can do something. */
713 wait_until_can_do_something(&readset, &writeset, &max_fd,
714 &nalloc, max_time_milliseconds);
716 if (received_sigterm) {
717 logit("Exiting on signal %d", received_sigterm);
718 /* Clean up sessions, utmp, etc. */
722 /* Process any channel events. */
723 channel_after_select(readset, writeset);
725 /* Process input from the client and from program stdout/stderr. */
726 process_input(readset);
728 /* Process output to the client and to program stdin. */
729 process_output(writeset);
736 /* Cleanup and termination code. */
738 /* Wait until all output has been sent to the client. */
741 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
742 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
744 /* Free and clear the buffers. */
745 buffer_free(&stdin_buffer);
746 buffer_free(&stdout_buffer);
747 buffer_free(&stderr_buffer);
749 /* Close the file descriptors. */
764 /* We no longer want our SIGCHLD handler to be called. */
765 mysignal(SIGCHLD, SIG_DFL);
767 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
769 packet_disconnect("wait: %.100s", strerror(errno));
771 error("Strange, wait returned pid %ld, expected %ld",
772 (long)wait_pid, (long)pid);
774 /* Check if it exited normally. */
775 if (WIFEXITED(wait_status)) {
776 /* Yes, normal exit. Get exit status and send it to the client. */
777 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
778 packet_start(SSH_SMSG_EXITSTATUS);
779 packet_put_int(WEXITSTATUS(wait_status));
784 * Wait for exit confirmation. Note that there might be
785 * other packets coming before it; however, the program has
786 * already died so we just ignore them. The client is
787 * supposed to respond with the confirmation when it receives
791 type = packet_read();
793 while (type != SSH_CMSG_EXIT_CONFIRMATION);
795 debug("Received exit confirmation.");
798 /* Check if the program terminated due to a signal. */
799 if (WIFSIGNALED(wait_status))
800 packet_disconnect("Command terminated on signal %d.",
801 WTERMSIG(wait_status));
803 /* Some weird exit cause. Just exit. */
804 packet_disconnect("wait returned status %04x.", wait_status);
809 collect_children(void)
815 /* block SIGCHLD while we check for dead children */
817 sigaddset(&nset, SIGCHLD);
818 sigprocmask(SIG_BLOCK, &nset, &oset);
819 if (child_terminated) {
820 debug("Received SIGCHLD.");
821 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
822 (pid < 0 && errno == EINTR))
824 session_close_by_pid(pid, status);
825 child_terminated = 0;
827 sigprocmask(SIG_SETMASK, &oset, NULL);
831 server_loop2(Authctxt *authctxt)
833 fd_set *readset = NULL, *writeset = NULL;
834 int rekeying = 0, max_fd, nalloc = 0;
835 double start_time, total_time;
837 debug("Entering interactive session for SSH2.");
838 start_time = get_current_time();
840 mysignal(SIGCHLD, sigchld_handler);
841 child_terminated = 0;
842 connection_in = packet_get_connection_in();
843 connection_out = packet_get_connection_out();
846 signal(SIGTERM, sigterm_handler);
847 signal(SIGINT, sigterm_handler);
848 signal(SIGQUIT, sigterm_handler);
853 max_fd = MAX(connection_in, connection_out);
854 max_fd = MAX(max_fd, notify_pipe[0]);
856 server_init_dispatch();
859 process_buffered_input_packets();
861 rekeying = (xxx_kex != NULL && !xxx_kex->done);
863 if (!rekeying && packet_not_very_much_data_to_write())
864 channel_output_poll();
865 wait_until_can_do_something(&readset, &writeset, &max_fd,
868 if (received_sigterm) {
869 logit("Exiting on signal %d", received_sigterm);
870 /* Clean up sessions, utmp, etc. */
876 channel_after_select(readset, writeset);
877 if (packet_need_rekeying()) {
878 debug("need rekeying");
880 kex_send_kexinit(xxx_kex);
883 process_input(readset);
884 if (connection_closed)
886 process_output(writeset);
895 /* free all channels, no more reads and writes */
898 /* free remaining sessions, e.g. remove wtmp entries */
899 session_destroy_all(NULL);
900 total_time = get_current_time() - start_time;
901 logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
902 get_remote_ipaddr(), get_remote_port(),
903 stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
904 fdout_bytes / total_time);
908 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
910 debug("Got %d/%u for keepalive", type, seq);
912 * reset timeout, since we got a sane answer from the client.
913 * even if this was generated by something other than
914 * the bogus CHANNEL_REQUEST we send for keepalives.
916 keep_alive_timeouts = 0;
920 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
925 /* Stdin data from the client. Append it to the buffer. */
926 /* Ignore any data if the client has closed stdin. */
929 data = packet_get_string(&data_len);
931 buffer_append(&stdin_buffer, data, data_len);
932 memset(data, 0, data_len);
937 server_input_eof(int type, u_int32_t seq, void *ctxt)
940 * Eof from the client. The stdin descriptor to the
941 * program will be closed when all buffered data has
944 debug("EOF received for stdin.");
950 server_input_window_size(int type, u_int32_t seq, void *ctxt)
952 u_int row = packet_get_int();
953 u_int col = packet_get_int();
954 u_int xpixel = packet_get_int();
955 u_int ypixel = packet_get_int();
957 debug("Window change received.");
960 pty_change_window_size(fdin, row, col, xpixel, ypixel);
964 server_request_direct_tcpip(void)
967 char *target, *originator;
968 u_short target_port, originator_port;
970 target = packet_get_string(NULL);
971 target_port = packet_get_int();
972 originator = packet_get_string(NULL);
973 originator_port = packet_get_int();
976 debug("server_request_direct_tcpip: originator %s port %d, target %s "
977 "port %d", originator, originator_port, target, target_port);
979 /* XXX check permission */
980 c = channel_connect_to(target, target_port,
981 "direct-tcpip", "direct-tcpip");
990 server_request_tun(void)
996 mode = packet_get_int();
998 case SSH_TUNMODE_POINTOPOINT:
999 case SSH_TUNMODE_ETHERNET:
1002 packet_send_debug("Unsupported tunnel device mode.");
1005 if ((options.permit_tun & mode) == 0) {
1006 packet_send_debug("Server has rejected tunnel device "
1011 tun = packet_get_int();
1012 if (forced_tun_device != -1) {
1013 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
1015 tun = forced_tun_device;
1017 sock = tun_open(tun, mode);
1020 if (options.hpn_disabled)
1021 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1022 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1024 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1025 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1027 #if defined(SSH_TUN_FILTER)
1028 if (mode == SSH_TUNMODE_POINTOPOINT)
1029 channel_register_filter(c->self, sys_tun_infilter,
1030 sys_tun_outfilter, NULL, NULL);
1035 packet_send_debug("Failed to open the tunnel device.");
1040 server_request_session(void)
1044 debug("input_session_request");
1047 if (no_more_sessions) {
1048 packet_disconnect("Possible attack: attempt to open a session "
1049 "after additional sessions disabled");
1053 * A server session has no fd to read or write until a
1054 * CHANNEL_REQUEST for a shell is made, so we set the type to
1055 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
1056 * CHANNEL_REQUEST messages is registered.
1058 c = channel_new("session", SSH_CHANNEL_LARVAL,
1059 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1060 0, "server-session", 1);
1061 if ((options.tcp_rcv_buf_poll) && (!options.hpn_disabled))
1062 c->dynamic_window = 1;
1063 if (session_open(the_authctxt, c->self) != 1) {
1064 debug("session open failed, free channel %d", c->self);
1068 channel_register_cleanup(c->self, session_close_by_channel, 0);
1073 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1078 u_int rmaxpack, rwindow, len;
1080 ctype = packet_get_string(&len);
1081 rchan = packet_get_int();
1082 rwindow = packet_get_int();
1083 rmaxpack = packet_get_int();
1085 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1086 ctype, rchan, rwindow, rmaxpack);
1088 if (strcmp(ctype, "session") == 0) {
1089 c = server_request_session();
1090 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1091 c = server_request_direct_tcpip();
1092 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1093 c = server_request_tun();
1096 debug("server_input_channel_open: confirm %s", ctype);
1097 c->remote_id = rchan;
1098 c->remote_window = rwindow;
1099 c->remote_maxpacket = rmaxpack;
1100 if (c->type != SSH_CHANNEL_CONNECTING) {
1101 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1102 packet_put_int(c->remote_id);
1103 packet_put_int(c->self);
1104 packet_put_int(c->local_window);
1105 packet_put_int(c->local_maxpacket);
1109 debug("server_input_channel_open: failure %s", ctype);
1110 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1111 packet_put_int(rchan);
1112 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1113 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1114 packet_put_cstring("open failed");
1115 packet_put_cstring("");
1123 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1127 int success = 0, allocated_listen_port = 0;
1129 rtype = packet_get_string(NULL);
1130 want_reply = packet_get_char();
1131 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1133 /* -R style forwarding */
1134 if (strcmp(rtype, "tcpip-forward") == 0) {
1136 char *listen_address;
1137 u_short listen_port;
1139 pw = the_authctxt->pw;
1140 if (pw == NULL || !the_authctxt->valid)
1141 fatal("server_input_global_request: no/invalid user");
1142 listen_address = packet_get_string(NULL);
1143 listen_port = (u_short)packet_get_int();
1144 debug("server_input_global_request: tcpip-forward listen %s port %d",
1145 listen_address, listen_port);
1147 /* check permissions */
1148 if (!options.allow_tcp_forwarding ||
1149 no_port_forwarding_flag ||
1150 (!want_reply && listen_port == 0)
1151 #ifndef NO_IPPORT_RESERVED_CONCEPT
1152 || (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)
1156 packet_send_debug("Server has disabled port forwarding.");
1158 /* Start listening on the port */
1159 success = channel_setup_remote_fwd_listener(
1160 listen_address, listen_port,
1161 &allocated_listen_port, options.gateway_ports);
1163 xfree(listen_address);
1164 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1165 char *cancel_address;
1166 u_short cancel_port;
1168 cancel_address = packet_get_string(NULL);
1169 cancel_port = (u_short)packet_get_int();
1170 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1171 cancel_address, cancel_port);
1173 success = channel_cancel_rport_listener(cancel_address,
1175 xfree(cancel_address);
1176 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
1177 no_more_sessions = 1;
1181 packet_start(success ?
1182 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1183 if (success && allocated_listen_port > 0)
1184 packet_put_int(allocated_listen_port);
1186 packet_write_wait();
1192 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1195 int id, reply, success = 0;
1198 id = packet_get_int();
1199 rtype = packet_get_string(NULL);
1200 reply = packet_get_char();
1202 debug("server_input_channel_req: channel %d request %s reply %d",
1205 if ((c = channel_lookup(id)) == NULL)
1206 packet_disconnect("server_input_channel_req: "
1207 "unknown channel %d", id);
1208 if (!strcmp(rtype, "eow@openssh.com")) {
1211 } else if ((c->type == SSH_CHANNEL_LARVAL ||
1212 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
1213 success = session_input_channel_req(c, rtype);
1215 packet_start(success ?
1216 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1217 packet_put_int(c->remote_id);
1224 server_init_dispatch_20(void)
1226 debug("server_init_dispatch_20");
1227 dispatch_init(&dispatch_protocol_error);
1228 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1229 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1230 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1231 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1232 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1233 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1234 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1235 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1236 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1237 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1239 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
1240 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1241 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1242 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1244 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1247 server_init_dispatch_13(void)
1249 debug("server_init_dispatch_13");
1250 dispatch_init(NULL);
1251 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1252 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1253 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1254 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1255 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1256 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1257 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1258 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1259 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1262 server_init_dispatch_15(void)
1264 server_init_dispatch_13();
1265 debug("server_init_dispatch_15");
1266 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1267 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1270 server_init_dispatch(void)
1273 server_init_dispatch_20();
1275 server_init_dispatch_13();
1277 server_init_dispatch_15();