2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Server main loop for handling the interactive session.
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
13 * SSH2 support by Markus Friedl.
14 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 RCSID("$OpenBSD: serverloop.c,v 1.128 2006/03/04 04:12:58 djm Exp $");
40 #include <sys/types.h>
60 #include "auth-options.h"
61 #include "serverloop.h"
65 extern ServerOptions options;
69 extern Authctxt *the_authctxt;
70 extern int use_privsep;
72 static Buffer stdin_buffer; /* Buffer for stdin data. */
73 static Buffer stdout_buffer; /* Buffer for stdout data. */
74 static Buffer stderr_buffer; /* Buffer for stderr data. */
75 static int fdin; /* Descriptor for stdin (for writing) */
76 static int fdout; /* Descriptor for stdout (for reading);
77 May be same number as fdin. */
78 static int fderr; /* Descriptor for stderr. May be -1. */
79 static long stdin_bytes = 0; /* Number of bytes written to stdin. */
80 static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
81 static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
82 static long fdout_bytes = 0; /* Number of stdout bytes read from program. */
83 static int stdin_eof = 0; /* EOF message received from client. */
84 static int fdout_eof = 0; /* EOF encountered reading from fdout. */
85 static int fderr_eof = 0; /* EOF encountered readung from fderr. */
86 static int fdin_is_tty = 0; /* fdin points to a tty. */
87 static int connection_in; /* Connection to client (input). */
88 static int connection_out; /* Connection to client (output). */
89 static int connection_closed = 0; /* Connection to client closed. */
90 static u_int buffer_high; /* "Soft" max buffer size. */
91 static int client_alive_timeouts = 0;
94 * This SIGCHLD kludge is used to detect when the child exits. The server
95 * will exit after that, as soon as forwarded connections have terminated.
98 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
100 /* Cleanup on signals (!use_privsep case only) */
101 static volatile sig_atomic_t received_sigterm = 0;
104 static void server_init_dispatch(void);
107 * we write to this pipe if a SIGCHLD is caught in order to avoid
108 * the race between select() and child_terminated
110 static int notify_pipe[2];
114 if (pipe(notify_pipe) < 0) {
115 error("pipe(notify_pipe) failed %s", strerror(errno));
116 } else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
117 (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
118 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
119 close(notify_pipe[0]);
120 close(notify_pipe[1]);
122 set_nonblock(notify_pipe[0]);
123 set_nonblock(notify_pipe[1]);
126 notify_pipe[0] = -1; /* read end */
127 notify_pipe[1] = -1; /* write end */
132 if (notify_pipe[1] != -1)
133 write(notify_pipe[1], "", 1);
136 notify_prepare(fd_set *readset)
138 if (notify_pipe[0] != -1)
139 FD_SET(notify_pipe[0], readset);
142 notify_done(fd_set *readset)
146 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
147 while (read(notify_pipe[0], &c, 1) != -1)
148 debug2("notify_done: reading");
152 sigchld_handler(int sig)
154 int save_errno = errno;
155 child_terminated = 1;
157 mysignal(SIGCHLD, sigchld_handler);
164 sigterm_handler(int sig)
166 received_sigterm = sig;
170 * Make packets from buffered stderr data, and buffer it for sending
174 make_packets_from_stderr_data(void)
178 /* Send buffered stderr data to the client. */
179 while (buffer_len(&stderr_buffer) > 0 &&
180 packet_not_very_much_data_to_write()) {
181 len = buffer_len(&stderr_buffer);
182 if (packet_is_interactive()) {
186 /* Keep the packets at reasonable size. */
187 if (len > packet_get_maxsize())
188 len = packet_get_maxsize();
190 packet_start(SSH_SMSG_STDERR_DATA);
191 packet_put_string(buffer_ptr(&stderr_buffer), len);
193 buffer_consume(&stderr_buffer, len);
199 * Make packets from buffered stdout data, and buffer it for sending to the
203 make_packets_from_stdout_data(void)
207 /* Send buffered stdout data to the client. */
208 while (buffer_len(&stdout_buffer) > 0 &&
209 packet_not_very_much_data_to_write()) {
210 len = buffer_len(&stdout_buffer);
211 if (packet_is_interactive()) {
215 /* Keep the packets at reasonable size. */
216 if (len > packet_get_maxsize())
217 len = packet_get_maxsize();
219 packet_start(SSH_SMSG_STDOUT_DATA);
220 packet_put_string(buffer_ptr(&stdout_buffer), len);
222 buffer_consume(&stdout_buffer, len);
228 client_alive_check(void)
232 /* timeout, check to see how many we have had */
233 if (++client_alive_timeouts > options.client_alive_count_max)
234 packet_disconnect("Timeout, your session not responding.");
237 * send a bogus global/channel request with "wantreply",
238 * we should get back a failure
240 if ((channel_id = channel_find_open()) == -1) {
241 packet_start(SSH2_MSG_GLOBAL_REQUEST);
242 packet_put_cstring("keepalive@openssh.com");
243 packet_put_char(1); /* boolean: want reply */
245 channel_request_start(channel_id, "keepalive@openssh.com", 1);
251 * Sleep in select() until we can do something. This will initialize the
252 * select masks. Upon return, the masks will indicate which descriptors
253 * have data or can accept data. Optionally, a maximum time can be specified
254 * for the duration of the wait (0 = infinite).
257 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
258 u_int *nallocp, u_int max_time_milliseconds)
260 struct timeval tv, *tvp;
262 int client_alive_scheduled = 0;
265 * if using client_alive, set the max timeout accordingly,
266 * and indicate that this particular timeout was for client
267 * alive by setting the client_alive_scheduled flag.
269 * this could be randomized somewhat to make traffic
270 * analysis more difficult, but we're not doing it yet.
273 max_time_milliseconds == 0 && options.client_alive_interval) {
274 client_alive_scheduled = 1;
275 max_time_milliseconds = options.client_alive_interval * 1000;
278 /* Allocate and update select() masks for channel descriptors. */
279 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
283 /* wrong: bad condition XXX */
284 if (channel_not_very_much_buffered_data())
286 FD_SET(connection_in, *readsetp);
289 * Read packets from the client unless we have too much
290 * buffered stdin or channel data.
292 if (buffer_len(&stdin_buffer) < buffer_high &&
293 channel_not_very_much_buffered_data())
294 FD_SET(connection_in, *readsetp);
296 * If there is not too much data already buffered going to
297 * the client, try to get some more data from the program.
299 if (packet_not_very_much_data_to_write()) {
301 FD_SET(fdout, *readsetp);
303 FD_SET(fderr, *readsetp);
306 * If we have buffered data, try to write some of that data
309 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
310 FD_SET(fdin, *writesetp);
312 notify_prepare(*readsetp);
315 * If we have buffered packet data going to the client, mark that
318 if (packet_have_data_to_write())
319 FD_SET(connection_out, *writesetp);
322 * If child has terminated and there is enough buffer space to read
323 * from it, then read as much as is available and exit.
325 if (child_terminated && packet_not_very_much_data_to_write())
326 if (max_time_milliseconds == 0 || client_alive_scheduled)
327 max_time_milliseconds = 100;
329 if (max_time_milliseconds == 0)
332 tv.tv_sec = max_time_milliseconds / 1000;
333 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
337 /* Wait for something to happen, or the timeout to expire. */
338 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
341 memset(*readsetp, 0, *nallocp);
342 memset(*writesetp, 0, *nallocp);
344 error("select: %.100s", strerror(errno));
345 } else if (ret == 0 && client_alive_scheduled)
346 client_alive_check();
348 notify_done(*readsetp);
352 * Processes input from the client and the program. Input data is stored
353 * in buffers and processed later.
356 process_input(fd_set * readset)
361 /* Read and buffer any input data from the client. */
362 if (FD_ISSET(connection_in, readset)) {
363 len = read(connection_in, buf, sizeof(buf));
365 verbose("Connection closed by %.100s",
366 get_remote_ipaddr());
367 connection_closed = 1;
371 } else if (len < 0) {
372 if (errno != EINTR && errno != EAGAIN) {
373 verbose("Read error from remote host "
375 get_remote_ipaddr(), strerror(errno));
379 /* Buffer any received data. */
380 packet_process_incoming(buf, len);
386 /* Read and buffer any available stdout data from the program. */
387 if (!fdout_eof && FD_ISSET(fdout, readset)) {
388 len = read(fdout, buf, sizeof(buf));
389 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
391 } else if (len <= 0) {
394 buffer_append(&stdout_buffer, buf, len);
398 /* Read and buffer any available stderr data from the program. */
399 if (!fderr_eof && FD_ISSET(fderr, readset)) {
400 len = read(fderr, buf, sizeof(buf));
401 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
403 } else if (len <= 0) {
406 buffer_append(&stderr_buffer, buf, len);
412 * Sends data from internal buffers to client program stdin.
415 process_output(fd_set * writeset)
422 /* Write buffered data to program stdin. */
423 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
424 data = buffer_ptr(&stdin_buffer);
425 dlen = buffer_len(&stdin_buffer);
426 len = write(fdin, data, dlen);
427 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
429 } else if (len <= 0) {
433 shutdown(fdin, SHUT_WR); /* We will no longer send. */
436 /* Successful write. */
437 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
438 tcgetattr(fdin, &tio) == 0 &&
439 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
441 * Simulate echo to reduce the impact of
444 packet_send_ignore(len);
447 /* Consume the data from the buffer. */
448 buffer_consume(&stdin_buffer, len);
449 /* Update the count of bytes written to the program. */
453 /* Send any buffered packet data to the client. */
454 if (FD_ISSET(connection_out, writeset))
459 * Wait until all buffered output has been sent to the client.
460 * This is used when the program terminates.
465 /* Send any buffered stdout data to the client. */
466 if (buffer_len(&stdout_buffer) > 0) {
467 packet_start(SSH_SMSG_STDOUT_DATA);
468 packet_put_string(buffer_ptr(&stdout_buffer),
469 buffer_len(&stdout_buffer));
471 /* Update the count of sent bytes. */
472 stdout_bytes += buffer_len(&stdout_buffer);
474 /* Send any buffered stderr data to the client. */
475 if (buffer_len(&stderr_buffer) > 0) {
476 packet_start(SSH_SMSG_STDERR_DATA);
477 packet_put_string(buffer_ptr(&stderr_buffer),
478 buffer_len(&stderr_buffer));
480 /* Update the count of sent bytes. */
481 stderr_bytes += buffer_len(&stderr_buffer);
483 /* Wait until all buffered data has been written to the client. */
488 process_buffered_input_packets(void)
490 dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
494 * Performs the interactive session. This handles data transmission between
495 * the client and the program. Note that the notion of stdin, stdout, and
496 * stderr in this function is sort of reversed: this function writes to
497 * stdin (of the child program), and reads from stdout and stderr (of the
501 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
503 fd_set *readset = NULL, *writeset = NULL;
506 int wait_status; /* Status returned by wait(). */
507 pid_t wait_pid; /* pid returned by wait(). */
508 int waiting_termination = 0; /* Have displayed waiting close message. */
509 u_int max_time_milliseconds;
510 u_int previous_stdout_buffer_bytes;
511 u_int stdout_buffer_bytes;
514 debug("Entering interactive session.");
516 /* Initialize the SIGCHLD kludge. */
517 child_terminated = 0;
518 mysignal(SIGCHLD, sigchld_handler);
521 signal(SIGTERM, sigterm_handler);
522 signal(SIGINT, sigterm_handler);
523 signal(SIGQUIT, sigterm_handler);
526 /* Initialize our global variables. */
534 /* we don't have stderr for interactive terminal sessions, see below */
538 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
541 connection_in = packet_get_connection_in();
542 connection_out = packet_get_connection_out();
546 previous_stdout_buffer_bytes = 0;
548 /* Set approximate I/O buffer size. */
549 if (packet_is_interactive())
552 buffer_high = 64 * 1024;
555 /* Initialize max_fd to the maximum of the known file descriptors. */
556 max_fd = MAX(connection_in, connection_out);
557 max_fd = MAX(max_fd, fdin);
558 max_fd = MAX(max_fd, fdout);
560 max_fd = MAX(max_fd, fderr);
563 /* Initialize Initialize buffers. */
564 buffer_init(&stdin_buffer);
565 buffer_init(&stdout_buffer);
566 buffer_init(&stderr_buffer);
569 * If we have no separate fderr (which is the case when we have a pty
570 * - there we cannot make difference between data sent to stdout and
571 * stderr), indicate that we have seen an EOF from stderr. This way
572 * we don't need to check the descriptor everywhere.
577 server_init_dispatch();
579 /* Main loop of the server for the interactive session mode. */
582 /* Process buffered packets from the client. */
583 process_buffered_input_packets();
586 * If we have received eof, and there is no more pending
587 * input data, cause a real eof by closing fdin.
589 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
593 shutdown(fdin, SHUT_WR); /* We will no longer send. */
596 /* Make packets from buffered stderr data to send to the client. */
597 make_packets_from_stderr_data();
600 * Make packets from buffered stdout data to send to the
601 * client. If there is very little to send, this arranges to
602 * not send them now, but to wait a short while to see if we
603 * are getting more data. This is necessary, as some systems
604 * wake up readers from a pty after each separate character.
606 max_time_milliseconds = 0;
607 stdout_buffer_bytes = buffer_len(&stdout_buffer);
608 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
609 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
610 /* try again after a while */
611 max_time_milliseconds = 10;
614 make_packets_from_stdout_data();
616 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
618 /* Send channel data to the client. */
619 if (packet_not_very_much_data_to_write())
620 channel_output_poll();
623 * Bail out of the loop if the program has closed its output
624 * descriptors, and we have no more data to send to the
625 * client, and there is no pending buffered data.
627 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
628 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
629 if (!channel_still_open())
631 if (!waiting_termination) {
632 const char *s = "Waiting for forwarded connections to terminate...\r\n";
634 waiting_termination = 1;
635 buffer_append(&stderr_buffer, s, strlen(s));
637 /* Display list of open channels. */
638 cp = channel_open_message();
639 buffer_append(&stderr_buffer, cp, strlen(cp));
643 max_fd = MAX(connection_in, connection_out);
644 max_fd = MAX(max_fd, fdin);
645 max_fd = MAX(max_fd, fdout);
646 max_fd = MAX(max_fd, fderr);
647 max_fd = MAX(max_fd, notify_pipe[0]);
649 /* Sleep in select() until we can do something. */
650 wait_until_can_do_something(&readset, &writeset, &max_fd,
651 &nalloc, max_time_milliseconds);
653 if (received_sigterm) {
654 logit("Exiting on signal %d", received_sigterm);
655 /* Clean up sessions, utmp, etc. */
659 /* Process any channel events. */
660 channel_after_select(readset, writeset);
662 /* Process input from the client and from program stdout/stderr. */
663 process_input(readset);
665 /* Process output to the client and to program stdin. */
666 process_output(writeset);
673 /* Cleanup and termination code. */
675 /* Wait until all output has been sent to the client. */
678 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
679 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
681 /* Free and clear the buffers. */
682 buffer_free(&stdin_buffer);
683 buffer_free(&stdout_buffer);
684 buffer_free(&stderr_buffer);
686 /* Close the file descriptors. */
701 /* We no longer want our SIGCHLD handler to be called. */
702 mysignal(SIGCHLD, SIG_DFL);
704 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
706 packet_disconnect("wait: %.100s", strerror(errno));
708 error("Strange, wait returned pid %ld, expected %ld",
709 (long)wait_pid, (long)pid);
711 /* Check if it exited normally. */
712 if (WIFEXITED(wait_status)) {
713 /* Yes, normal exit. Get exit status and send it to the client. */
714 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
715 packet_start(SSH_SMSG_EXITSTATUS);
716 packet_put_int(WEXITSTATUS(wait_status));
721 * Wait for exit confirmation. Note that there might be
722 * other packets coming before it; however, the program has
723 * already died so we just ignore them. The client is
724 * supposed to respond with the confirmation when it receives
728 type = packet_read();
730 while (type != SSH_CMSG_EXIT_CONFIRMATION);
732 debug("Received exit confirmation.");
735 /* Check if the program terminated due to a signal. */
736 if (WIFSIGNALED(wait_status))
737 packet_disconnect("Command terminated on signal %d.",
738 WTERMSIG(wait_status));
740 /* Some weird exit cause. Just exit. */
741 packet_disconnect("wait returned status %04x.", wait_status);
746 collect_children(void)
752 /* block SIGCHLD while we check for dead children */
754 sigaddset(&nset, SIGCHLD);
755 sigprocmask(SIG_BLOCK, &nset, &oset);
756 if (child_terminated) {
757 debug("Received SIGCHLD.");
758 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
759 (pid < 0 && errno == EINTR))
761 session_close_by_pid(pid, status);
762 child_terminated = 0;
764 sigprocmask(SIG_SETMASK, &oset, NULL);
768 server_loop2(Authctxt *authctxt)
770 fd_set *readset = NULL, *writeset = NULL;
771 int rekeying = 0, max_fd, nalloc = 0;
773 debug("Entering interactive session for SSH2.");
775 mysignal(SIGCHLD, sigchld_handler);
776 child_terminated = 0;
777 connection_in = packet_get_connection_in();
778 connection_out = packet_get_connection_out();
781 signal(SIGTERM, sigterm_handler);
782 signal(SIGINT, sigterm_handler);
783 signal(SIGQUIT, sigterm_handler);
788 max_fd = MAX(connection_in, connection_out);
789 max_fd = MAX(max_fd, notify_pipe[0]);
791 server_init_dispatch();
794 process_buffered_input_packets();
796 rekeying = (xxx_kex != NULL && !xxx_kex->done);
798 if (!rekeying && packet_not_very_much_data_to_write())
799 channel_output_poll();
800 wait_until_can_do_something(&readset, &writeset, &max_fd,
803 if (received_sigterm) {
804 logit("Exiting on signal %d", received_sigterm);
805 /* Clean up sessions, utmp, etc. */
811 channel_after_select(readset, writeset);
812 if (packet_need_rekeying()) {
813 debug("need rekeying");
815 kex_send_kexinit(xxx_kex);
818 process_input(readset);
819 if (connection_closed)
821 process_output(writeset);
830 /* free all channels, no more reads and writes */
833 /* free remaining sessions, e.g. remove wtmp entries */
834 session_destroy_all(NULL);
838 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
840 debug("Got %d/%u for keepalive", type, seq);
842 * reset timeout, since we got a sane answer from the client.
843 * even if this was generated by something other than
844 * the bogus CHANNEL_REQUEST we send for keepalives.
846 client_alive_timeouts = 0;
850 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
855 /* Stdin data from the client. Append it to the buffer. */
856 /* Ignore any data if the client has closed stdin. */
859 data = packet_get_string(&data_len);
861 buffer_append(&stdin_buffer, data, data_len);
862 memset(data, 0, data_len);
867 server_input_eof(int type, u_int32_t seq, void *ctxt)
870 * Eof from the client. The stdin descriptor to the
871 * program will be closed when all buffered data has
874 debug("EOF received for stdin.");
880 server_input_window_size(int type, u_int32_t seq, void *ctxt)
882 int row = packet_get_int();
883 int col = packet_get_int();
884 int xpixel = packet_get_int();
885 int ypixel = packet_get_int();
887 debug("Window change received.");
890 pty_change_window_size(fdin, row, col, xpixel, ypixel);
894 server_request_direct_tcpip(void)
898 char *target, *originator;
899 int target_port, originator_port;
901 target = packet_get_string(NULL);
902 target_port = packet_get_int();
903 originator = packet_get_string(NULL);
904 originator_port = packet_get_int();
907 debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
908 originator, originator_port, target, target_port);
910 /* XXX check permission */
911 sock = channel_connect_to(target, target_port);
916 c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
917 sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
918 CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
923 server_request_tun(void)
929 mode = packet_get_int();
931 case SSH_TUNMODE_POINTOPOINT:
932 case SSH_TUNMODE_ETHERNET:
935 packet_send_debug("Unsupported tunnel device mode.");
938 if ((options.permit_tun & mode) == 0) {
939 packet_send_debug("Server has rejected tunnel device "
944 tun = packet_get_int();
945 if (forced_tun_device != -1) {
946 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
948 tun = forced_tun_device;
950 sock = tun_open(tun, mode);
953 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
954 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
956 #if defined(SSH_TUN_FILTER)
957 if (mode == SSH_TUNMODE_POINTOPOINT)
958 channel_register_filter(c->self, sys_tun_infilter,
964 packet_send_debug("Failed to open the tunnel device.");
969 server_request_session(void)
973 debug("input_session_request");
976 * A server session has no fd to read or write until a
977 * CHANNEL_REQUEST for a shell is made, so we set the type to
978 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
979 * CHANNEL_REQUEST messages is registered.
981 c = channel_new("session", SSH_CHANNEL_LARVAL,
982 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
983 0, "server-session", 1);
984 if (session_open(the_authctxt, c->self) != 1) {
985 debug("session open failed, free channel %d", c->self);
989 channel_register_cleanup(c->self, session_close_by_channel, 0);
994 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
999 u_int rmaxpack, rwindow, len;
1001 ctype = packet_get_string(&len);
1002 rchan = packet_get_int();
1003 rwindow = packet_get_int();
1004 rmaxpack = packet_get_int();
1006 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1007 ctype, rchan, rwindow, rmaxpack);
1009 if (strcmp(ctype, "session") == 0) {
1010 c = server_request_session();
1011 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1012 c = server_request_direct_tcpip();
1013 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1014 c = server_request_tun();
1017 debug("server_input_channel_open: confirm %s", ctype);
1018 c->remote_id = rchan;
1019 c->remote_window = rwindow;
1020 c->remote_maxpacket = rmaxpack;
1021 if (c->type != SSH_CHANNEL_CONNECTING) {
1022 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1023 packet_put_int(c->remote_id);
1024 packet_put_int(c->self);
1025 packet_put_int(c->local_window);
1026 packet_put_int(c->local_maxpacket);
1030 debug("server_input_channel_open: failure %s", ctype);
1031 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1032 packet_put_int(rchan);
1033 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1034 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1035 packet_put_cstring("open failed");
1036 packet_put_cstring("");
1044 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1050 rtype = packet_get_string(NULL);
1051 want_reply = packet_get_char();
1052 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1054 /* -R style forwarding */
1055 if (strcmp(rtype, "tcpip-forward") == 0) {
1057 char *listen_address;
1058 u_short listen_port;
1060 pw = the_authctxt->pw;
1061 if (pw == NULL || !the_authctxt->valid)
1062 fatal("server_input_global_request: no/invalid user");
1063 listen_address = packet_get_string(NULL);
1064 listen_port = (u_short)packet_get_int();
1065 debug("server_input_global_request: tcpip-forward listen %s port %d",
1066 listen_address, listen_port);
1068 /* check permissions */
1069 if (!options.allow_tcp_forwarding ||
1070 no_port_forwarding_flag
1071 #ifndef NO_IPPORT_RESERVED_CONCEPT
1072 || (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)
1076 packet_send_debug("Server has disabled port forwarding.");
1078 /* Start listening on the port */
1079 success = channel_setup_remote_fwd_listener(
1080 listen_address, listen_port, options.gateway_ports);
1082 xfree(listen_address);
1083 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1084 char *cancel_address;
1085 u_short cancel_port;
1087 cancel_address = packet_get_string(NULL);
1088 cancel_port = (u_short)packet_get_int();
1089 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1090 cancel_address, cancel_port);
1092 success = channel_cancel_rport_listener(cancel_address,
1096 packet_start(success ?
1097 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1099 packet_write_wait();
1104 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1107 int id, reply, success = 0;
1110 id = packet_get_int();
1111 rtype = packet_get_string(NULL);
1112 reply = packet_get_char();
1114 debug("server_input_channel_req: channel %d request %s reply %d",
1117 if ((c = channel_lookup(id)) == NULL)
1118 packet_disconnect("server_input_channel_req: "
1119 "unknown channel %d", id);
1120 if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1121 success = session_input_channel_req(c, rtype);
1123 packet_start(success ?
1124 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1125 packet_put_int(c->remote_id);
1132 server_init_dispatch_20(void)
1134 debug("server_init_dispatch_20");
1135 dispatch_init(&dispatch_protocol_error);
1136 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1137 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1138 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1139 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1140 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1141 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1142 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1143 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1144 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1145 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1147 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1148 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1149 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1151 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1154 server_init_dispatch_13(void)
1156 debug("server_init_dispatch_13");
1157 dispatch_init(NULL);
1158 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1159 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1160 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1161 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1162 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1163 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1164 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1165 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1166 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1169 server_init_dispatch_15(void)
1171 server_init_dispatch_13();
1172 debug("server_init_dispatch_15");
1173 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1174 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1177 server_init_dispatch(void)
1180 server_init_dispatch_20();
1182 server_init_dispatch_13();
1184 server_init_dispatch_15();