1 /* $OpenBSD: serverloop.c,v 1.182 2016/02/08 10:57:07 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/param.h> /* MIN MAX */
41 #include <sys/types.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"
79 #include "auth-options.h"
80 #include "serverloop.h"
83 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 long stdin_bytes = 0; /* Number of bytes written to stdin. */
97 static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
98 static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
99 static 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 * we write to this pipe if a SIGCHLD is caught in order to avoid
125 * the race between select() and child_terminated
127 static int notify_pipe[2];
131 if (pipe(notify_pipe) < 0) {
132 error("pipe(notify_pipe) failed %s", strerror(errno));
133 } else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) ||
134 (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) {
135 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
136 close(notify_pipe[0]);
137 close(notify_pipe[1]);
139 set_nonblock(notify_pipe[0]);
140 set_nonblock(notify_pipe[1]);
143 notify_pipe[0] = -1; /* read end */
144 notify_pipe[1] = -1; /* write end */
149 if (notify_pipe[1] != -1)
150 (void)write(notify_pipe[1], "", 1);
153 notify_prepare(fd_set *readset)
155 if (notify_pipe[0] != -1)
156 FD_SET(notify_pipe[0], readset);
159 notify_done(fd_set *readset)
163 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
164 while (read(notify_pipe[0], &c, 1) != -1)
165 debug2("notify_done: reading");
170 sigchld_handler(int sig)
172 int save_errno = errno;
173 child_terminated = 1;
175 mysignal(SIGCHLD, sigchld_handler);
183 sigterm_handler(int sig)
185 received_sigterm = sig;
189 * Make packets from buffered stderr data, and buffer it for sending
193 make_packets_from_stderr_data(void)
197 /* Send buffered stderr data to the client. */
198 while (buffer_len(&stderr_buffer) > 0 &&
199 packet_not_very_much_data_to_write()) {
200 len = buffer_len(&stderr_buffer);
201 if (packet_is_interactive()) {
205 /* Keep the packets at reasonable size. */
206 if (len > packet_get_maxsize())
207 len = packet_get_maxsize();
209 packet_start(SSH_SMSG_STDERR_DATA);
210 packet_put_string(buffer_ptr(&stderr_buffer), len);
212 buffer_consume(&stderr_buffer, len);
218 * Make packets from buffered stdout data, and buffer it for sending to the
222 make_packets_from_stdout_data(void)
226 /* Send buffered stdout data to the client. */
227 while (buffer_len(&stdout_buffer) > 0 &&
228 packet_not_very_much_data_to_write()) {
229 len = buffer_len(&stdout_buffer);
230 if (packet_is_interactive()) {
234 /* Keep the packets at reasonable size. */
235 if (len > packet_get_maxsize())
236 len = packet_get_maxsize();
238 packet_start(SSH_SMSG_STDOUT_DATA);
239 packet_put_string(buffer_ptr(&stdout_buffer), len);
241 buffer_consume(&stdout_buffer, len);
247 client_alive_check(void)
251 /* timeout, check to see how many we have had */
252 if (packet_inc_alive_timeouts() > options.client_alive_count_max) {
253 logit("Timeout, client not responding.");
258 * send a bogus global/channel request with "wantreply",
259 * we should get back a failure
261 if ((channel_id = channel_find_open()) == -1) {
262 packet_start(SSH2_MSG_GLOBAL_REQUEST);
263 packet_put_cstring("keepalive@openssh.com");
264 packet_put_char(1); /* boolean: want reply */
266 channel_request_start(channel_id, "keepalive@openssh.com", 1);
272 * Sleep in select() until we can do something. This will initialize the
273 * select masks. Upon return, the masks will indicate which descriptors
274 * have data or can accept data. Optionally, a maximum time can be specified
275 * for the duration of the wait (0 = infinite).
278 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
279 u_int *nallocp, u_int64_t max_time_milliseconds)
281 struct timeval tv, *tvp;
283 time_t minwait_secs = 0;
284 int client_alive_scheduled = 0;
285 int program_alive_scheduled = 0;
287 /* Allocate and update select() masks for channel descriptors. */
288 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
291 if (minwait_secs != 0)
292 max_time_milliseconds = MIN(max_time_milliseconds,
293 (u_int)minwait_secs * 1000);
296 * if using client_alive, set the max timeout accordingly,
297 * and indicate that this particular timeout was for client
298 * alive by setting the client_alive_scheduled flag.
300 * this could be randomized somewhat to make traffic
301 * analysis more difficult, but we're not doing it yet.
304 max_time_milliseconds == 0 && options.client_alive_interval) {
305 client_alive_scheduled = 1;
306 max_time_milliseconds =
307 (u_int64_t)options.client_alive_interval * 1000;
312 /* wrong: bad condition XXX */
313 if (channel_not_very_much_buffered_data())
315 FD_SET(connection_in, *readsetp);
318 * Read packets from the client unless we have too much
319 * buffered stdin or channel data.
321 if (buffer_len(&stdin_buffer) < buffer_high &&
322 channel_not_very_much_buffered_data())
323 FD_SET(connection_in, *readsetp);
325 * If there is not too much data already buffered going to
326 * the client, try to get some more data from the program.
328 if (packet_not_very_much_data_to_write()) {
329 program_alive_scheduled = child_terminated;
331 FD_SET(fdout, *readsetp);
333 FD_SET(fderr, *readsetp);
336 * If we have buffered data, try to write some of that data
339 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
340 FD_SET(fdin, *writesetp);
342 notify_prepare(*readsetp);
345 * If we have buffered packet data going to the client, mark that
348 if (packet_have_data_to_write())
349 FD_SET(connection_out, *writesetp);
352 * If child has terminated and there is enough buffer space to read
353 * from it, then read as much as is available and exit.
355 if (child_terminated && packet_not_very_much_data_to_write())
356 if (max_time_milliseconds == 0 || client_alive_scheduled)
357 max_time_milliseconds = 100;
359 if (max_time_milliseconds == 0)
362 tv.tv_sec = max_time_milliseconds / 1000;
363 tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
367 /* Wait for something to happen, or the timeout to expire. */
368 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
371 memset(*readsetp, 0, *nallocp);
372 memset(*writesetp, 0, *nallocp);
374 error("select: %.100s", strerror(errno));
376 if (ret == 0 && client_alive_scheduled)
377 client_alive_check();
378 if (!compat20 && program_alive_scheduled && fdin_is_tty) {
380 FD_SET(fdout, *readsetp);
382 FD_SET(fderr, *readsetp);
386 notify_done(*readsetp);
390 * Processes input from the client and the program. Input data is stored
391 * in buffers and processed later.
394 process_input(fd_set *readset)
399 /* Read and buffer any input data from the client. */
400 if (FD_ISSET(connection_in, readset)) {
401 len = read(connection_in, buf, sizeof(buf));
403 verbose("Connection closed by %.100s",
404 get_remote_ipaddr());
405 connection_closed = 1;
409 } else if (len < 0) {
410 if (errno != EINTR && errno != EAGAIN &&
411 errno != EWOULDBLOCK) {
412 verbose("Read error from remote host "
414 get_remote_ipaddr(), strerror(errno));
418 /* Buffer any received data. */
419 packet_process_incoming(buf, len);
425 /* Read and buffer any available stdout data from the program. */
426 if (!fdout_eof && FD_ISSET(fdout, readset)) {
428 len = read(fdout, buf, sizeof(buf));
429 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
430 errno == EWOULDBLOCK) && !child_terminated))) {
433 } else if (len <= 0) {
435 } else if ((!isatty(fdout) && len <= 0) ||
436 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
440 buffer_append(&stdout_buffer, buf, len);
444 /* Read and buffer any available stderr data from the program. */
445 if (!fderr_eof && FD_ISSET(fderr, readset)) {
447 len = read(fderr, buf, sizeof(buf));
448 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
449 errno == EWOULDBLOCK) && !child_terminated))) {
452 } else if (len <= 0) {
454 } else if ((!isatty(fderr) && len <= 0) ||
455 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
459 buffer_append(&stderr_buffer, buf, len);
465 * Sends data from internal buffers to client program stdin.
468 process_output(fd_set *writeset)
475 /* Write buffered data to program stdin. */
476 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
477 data = buffer_ptr(&stdin_buffer);
478 dlen = buffer_len(&stdin_buffer);
479 len = write(fdin, data, dlen);
481 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
483 } else if (len <= 0) {
487 shutdown(fdin, SHUT_WR); /* We will no longer send. */
490 /* Successful write. */
491 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
492 tcgetattr(fdin, &tio) == 0 &&
493 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
495 * Simulate echo to reduce the impact of
498 packet_send_ignore(len);
501 /* Consume the data from the buffer. */
502 buffer_consume(&stdin_buffer, len);
503 /* Update the count of bytes written to the program. */
507 /* Send any buffered packet data to the client. */
508 if (FD_ISSET(connection_out, writeset))
513 * Wait until all buffered output has been sent to the client.
514 * This is used when the program terminates.
519 /* Send any buffered stdout data to the client. */
520 if (buffer_len(&stdout_buffer) > 0) {
521 packet_start(SSH_SMSG_STDOUT_DATA);
522 packet_put_string(buffer_ptr(&stdout_buffer),
523 buffer_len(&stdout_buffer));
525 /* Update the count of sent bytes. */
526 stdout_bytes += buffer_len(&stdout_buffer);
528 /* Send any buffered stderr data to the client. */
529 if (buffer_len(&stderr_buffer) > 0) {
530 packet_start(SSH_SMSG_STDERR_DATA);
531 packet_put_string(buffer_ptr(&stderr_buffer),
532 buffer_len(&stderr_buffer));
534 /* Update the count of sent bytes. */
535 stderr_bytes += buffer_len(&stderr_buffer);
537 /* Wait until all buffered data has been written to the client. */
542 process_buffered_input_packets(void)
544 dispatch_run(DISPATCH_NONBLOCK, NULL, active_state);
548 * Performs the interactive session. This handles data transmission between
549 * the client and the program. Note that the notion of stdin, stdout, and
550 * stderr in this function is sort of reversed: this function writes to
551 * stdin (of the child program), and reads from stdout and stderr (of the
555 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
557 fd_set *readset = NULL, *writeset = NULL;
560 int wait_status; /* Status returned by wait(). */
561 pid_t wait_pid; /* pid returned by wait(). */
562 int waiting_termination = 0; /* Have displayed waiting close message. */
563 u_int64_t max_time_milliseconds;
564 u_int previous_stdout_buffer_bytes;
565 u_int stdout_buffer_bytes;
568 debug("Entering interactive session.");
570 /* Initialize the SIGCHLD kludge. */
571 child_terminated = 0;
572 mysignal(SIGCHLD, sigchld_handler);
575 signal(SIGTERM, sigterm_handler);
576 signal(SIGINT, sigterm_handler);
577 signal(SIGQUIT, sigterm_handler);
580 /* Initialize our global variables. */
588 /* we don't have stderr for interactive terminal sessions, see below */
592 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
595 connection_in = packet_get_connection_in();
596 connection_out = packet_get_connection_out();
600 previous_stdout_buffer_bytes = 0;
602 /* Set approximate I/O buffer size. */
603 if (packet_is_interactive())
606 buffer_high = 64 * 1024;
609 /* Initialize max_fd to the maximum of the known file descriptors. */
610 max_fd = MAX(connection_in, connection_out);
611 max_fd = MAX(max_fd, fdin);
612 max_fd = MAX(max_fd, fdout);
614 max_fd = MAX(max_fd, fderr);
617 /* Initialize Initialize buffers. */
618 buffer_init(&stdin_buffer);
619 buffer_init(&stdout_buffer);
620 buffer_init(&stderr_buffer);
623 * If we have no separate fderr (which is the case when we have a pty
624 * - there we cannot make difference between data sent to stdout and
625 * stderr), indicate that we have seen an EOF from stderr. This way
626 * we don't need to check the descriptor everywhere.
631 server_init_dispatch();
633 /* Main loop of the server for the interactive session mode. */
636 /* Process buffered packets from the client. */
637 process_buffered_input_packets();
640 * If we have received eof, and there is no more pending
641 * input data, cause a real eof by closing fdin.
643 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
647 shutdown(fdin, SHUT_WR); /* We will no longer send. */
650 /* Make packets from buffered stderr data to send to the client. */
651 make_packets_from_stderr_data();
654 * Make packets from buffered stdout data to send to the
655 * client. If there is very little to send, this arranges to
656 * not send them now, but to wait a short while to see if we
657 * are getting more data. This is necessary, as some systems
658 * wake up readers from a pty after each separate character.
660 max_time_milliseconds = 0;
661 stdout_buffer_bytes = buffer_len(&stdout_buffer);
662 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
663 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
664 /* try again after a while */
665 max_time_milliseconds = 10;
668 make_packets_from_stdout_data();
670 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
672 /* Send channel data to the client. */
673 if (packet_not_very_much_data_to_write())
674 channel_output_poll();
677 * Bail out of the loop if the program has closed its output
678 * descriptors, and we have no more data to send to the
679 * client, and there is no pending buffered data.
681 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
682 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
683 if (!channel_still_open())
685 if (!waiting_termination) {
686 const char *s = "Waiting for forwarded connections to terminate...\r\n";
688 waiting_termination = 1;
689 buffer_append(&stderr_buffer, s, strlen(s));
691 /* Display list of open channels. */
692 cp = channel_open_message();
693 buffer_append(&stderr_buffer, cp, strlen(cp));
697 max_fd = MAX(connection_in, connection_out);
698 max_fd = MAX(max_fd, fdin);
699 max_fd = MAX(max_fd, fdout);
700 max_fd = MAX(max_fd, fderr);
701 max_fd = MAX(max_fd, notify_pipe[0]);
703 /* Sleep in select() until we can do something. */
704 wait_until_can_do_something(&readset, &writeset, &max_fd,
705 &nalloc, max_time_milliseconds);
707 if (received_sigterm) {
708 logit("Exiting on signal %d", (int)received_sigterm);
709 /* Clean up sessions, utmp, etc. */
713 /* Process any channel events. */
714 channel_after_select(readset, writeset);
716 /* Process input from the client and from program stdout/stderr. */
717 process_input(readset);
719 /* Process output to the client and to program stdin. */
720 process_output(writeset);
725 /* Cleanup and termination code. */
727 /* Wait until all output has been sent to the client. */
730 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
731 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
733 /* Free and clear the buffers. */
734 buffer_free(&stdin_buffer);
735 buffer_free(&stdout_buffer);
736 buffer_free(&stderr_buffer);
738 /* Close the file descriptors. */
753 /* We no longer want our SIGCHLD handler to be called. */
754 mysignal(SIGCHLD, SIG_DFL);
756 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
758 packet_disconnect("wait: %.100s", strerror(errno));
760 error("Strange, wait returned pid %ld, expected %ld",
761 (long)wait_pid, (long)pid);
763 /* Check if it exited normally. */
764 if (WIFEXITED(wait_status)) {
765 /* Yes, normal exit. Get exit status and send it to the client. */
766 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
767 packet_start(SSH_SMSG_EXITSTATUS);
768 packet_put_int(WEXITSTATUS(wait_status));
773 * Wait for exit confirmation. Note that there might be
774 * other packets coming before it; however, the program has
775 * already died so we just ignore them. The client is
776 * supposed to respond with the confirmation when it receives
780 type = packet_read();
782 while (type != SSH_CMSG_EXIT_CONFIRMATION);
784 debug("Received exit confirmation.");
787 /* Check if the program terminated due to a signal. */
788 if (WIFSIGNALED(wait_status))
789 packet_disconnect("Command terminated on signal %d.",
790 WTERMSIG(wait_status));
792 /* Some weird exit cause. Just exit. */
793 packet_disconnect("wait returned status %04x.", wait_status);
798 collect_children(void)
804 /* block SIGCHLD while we check for dead children */
806 sigaddset(&nset, SIGCHLD);
807 sigprocmask(SIG_BLOCK, &nset, &oset);
808 if (child_terminated) {
809 debug("Received SIGCHLD.");
810 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
811 (pid < 0 && errno == EINTR))
813 session_close_by_pid(pid, status);
814 child_terminated = 0;
816 sigprocmask(SIG_SETMASK, &oset, NULL);
820 server_loop2(Authctxt *authctxt)
822 fd_set *readset = NULL, *writeset = NULL;
825 u_int64_t rekey_timeout_ms = 0;
827 debug("Entering interactive session for SSH2.");
829 mysignal(SIGCHLD, sigchld_handler);
830 child_terminated = 0;
831 connection_in = packet_get_connection_in();
832 connection_out = packet_get_connection_out();
835 signal(SIGTERM, sigterm_handler);
836 signal(SIGINT, sigterm_handler);
837 signal(SIGQUIT, sigterm_handler);
842 max_fd = MAX(connection_in, connection_out);
843 max_fd = MAX(max_fd, notify_pipe[0]);
845 server_init_dispatch();
848 process_buffered_input_packets();
850 if (!ssh_packet_is_rekeying(active_state) &&
851 packet_not_very_much_data_to_write())
852 channel_output_poll();
853 if (options.rekey_interval > 0 && compat20 &&
854 !ssh_packet_is_rekeying(active_state))
855 rekey_timeout_ms = packet_get_rekey_timeout() * 1000;
857 rekey_timeout_ms = 0;
859 wait_until_can_do_something(&readset, &writeset, &max_fd,
860 &nalloc, rekey_timeout_ms);
862 if (received_sigterm) {
863 logit("Exiting on signal %d", (int)received_sigterm);
864 /* Clean up sessions, utmp, etc. */
869 if (!ssh_packet_is_rekeying(active_state))
870 channel_after_select(readset, writeset);
871 process_input(readset);
872 if (connection_closed)
874 process_output(writeset);
881 /* free all channels, no more reads and writes */
884 /* free remaining sessions, e.g. remove wtmp entries */
885 session_destroy_all(NULL);
889 server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
891 debug("Got %d/%u for keepalive", type, seq);
893 * reset timeout, since we got a sane answer from the client.
894 * even if this was generated by something other than
895 * the bogus CHANNEL_REQUEST we send for keepalives.
897 packet_set_alive_timeouts(0);
902 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
907 /* Stdin data from the client. Append it to the buffer. */
908 /* Ignore any data if the client has closed stdin. */
911 data = packet_get_string(&data_len);
913 buffer_append(&stdin_buffer, data, data_len);
914 explicit_bzero(data, data_len);
920 server_input_eof(int type, u_int32_t seq, void *ctxt)
923 * Eof from the client. The stdin descriptor to the
924 * program will be closed when all buffered data has
927 debug("EOF received for stdin.");
934 server_input_window_size(int type, u_int32_t seq, void *ctxt)
936 u_int row = packet_get_int();
937 u_int col = packet_get_int();
938 u_int xpixel = packet_get_int();
939 u_int ypixel = packet_get_int();
941 debug("Window change received.");
944 pty_change_window_size(fdin, row, col, xpixel, ypixel);
949 server_request_direct_tcpip(void)
952 char *target, *originator;
953 u_short target_port, originator_port;
955 target = packet_get_string(NULL);
956 target_port = packet_get_int();
957 originator = packet_get_string(NULL);
958 originator_port = packet_get_int();
961 debug("server_request_direct_tcpip: originator %s port %d, target %s "
962 "port %d", originator, originator_port, target, target_port);
964 /* XXX fine grained permissions */
965 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
966 !no_port_forwarding_flag) {
967 c = channel_connect_to_port(target, target_port,
968 "direct-tcpip", "direct-tcpip");
970 logit("refused local port forward: "
971 "originator %s port %d, target %s port %d",
972 originator, originator_port, target, target_port);
982 server_request_direct_streamlocal(void)
985 char *target, *originator;
986 u_short originator_port;
988 target = packet_get_string(NULL);
989 originator = packet_get_string(NULL);
990 originator_port = packet_get_int();
993 debug("server_request_direct_streamlocal: originator %s port %d, target %s",
994 originator, originator_port, target);
996 /* XXX fine grained permissions */
997 if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
998 !no_port_forwarding_flag && use_privsep) {
999 c = channel_connect_to_path(target,
1000 "direct-streamlocal@openssh.com", "direct-streamlocal");
1002 logit("refused streamlocal port forward: "
1003 "originator %s port %d, target %s",
1004 originator, originator_port, target);
1014 server_request_tun(void)
1020 mode = packet_get_int();
1022 case SSH_TUNMODE_POINTOPOINT:
1023 case SSH_TUNMODE_ETHERNET:
1026 packet_send_debug("Unsupported tunnel device mode.");
1029 if ((options.permit_tun & mode) == 0) {
1030 packet_send_debug("Server has rejected tunnel device "
1035 tun = packet_get_int();
1036 if (forced_tun_device != -1) {
1037 if (tun != SSH_TUNID_ANY && forced_tun_device != tun)
1039 tun = forced_tun_device;
1041 sock = tun_open(tun, mode);
1044 c = channel_new("tun", SSH_CHANNEL_OPEN, sock, sock, -1,
1045 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1047 #if defined(SSH_TUN_FILTER)
1048 if (mode == SSH_TUNMODE_POINTOPOINT)
1049 channel_register_filter(c->self, sys_tun_infilter,
1050 sys_tun_outfilter, NULL, NULL);
1055 packet_send_debug("Failed to open the tunnel device.");
1060 server_request_session(void)
1064 debug("input_session_request");
1067 if (no_more_sessions) {
1068 packet_disconnect("Possible attack: attempt to open a session "
1069 "after additional sessions disabled");
1073 * A server session has no fd to read or write until a
1074 * CHANNEL_REQUEST for a shell is made, so we set the type to
1075 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
1076 * CHANNEL_REQUEST messages is registered.
1078 c = channel_new("session", SSH_CHANNEL_LARVAL,
1079 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
1080 0, "server-session", 1);
1081 if (session_open(the_authctxt, c->self) != 1) {
1082 debug("session open failed, free channel %d", c->self);
1086 channel_register_cleanup(c->self, session_close_by_channel, 0);
1091 server_input_channel_open(int type, u_int32_t seq, void *ctxt)
1096 u_int rmaxpack, rwindow, len;
1098 ctype = packet_get_string(&len);
1099 rchan = packet_get_int();
1100 rwindow = packet_get_int();
1101 rmaxpack = packet_get_int();
1103 debug("server_input_channel_open: ctype %s rchan %d win %d max %d",
1104 ctype, rchan, rwindow, rmaxpack);
1106 if (strcmp(ctype, "session") == 0) {
1107 c = server_request_session();
1108 } else if (strcmp(ctype, "direct-tcpip") == 0) {
1109 c = server_request_direct_tcpip();
1110 } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
1111 c = server_request_direct_streamlocal();
1112 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
1113 c = server_request_tun();
1116 debug("server_input_channel_open: confirm %s", ctype);
1117 c->remote_id = rchan;
1118 c->remote_window = rwindow;
1119 c->remote_maxpacket = rmaxpack;
1120 if (c->type != SSH_CHANNEL_CONNECTING) {
1121 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1122 packet_put_int(c->remote_id);
1123 packet_put_int(c->self);
1124 packet_put_int(c->local_window);
1125 packet_put_int(c->local_maxpacket);
1129 debug("server_input_channel_open: failure %s", ctype);
1130 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1131 packet_put_int(rchan);
1132 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1133 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1134 packet_put_cstring("open failed");
1135 packet_put_cstring("");
1144 server_input_hostkeys_prove(struct sshbuf **respp)
1146 struct ssh *ssh = active_state; /* XXX */
1147 struct sshbuf *resp = NULL;
1148 struct sshbuf *sigbuf = NULL;
1149 struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
1150 int r, ndx, success = 0;
1155 if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
1156 fatal("%s: sshbuf_new", __func__);
1158 while (ssh_packet_remaining(ssh) > 0) {
1161 if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
1162 (r = sshkey_from_blob(blob, blen, &key)) != 0) {
1163 error("%s: couldn't parse key: %s",
1164 __func__, ssh_err(r));
1168 * Better check that this is actually one of our hostkeys
1169 * before attempting to sign anything with it.
1171 if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
1172 error("%s: unknown host %s key",
1173 __func__, sshkey_type(key));
1177 * XXX refactor: make kex->sign just use an index rather
1178 * than passing in public and private keys
1180 if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
1181 (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
1182 error("%s: can't retrieve hostkey %d", __func__, ndx);
1185 sshbuf_reset(sigbuf);
1188 if ((r = sshbuf_put_cstring(sigbuf,
1189 "hostkeys-prove-00@openssh.com")) != 0 ||
1190 (r = sshbuf_put_string(sigbuf,
1191 ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
1192 (r = sshkey_puts(key, sigbuf)) != 0 ||
1193 (r = ssh->kex->sign(key_prv, key_pub, &sig, &slen,
1194 sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), NULL, 0)) != 0 ||
1195 (r = sshbuf_put_string(resp, sig, slen)) != 0) {
1196 error("%s: couldn't prepare signature: %s",
1197 __func__, ssh_err(r));
1203 resp = NULL; /* don't free it */
1208 sshbuf_free(sigbuf);
1214 server_input_global_request(int type, u_int32_t seq, void *ctxt)
1218 int r, success = 0, allocated_listen_port = 0;
1219 struct sshbuf *resp = NULL;
1221 rtype = packet_get_string(NULL);
1222 want_reply = packet_get_char();
1223 debug("server_input_global_request: rtype %s want_reply %d", rtype, want_reply);
1225 /* -R style forwarding */
1226 if (strcmp(rtype, "tcpip-forward") == 0) {
1230 pw = the_authctxt->pw;
1231 if (pw == NULL || !the_authctxt->valid)
1232 fatal("server_input_global_request: no/invalid user");
1233 memset(&fwd, 0, sizeof(fwd));
1234 fwd.listen_host = packet_get_string(NULL);
1235 fwd.listen_port = (u_short)packet_get_int();
1236 debug("server_input_global_request: tcpip-forward listen %s port %d",
1237 fwd.listen_host, fwd.listen_port);
1239 /* check permissions */
1240 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
1241 no_port_forwarding_flag ||
1242 (!want_reply && fwd.listen_port == 0)
1243 #ifndef NO_IPPORT_RESERVED_CONCEPT
1244 || (fwd.listen_port != 0 && fwd.listen_port < IPPORT_RESERVED &&
1249 packet_send_debug("Server has disabled port forwarding.");
1251 /* Start listening on the port */
1252 success = channel_setup_remote_fwd_listener(&fwd,
1253 &allocated_listen_port, &options.fwd_opts);
1255 free(fwd.listen_host);
1256 if ((resp = sshbuf_new()) == NULL)
1257 fatal("%s: sshbuf_new", __func__);
1258 if (allocated_listen_port != 0 &&
1259 (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
1260 fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
1261 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
1264 memset(&fwd, 0, sizeof(fwd));
1265 fwd.listen_host = packet_get_string(NULL);
1266 fwd.listen_port = (u_short)packet_get_int();
1267 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
1268 fwd.listen_host, fwd.listen_port);
1270 success = channel_cancel_rport_listener(&fwd);
1271 free(fwd.listen_host);
1272 } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
1275 memset(&fwd, 0, sizeof(fwd));
1276 fwd.listen_path = packet_get_string(NULL);
1277 debug("server_input_global_request: streamlocal-forward listen path %s",
1280 /* check permissions */
1281 if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
1282 || no_port_forwarding_flag || !use_privsep) {
1284 packet_send_debug("Server has disabled port forwarding.");
1286 /* Start listening on the socket */
1287 success = channel_setup_remote_fwd_listener(
1288 &fwd, NULL, &options.fwd_opts);
1290 free(fwd.listen_path);
1291 } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
1294 memset(&fwd, 0, sizeof(fwd));
1295 fwd.listen_path = packet_get_string(NULL);
1296 debug("%s: cancel-streamlocal-forward path %s", __func__,
1299 success = channel_cancel_rport_listener(&fwd);
1300 free(fwd.listen_path);
1301 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
1302 no_more_sessions = 1;
1304 } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
1305 success = server_input_hostkeys_prove(&resp);
1308 packet_start(success ?
1309 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1310 if (success && resp != NULL)
1311 ssh_packet_put_raw(active_state, sshbuf_ptr(resp),
1314 packet_write_wait();
1322 server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1325 int id, reply, success = 0;
1328 id = packet_get_int();
1329 rtype = packet_get_string(NULL);
1330 reply = packet_get_char();
1332 debug("server_input_channel_req: channel %d request %s reply %d",
1335 if ((c = channel_lookup(id)) == NULL)
1336 packet_disconnect("server_input_channel_req: "
1337 "unknown channel %d", id);
1338 if (!strcmp(rtype, "eow@openssh.com")) {
1341 } else if ((c->type == SSH_CHANNEL_LARVAL ||
1342 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
1343 success = session_input_channel_req(c, rtype);
1344 if (reply && !(c->flags & CHAN_CLOSE_SENT)) {
1345 packet_start(success ?
1346 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1347 packet_put_int(c->remote_id);
1355 server_init_dispatch_20(void)
1357 debug("server_init_dispatch_20");
1358 dispatch_init(&dispatch_protocol_error);
1359 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1360 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1361 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1362 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1363 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
1364 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1365 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1366 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
1367 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1368 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
1370 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
1371 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
1372 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
1373 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
1375 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1378 server_init_dispatch_13(void)
1380 debug("server_init_dispatch_13");
1381 dispatch_init(NULL);
1382 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1383 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1384 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1385 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1386 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1387 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1388 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1389 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1390 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1393 server_init_dispatch_15(void)
1395 server_init_dispatch_13();
1396 debug("server_init_dispatch_15");
1397 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1398 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1401 server_init_dispatch(void)
1404 server_init_dispatch_20();
1406 server_init_dispatch_13();
1408 server_init_dispatch_15();