1 /* $OpenBSD: serverloop.c,v 1.137 2006/07/06 16:03:53 stevesk 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>
42 #include <sys/socket.h>
44 #include <netinet/in.h>
64 #include "auth-options.h"
65 #include "serverloop.h"
69 extern ServerOptions options;
73 extern Authctxt *the_authctxt;
74 extern int use_privsep;
76 static Buffer stdin_buffer; /* Buffer for stdin data. */
77 static Buffer stdout_buffer; /* Buffer for stdout data. */
78 static Buffer stderr_buffer; /* Buffer for stderr data. */
79 static int fdin; /* Descriptor for stdin (for writing) */
80 static int fdout; /* Descriptor for stdout (for reading);
81 May be same number as fdin. */
82 static int fderr; /* Descriptor for stderr. May be -1. */
83 static long stdin_bytes = 0; /* Number of bytes written to stdin. */
84 static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
85 static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
86 static long fdout_bytes = 0; /* Number of stdout bytes read from program. */
87 static int stdin_eof = 0; /* EOF message received from client. */
88 static int fdout_eof = 0; /* EOF encountered reading from fdout. */
89 static int fderr_eof = 0; /* EOF encountered readung from fderr. */
90 static int fdin_is_tty = 0; /* fdin points to a tty. */
91 static int connection_in; /* Connection to client (input). */
92 static int connection_out; /* Connection to client (output). */
93 static int connection_closed = 0; /* Connection to client closed. */
94 static u_int buffer_high; /* "Soft" max buffer size. */
95 static int client_alive_timeouts = 0;
98 * This SIGCHLD kludge is used to detect when the child exits. The server
99 * will exit after that, as soon as forwarded connections have terminated.
102 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
104 /* Cleanup on signals (!use_privsep case only) */
105 static volatile sig_atomic_t received_sigterm = 0;
108 static void server_init_dispatch(void);
111 * we write to this pipe if a SIGCHLD is caught in order to avoid
112 * the race between select() and child_terminated
114 static int notify_pipe[2];
118 if (pipe(notify_pipe) < 0) {
119 error("pipe(notify_pipe) failed %s", strerror(errno));
120 } else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
121 (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
122 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
123 close(notify_pipe[0]);
124 close(notify_pipe[1]);
126 set_nonblock(notify_pipe[0]);
127 set_nonblock(notify_pipe[1]);
130 notify_pipe[0] = -1; /* read end */
131 notify_pipe[1] = -1; /* write end */
136 if (notify_pipe[1] != -1)
137 write(notify_pipe[1], "", 1);
140 notify_prepare(fd_set *readset)
142 if (notify_pipe[0] != -1)
143 FD_SET(notify_pipe[0], readset);
146 notify_done(fd_set *readset)
150 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
151 while (read(notify_pipe[0], &c, 1) != -1)
152 debug2("notify_done: reading");
157 sigchld_handler(int sig)
159 int save_errno = errno;
160 child_terminated = 1;
162 mysignal(SIGCHLD, sigchld_handler);
170 sigterm_handler(int sig)
172 received_sigterm = sig;
176 * Make packets from buffered stderr data, and buffer it for sending
180 make_packets_from_stderr_data(void)
184 /* Send buffered stderr data to the client. */
185 while (buffer_len(&stderr_buffer) > 0 &&
186 packet_not_very_much_data_to_write()) {
187 len = buffer_len(&stderr_buffer);
188 if (packet_is_interactive()) {
192 /* Keep the packets at reasonable size. */
193 if (len > packet_get_maxsize())
194 len = packet_get_maxsize();
196 packet_start(SSH_SMSG_STDERR_DATA);
197 packet_put_string(buffer_ptr(&stderr_buffer), len);
199 buffer_consume(&stderr_buffer, len);
205 * Make packets from buffered stdout data, and buffer it for sending to the
209 make_packets_from_stdout_data(void)
213 /* Send buffered stdout data to the client. */
214 while (buffer_len(&stdout_buffer) > 0 &&
215 packet_not_very_much_data_to_write()) {
216 len = buffer_len(&stdout_buffer);
217 if (packet_is_interactive()) {
221 /* Keep the packets at reasonable size. */
222 if (len > packet_get_maxsize())
223 len = packet_get_maxsize();
225 packet_start(SSH_SMSG_STDOUT_DATA);
226 packet_put_string(buffer_ptr(&stdout_buffer), len);
228 buffer_consume(&stdout_buffer, len);
234 client_alive_check(void)
238 /* timeout, check to see how many we have had */
239 if (++client_alive_timeouts > options.client_alive_count_max)
240 packet_disconnect("Timeout, your session not responding.");
243 * send a bogus global/channel request with "wantreply",
244 * we should get back a failure
246 if ((channel_id = channel_find_open()) == -1) {
247 packet_start(SSH2_MSG_GLOBAL_REQUEST);
248 packet_put_cstring("keepalive@openssh.com");
249 packet_put_char(1); /* boolean: want reply */
251 channel_request_start(channel_id, "keepalive@openssh.com", 1);
257 * Sleep in select() until we can do something. This will initialize the
258 * select masks. Upon return, the masks will indicate which descriptors
259 * have data or can accept data. Optionally, a maximum time can be specified
260 * for the duration of the wait (0 = infinite).
263 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
264 u_int *nallocp, u_int max_time_milliseconds)
266 struct timeval tv, *tvp;
268 int client_alive_scheduled = 0;
271 * if using client_alive, set the max timeout accordingly,
272 * and indicate that this particular timeout was for client
273 * alive by setting the client_alive_scheduled flag.
275 * this could be randomized somewhat to make traffic
276 * analysis more difficult, but we're not doing it yet.
279 max_time_milliseconds == 0 && options.client_alive_interval) {
280 client_alive_scheduled = 1;
281 max_time_milliseconds = options.client_alive_interval * 1000;
284 /* Allocate and update select() masks for channel descriptors. */
285 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
289 /* wrong: bad condition XXX */
290 if (channel_not_very_much_buffered_data())
292 FD_SET(connection_in, *readsetp);
295 * Read packets from the client unless we have too much
296 * buffered stdin or channel data.
298 if (buffer_len(&stdin_buffer) < buffer_high &&
299 channel_not_very_much_buffered_data())
300 FD_SET(connection_in, *readsetp);
302 * If there is not too much data already buffered going to
303 * the client, try to get some more data from the program.
305 if (packet_not_very_much_data_to_write()) {
307 FD_SET(fdout, *readsetp);
309 FD_SET(fderr, *readsetp);
312 * If we have buffered data, try to write some of that data
315 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
316 FD_SET(fdin, *writesetp);
318 notify_prepare(*readsetp);
321 * If we have buffered packet data going to the client, mark that
324 if (packet_have_data_to_write())
325 FD_SET(connection_out, *writesetp);
328 * If child has terminated and there is enough buffer space to read
329 * from it, then read as much as is available and exit.
331 if (child_terminated && packet_not_very_much_data_to_write())
332 if (max_time_milliseconds == 0 || client_alive_scheduled)
333 max_time_milliseconds = 100;
335 if (max_time_milliseconds == 0)
338 tv.tv_sec = max_time_milliseconds / 1000;
339 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
343 /* Wait for something to happen, or the timeout to expire. */
344 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
347 memset(*readsetp, 0, *nallocp);
348 memset(*writesetp, 0, *nallocp);
350 error("select: %.100s", strerror(errno));
351 } else if (ret == 0 && client_alive_scheduled)
352 client_alive_check();
354 notify_done(*readsetp);
358 * Processes input from the client and the program. Input data is stored
359 * in buffers and processed later.
362 process_input(fd_set *readset)
367 /* Read and buffer any input data from the client. */
368 if (FD_ISSET(connection_in, readset)) {
369 len = read(connection_in, buf, sizeof(buf));
371 verbose("Connection closed by %.100s",
372 get_remote_ipaddr());
373 connection_closed = 1;
377 } else if (len < 0) {
378 if (errno != EINTR && errno != EAGAIN) {
379 verbose("Read error from remote host "
381 get_remote_ipaddr(), strerror(errno));
385 /* Buffer any received data. */
386 packet_process_incoming(buf, len);
392 /* Read and buffer any available stdout data from the program. */
393 if (!fdout_eof && FD_ISSET(fdout, readset)) {
395 len = read(fdout, buf, sizeof(buf));
396 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
399 } else if (len <= 0) {
401 } else if ((!isatty(fdout) && len <= 0) ||
402 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
406 buffer_append(&stdout_buffer, buf, len);
410 /* Read and buffer any available stderr data from the program. */
411 if (!fderr_eof && FD_ISSET(fderr, readset)) {
413 len = read(fderr, buf, sizeof(buf));
414 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
417 } else if (len <= 0) {
419 } else if ((!isatty(fderr) && len <= 0) ||
420 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
424 buffer_append(&stderr_buffer, buf, len);
430 * Sends data from internal buffers to client program stdin.
433 process_output(fd_set *writeset)
440 /* Write buffered data to program stdin. */
441 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
442 data = buffer_ptr(&stdin_buffer);
443 dlen = buffer_len(&stdin_buffer);
444 len = write(fdin, data, dlen);
445 if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
447 } else if (len <= 0) {
451 shutdown(fdin, SHUT_WR); /* We will no longer send. */
454 /* Successful write. */
455 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
456 tcgetattr(fdin, &tio) == 0 &&
457 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
459 * Simulate echo to reduce the impact of
462 packet_send_ignore(len);
465 /* Consume the data from the buffer. */
466 buffer_consume(&stdin_buffer, len);
467 /* Update the count of bytes written to the program. */
471 /* Send any buffered packet data to the client. */
472 if (FD_ISSET(connection_out, writeset))
477 * Wait until all buffered output has been sent to the client.
478 * This is used when the program terminates.
483 /* Send any buffered stdout data to the client. */
484 if (buffer_len(&stdout_buffer) > 0) {
485 packet_start(SSH_SMSG_STDOUT_DATA);
486 packet_put_string(buffer_ptr(&stdout_buffer),
487 buffer_len(&stdout_buffer));
489 /* Update the count of sent bytes. */
490 stdout_bytes += buffer_len(&stdout_buffer);
492 /* Send any buffered stderr data to the client. */
493 if (buffer_len(&stderr_buffer) > 0) {
494 packet_start(SSH_SMSG_STDERR_DATA);
495 packet_put_string(buffer_ptr(&stderr_buffer),
496 buffer_len(&stderr_buffer));
498 /* Update the count of sent bytes. */
499 stderr_bytes += buffer_len(&stderr_buffer);
501 /* Wait until all buffered data has been written to the client. */
506 process_buffered_input_packets(void)
508 dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
512 * Performs the interactive session. This handles data transmission between
513 * the client and the program. Note that the notion of stdin, stdout, and
514 * stderr in this function is sort of reversed: this function writes to
515 * stdin (of the child program), and reads from stdout and stderr (of the
519 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
521 fd_set *readset = NULL, *writeset = NULL;
524 int wait_status; /* Status returned by wait(). */
525 pid_t wait_pid; /* pid returned by wait(). */
526 int waiting_termination = 0; /* Have displayed waiting close message. */
527 u_int max_time_milliseconds;
528 u_int previous_stdout_buffer_bytes;
529 u_int stdout_buffer_bytes;
532 debug("Entering interactive session.");
534 /* Initialize the SIGCHLD kludge. */
535 child_terminated = 0;
536 mysignal(SIGCHLD, sigchld_handler);
539 signal(SIGTERM, sigterm_handler);
540 signal(SIGINT, sigterm_handler);
541 signal(SIGQUIT, sigterm_handler);
544 /* Initialize our global variables. */
552 /* we don't have stderr for interactive terminal sessions, see below */
556 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
559 connection_in = packet_get_connection_in();
560 connection_out = packet_get_connection_out();
564 previous_stdout_buffer_bytes = 0;
566 /* Set approximate I/O buffer size. */
567 if (packet_is_interactive())
570 buffer_high = 64 * 1024;
573 /* Initialize max_fd to the maximum of the known file descriptors. */
574 max_fd = MAX(connection_in, connection_out);
575 max_fd = MAX(max_fd, fdin);
576 max_fd = MAX(max_fd, fdout);
578 max_fd = MAX(max_fd, fderr);
581 /* Initialize Initialize buffers. */
582 buffer_init(&stdin_buffer);
583 buffer_init(&stdout_buffer);
584 buffer_init(&stderr_buffer);
587 * If we have no separate fderr (which is the case when we have a pty
588 * - there we cannot make difference between data sent to stdout and
589 * stderr), indicate that we have seen an EOF from stderr. This way
590 * we don't need to check the descriptor everywhere.
595 server_init_dispatch();
597 /* Main loop of the server for the interactive session mode. */
600 /* Process buffered packets from the client. */
601 process_buffered_input_packets();
604 * If we have received eof, and there is no more pending
605 * input data, cause a real eof by closing fdin.
607 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
611 shutdown(fdin, SHUT_WR); /* We will no longer send. */
614 /* Make packets from buffered stderr data to send to the client. */
615 make_packets_from_stderr_data();
618 * Make packets from buffered stdout data to send to the
619 * client. If there is very little to send, this arranges to
620 * not send them now, but to wait a short while to see if we
621 * are getting more data. This is necessary, as some systems
622 * wake up readers from a pty after each separate character.
624 max_time_milliseconds = 0;
625 stdout_buffer_bytes = buffer_len(&stdout_buffer);
626 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
627 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
628 /* try again after a while */
629 max_time_milliseconds = 10;
632 make_packets_from_stdout_data();
634 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
636 /* Send channel data to the client. */
637 if (packet_not_very_much_data_to_write())
638 channel_output_poll();
641 * Bail out of the loop if the program has closed its output
642 * descriptors, and we have no more data to send to the
643 * client, and there is no pending buffered data.
645 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
646 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
647 if (!channel_still_open())
649 if (!waiting_termination) {
650 const char *s = "Waiting for forwarded connections to terminate...\r\n";
652 waiting_termination = 1;
653 buffer_append(&stderr_buffer, s, strlen(s));
655 /* Display list of open channels. */
656 cp = channel_open_message();
657 buffer_append(&stderr_buffer, cp, strlen(cp));
661 max_fd = MAX(connection_in, connection_out);
662 max_fd = MAX(max_fd, fdin);
663 max_fd = MAX(max_fd, fdout);
664 max_fd = MAX(max_fd, fderr);
665 max_fd = MAX(max_fd, notify_pipe[0]);
667 /* Sleep in select() until we can do something. */
668 wait_until_can_do_something(&readset, &writeset, &max_fd,
669 &nalloc, max_time_milliseconds);
671 if (received_sigterm) {
672 logit("Exiting on signal %d", received_sigterm);
673 /* Clean up sessions, utmp, etc. */
677 /* Process any channel events. */
678 channel_after_select(readset, writeset);
680 /* Process input from the client and from program stdout/stderr. */
681 process_input(readset);
683 /* Process output to the client and to program stdin. */
684 process_output(writeset);
691 /* Cleanup and termination code. */
693 /* Wait until all output has been sent to the client. */
696 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
697 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
699 /* Free and clear the buffers. */
700 buffer_free(&stdin_buffer);
701 buffer_free(&stdout_buffer);
702 buffer_free(&stderr_buffer);
704 /* Close the file descriptors. */
719 /* We no longer want our SIGCHLD handler to be called. */
720 mysignal(SIGCHLD, SIG_DFL);
722 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
724 packet_disconnect("wait: %.100s", strerror(errno));
726 error("Strange, wait returned pid %ld, expected %ld",
727 (long)wait_pid, (long)pid);
729 /* Check if it exited normally. */
730 if (WIFEXITED(wait_status)) {
731 /* Yes, normal exit. Get exit status and send it to the client. */
732 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
733 packet_start(SSH_SMSG_EXITSTATUS);
734 packet_put_int(WEXITSTATUS(wait_status));
739 * Wait for exit confirmation. Note that there might be
740 * other packets coming before it; however, the program has
741 * already died so we just ignore them. The client is
742 * supposed to respond with the confirmation when it receives
746 type = packet_read();
748 while (type != SSH_CMSG_EXIT_CONFIRMATION);
750 debug("Received exit confirmation.");
753 /* Check if the program terminated due to a signal. */
754 if (WIFSIGNALED(wait_status))
755 packet_disconnect("Command terminated on signal %d.",
756 WTERMSIG(wait_status));
758 /* Some weird exit cause. Just exit. */
759 packet_disconnect("wait returned status %04x.", wait_status);
764 collect_children(void)
770 /* block SIGCHLD while we check for dead children */
772 sigaddset(&nset, SIGCHLD);
773 sigprocmask(SIG_BLOCK, &nset, &oset);
774 if (child_terminated) {
775 debug("Received SIGCHLD.");
776 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
777 (pid < 0 && errno == EINTR))
779 session_close_by_pid(pid, status);
780 child_terminated = 0;
782 sigprocmask(SIG_SETMASK, &oset, NULL);
786 server_loop2(Authctxt *authctxt)
788 fd_set *readset = NULL, *writeset = NULL;
789 int rekeying = 0, max_fd, nalloc = 0;
791 debug("Entering interactive session for SSH2.");
793 mysignal(SIGCHLD, sigchld_handler);
794 child_terminated = 0;
795 connection_in = packet_get_connection_in();
796 connection_out = packet_get_connection_out();
799 signal(SIGTERM, sigterm_handler);
800 signal(SIGINT, sigterm_handler);
801 signal(SIGQUIT, sigterm_handler);
806 max_fd = MAX(connection_in, connection_out);
807 max_fd = MAX(max_fd, notify_pipe[0]);
809 server_init_dispatch();
812 process_buffered_input_packets();
814 rekeying = (xxx_kex != NULL && !xxx_kex->done);
816 if (!rekeying && packet_not_very_much_data_to_write())
817 channel_output_poll();
818 wait_until_can_do_something(&readset, &writeset, &max_fd,
821 if (received_sigterm) {
822 logit("Exiting on signal %d", received_sigterm);
823 /* Clean up sessions, utmp, etc. */
829 channel_after_select(readset, writeset);
830 if (packet_need_rekeying()) {
831 debug("need rekeying");
833 kex_send_kexinit(xxx_kex);
836 process_input(readset);
837 if (connection_closed)
839 process_output(writeset);
848 /* free all channels, no more reads and writes */
851 /* free remaining sessions, e.g. remove wtmp entries */
852 session_destroy_all(NULL);
856 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
858 debug("Got %d/%u for keepalive", type, seq);
860 * reset timeout, since we got a sane answer from the client.
861 * even if this was generated by something other than
862 * the bogus CHANNEL_REQUEST we send for keepalives.
864 client_alive_timeouts = 0;
868 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
873 /* Stdin data from the client. Append it to the buffer. */
874 /* Ignore any data if the client has closed stdin. */
877 data = packet_get_string(&data_len);
879 buffer_append(&stdin_buffer, data, data_len);
880 memset(data, 0, data_len);
885 server_input_eof(int type, u_int32_t seq, void *ctxt)
888 * Eof from the client. The stdin descriptor to the
889 * program will be closed when all buffered data has
892 debug("EOF received for stdin.");
898 server_input_window_size(int type, u_int32_t seq, void *ctxt)
900 u_int row = packet_get_int();
901 u_int col = packet_get_int();
902 u_int xpixel = packet_get_int();
903 u_int ypixel = packet_get_int();
905 debug("Window change received.");
908 pty_change_window_size(fdin, row, col, xpixel, ypixel);
912 server_request_direct_tcpip(void)
916 char *target, *originator;
917 int target_port, originator_port;
919 target = packet_get_string(NULL);
920 target_port = packet_get_int();
921 originator = packet_get_string(NULL);
922 originator_port = packet_get_int();
925 debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
926 originator, originator_port, target, target_port);
928 /* XXX check permission */
929 sock = channel_connect_to(target, target_port);
934 c = channel_new("direct-tcpip", SSH_CHANNEL_CONNECTING,
935 sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
936 CHAN_TCP_PACKET_DEFAULT, 0, "direct-tcpip", 1);
941 server_request_tun(void)
947 mode = packet_get_int();
949 case SSH_TUNMODE_POINTOPOINT:
950 case SSH_TUNMODE_ETHERNET:
953 packet_send_debug("Unsupported tunnel device mode.");
956 if ((options.permit_tun & mode) == 0) {
957 packet_send_debug("Server has rejected tunnel device "
962 tun = packet_get_int();
963 if (forced_tun_device != -1) {
964 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
966 tun = forced_tun_device;
968 sock = tun_open(tun, mode);
971 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
972 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
974 #if defined(SSH_TUN_FILTER)
975 if (mode == SSH_TUNMODE_POINTOPOINT)
976 channel_register_filter(c->self, sys_tun_infilter,
982 packet_send_debug("Failed to open the tunnel device.");
987 server_request_session(void)
991 debug("input_session_request");
994 * A server session has no fd to read or write until a
995 * CHANNEL_REQUEST for a shell is made, so we set the type to
996 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
997 * CHANNEL_REQUEST messages is registered.
999 c = channel_new("session", SSH_CHANNEL_LARVAL,
1000 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1001 0, "server-session", 1);
1002 if (session_open(the_authctxt, c->self) != 1) {
1003 debug("session open failed, free channel %d", c->self);
1007 channel_register_cleanup(c->self, session_close_by_channel, 0);
1012 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1017 u_int rmaxpack, rwindow, len;
1019 ctype = packet_get_string(&len);
1020 rchan = packet_get_int();
1021 rwindow = packet_get_int();
1022 rmaxpack = packet_get_int();
1024 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1025 ctype, rchan, rwindow, rmaxpack);
1027 if (strcmp(ctype, "session") == 0) {
1028 c = server_request_session();
1029 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1030 c = server_request_direct_tcpip();
1031 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1032 c = server_request_tun();
1035 debug("server_input_channel_open: confirm %s", ctype);
1036 c->remote_id = rchan;
1037 c->remote_window = rwindow;
1038 c->remote_maxpacket = rmaxpack;
1039 if (c->type != SSH_CHANNEL_CONNECTING) {
1040 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1041 packet_put_int(c->remote_id);
1042 packet_put_int(c->self);
1043 packet_put_int(c->local_window);
1044 packet_put_int(c->local_maxpacket);
1048 debug("server_input_channel_open: failure %s", ctype);
1049 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1050 packet_put_int(rchan);
1051 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1052 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1053 packet_put_cstring("open failed");
1054 packet_put_cstring("");
1062 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1068 rtype = packet_get_string(NULL);
1069 want_reply = packet_get_char();
1070 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1072 /* -R style forwarding */
1073 if (strcmp(rtype, "tcpip-forward") == 0) {
1075 char *listen_address;
1076 u_short listen_port;
1078 pw = the_authctxt->pw;
1079 if (pw == NULL || !the_authctxt->valid)
1080 fatal("server_input_global_request: no/invalid user");
1081 listen_address = packet_get_string(NULL);
1082 listen_port = (u_short)packet_get_int();
1083 debug("server_input_global_request: tcpip-forward listen %s port %d",
1084 listen_address, listen_port);
1086 /* check permissions */
1087 if (!options.allow_tcp_forwarding ||
1088 no_port_forwarding_flag
1089 #ifndef NO_IPPORT_RESERVED_CONCEPT
1090 || (listen_port < IPPORT_RESERVED && pw->pw_uid != 0)
1094 packet_send_debug("Server has disabled port forwarding.");
1096 /* Start listening on the port */
1097 success = channel_setup_remote_fwd_listener(
1098 listen_address, listen_port, options.gateway_ports);
1100 xfree(listen_address);
1101 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1102 char *cancel_address;
1103 u_short cancel_port;
1105 cancel_address = packet_get_string(NULL);
1106 cancel_port = (u_short)packet_get_int();
1107 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1108 cancel_address, cancel_port);
1110 success = channel_cancel_rport_listener(cancel_address,
1112 xfree(cancel_address);
1115 packet_start(success ?
1116 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1118 packet_write_wait();
1124 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1127 int id, reply, success = 0;
1130 id = packet_get_int();
1131 rtype = packet_get_string(NULL);
1132 reply = packet_get_char();
1134 debug("server_input_channel_req: channel %d request %s reply %d",
1137 if ((c = channel_lookup(id)) == NULL)
1138 packet_disconnect("server_input_channel_req: "
1139 "unknown channel %d", id);
1140 if (c->type == SSH_CHANNEL_LARVAL || c->type == SSH_CHANNEL_OPEN)
1141 success = session_input_channel_req(c, rtype);
1143 packet_start(success ?
1144 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1145 packet_put_int(c->remote_id);
1152 server_init_dispatch_20(void)
1154 debug("server_init_dispatch_20");
1155 dispatch_init(&dispatch_protocol_error);
1156 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1157 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1158 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1159 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1160 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1161 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1162 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1163 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1164 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1165 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1167 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1168 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1169 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1171 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1174 server_init_dispatch_13(void)
1176 debug("server_init_dispatch_13");
1177 dispatch_init(NULL);
1178 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1179 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1180 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1181 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1182 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1183 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1184 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1185 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1186 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1189 server_init_dispatch_15(void)
1191 server_init_dispatch_13();
1192 debug("server_init_dispatch_15");
1193 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1194 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1197 server_init_dispatch(void)
1200 server_init_dispatch_20();
1202 server_init_dispatch_13();
1204 server_init_dispatch_15();