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