1 /* $OpenBSD: serverloop.c,v 1.222 2020/01/30 07:21:38 djm Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Server main loop for handling the interactive session.
7 *
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".
13 *
14 * SSH2 support by Markus Friedl.
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
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.
25 *
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.
36 */
37
38 #include "includes.h"
39
40 #include <sys/types.h>
41 #include <sys/wait.h>
42 #include <sys/socket.h>
43 #ifdef HAVE_SYS_TIME_H
44 # include <sys/time.h>
45 #endif
46
47 #include <netinet/in.h>
48
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <pwd.h>
52 #include <limits.h>
53 #include <signal.h>
54 #include <string.h>
55 #include <termios.h>
56 #include <unistd.h>
57 #include <stdarg.h>
58
59 #include "openbsd-compat/sys-queue.h"
60 #include "xmalloc.h"
61 #include "packet.h"
62 #include "sshbuf.h"
63 #include "log.h"
64 #include "misc.h"
65 #include "servconf.h"
66 #include "canohost.h"
67 #include "sshpty.h"
68 #include "channels.h"
69 #include "compat.h"
70 #include "ssh2.h"
71 #include "sshkey.h"
72 #include "cipher.h"
73 #include "kex.h"
74 #include "hostfile.h"
75 #include "auth.h"
76 #include "session.h"
77 #include "dispatch.h"
78 #include "auth-options.h"
79 #include "serverloop.h"
80 #include "ssherr.h"
81
82 extern ServerOptions options;
83
84 /* XXX */
85 extern Authctxt *the_authctxt;
86 extern struct sshauthopt *auth_opts;
87 extern int use_privsep;
88
89 static int no_more_sessions = 0; /* Disallow further sessions. */
90
91 /*
92 * This SIGCHLD kludge is used to detect when the child exits. The server
93 * will exit after that, as soon as forwarded connections have terminated.
94 */
95
96 static volatile sig_atomic_t child_terminated = 0; /* The child has terminated. */
97
98 /* Cleanup on signals (!use_privsep case only) */
99 static volatile sig_atomic_t received_sigterm = 0;
100
101 /* prototypes */
102 static void server_init_dispatch(struct ssh *);
103
104 /* requested tunnel forwarding interface(s), shared with session.c */
105 char *tun_fwd_ifnames = NULL;
106
107 /* returns 1 if bind to specified port by specified user is permitted */
108 static int
bind_permitted(int port,uid_t uid)109 bind_permitted(int port, uid_t uid)
110 {
111 if (use_privsep)
112 return 1; /* allow system to decide */
113 if (port < IPPORT_RESERVED && uid != 0)
114 return 0;
115 return 1;
116 }
117
118 /*
119 * we write to this pipe if a SIGCHLD is caught in order to avoid
120 * the race between select() and child_terminated
121 */
122 static int notify_pipe[2];
123 static void
notify_setup(void)124 notify_setup(void)
125 {
126 if (pipe(notify_pipe) == -1) {
127 error("pipe(notify_pipe) failed %s", strerror(errno));
128 } else if ((fcntl(notify_pipe[0], F_SETFD, FD_CLOEXEC) == -1) ||
129 (fcntl(notify_pipe[1], F_SETFD, FD_CLOEXEC) == -1)) {
130 error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
131 close(notify_pipe[0]);
132 close(notify_pipe[1]);
133 } else {
134 set_nonblock(notify_pipe[0]);
135 set_nonblock(notify_pipe[1]);
136 return;
137 }
138 notify_pipe[0] = -1; /* read end */
139 notify_pipe[1] = -1; /* write end */
140 }
141 static void
notify_parent(void)142 notify_parent(void)
143 {
144 if (notify_pipe[1] != -1)
145 (void)write(notify_pipe[1], "", 1);
146 }
147 static void
notify_prepare(fd_set * readset)148 notify_prepare(fd_set *readset)
149 {
150 if (notify_pipe[0] != -1)
151 FD_SET(notify_pipe[0], readset);
152 }
153 static void
notify_done(fd_set * readset)154 notify_done(fd_set *readset)
155 {
156 char c;
157
158 if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
159 while (read(notify_pipe[0], &c, 1) != -1)
160 debug2("%s: reading", __func__);
161 }
162
163 /*ARGSUSED*/
164 static void
sigchld_handler(int sig)165 sigchld_handler(int sig)
166 {
167 int save_errno = errno;
168 child_terminated = 1;
169 notify_parent();
170 errno = save_errno;
171 }
172
173 /*ARGSUSED*/
174 static void
sigterm_handler(int sig)175 sigterm_handler(int sig)
176 {
177 received_sigterm = sig;
178 }
179
180 static void
client_alive_check(struct ssh * ssh)181 client_alive_check(struct ssh *ssh)
182 {
183 char remote_id[512];
184 int r, channel_id;
185
186 /* timeout, check to see how many we have had */
187 if (options.client_alive_count_max > 0 &&
188 ssh_packet_inc_alive_timeouts(ssh) >
189 options.client_alive_count_max) {
190 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
191 logit("Timeout, client not responding from %s", remote_id);
192 cleanup_exit(255);
193 }
194
195 /*
196 * send a bogus global/channel request with "wantreply",
197 * we should get back a failure
198 */
199 if ((channel_id = channel_find_open(ssh)) == -1) {
200 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
201 (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com"))
202 != 0 ||
203 (r = sshpkt_put_u8(ssh, 1)) != 0) /* boolean: want reply */
204 fatal("%s: %s", __func__, ssh_err(r));
205 } else {
206 channel_request_start(ssh, channel_id,
207 "keepalive@openssh.com", 1);
208 }
209 if ((r = sshpkt_send(ssh)) != 0)
210 fatal("%s: %s", __func__, ssh_err(r));
211 }
212
213 /*
214 * Sleep in select() until we can do something. This will initialize the
215 * select masks. Upon return, the masks will indicate which descriptors
216 * have data or can accept data. Optionally, a maximum time can be specified
217 * for the duration of the wait (0 = infinite).
218 */
219 static void
wait_until_can_do_something(struct ssh * ssh,int connection_in,int connection_out,fd_set ** readsetp,fd_set ** writesetp,int * maxfdp,u_int * nallocp,u_int64_t max_time_ms)220 wait_until_can_do_something(struct ssh *ssh,
221 int connection_in, int connection_out,
222 fd_set **readsetp, fd_set **writesetp, int *maxfdp,
223 u_int *nallocp, u_int64_t max_time_ms)
224 {
225 struct timeval tv, *tvp;
226 int ret;
227 time_t minwait_secs = 0;
228 int client_alive_scheduled = 0;
229 /* time we last heard from the client OR sent a keepalive */
230 static time_t last_client_time;
231
232 /* Allocate and update select() masks for channel descriptors. */
233 channel_prepare_select(ssh, readsetp, writesetp, maxfdp,
234 nallocp, &minwait_secs);
235
236 /* XXX need proper deadline system for rekey/client alive */
237 if (minwait_secs != 0)
238 max_time_ms = MINIMUM(max_time_ms, (u_int)minwait_secs * 1000);
239
240 /*
241 * if using client_alive, set the max timeout accordingly,
242 * and indicate that this particular timeout was for client
243 * alive by setting the client_alive_scheduled flag.
244 *
245 * this could be randomized somewhat to make traffic
246 * analysis more difficult, but we're not doing it yet.
247 */
248 if (options.client_alive_interval) {
249 uint64_t keepalive_ms =
250 (uint64_t)options.client_alive_interval * 1000;
251
252 if (max_time_ms == 0 || max_time_ms > keepalive_ms) {
253 max_time_ms = keepalive_ms;
254 client_alive_scheduled = 1;
255 }
256 }
257
258 #if 0
259 /* wrong: bad condition XXX */
260 if (channel_not_very_much_buffered_data())
261 #endif
262 FD_SET(connection_in, *readsetp);
263 notify_prepare(*readsetp);
264
265 /*
266 * If we have buffered packet data going to the client, mark that
267 * descriptor.
268 */
269 if (ssh_packet_have_data_to_write(ssh))
270 FD_SET(connection_out, *writesetp);
271
272 /*
273 * If child has terminated and there is enough buffer space to read
274 * from it, then read as much as is available and exit.
275 */
276 if (child_terminated && ssh_packet_not_very_much_data_to_write(ssh))
277 if (max_time_ms == 0 || client_alive_scheduled)
278 max_time_ms = 100;
279
280 if (max_time_ms == 0)
281 tvp = NULL;
282 else {
283 tv.tv_sec = max_time_ms / 1000;
284 tv.tv_usec = 1000 * (max_time_ms % 1000);
285 tvp = &tv;
286 }
287
288 /* Wait for something to happen, or the timeout to expire. */
289 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
290
291 if (ret == -1) {
292 memset(*readsetp, 0, *nallocp);
293 memset(*writesetp, 0, *nallocp);
294 if (errno != EINTR)
295 error("select: %.100s", strerror(errno));
296 } else if (client_alive_scheduled) {
297 time_t now = monotime();
298
299 /*
300 * If the select timed out, or returned for some other reason
301 * but we haven't heard from the client in time, send keepalive.
302 */
303 if (ret == 0 || (last_client_time != 0 && last_client_time +
304 options.client_alive_interval <= now)) {
305 client_alive_check(ssh);
306 last_client_time = now;
307 } else if (FD_ISSET(connection_in, *readsetp)) {
308 last_client_time = now;
309 }
310 }
311
312 notify_done(*readsetp);
313 }
314
315 /*
316 * Processes input from the client and the program. Input data is stored
317 * in buffers and processed later.
318 */
319 static int
process_input(struct ssh * ssh,fd_set * readset,int connection_in)320 process_input(struct ssh *ssh, fd_set *readset, int connection_in)
321 {
322 int r, len;
323 char buf[16384];
324
325 /* Read and buffer any input data from the client. */
326 if (FD_ISSET(connection_in, readset)) {
327 len = read(connection_in, buf, sizeof(buf));
328 if (len == 0) {
329 verbose("Connection closed by %.100s port %d",
330 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
331 return -1;
332 } else if (len == -1) {
333 if (errno != EINTR && errno != EAGAIN &&
334 errno != EWOULDBLOCK) {
335 verbose("Read error from remote host "
336 "%.100s port %d: %.100s",
337 ssh_remote_ipaddr(ssh),
338 ssh_remote_port(ssh), strerror(errno));
339 cleanup_exit(255);
340 }
341 } else {
342 /* Buffer any received data. */
343 if ((r = ssh_packet_process_incoming(ssh, buf, len))
344 != 0)
345 fatal("%s: ssh_packet_process_incoming: %s",
346 __func__, ssh_err(r));
347 }
348 }
349 return 0;
350 }
351
352 /*
353 * Sends data from internal buffers to client program stdin.
354 */
355 static void
process_output(struct ssh * ssh,fd_set * writeset,int connection_out)356 process_output(struct ssh *ssh, fd_set *writeset, int connection_out)
357 {
358 int r;
359
360 /* Send any buffered packet data to the client. */
361 if (FD_ISSET(connection_out, writeset)) {
362 if ((r = ssh_packet_write_poll(ssh)) != 0) {
363 sshpkt_fatal(ssh, r, "%s: ssh_packet_write_poll",
364 __func__);
365 }
366 }
367 }
368
369 static void
process_buffered_input_packets(struct ssh * ssh)370 process_buffered_input_packets(struct ssh *ssh)
371 {
372 ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, NULL);
373 }
374
375 static void
collect_children(struct ssh * ssh)376 collect_children(struct ssh *ssh)
377 {
378 pid_t pid;
379 sigset_t oset, nset;
380 int status;
381
382 /* block SIGCHLD while we check for dead children */
383 sigemptyset(&nset);
384 sigaddset(&nset, SIGCHLD);
385 sigprocmask(SIG_BLOCK, &nset, &oset);
386 if (child_terminated) {
387 debug("Received SIGCHLD.");
388 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
389 (pid == -1 && errno == EINTR))
390 if (pid > 0)
391 session_close_by_pid(ssh, pid, status);
392 child_terminated = 0;
393 }
394 sigprocmask(SIG_SETMASK, &oset, NULL);
395 }
396
397 void
server_loop2(struct ssh * ssh,Authctxt * authctxt)398 server_loop2(struct ssh *ssh, Authctxt *authctxt)
399 {
400 fd_set *readset = NULL, *writeset = NULL;
401 int max_fd;
402 u_int nalloc = 0, connection_in, connection_out;
403 u_int64_t rekey_timeout_ms = 0;
404
405 debug("Entering interactive session for SSH2.");
406
407 ssh_signal(SIGCHLD, sigchld_handler);
408 child_terminated = 0;
409 connection_in = ssh_packet_get_connection_in(ssh);
410 connection_out = ssh_packet_get_connection_out(ssh);
411
412 if (!use_privsep) {
413 ssh_signal(SIGTERM, sigterm_handler);
414 ssh_signal(SIGINT, sigterm_handler);
415 ssh_signal(SIGQUIT, sigterm_handler);
416 }
417
418 notify_setup();
419
420 max_fd = MAXIMUM(connection_in, connection_out);
421 max_fd = MAXIMUM(max_fd, notify_pipe[0]);
422
423 server_init_dispatch(ssh);
424
425 for (;;) {
426 process_buffered_input_packets(ssh);
427
428 if (!ssh_packet_is_rekeying(ssh) &&
429 ssh_packet_not_very_much_data_to_write(ssh))
430 channel_output_poll(ssh);
431 if (options.rekey_interval > 0 &&
432 !ssh_packet_is_rekeying(ssh)) {
433 rekey_timeout_ms = ssh_packet_get_rekey_timeout(ssh) *
434 1000;
435 } else {
436 rekey_timeout_ms = 0;
437 }
438
439 wait_until_can_do_something(ssh, connection_in, connection_out,
440 &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms);
441
442 if (received_sigterm) {
443 logit("Exiting on signal %d", (int)received_sigterm);
444 /* Clean up sessions, utmp, etc. */
445 cleanup_exit(255);
446 }
447
448 collect_children(ssh);
449 if (!ssh_packet_is_rekeying(ssh))
450 channel_after_select(ssh, readset, writeset);
451 if (process_input(ssh, readset, connection_in) < 0)
452 break;
453 process_output(ssh, writeset, connection_out);
454 }
455 collect_children(ssh);
456
457 free(readset);
458 free(writeset);
459
460 /* free all channels, no more reads and writes */
461 channel_free_all(ssh);
462
463 /* free remaining sessions, e.g. remove wtmp entries */
464 session_destroy_all(ssh, NULL);
465 }
466
467 static int
server_input_keep_alive(int type,u_int32_t seq,struct ssh * ssh)468 server_input_keep_alive(int type, u_int32_t seq, struct ssh *ssh)
469 {
470 debug("Got %d/%u for keepalive", type, seq);
471 /*
472 * reset timeout, since we got a sane answer from the client.
473 * even if this was generated by something other than
474 * the bogus CHANNEL_REQUEST we send for keepalives.
475 */
476 ssh_packet_set_alive_timeouts(ssh, 0);
477 return 0;
478 }
479
480 static Channel *
server_request_direct_tcpip(struct ssh * ssh,int * reason,const char ** errmsg)481 server_request_direct_tcpip(struct ssh *ssh, int *reason, const char **errmsg)
482 {
483 Channel *c = NULL;
484 char *target = NULL, *originator = NULL;
485 u_int target_port = 0, originator_port = 0;
486 int r;
487
488 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
489 (r = sshpkt_get_u32(ssh, &target_port)) != 0 ||
490 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
491 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
492 (r = sshpkt_get_end(ssh)) != 0)
493 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
494 if (target_port > 0xFFFF) {
495 error("%s: invalid target port", __func__);
496 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
497 goto out;
498 }
499 if (originator_port > 0xFFFF) {
500 error("%s: invalid originator port", __func__);
501 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
502 goto out;
503 }
504
505 debug("%s: originator %s port %u, target %s port %u", __func__,
506 originator, originator_port, target, target_port);
507
508 /* XXX fine grained permissions */
509 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0 &&
510 auth_opts->permit_port_forwarding_flag &&
511 !options.disable_forwarding) {
512 c = channel_connect_to_port(ssh, target, target_port,
513 "direct-tcpip", "direct-tcpip", reason, errmsg);
514 } else {
515 logit("refused local port forward: "
516 "originator %s port %d, target %s port %d",
517 originator, originator_port, target, target_port);
518 if (reason != NULL)
519 *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
520 }
521
522 out:
523 free(originator);
524 free(target);
525 return c;
526 }
527
528 static Channel *
server_request_direct_streamlocal(struct ssh * ssh)529 server_request_direct_streamlocal(struct ssh *ssh)
530 {
531 Channel *c = NULL;
532 char *target = NULL, *originator = NULL;
533 u_int originator_port = 0;
534 struct passwd *pw = the_authctxt->pw;
535 int r;
536
537 if (pw == NULL || !the_authctxt->valid)
538 fatal("%s: no/invalid user", __func__);
539
540 if ((r = sshpkt_get_cstring(ssh, &target, NULL)) != 0 ||
541 (r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
542 (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
543 (r = sshpkt_get_end(ssh)) != 0)
544 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
545 if (originator_port > 0xFFFF) {
546 error("%s: invalid originator port", __func__);
547 goto out;
548 }
549
550 debug("%s: originator %s port %d, target %s", __func__,
551 originator, originator_port, target);
552
553 /* XXX fine grained permissions */
554 if ((options.allow_streamlocal_forwarding & FORWARD_LOCAL) != 0 &&
555 auth_opts->permit_port_forwarding_flag &&
556 !options.disable_forwarding && (pw->pw_uid == 0 || use_privsep)) {
557 c = channel_connect_to_path(ssh, target,
558 "direct-streamlocal@openssh.com", "direct-streamlocal");
559 } else {
560 logit("refused streamlocal port forward: "
561 "originator %s port %d, target %s",
562 originator, originator_port, target);
563 }
564
565 out:
566 free(originator);
567 free(target);
568 return c;
569 }
570
571 static Channel *
server_request_tun(struct ssh * ssh)572 server_request_tun(struct ssh *ssh)
573 {
574 Channel *c = NULL;
575 u_int mode, tun;
576 int r, sock;
577 char *tmp, *ifname = NULL;
578
579 if ((r = sshpkt_get_u32(ssh, &mode)) != 0)
580 sshpkt_fatal(ssh, r, "%s: parse mode", __func__);
581 switch (mode) {
582 case SSH_TUNMODE_POINTOPOINT:
583 case SSH_TUNMODE_ETHERNET:
584 break;
585 default:
586 ssh_packet_send_debug(ssh, "Unsupported tunnel device mode.");
587 return NULL;
588 }
589 if ((options.permit_tun & mode) == 0) {
590 ssh_packet_send_debug(ssh, "Server has rejected tunnel device "
591 "forwarding");
592 return NULL;
593 }
594
595 if ((r = sshpkt_get_u32(ssh, &tun)) != 0)
596 sshpkt_fatal(ssh, r, "%s: parse device", __func__);
597 if (tun > INT_MAX) {
598 debug("%s: invalid tun", __func__);
599 goto done;
600 }
601 if (auth_opts->force_tun_device != -1) {
602 if (tun != SSH_TUNID_ANY &&
603 auth_opts->force_tun_device != (int)tun)
604 goto done;
605 tun = auth_opts->force_tun_device;
606 }
607 sock = tun_open(tun, mode, &ifname);
608 if (sock < 0)
609 goto done;
610 debug("Tunnel forwarding using interface %s", ifname);
611
612 c = channel_new(ssh, "tun", SSH_CHANNEL_OPEN, sock, sock, -1,
613 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
614 c->datagram = 1;
615 #if defined(SSH_TUN_FILTER)
616 if (mode == SSH_TUNMODE_POINTOPOINT)
617 channel_register_filter(ssh, c->self, sys_tun_infilter,
618 sys_tun_outfilter, NULL, NULL);
619 #endif
620
621 /*
622 * Update the list of names exposed to the session
623 * XXX remove these if the tunnels are closed (won't matter
624 * much if they are already in the environment though)
625 */
626 tmp = tun_fwd_ifnames;
627 xasprintf(&tun_fwd_ifnames, "%s%s%s",
628 tun_fwd_ifnames == NULL ? "" : tun_fwd_ifnames,
629 tun_fwd_ifnames == NULL ? "" : ",",
630 ifname);
631 free(tmp);
632 free(ifname);
633
634 done:
635 if (c == NULL)
636 ssh_packet_send_debug(ssh, "Failed to open the tunnel device.");
637 return c;
638 }
639
640 static Channel *
server_request_session(struct ssh * ssh)641 server_request_session(struct ssh *ssh)
642 {
643 Channel *c;
644 int r;
645
646 debug("input_session_request");
647 if ((r = sshpkt_get_end(ssh)) != 0)
648 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
649
650 if (no_more_sessions) {
651 ssh_packet_disconnect(ssh, "Possible attack: attempt to open a "
652 "session after additional sessions disabled");
653 }
654
655 /*
656 * A server session has no fd to read or write until a
657 * CHANNEL_REQUEST for a shell is made, so we set the type to
658 * SSH_CHANNEL_LARVAL. Additionally, a callback for handling all
659 * CHANNEL_REQUEST messages is registered.
660 */
661 c = channel_new(ssh, "session", SSH_CHANNEL_LARVAL,
662 -1, -1, -1, /*window size*/0, CHAN_SES_PACKET_DEFAULT,
663 0, "server-session", 1);
664 if (session_open(the_authctxt, c->self) != 1) {
665 debug("session open failed, free channel %d", c->self);
666 channel_free(ssh, c);
667 return NULL;
668 }
669 channel_register_cleanup(ssh, c->self, session_close_by_channel, 0);
670 return c;
671 }
672
673 static int
server_input_channel_open(int type,u_int32_t seq,struct ssh * ssh)674 server_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
675 {
676 Channel *c = NULL;
677 char *ctype = NULL;
678 const char *errmsg = NULL;
679 int r, reason = SSH2_OPEN_CONNECT_FAILED;
680 u_int rchan = 0, rmaxpack = 0, rwindow = 0;
681
682 if ((r = sshpkt_get_cstring(ssh, &ctype, NULL)) != 0 ||
683 (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
684 (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
685 (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
686 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
687 debug("%s: ctype %s rchan %u win %u max %u", __func__,
688 ctype, rchan, rwindow, rmaxpack);
689
690 if (strcmp(ctype, "session") == 0) {
691 c = server_request_session(ssh);
692 } else if (strcmp(ctype, "direct-tcpip") == 0) {
693 c = server_request_direct_tcpip(ssh, &reason, &errmsg);
694 } else if (strcmp(ctype, "direct-streamlocal@openssh.com") == 0) {
695 c = server_request_direct_streamlocal(ssh);
696 } else if (strcmp(ctype, "tun@openssh.com") == 0) {
697 c = server_request_tun(ssh);
698 }
699 if (c != NULL) {
700 debug("%s: confirm %s", __func__, ctype);
701 c->remote_id = rchan;
702 c->have_remote_id = 1;
703 c->remote_window = rwindow;
704 c->remote_maxpacket = rmaxpack;
705 if (c->type != SSH_CHANNEL_CONNECTING) {
706 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
707 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
708 (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
709 (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
710 (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
711 (r = sshpkt_send(ssh)) != 0) {
712 sshpkt_fatal(ssh, r,
713 "%s: send open confirm", __func__);
714 }
715 }
716 } else {
717 debug("%s: failure %s", __func__, ctype);
718 if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
719 (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
720 (r = sshpkt_put_u32(ssh, reason)) != 0 ||
721 (r = sshpkt_put_cstring(ssh, errmsg ? errmsg : "open failed")) != 0 ||
722 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
723 (r = sshpkt_send(ssh)) != 0) {
724 sshpkt_fatal(ssh, r,
725 "%s: send open failure", __func__);
726 }
727 }
728 free(ctype);
729 return 0;
730 }
731
732 static int
server_input_hostkeys_prove(struct ssh * ssh,struct sshbuf ** respp)733 server_input_hostkeys_prove(struct ssh *ssh, struct sshbuf **respp)
734 {
735 struct sshbuf *resp = NULL;
736 struct sshbuf *sigbuf = NULL;
737 struct sshkey *key = NULL, *key_pub = NULL, *key_prv = NULL;
738 int r, ndx, kexsigtype, use_kexsigtype, success = 0;
739 const u_char *blob;
740 u_char *sig = 0;
741 size_t blen, slen;
742
743 if ((resp = sshbuf_new()) == NULL || (sigbuf = sshbuf_new()) == NULL)
744 fatal("%s: sshbuf_new", __func__);
745
746 kexsigtype = sshkey_type_plain(
747 sshkey_type_from_name(ssh->kex->hostkey_alg));
748 while (ssh_packet_remaining(ssh) > 0) {
749 sshkey_free(key);
750 key = NULL;
751 if ((r = sshpkt_get_string_direct(ssh, &blob, &blen)) != 0 ||
752 (r = sshkey_from_blob(blob, blen, &key)) != 0) {
753 error("%s: couldn't parse key: %s",
754 __func__, ssh_err(r));
755 goto out;
756 }
757 /*
758 * Better check that this is actually one of our hostkeys
759 * before attempting to sign anything with it.
760 */
761 if ((ndx = ssh->kex->host_key_index(key, 1, ssh)) == -1) {
762 error("%s: unknown host %s key",
763 __func__, sshkey_type(key));
764 goto out;
765 }
766 /*
767 * XXX refactor: make kex->sign just use an index rather
768 * than passing in public and private keys
769 */
770 if ((key_prv = get_hostkey_by_index(ndx)) == NULL &&
771 (key_pub = get_hostkey_public_by_index(ndx, ssh)) == NULL) {
772 error("%s: can't retrieve hostkey %d", __func__, ndx);
773 goto out;
774 }
775 sshbuf_reset(sigbuf);
776 free(sig);
777 sig = NULL;
778 /*
779 * For RSA keys, prefer to use the signature type negotiated
780 * during KEX to the default (SHA1).
781 */
782 use_kexsigtype = kexsigtype == KEY_RSA &&
783 sshkey_type_plain(key->type) == KEY_RSA;
784 if ((r = sshbuf_put_cstring(sigbuf,
785 "hostkeys-prove-00@openssh.com")) != 0 ||
786 (r = sshbuf_put_string(sigbuf,
787 ssh->kex->session_id, ssh->kex->session_id_len)) != 0 ||
788 (r = sshkey_puts(key, sigbuf)) != 0 ||
789 (r = ssh->kex->sign(ssh, key_prv, key_pub, &sig, &slen,
790 sshbuf_ptr(sigbuf), sshbuf_len(sigbuf),
791 use_kexsigtype ? ssh->kex->hostkey_alg : NULL)) != 0 ||
792 (r = sshbuf_put_string(resp, sig, slen)) != 0) {
793 error("%s: couldn't prepare signature: %s",
794 __func__, ssh_err(r));
795 goto out;
796 }
797 }
798 /* Success */
799 *respp = resp;
800 resp = NULL; /* don't free it */
801 success = 1;
802 out:
803 free(sig);
804 sshbuf_free(resp);
805 sshbuf_free(sigbuf);
806 sshkey_free(key);
807 return success;
808 }
809
810 static int
server_input_global_request(int type,u_int32_t seq,struct ssh * ssh)811 server_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
812 {
813 char *rtype = NULL;
814 u_char want_reply = 0;
815 int r, success = 0, allocated_listen_port = 0;
816 u_int port = 0;
817 struct sshbuf *resp = NULL;
818 struct passwd *pw = the_authctxt->pw;
819 struct Forward fwd;
820
821 memset(&fwd, 0, sizeof(fwd));
822 if (pw == NULL || !the_authctxt->valid)
823 fatal("%s: no/invalid user", __func__);
824
825 if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
826 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
827 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
828 debug("%s: rtype %s want_reply %d", __func__, rtype, want_reply);
829
830 /* -R style forwarding */
831 if (strcmp(rtype, "tcpip-forward") == 0) {
832 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
833 (r = sshpkt_get_u32(ssh, &port)) != 0)
834 sshpkt_fatal(ssh, r, "%s: parse tcpip-forward", __func__);
835 debug("%s: tcpip-forward listen %s port %u", __func__,
836 fwd.listen_host, port);
837 if (port <= INT_MAX)
838 fwd.listen_port = (int)port;
839 /* check permissions */
840 if (port > INT_MAX ||
841 (options.allow_tcp_forwarding & FORWARD_REMOTE) == 0 ||
842 !auth_opts->permit_port_forwarding_flag ||
843 options.disable_forwarding ||
844 (!want_reply && fwd.listen_port == 0) ||
845 (fwd.listen_port != 0 &&
846 !bind_permitted(fwd.listen_port, pw->pw_uid))) {
847 success = 0;
848 ssh_packet_send_debug(ssh, "Server has disabled port forwarding.");
849 } else {
850 /* Start listening on the port */
851 success = channel_setup_remote_fwd_listener(ssh, &fwd,
852 &allocated_listen_port, &options.fwd_opts);
853 }
854 if ((resp = sshbuf_new()) == NULL)
855 fatal("%s: sshbuf_new", __func__);
856 if (allocated_listen_port != 0 &&
857 (r = sshbuf_put_u32(resp, allocated_listen_port)) != 0)
858 fatal("%s: sshbuf_put_u32: %s", __func__, ssh_err(r));
859 } else if (strcmp(rtype, "cancel-tcpip-forward") == 0) {
860 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_host, NULL)) != 0 ||
861 (r = sshpkt_get_u32(ssh, &port)) != 0)
862 sshpkt_fatal(ssh, r, "%s: parse cancel-tcpip-forward", __func__);
863
864 debug("%s: cancel-tcpip-forward addr %s port %d", __func__,
865 fwd.listen_host, port);
866 if (port <= INT_MAX) {
867 fwd.listen_port = (int)port;
868 success = channel_cancel_rport_listener(ssh, &fwd);
869 }
870 } else if (strcmp(rtype, "streamlocal-forward@openssh.com") == 0) {
871 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
872 sshpkt_fatal(ssh, r, "%s: parse streamlocal-forward@openssh.com", __func__);
873 debug("%s: streamlocal-forward listen path %s", __func__,
874 fwd.listen_path);
875
876 /* check permissions */
877 if ((options.allow_streamlocal_forwarding & FORWARD_REMOTE) == 0
878 || !auth_opts->permit_port_forwarding_flag ||
879 options.disable_forwarding ||
880 (pw->pw_uid != 0 && !use_privsep)) {
881 success = 0;
882 ssh_packet_send_debug(ssh, "Server has disabled "
883 "streamlocal forwarding.");
884 } else {
885 /* Start listening on the socket */
886 success = channel_setup_remote_fwd_listener(ssh,
887 &fwd, NULL, &options.fwd_opts);
888 }
889 } else if (strcmp(rtype, "cancel-streamlocal-forward@openssh.com") == 0) {
890 if ((r = sshpkt_get_cstring(ssh, &fwd.listen_path, NULL)) != 0)
891 sshpkt_fatal(ssh, r, "%s: parse cancel-streamlocal-forward@openssh.com", __func__);
892 debug("%s: cancel-streamlocal-forward path %s", __func__,
893 fwd.listen_path);
894
895 success = channel_cancel_rport_listener(ssh, &fwd);
896 } else if (strcmp(rtype, "no-more-sessions@openssh.com") == 0) {
897 no_more_sessions = 1;
898 success = 1;
899 } else if (strcmp(rtype, "hostkeys-prove-00@openssh.com") == 0) {
900 success = server_input_hostkeys_prove(ssh, &resp);
901 }
902 /* XXX sshpkt_get_end() */
903 if (want_reply) {
904 if ((r = sshpkt_start(ssh, success ?
905 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE)) != 0 ||
906 (success && resp != NULL && (r = sshpkt_putb(ssh, resp)) != 0) ||
907 (r = sshpkt_send(ssh)) != 0 ||
908 (r = ssh_packet_write_wait(ssh)) != 0)
909 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
910 }
911 free(fwd.listen_host);
912 free(fwd.listen_path);
913 free(rtype);
914 sshbuf_free(resp);
915 return 0;
916 }
917
918 static int
server_input_channel_req(int type,u_int32_t seq,struct ssh * ssh)919 server_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
920 {
921 Channel *c;
922 int r, success = 0;
923 char *rtype = NULL;
924 u_char want_reply = 0;
925 u_int id = 0;
926
927 if ((r = sshpkt_get_u32(ssh, &id)) != 0 ||
928 (r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
929 (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
930 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
931
932 debug("server_input_channel_req: channel %u request %s reply %d",
933 id, rtype, want_reply);
934
935 if (id >= INT_MAX || (c = channel_lookup(ssh, (int)id)) == NULL) {
936 ssh_packet_disconnect(ssh, "%s: unknown channel %d",
937 __func__, id);
938 }
939 if (!strcmp(rtype, "eow@openssh.com")) {
940 if ((r = sshpkt_get_end(ssh)) != 0)
941 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
942 chan_rcvd_eow(ssh, c);
943 } else if ((c->type == SSH_CHANNEL_LARVAL ||
944 c->type == SSH_CHANNEL_OPEN) && strcmp(c->ctype, "session") == 0)
945 success = session_input_channel_req(ssh, c, rtype);
946 if (want_reply && !(c->flags & CHAN_CLOSE_SENT)) {
947 if (!c->have_remote_id)
948 fatal("%s: channel %d: no remote_id",
949 __func__, c->self);
950 if ((r = sshpkt_start(ssh, success ?
951 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
952 (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
953 (r = sshpkt_send(ssh)) != 0)
954 sshpkt_fatal(ssh, r, "%s: send reply", __func__);
955 }
956 free(rtype);
957 return 0;
958 }
959
960 static void
server_init_dispatch(struct ssh * ssh)961 server_init_dispatch(struct ssh *ssh)
962 {
963 debug("server_init_dispatch");
964 ssh_dispatch_init(ssh, &dispatch_protocol_error);
965 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
966 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
967 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
968 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
969 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &server_input_channel_open);
970 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
971 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
972 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &server_input_channel_req);
973 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
974 ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &server_input_global_request);
975 /* client_alive */
976 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &server_input_keep_alive);
977 ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &server_input_keep_alive);
978 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &server_input_keep_alive);
979 ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &server_input_keep_alive);
980 /* rekeying */
981 ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
982 }
983