1 /*        $NetBSD: serverloop.c,v 1.38 2025/04/09 15:49:32 christos Exp $       */
2 /* $OpenBSD: serverloop.c,v 1.241 2024/11/26 22:01:37 djm Exp $ */
3 
4 /*
5  * Author: Tatu Ylonen <ylo@cs.hut.fi>
6  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7  *                    All rights reserved
8  * Server main loop for handling the interactive session.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 support by Markus Friedl.
17  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 #include "includes.h"
41 __RCSID("$NetBSD: serverloop.c,v 1.38 2025/04/09 15:49:32 christos Exp $");
42 
43 #include <sys/param.h>        /* MIN MAX */
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/queue.h>
49 
50 #include <netinet/in.h>
51 
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <pwd.h>
55 #include <limits.h>
56 #include <poll.h>
57 #include <signal.h>
58 #include <string.h>
59 #include <termios.h>
60 #include <unistd.h>
61 #include <stdarg.h>
62 
63 #include "xmalloc.h"
64 #include "packet.h"
65 #include "sshbuf.h"
66 #include "log.h"
67 #include "misc.h"
68 #include "servconf.h"
69 #include "canohost.h"
70 #include "sshpty.h"
71 #include "channels.h"
72 #include "ssh2.h"
73 #include "sshkey.h"
74 #include "cipher.h"
75 #include "kex.h"
76 #include "hostfile.h"
77 #include "auth.h"
78 #include "session.h"
79 #include "dispatch.h"
80 #include "auth-options.h"
81 #include "serverloop.h"
82 #include "ssherr.h"
83 
84 static u_long stdin_bytes = 0;  /* Number of bytes written to stdin. */
85 static u_long fdout_bytes = 0;  /* Number of stdout bytes read from program. */
86 
87 extern ServerOptions options;
88 
89 /* XXX */
90 extern Authctxt *the_authctxt;
91 extern struct sshauthopt *auth_opts;
92 
93 static int no_more_sessions = 0; /* Disallow further sessions. */
94 
95 static volatile sig_atomic_t child_terminated = 0;          /* The child has terminated. */
96 
97 /* prototypes */
98 static void server_init_dispatch(struct ssh *);
99 
100 /* requested tunnel forwarding interface(s), shared with session.c */
101 char *tun_fwd_ifnames = NULL;
102 
103 /*
104  * Returns current time in seconds from Jan 1, 1970 with the maximum
105  * available resolution.
106  */
107 
108 static double
get_current_time(void)109 get_current_time(void)
110 {
111           struct timeval tv;
112           gettimeofday(&tv, NULL);
113           return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
114 }
115 
116 static void
sigchld_handler(int sig)117 sigchld_handler(int sig)
118 {
119           child_terminated = 1;
120 }
121 
122 static void
client_alive_check(struct ssh * ssh)123 client_alive_check(struct ssh *ssh)
124 {
125           char remote_id[512];
126           int r, channel_id;
127 
128           /* timeout, check to see how many we have had */
129           if (options.client_alive_count_max > 0 &&
130               ssh_packet_inc_alive_timeouts(ssh) >
131               options.client_alive_count_max) {
132                     sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
133                     logit("Timeout, client not responding from %s", remote_id);
134                     cleanup_exit(255);
135           }
136 
137           /*
138            * send a bogus global/channel request with "wantreply",
139            * we should get back a failure
140            */
141           if ((channel_id = channel_find_open(ssh)) == -1) {
142                     if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
143                         (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com"))
144                         != 0 ||
145                         (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */
146                               fatal_fr(r, "compose");
147           } else {
148                     channel_request_start(ssh, channel_id,
149                         "keepalive@openssh.com", 1);
150           }
151           if ((r = sshpkt_send(ssh)) != 0)
152                     fatal_fr(r, "send");
153 }
154 
155 /*
156  * Sleep in ppoll() until we can do something.
157  * Optionally, a maximum time can be specified for the duration of
158  * the wait (0 = infinite).
159  */
160 static void
wait_until_can_do_something(struct ssh * ssh,int connection_in,int connection_out,struct pollfd ** pfdp,u_int * npfd_allocp,u_int * npfd_activep,sigset_t * sigsetp,int * conn_in_readyp,int * conn_out_readyp)161 wait_until_can_do_something(struct ssh *ssh,
162     int connection_in, int connection_out, struct pollfd **pfdp,
163     u_int *npfd_allocp, u_int *npfd_activep, sigset_t *sigsetp,
164     int *conn_in_readyp, int *conn_out_readyp)
165 {
166           struct timespec timeout;
167           char remote_id[512];
168           int ret;
169           int client_alive_scheduled = 0;
170           u_int p;
171           time_t now;
172           static time_t last_client_time, unused_connection_expiry;
173 
174           *conn_in_readyp = *conn_out_readyp = 0;
175 
176           /* Prepare channel poll. First two pollfd entries are reserved */
177           ptimeout_init(&timeout);
178           channel_prepare_poll(ssh, pfdp, npfd_allocp, npfd_activep, 2, &timeout);
179           now = monotime();
180           if (*npfd_activep < 2)
181                     fatal_f("bad npfd %u", *npfd_activep); /* shouldn't happen */
182           if (options.rekey_interval > 0 && !ssh_packet_is_rekeying(ssh)) {
183                     ptimeout_deadline_sec(&timeout,
184                         ssh_packet_get_rekey_timeout(ssh));
185           }
186 
187           /*
188            * If no channels are open and UnusedConnectionTimeout is set, then
189            * start the clock to terminate the connection.
190            */
191           if (options.unused_connection_timeout != 0) {
192                     if (channel_still_open(ssh) || unused_connection_expiry == 0) {
193                               unused_connection_expiry = now +
194                                   options.unused_connection_timeout;
195                     }
196                     ptimeout_deadline_monotime(&timeout, unused_connection_expiry);
197           }
198 
199           /*
200            * if using client_alive, set the max timeout accordingly,
201            * and indicate that this particular timeout was for client
202            * alive by setting the client_alive_scheduled flag.
203            *
204            * this could be randomized somewhat to make traffic
205            * analysis more difficult, but we're not doing it yet.
206            */
207           if (options.client_alive_interval) {
208                     /* Time we last heard from the client OR sent a keepalive */
209                     if (last_client_time == 0)
210                               last_client_time = now;
211                     ptimeout_deadline_sec(&timeout, options.client_alive_interval);
212                     /* XXX ? deadline_monotime(last_client_time + alive_interval) */
213                     client_alive_scheduled = 1;
214           }
215 
216 #if 0
217           /* wrong: bad condition XXX */
218           if (channel_not_very_much_buffered_data())
219 #endif
220           /* Monitor client connection on reserved pollfd entries */
221           (*pfdp)[0].fd = connection_in;
222           (*pfdp)[0].events = POLLIN;
223           (*pfdp)[1].fd = connection_out;
224           (*pfdp)[1].events = ssh_packet_have_data_to_write(ssh) ? POLLOUT : 0;
225 
226           /*
227            * If child has terminated and there is enough buffer space to read
228            * from it, then read as much as is available and exit.
229            */
230           if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh))
231                     ptimeout_deadline_ms(&timeout, 100);
232 
233           /* Wait for something to happen, or the timeout to expire. */
234           ret = ppoll(*pfdp, *npfd_activep, ptimeout_get_tsp(&timeout), sigsetp);
235 
236           if (ret == -1) {
237                     for (p = 0; p < *npfd_activep; p++)
238                               (*pfdp)[p].revents = 0;
239                     if (errno != EINTR)
240                               fatal_f("ppoll: %.100s", strerror(errno));
241                     return;
242           }
243 
244           *conn_in_readyp = (*pfdp)[0].revents != 0;
245           *conn_out_readyp = (*pfdp)[1].revents != 0;
246 
247           now = monotime(); /* need to reset after ppoll() */
248           /* ClientAliveInterval probing */
249           if (client_alive_scheduled) {
250                     if (ret == 0 &&
251                         now >= last_client_time + options.client_alive_interval) {
252                               /* ppoll timed out and we're due to probe */
253                               client_alive_check(ssh);
254                               last_client_time = now;
255                     } else if (ret != 0 && *conn_in_readyp) {
256                               /* Data from peer; reset probe timer. */
257                               last_client_time = now;
258                     }
259           }
260 
261           /* UnusedConnectionTimeout handling */
262           if (unused_connection_expiry != 0 &&
263               now > unused_connection_expiry && !channel_still_open(ssh)) {
264                     sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
265                     logit("terminating inactive connection from %s", remote_id);
266                     cleanup_exit(255);
267           }
268 }
269 
270 /*
271  * Processes input from the client and the program.  Input data is stored
272  * in buffers and processed later.
273  */
274 static int
process_input(struct ssh * ssh,int connection_in)275 process_input(struct ssh *ssh, int connection_in)
276 {
277           int r;
278 
279           if ((r = ssh_packet_process_read(ssh, connection_in)) == 0)
280                     return 0; /* success */
281           if (r == SSH_ERR_SYSTEM_ERROR) {
282                     if (errno == EAGAIN || errno == EINTR)
283                               return 0;
284                     if (errno == EPIPE) {
285                               logit("Connection closed by %.100s port %d",
286                                   ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
287                               return -1;
288                     }
289                     logit("Read error from remote host %s port %d: %s",
290                         ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
291                         strerror(errno));
292                     cleanup_exit(255);
293           }
294           return -1;
295 }
296 
297 /*
298  * Sends data from internal buffers to client program stdin.
299  */
300 static void
process_output(struct ssh * ssh,int connection_out)301 process_output(struct ssh *ssh, int connection_out)
302 {
303           int r;
304 
305           /* Send any buffered packet data to the client. */
306           if ((r = ssh_packet_write_poll(ssh)) < 0) {
307                     sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
308                         __func__);
309           }
310 }
311 
312 static void
process_buffered_input_packets(struct ssh * ssh)313 process_buffered_input_packets(struct ssh *ssh)
314 {
315           ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL);
316 }
317 
318 static void
collect_children(struct ssh * ssh)319 collect_children(struct ssh *ssh)
320 {
321           pid_t pid;
322           int status;
323 
324           if (child_terminated) {
325                     debug("Received SIGCHLD.");
326                     while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
327                         (pid == -1 && errno == EINTR))
328                               if (pid > 0)
329                                         session_close_by_pid(ssh, pid, status);
330                     child_terminated = 0;
331           }
332 }
333 
334 void
server_loop2(struct ssh * ssh,Authctxt * authctxt)335 server_loop2(struct ssh *ssh, Authctxt *authctxt)
336 {
337           struct pollfd *pfd = NULL;
338           u_int npfd_alloc = 0, npfd_active = 0;
339           int r, conn_in_ready, conn_out_ready;
340           u_int connection_in, connection_out;
341           double start_time, total_time;
342           sigset_t bsigset, osigset;
343 
344           debug("Entering interactive session for SSH2.");
345           start_time = get_current_time();
346 
347           if (sigemptyset(&bsigset) == -1 || sigaddset(&bsigset, SIGCHLD) == -1)
348                     error_f("bsigset setup: %s", strerror(errno));
349           ssh_signal(SIGCHLD, sigchld_handler);
350           child_terminated = 0;
351           connection_in = ssh_packet_get_connection_in(ssh);
352           connection_out = ssh_packet_get_connection_out(ssh);
353 
354           server_init_dispatch(ssh);
355 
356           for (;;) {
357                     process_buffered_input_packets(ssh);
358 
359                     if (!ssh_packet_is_rekeying(ssh) &&
360                         ssh_packet_not_very_much_data_to_write(ssh))
361                               channel_output_poll(ssh);
362 
363                     /*
364                      * Block SIGCHLD while we check for dead children, then pass
365                      * the old signal mask through to ppoll() so that it'll wake
366                      * up immediately if a child exits after we've called waitpid().
367                      */
368                     if (sigprocmask(SIG_BLOCK, &bsigset, &osigset) == -1)
369                               error_f("bsigset sigprocmask: %s", strerror(errno));
370                     collect_children(ssh);
371                     wait_until_can_do_something(ssh, connection_in, connection_out,
372                         &pfd, &npfd_alloc, &npfd_active, &osigset,
373                         &conn_in_ready, &conn_out_ready);
374                     if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1)
375                               error_f("osigset sigprocmask: %s", strerror(errno));
376 
377                     channel_after_poll(ssh, pfd, npfd_active);
378                     if (conn_in_ready &&
379                         process_input(ssh, connection_in) < 0)
380                               break;
381                     /* A timeout may have triggered rekeying */
382                     if ((r = ssh_packet_check_rekey(ssh)) != 0)
383                               fatal_fr(r, "cannot start rekeying");
384                     if (conn_out_ready)
385                               process_output(ssh, connection_out);
386           }
387           collect_children(ssh);
388           free(pfd);
389 
390           /* free all channels, no more reads and writes */
391           channel_free_all(ssh);
392 
393           /* free remaining sessions, e.g. remove wtmp entries */
394           session_destroy_all(ssh, NULL);
395           total_time = get_current_time() - start_time;
396           logit("SSH: Server;LType: Throughput;Remote: %s-%d;IN: %lu;OUT: %lu;Duration: %.1f;tPut_in: %.1f;tPut_out: %.1f",
397                 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
398                 stdin_bytes, fdout_bytes, total_time, stdin_bytes / total_time,
399                 fdout_bytes / total_time);
400 }
401 
402 static int
server_input_keep_alive(int type,u_int32_t seq,struct ssh * ssh)403 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
404 {
405           debug("Got %d/%u for keepalive", type, seq);
406           /*
407            * reset timeout, since we got a sane answer from the client.
408            * even if this was generated by something other than
409            * the bogus CHANNEL_REQUEST we send for keepalives.
410            */
411           ssh_packet_set_alive_timeouts(ssh, 0);
412           return 0;
413 }
414 
415 static Channel *
server_request_direct_tcpip(struct ssh * ssh,int * reason,const char ** errmsg)416 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
417 {
418           Channel *c = NULL;
419           char *target = NULL, *originator = NULL;
420           u_int target_port = 0, originator_port = 0;
421           int r;
422 
423           if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
424               (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
425               (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
426               (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
427               (r = sshpkt_get_end(ssh)) != 0)
428                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
429           if (target_port > 0xFFFF) {
430                     error_f("invalid target port");
431                     *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
432                     goto out;
433           }
434           if (originator_port > 0xFFFF) {
435                     error_f("invalid originator port");
436                     *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
437                     goto out;
438           }
439 
440           debug_f("originator %s port %u, target %s port %u",
441               originator, originator_port, target, target_port);
442 
443           /* XXX fine grained permissions */
444           if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
445               auth_opts->permit_port_forwarding_flag &&
446               !options.disable_forwarding) {
447                     c = channel_connect_to_port(ssh, target, target_port,
448                         "direct-tcpip", "direct-tcpip", reason, errmsg);
449           } else {
450                     logit("refused local port forward: "
451                         "originator %s port %d, target %s port %d",
452                         originator, originator_port, target, target_port);
453                     if (reason != NULL)
454                               *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
455           }
456 
457  out:
458           free(originator);
459           free(target);
460           return c;
461 }
462 
463 static Channel *
server_request_direct_streamlocal(struct ssh * ssh)464 server_request_direct_streamlocal(struct ssh *ssh)
465 {
466           Channel *c = NULL;
467           char *target = NULL, *originator = NULL;
468           u_int originator_port = 0;
469           struct passwd *pw = the_authctxt->pw;
470           int r;
471 
472           if (pw == NULL || !the_authctxt->valid)
473                     fatal_f("no/invalid user");
474 
475           if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
476               (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
477               (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
478               (r = sshpkt_get_end(ssh)) != 0)
479                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
480           if (originator_port > 0xFFFF) {
481                     error_f("invalid originator port");
482                     goto out;
483           }
484 
485           debug_f("originator %s port %d, target %s",
486               originator, originator_port, target);
487 
488           /* XXX fine grained permissions */
489           if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
490               auth_opts->permit_port_forwarding_flag &&
491               !options.disable_forwarding) {
492                     c = channel_connect_to_path(ssh, target,
493                         "direct-streamlocal@openssh.com", "direct-streamlocal");
494           } else {
495                     logit("refused streamlocal port forward: "
496                         "originator %s port %d, target %s",
497                         originator, originator_port, target);
498           }
499 
500 out:
501           free(originator);
502           free(target);
503           return c;
504 }
505 
506 static Channel *
server_request_tun(struct ssh * ssh)507 server_request_tun(struct ssh *ssh)
508 {
509           Channel *c = NULL;
510           u_int mode, tun;
511           int r, sock;
512           char *tmp, *ifname = NULL;
513 
514           if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
515                     sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
516           switch (mode) {
517           case SSH_TUNMODE_POINTOPOINT:
518           case SSH_TUNMODE_ETHERNET:
519                     break;
520           default:
521                     ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
522                     return NULL;
523           }
524           if ((options.permit_tun & mode) == 0) {
525                     ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
526                         "forwarding");
527                     return NULL;
528           }
529 
530           if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
531                     sshpkt_fatal(ssh, r, "%s: parse device", __func__);
532           if (tun > INT_MAX) {
533                     debug_f("invalid tun");
534                     goto done;
535           }
536           if (auth_opts->force_tun_device != -1) {
537                     if (tun != SSH_TUNID_ANY &&
538                         auth_opts->force_tun_device != (int)tun)
539                               goto done;
540                     tun = auth_opts->force_tun_device;
541           }
542           sock = tun_open(tun, mode, &ifname);
543           if (sock < 0)
544                     goto done;
545           debug("Tunnel forwarding using interface %s", ifname);
546 
547           if (options.hpn_disabled)
548           c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
549               CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
550           else
551                     c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
552                         options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
553           c->datagram = 1;
554 
555           /*
556            * Update the list of names exposed to the session
557            * XXX remove these if the tunnels are closed (won't matter
558            * much if they are already in the environment though)
559            */
560           tmp = tun_fwd_ifnames;
561           xasprintf(&tun_fwd_ifnames, "%s%s%s",
562               tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
563               tun_fwd_ifnames == NULL ? "" : ",",
564               ifname);
565           free(tmp);
566           free(ifname);
567 
568  done:
569           if (c == NULL)
570                     ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
571           return c;
572 }
573 
574 static Channel *
server_request_session(struct ssh * ssh)575 server_request_session(struct ssh *ssh)
576 {
577           Channel *c;
578           int r;
579 
580           debug("input_session_request");
581           if ((r = sshpkt_get_end(ssh)) != 0)
582                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
583 
584           if (no_more_sessions) {
585                     ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
586                         "session after additional sessions disabled");
587           }
588 
589           /*
590            * A server session has no fd to read or write until a
591            * CHANNEL_REQUEST for a shell is made, so we set the type to
592            * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
593            * CHANNEL_REQUEST messages is registered.
594            */
595           c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
596               -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
597               0, "server-session", 1);
598           if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled))
599                     c->dynamic_window = 1;
600           if (session_open(the_authctxt, c->self) != 1) {
601                     debug("session open failed, free channel %d", c->self);
602                     channel_free(ssh, c);
603                     return NULL;
604           }
605           channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
606           return c;
607 }
608 
609 static int
server_input_channel_open(int type,u_int32_t seq,struct ssh * ssh)610 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
611 {
612           Channel *c = NULL;
613           char *ctype = NULL;
614           const char *errmsg = NULL;
615           int r, reason = SSH2_OPEN_CONNECT_FAILED;
616           u_int rchan = 0, rmaxpack = 0, rwindow = 0;
617 
618           if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
619               (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
620               (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
621               (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
622                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
623           debug_f("ctype %s rchan %u win %u max %u",
624               ctype, rchan, rwindow, rmaxpack);
625 
626           if (strcmp(ctype, "session") == 0) {
627                     c = server_request_session(ssh);
628           } else if (strcmp(ctype, "direct-tcpip") == 0) {
629                     c = server_request_direct_tcpip(ssh, &reason, &errmsg);
630           } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
631                     c = server_request_direct_streamlocal(ssh);
632           } else if (strcmp(ctype, "tun@openssh.com") == 0) {
633                     c = server_request_tun(ssh);
634           }
635           if (c != NULL) {
636                     debug_f("confirm %s", ctype);
637                     c->remote_id = rchan;
638                     c->have_remote_id = 1;
639                     c->remote_window = rwindow;
640                     c->remote_maxpacket = rmaxpack;
641                     if (c->type != SSH_CHANNEL_CONNECTING) {
642                               if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
643                                   (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
644                                   (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
645                                   (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
646                                   (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
647                                   (r = sshpkt_send(ssh)) != 0) {
648                                         sshpkt_fatal(ssh, r,
649                                             "%s: send open confirm", __func__);
650                               }
651                     }
652           } else {
653                     debug_f("failure %s", ctype);
654                     if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
655                         (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
656                         (r = sshpkt_put_u32(ssh, reason)) != 0 ||
657                         (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
658                         (r = sshpkt_put_cstring(ssh, "")) != 0 ||
659                         (r = sshpkt_send(ssh)) != 0) {
660                               sshpkt_fatal(ssh, r,
661                                   "%s: send open failure", __func__);
662                     }
663           }
664           free(ctype);
665           return 0;
666 }
667 
668 static int
server_input_hostkeys_prove(struct ssh * ssh,struct sshbuf ** respp)669 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
670 {
671           struct sshbuf *resp = NULL;
672           struct sshbuf *sigbuf = NULL;
673           struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
674           int r, ndx, success = 0;
675           const u_char *blob;
676           const char *sigalg, *kex_rsa_sigalg = NULL;
677           u_char *sig = 0;
678           size_t blen, slen;
679 
680           if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
681                     fatal_f("sshbuf_new");
682           if (sshkey_type_plain(sshkey_type_from_name(
683               ssh->kex->hostkey_alg)) == KEY_RSA)
684                     kex_rsa_sigalg = ssh->kex->hostkey_alg;
685           while (ssh_packet_remaining(ssh) > 0) {
686                     sshkey_free(key);
687                     key = NULL;
688                     if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
689                         (r = sshkey_from_blob(blob, blen, &key)) != 0) {
690                               error_fr(r, "parse key");
691                               goto out;
692                     }
693                     /*
694                      * Better check that this is actually one of our hostkeys
695                      * before attempting to sign anything with it.
696                      */
697                     if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
698                               error_f("unknown host %s key", sshkey_type(key));
699                               goto out;
700                     }
701                     /*
702                      * XXX refactor: make kex->sign just use an index rather
703                      * than passing in public and private keys
704                      */
705                     if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
706                         (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
707                               error_f("can't retrieve hostkey %d", ndx);
708                               goto out;
709                     }
710                     sshbuf_reset(sigbuf);
711                     free(sig);
712                     sig = NULL;
713                     /*
714                      * For RSA keys, prefer to use the signature type negotiated
715                      * during KEX to the default (SHA1).
716                      */
717                     sigalg = sshkey_ssh_name(key);
718                     if (sshkey_type_plain(key->type) == KEY_RSA) {
719                               if (kex_rsa_sigalg != NULL)
720                                         sigalg = kex_rsa_sigalg;
721                               else if (ssh->kex->flags & KEX_RSA_SHA2_512_SUPPORTED)
722                                         sigalg = "rsa-sha2-512";
723                               else if (ssh->kex->flags & KEX_RSA_SHA2_256_SUPPORTED)
724                                         sigalg = "rsa-sha2-256";
725                     }
726 
727                     debug3_f("sign %s key (index %d) using sigalg %s",
728                         sshkey_type(key), ndx, sigalg == NULL ? "default" : sigalg);
729                     if ((r = sshbuf_put_cstring(sigbuf,
730                         "hostkeys-prove-00@openssh.com")) != 0 ||
731                         (r = sshbuf_put_stringb(sigbuf,
732                         ssh->kex->session_id)) != 0 ||
733                         (r = sshkey_puts(key, sigbuf)) != 0 ||
734                         (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
735                         sshbuf_ptr(sigbuf), sshbuf_len(sigbuf), sigalg)) != 0 ||
736                         (r = sshbuf_put_string(resp, sig, slen)) != 0) {
737                               error_fr(r, "assemble signature");
738                               goto out;
739                     }
740           }
741           /* Success */
742           *respp = resp;
743           resp = NULL; /* don't free it */
744           success = 1;
745  out:
746           free(sig);
747           sshbuf_free(resp);
748           sshbuf_free(sigbuf);
749           sshkey_free(key);
750           return success;
751 }
752 
753 static int
server_input_global_request(int type,u_int32_t seq,struct ssh * ssh)754 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
755 {
756           char *rtype = NULL;
757           u_char want_reply = 0;
758           int r, success = 0, allocated_listen_port = 0;
759           u_int port = 0;
760           struct sshbuf *resp = NULL;
761           struct passwd *pw = the_authctxt->pw;
762           struct Forward fwd;
763 
764           memset(&fwd, 0, sizeof(fwd));
765           if (pw == NULL || !the_authctxt->valid)
766                     fatal_f("no/invalid user");
767 
768           if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
769               (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
770                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
771           debug_f("rtype %s want_reply %d", rtype, want_reply);
772 
773           /* -R style forwarding */
774           if (strcmp(rtype, "tcpip-forward") == 0) {
775                     if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
776                         (r = sshpkt_get_u32(ssh, &port)) != 0)
777                               sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
778                     debug_f("tcpip-forward listen %s port %u",
779                         fwd.listen_host, port);
780                     if (port <= INT_MAX)
781                               fwd.listen_port = (int)port;
782                     /* check permissions */
783                     if (port > INT_MAX ||
784                         (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
785                         !auth_opts->permit_port_forwarding_flag ||
786                         options.disable_forwarding ||
787                         (!want_reply && fwd.listen_port == 0)) {
788                               success = 0;
789                               ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
790                     } else {
791                               /* Start listening on the port */
792                               success = channel_setup_remote_fwd_listener(ssh, &fwd,
793                                   &allocated_listen_port, &options.fwd_opts);
794                     }
795                     if ((resp = sshbuf_new()) == NULL)
796                               fatal_f("sshbuf_new");
797                     if (allocated_listen_port != 0 &&
798                         (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
799                               fatal_fr(r, "sshbuf_put_u32");
800           } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
801                     if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
802                         (r = sshpkt_get_u32(ssh, &port)) != 0)
803                               sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
804 
805                     debug_f("cancel-tcpip-forward addr %s port %d",
806                         fwd.listen_host, port);
807                     if (port <= INT_MAX) {
808                               fwd.listen_port = (int)port;
809                               success = channel_cancel_rport_listener(ssh, &fwd);
810                     }
811           } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
812                     if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
813                               sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
814                     debug_f("streamlocal-forward listen path %s",
815                         fwd.listen_path);
816 
817                     /* check permissions */
818                     if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
819                         || !auth_opts->permit_port_forwarding_flag ||
820                         options.disable_forwarding) {
821                               success = 0;
822                               ssh_packet_send_debug(ssh, "Server has disabled "
823                                   "streamlocal forwarding.");
824                     } else {
825                               /* Start listening on the socket */
826                               success = channel_setup_remote_fwd_listener(ssh,
827                                   &fwd, NULL, &options.fwd_opts);
828                     }
829           } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
830                     if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
831                               sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
832                     debug_f("cancel-streamlocal-forward path %s",
833                         fwd.listen_path);
834 
835                     success = channel_cancel_rport_listener(ssh, &fwd);
836           } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
837                     no_more_sessions = 1;
838                     success = 1;
839           } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
840                     success = server_input_hostkeys_prove(ssh, &resp);
841           }
842           /* XXX sshpkt_get_end() */
843           if (want_reply) {
844                     if ((r = sshpkt_start(ssh, success ?
845                         SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
846                         (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
847                         (r = sshpkt_send(ssh)) != 0 ||
848                         (r = ssh_packet_write_wait(ssh)) < 0)
849                               sshpkt_fatal(ssh, r, "%s: send reply", __func__);
850           }
851           free(fwd.listen_host);
852           free(fwd.listen_path);
853           free(rtype);
854           sshbuf_free(resp);
855           return 0;
856 }
857 
858 static int
server_input_channel_req(int type,u_int32_t seq,struct ssh * ssh)859 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
860 {
861           Channel *c;
862           int r, success = 0;
863           char *rtype = NULL;
864           u_char want_reply = 0;
865           u_int id = 0;
866 
867           if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
868               (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
869               (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
870                     sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
871 
872           debug("server_input_channel_req: channel %u request %s reply %d",
873               id, rtype, want_reply);
874 
875           if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
876                     ssh_packet_disconnect(ssh, "%s: unknown channel %d",
877                         __func__, id);
878           }
879           if (!strcmp(rtype, "eow@openssh.com")) {
880                     if ((r = sshpkt_get_end(ssh)) != 0)
881                               sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
882                     chan_rcvd_eow(ssh, c);
883           } else if ((c->type == SSH_CHANNEL_LARVAL ||
884               c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
885                     success = session_input_channel_req(ssh, c, rtype);
886           if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
887                     if (!c->have_remote_id)
888                               fatal_f("channel %d: no remote_id", c->self);
889                     if ((r = sshpkt_start(ssh, success ?
890                         SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
891                         (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
892                         (r = sshpkt_send(ssh)) != 0)
893                               sshpkt_fatal(ssh, r, "%s: send reply", __func__);
894           }
895           free(rtype);
896           return 0;
897 }
898 
899 static void
server_init_dispatch(struct ssh * ssh)900 server_init_dispatch(struct ssh *ssh)
901 {
902           debug("server_init_dispatch");
903           ssh_dispatch_init(ssh, &dispatch_protocol_error);
904           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
905           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
906           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
907           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
908           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
909           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
910           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
911           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
912           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
913           ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
914           /* client_alive */
915           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
916           ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
917           ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
918           ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
919           /* rekeying */
920           ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
921 }
922