serverloop.c 30 KB

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