clientloop.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499
  1. /* $OpenBSD: clientloop.c,v 1.346 2020/09/16 03:07:31 dtucker 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. * The main loop for the interactive session (client side).
  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. *
  15. * Copyright (c) 1999 Theo de Raadt. 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. * SSH2 support added by Markus Friedl.
  39. * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
  40. *
  41. * Redistribution and use in source and binary forms, with or without
  42. * modification, are permitted provided that the following conditions
  43. * are met:
  44. * 1. Redistributions of source code must retain the above copyright
  45. * notice, this list of conditions and the following disclaimer.
  46. * 2. Redistributions in binary form must reproduce the above copyright
  47. * notice, this list of conditions and the following disclaimer in the
  48. * documentation and/or other materials provided with the distribution.
  49. *
  50. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  51. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  52. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  53. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  54. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  55. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  56. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  57. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  58. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  59. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  60. */
  61. #include "includes.h"
  62. #include <sys/types.h>
  63. #include <sys/ioctl.h>
  64. #ifdef HAVE_SYS_STAT_H
  65. # include <sys/stat.h>
  66. #endif
  67. #ifdef HAVE_SYS_TIME_H
  68. # include <sys/time.h>
  69. #endif
  70. #include <sys/socket.h>
  71. #include <ctype.h>
  72. #include <errno.h>
  73. #ifdef HAVE_PATHS_H
  74. #include <paths.h>
  75. #endif
  76. #include <signal.h>
  77. #include <stdio.h>
  78. #include <stdlib.h>
  79. #include <string.h>
  80. #include <stdarg.h>
  81. #include <termios.h>
  82. #include <pwd.h>
  83. #include <unistd.h>
  84. #include <limits.h>
  85. #include "openbsd-compat/sys-queue.h"
  86. #include "xmalloc.h"
  87. #include "ssh.h"
  88. #include "ssh2.h"
  89. #include "packet.h"
  90. #include "sshbuf.h"
  91. #include "compat.h"
  92. #include "channels.h"
  93. #include "dispatch.h"
  94. #include "sshkey.h"
  95. #include "cipher.h"
  96. #include "kex.h"
  97. #include "myproposal.h"
  98. #include "log.h"
  99. #include "misc.h"
  100. #include "readconf.h"
  101. #include "clientloop.h"
  102. #include "sshconnect.h"
  103. #include "authfd.h"
  104. #include "atomicio.h"
  105. #include "sshpty.h"
  106. #include "match.h"
  107. #include "msg.h"
  108. #include "ssherr.h"
  109. #include "hostfile.h"
  110. /* import options */
  111. extern Options options;
  112. /* Control socket */
  113. extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
  114. /*
  115. * Name of the host we are connecting to. This is the name given on the
  116. * command line, or the Hostname specified for the user-supplied name in a
  117. * configuration file.
  118. */
  119. extern char *host;
  120. /*
  121. * If this field is not NULL, the ForwardAgent socket is this path and different
  122. * instead of SSH_AUTH_SOCK.
  123. */
  124. extern char *forward_agent_sock_path;
  125. /*
  126. * Flag to indicate that we have received a window change signal which has
  127. * not yet been processed. This will cause a message indicating the new
  128. * window size to be sent to the server a little later. This is volatile
  129. * because this is updated in a signal handler.
  130. */
  131. static volatile sig_atomic_t received_window_change_signal = 0;
  132. static volatile sig_atomic_t received_signal = 0;
  133. /* Time when backgrounded control master using ControlPersist should exit */
  134. static time_t control_persist_exit_time = 0;
  135. /* Common data for the client loop code. */
  136. volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
  137. static int last_was_cr; /* Last character was a newline. */
  138. static int exit_status; /* Used to store the command exit status. */
  139. static struct sshbuf *stderr_buffer; /* Used for final exit message. */
  140. static int connection_in; /* Connection to server (input). */
  141. static int connection_out; /* Connection to server (output). */
  142. static int need_rekeying; /* Set to non-zero if rekeying is requested. */
  143. static int session_closed; /* In SSH2: login session closed. */
  144. static u_int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
  145. static time_t server_alive_time; /* Time to do server_alive_check */
  146. static void client_init_dispatch(struct ssh *ssh);
  147. int session_ident = -1;
  148. /* Track escape per proto2 channel */
  149. struct escape_filter_ctx {
  150. int escape_pending;
  151. int escape_char;
  152. };
  153. /* Context for channel confirmation replies */
  154. struct channel_reply_ctx {
  155. const char *request_type;
  156. int id;
  157. enum confirm_action action;
  158. };
  159. /* Global request success/failure callbacks */
  160. /* XXX move to struct ssh? */
  161. struct global_confirm {
  162. TAILQ_ENTRY(global_confirm) entry;
  163. global_confirm_cb *cb;
  164. void *ctx;
  165. int ref_count;
  166. };
  167. TAILQ_HEAD(global_confirms, global_confirm);
  168. static struct global_confirms global_confirms =
  169. TAILQ_HEAD_INITIALIZER(global_confirms);
  170. void ssh_process_session2_setup(int, int, int, struct sshbuf *);
  171. /*
  172. * Signal handler for the window change signal (SIGWINCH). This just sets a
  173. * flag indicating that the window has changed.
  174. */
  175. /*ARGSUSED */
  176. static void
  177. window_change_handler(int sig)
  178. {
  179. received_window_change_signal = 1;
  180. }
  181. /*
  182. * Signal handler for signals that cause the program to terminate. These
  183. * signals must be trapped to restore terminal modes.
  184. */
  185. /*ARGSUSED */
  186. static void
  187. signal_handler(int sig)
  188. {
  189. received_signal = sig;
  190. quit_pending = 1;
  191. }
  192. /*
  193. * Sets control_persist_exit_time to the absolute time when the
  194. * backgrounded control master should exit due to expiry of the
  195. * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
  196. * control master process, or if there is no ControlPersist timeout.
  197. */
  198. static void
  199. set_control_persist_exit_time(struct ssh *ssh)
  200. {
  201. if (muxserver_sock == -1 || !options.control_persist
  202. || options.control_persist_timeout == 0) {
  203. /* not using a ControlPersist timeout */
  204. control_persist_exit_time = 0;
  205. } else if (channel_still_open(ssh)) {
  206. /* some client connections are still open */
  207. if (control_persist_exit_time > 0)
  208. debug2("%s: cancel scheduled exit", __func__);
  209. control_persist_exit_time = 0;
  210. } else if (control_persist_exit_time <= 0) {
  211. /* a client connection has recently closed */
  212. control_persist_exit_time = monotime() +
  213. (time_t)options.control_persist_timeout;
  214. debug2("%s: schedule exit in %d seconds", __func__,
  215. options.control_persist_timeout);
  216. }
  217. /* else we are already counting down to the timeout */
  218. }
  219. #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
  220. static int
  221. client_x11_display_valid(const char *display)
  222. {
  223. size_t i, dlen;
  224. if (display == NULL)
  225. return 0;
  226. dlen = strlen(display);
  227. for (i = 0; i < dlen; i++) {
  228. if (!isalnum((u_char)display[i]) &&
  229. strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
  230. debug("Invalid character '%c' in DISPLAY", display[i]);
  231. return 0;
  232. }
  233. }
  234. return 1;
  235. }
  236. #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
  237. #define X11_TIMEOUT_SLACK 60
  238. int
  239. client_x11_get_proto(struct ssh *ssh, const char *display,
  240. const char *xauth_path, u_int trusted, u_int timeout,
  241. char **_proto, char **_data)
  242. {
  243. char *cmd, line[512], xdisplay[512];
  244. char xauthfile[PATH_MAX], xauthdir[PATH_MAX];
  245. static char proto[512], data[512];
  246. FILE *f;
  247. int got_data = 0, generated = 0, do_unlink = 0, r;
  248. struct stat st;
  249. u_int now, x11_timeout_real;
  250. *_proto = proto;
  251. *_data = data;
  252. proto[0] = data[0] = xauthfile[0] = xauthdir[0] = '\0';
  253. if (!client_x11_display_valid(display)) {
  254. if (display != NULL)
  255. logit("DISPLAY \"%s\" invalid; disabling X11 forwarding",
  256. display);
  257. return -1;
  258. }
  259. if (xauth_path != NULL && stat(xauth_path, &st) == -1) {
  260. debug("No xauth program.");
  261. xauth_path = NULL;
  262. }
  263. if (xauth_path != NULL) {
  264. /*
  265. * Handle FamilyLocal case where $DISPLAY does
  266. * not match an authorization entry. For this we
  267. * just try "xauth list unix:displaynum.screennum".
  268. * XXX: "localhost" match to determine FamilyLocal
  269. * is not perfect.
  270. */
  271. if (strncmp(display, "localhost:", 10) == 0) {
  272. if ((r = snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
  273. display + 10)) < 0 ||
  274. (size_t)r >= sizeof(xdisplay)) {
  275. error("%s: display name too long", __func__);
  276. return -1;
  277. }
  278. display = xdisplay;
  279. }
  280. if (trusted == 0) {
  281. /*
  282. * Generate an untrusted X11 auth cookie.
  283. *
  284. * The authentication cookie should briefly outlive
  285. * ssh's willingness to forward X11 connections to
  286. * avoid nasty fail-open behaviour in the X server.
  287. */
  288. mktemp_proto(xauthdir, sizeof(xauthdir));
  289. if (mkdtemp(xauthdir) == NULL) {
  290. error("%s: mkdtemp: %s",
  291. __func__, strerror(errno));
  292. return -1;
  293. }
  294. do_unlink = 1;
  295. if ((r = snprintf(xauthfile, sizeof(xauthfile),
  296. "%s/xauthfile", xauthdir)) < 0 ||
  297. (size_t)r >= sizeof(xauthfile)) {
  298. error("%s: xauthfile path too long", __func__);
  299. rmdir(xauthdir);
  300. return -1;
  301. }
  302. if (timeout == 0) {
  303. /* auth doesn't time out */
  304. xasprintf(&cmd, "%s -f %s generate %s %s "
  305. "untrusted 2>%s",
  306. xauth_path, xauthfile, display,
  307. SSH_X11_PROTO, _PATH_DEVNULL);
  308. } else {
  309. /* Add some slack to requested expiry */
  310. if (timeout < UINT_MAX - X11_TIMEOUT_SLACK)
  311. x11_timeout_real = timeout +
  312. X11_TIMEOUT_SLACK;
  313. else {
  314. /* Don't overflow on long timeouts */
  315. x11_timeout_real = UINT_MAX;
  316. }
  317. xasprintf(&cmd, "%s -f %s generate %s %s "
  318. "untrusted timeout %u 2>%s",
  319. xauth_path, xauthfile, display,
  320. SSH_X11_PROTO, x11_timeout_real,
  321. _PATH_DEVNULL);
  322. }
  323. debug2("%s: xauth command: %s", __func__, cmd);
  324. if (timeout != 0 && x11_refuse_time == 0) {
  325. now = monotime() + 1;
  326. if (UINT_MAX - timeout < now)
  327. x11_refuse_time = UINT_MAX;
  328. else
  329. x11_refuse_time = now + timeout;
  330. channel_set_x11_refuse_time(ssh,
  331. x11_refuse_time);
  332. }
  333. if (system(cmd) == 0)
  334. generated = 1;
  335. free(cmd);
  336. }
  337. /*
  338. * When in untrusted mode, we read the cookie only if it was
  339. * successfully generated as an untrusted one in the step
  340. * above.
  341. */
  342. if (trusted || generated) {
  343. xasprintf(&cmd,
  344. "%s %s%s list %s 2>" _PATH_DEVNULL,
  345. xauth_path,
  346. generated ? "-f " : "" ,
  347. generated ? xauthfile : "",
  348. display);
  349. debug2("x11_get_proto: %s", cmd);
  350. f = popen(cmd, "r");
  351. if (f && fgets(line, sizeof(line), f) &&
  352. sscanf(line, "%*s %511s %511s", proto, data) == 2)
  353. got_data = 1;
  354. if (f)
  355. pclose(f);
  356. free(cmd);
  357. }
  358. }
  359. if (do_unlink) {
  360. unlink(xauthfile);
  361. rmdir(xauthdir);
  362. }
  363. /* Don't fall back to fake X11 data for untrusted forwarding */
  364. if (!trusted && !got_data) {
  365. error("Warning: untrusted X11 forwarding setup failed: "
  366. "xauth key data not generated");
  367. return -1;
  368. }
  369. /*
  370. * If we didn't get authentication data, just make up some
  371. * data. The forwarding code will check the validity of the
  372. * response anyway, and substitute this data. The X11
  373. * server, however, will ignore this fake data and use
  374. * whatever authentication mechanisms it was using otherwise
  375. * for the local connection.
  376. */
  377. if (!got_data) {
  378. u_int8_t rnd[16];
  379. u_int i;
  380. logit("Warning: No xauth data; "
  381. "using fake authentication data for X11 forwarding.");
  382. strlcpy(proto, SSH_X11_PROTO, sizeof proto);
  383. arc4random_buf(rnd, sizeof(rnd));
  384. for (i = 0; i < sizeof(rnd); i++) {
  385. snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
  386. rnd[i]);
  387. }
  388. }
  389. return 0;
  390. }
  391. /*
  392. * Checks if the client window has changed, and sends a packet about it to
  393. * the server if so. The actual change is detected elsewhere (by a software
  394. * interrupt on Unix); this just checks the flag and sends a message if
  395. * appropriate.
  396. */
  397. static void
  398. client_check_window_change(struct ssh *ssh)
  399. {
  400. if (!received_window_change_signal)
  401. return;
  402. received_window_change_signal = 0;
  403. debug2("%s: changed", __func__);
  404. channel_send_window_changes(ssh);
  405. }
  406. static int
  407. client_global_request_reply(int type, u_int32_t seq, struct ssh *ssh)
  408. {
  409. struct global_confirm *gc;
  410. if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
  411. return 0;
  412. if (gc->cb != NULL)
  413. gc->cb(ssh, type, seq, gc->ctx);
  414. if (--gc->ref_count <= 0) {
  415. TAILQ_REMOVE(&global_confirms, gc, entry);
  416. freezero(gc, sizeof(*gc));
  417. }
  418. ssh_packet_set_alive_timeouts(ssh, 0);
  419. return 0;
  420. }
  421. static void
  422. schedule_server_alive_check(void)
  423. {
  424. if (options.server_alive_interval > 0)
  425. server_alive_time = monotime() + options.server_alive_interval;
  426. }
  427. static void
  428. server_alive_check(struct ssh *ssh)
  429. {
  430. int r;
  431. if (ssh_packet_inc_alive_timeouts(ssh) > options.server_alive_count_max) {
  432. logit("Timeout, server %s not responding.", host);
  433. cleanup_exit(255);
  434. }
  435. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  436. (r = sshpkt_put_cstring(ssh, "keepalive@openssh.com")) != 0 ||
  437. (r = sshpkt_put_u8(ssh, 1)) != 0 || /* boolean: want reply */
  438. (r = sshpkt_send(ssh)) != 0)
  439. fatal("%s: send packet: %s", __func__, ssh_err(r));
  440. /* Insert an empty placeholder to maintain ordering */
  441. client_register_global_confirm(NULL, NULL);
  442. schedule_server_alive_check();
  443. }
  444. /*
  445. * Waits until the client can do something (some data becomes available on
  446. * one of the file descriptors).
  447. */
  448. static void
  449. client_wait_until_can_do_something(struct ssh *ssh,
  450. fd_set **readsetp, fd_set **writesetp,
  451. int *maxfdp, u_int *nallocp, int rekeying)
  452. {
  453. struct timeval tv, *tvp;
  454. int timeout_secs;
  455. time_t minwait_secs = 0, now = monotime();
  456. int r, ret;
  457. /* Add any selections by the channel mechanism. */
  458. channel_prepare_select(ssh, readsetp, writesetp, maxfdp,
  459. nallocp, &minwait_secs);
  460. /* channel_prepare_select could have closed the last channel */
  461. if (session_closed && !channel_still_open(ssh) &&
  462. !ssh_packet_have_data_to_write(ssh)) {
  463. /* clear mask since we did not call select() */
  464. memset(*readsetp, 0, *nallocp);
  465. memset(*writesetp, 0, *nallocp);
  466. return;
  467. }
  468. FD_SET(connection_in, *readsetp);
  469. /* Select server connection if have data to write to the server. */
  470. if (ssh_packet_have_data_to_write(ssh))
  471. FD_SET(connection_out, *writesetp);
  472. /*
  473. * Wait for something to happen. This will suspend the process until
  474. * some selected descriptor can be read, written, or has some other
  475. * event pending, or a timeout expires.
  476. */
  477. timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
  478. if (options.server_alive_interval > 0)
  479. timeout_secs = MAXIMUM(server_alive_time - now, 0);
  480. if (options.rekey_interval > 0 && !rekeying)
  481. timeout_secs = MINIMUM(timeout_secs,
  482. ssh_packet_get_rekey_timeout(ssh));
  483. set_control_persist_exit_time(ssh);
  484. if (control_persist_exit_time > 0) {
  485. timeout_secs = MINIMUM(timeout_secs,
  486. control_persist_exit_time - now);
  487. if (timeout_secs < 0)
  488. timeout_secs = 0;
  489. }
  490. if (minwait_secs != 0)
  491. timeout_secs = MINIMUM(timeout_secs, (int)minwait_secs);
  492. if (timeout_secs == INT_MAX)
  493. tvp = NULL;
  494. else {
  495. tv.tv_sec = timeout_secs;
  496. tv.tv_usec = 0;
  497. tvp = &tv;
  498. }
  499. ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
  500. if (ret == -1) {
  501. /*
  502. * We have to clear the select masks, because we return.
  503. * We have to return, because the mainloop checks for the flags
  504. * set by the signal handlers.
  505. */
  506. memset(*readsetp, 0, *nallocp);
  507. memset(*writesetp, 0, *nallocp);
  508. if (errno == EINTR)
  509. return;
  510. /* Note: we might still have data in the buffers. */
  511. if ((r = sshbuf_putf(stderr_buffer,
  512. "select: %s\r\n", strerror(errno))) != 0)
  513. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  514. quit_pending = 1;
  515. } else if (options.server_alive_interval > 0 && !FD_ISSET(connection_in,
  516. *readsetp) && monotime() >= server_alive_time)
  517. /*
  518. * ServerAlive check is needed. We can't rely on the select
  519. * timing out since traffic on the client side such as port
  520. * forwards can keep waking it up.
  521. */
  522. server_alive_check(ssh);
  523. }
  524. static void
  525. client_suspend_self(struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr)
  526. {
  527. /* Flush stdout and stderr buffers. */
  528. if (sshbuf_len(bout) > 0)
  529. atomicio(vwrite, fileno(stdout), sshbuf_mutable_ptr(bout),
  530. sshbuf_len(bout));
  531. if (sshbuf_len(berr) > 0)
  532. atomicio(vwrite, fileno(stderr), sshbuf_mutable_ptr(berr),
  533. sshbuf_len(berr));
  534. leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  535. sshbuf_reset(bin);
  536. sshbuf_reset(bout);
  537. sshbuf_reset(berr);
  538. /* Send the suspend signal to the program itself. */
  539. kill(getpid(), SIGTSTP);
  540. /* Reset window sizes in case they have changed */
  541. received_window_change_signal = 1;
  542. enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  543. }
  544. static void
  545. client_process_net_input(struct ssh *ssh, fd_set *readset)
  546. {
  547. char buf[SSH_IOBUFSZ];
  548. int r, len;
  549. /*
  550. * Read input from the server, and add any such data to the buffer of
  551. * the packet subsystem.
  552. */
  553. if (FD_ISSET(connection_in, readset)) {
  554. schedule_server_alive_check();
  555. /* Read as much as possible. */
  556. len = read(connection_in, buf, sizeof(buf));
  557. if (len == 0) {
  558. /*
  559. * Received EOF. The remote host has closed the
  560. * connection.
  561. */
  562. if ((r = sshbuf_putf(stderr_buffer,
  563. "Connection to %.300s closed by remote host.\r\n",
  564. host)) != 0)
  565. fatal("%s: buffer error: %s",
  566. __func__, ssh_err(r));
  567. quit_pending = 1;
  568. return;
  569. }
  570. /*
  571. * There is a kernel bug on Solaris that causes select to
  572. * sometimes wake up even though there is no data available.
  573. */
  574. if (len == -1 &&
  575. (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
  576. len = 0;
  577. if (len == -1) {
  578. /*
  579. * An error has encountered. Perhaps there is a
  580. * network problem.
  581. */
  582. if ((r = sshbuf_putf(stderr_buffer,
  583. "Read from remote host %.300s: %.100s\r\n",
  584. host, strerror(errno))) != 0)
  585. fatal("%s: buffer error: %s",
  586. __func__, ssh_err(r));
  587. quit_pending = 1;
  588. return;
  589. }
  590. ssh_packet_process_incoming(ssh, buf, len);
  591. }
  592. }
  593. static void
  594. client_status_confirm(struct ssh *ssh, int type, Channel *c, void *ctx)
  595. {
  596. struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
  597. char errmsg[256];
  598. int r, tochan;
  599. /*
  600. * If a TTY was explicitly requested, then a failure to allocate
  601. * one is fatal.
  602. */
  603. if (cr->action == CONFIRM_TTY &&
  604. (options.request_tty == REQUEST_TTY_FORCE ||
  605. options.request_tty == REQUEST_TTY_YES))
  606. cr->action = CONFIRM_CLOSE;
  607. /* XXX suppress on mux _client_ quietmode */
  608. tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
  609. c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
  610. if (type == SSH2_MSG_CHANNEL_SUCCESS) {
  611. debug2("%s request accepted on channel %d",
  612. cr->request_type, c->self);
  613. } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
  614. if (tochan) {
  615. snprintf(errmsg, sizeof(errmsg),
  616. "%s request failed\r\n", cr->request_type);
  617. } else {
  618. snprintf(errmsg, sizeof(errmsg),
  619. "%s request failed on channel %d",
  620. cr->request_type, c->self);
  621. }
  622. /* If error occurred on primary session channel, then exit */
  623. if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
  624. fatal("%s", errmsg);
  625. /*
  626. * If error occurred on mux client, append to
  627. * their stderr.
  628. */
  629. if (tochan) {
  630. if ((r = sshbuf_put(c->extended, errmsg,
  631. strlen(errmsg))) != 0)
  632. fatal("%s: buffer error %s", __func__,
  633. ssh_err(r));
  634. } else
  635. error("%s", errmsg);
  636. if (cr->action == CONFIRM_TTY) {
  637. /*
  638. * If a TTY allocation error occurred, then arrange
  639. * for the correct TTY to leave raw mode.
  640. */
  641. if (c->self == session_ident)
  642. leave_raw_mode(0);
  643. else
  644. mux_tty_alloc_failed(ssh, c);
  645. } else if (cr->action == CONFIRM_CLOSE) {
  646. chan_read_failed(ssh, c);
  647. chan_write_failed(ssh, c);
  648. }
  649. }
  650. free(cr);
  651. }
  652. static void
  653. client_abandon_status_confirm(struct ssh *ssh, Channel *c, void *ctx)
  654. {
  655. free(ctx);
  656. }
  657. void
  658. client_expect_confirm(struct ssh *ssh, int id, const char *request,
  659. enum confirm_action action)
  660. {
  661. struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
  662. cr->request_type = request;
  663. cr->action = action;
  664. channel_register_status_confirm(ssh, id, client_status_confirm,
  665. client_abandon_status_confirm, cr);
  666. }
  667. void
  668. client_register_global_confirm(global_confirm_cb *cb, void *ctx)
  669. {
  670. struct global_confirm *gc, *last_gc;
  671. /* Coalesce identical callbacks */
  672. last_gc = TAILQ_LAST(&global_confirms, global_confirms);
  673. if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
  674. if (++last_gc->ref_count >= INT_MAX)
  675. fatal("%s: last_gc->ref_count = %d",
  676. __func__, last_gc->ref_count);
  677. return;
  678. }
  679. gc = xcalloc(1, sizeof(*gc));
  680. gc->cb = cb;
  681. gc->ctx = ctx;
  682. gc->ref_count = 1;
  683. TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
  684. }
  685. static void
  686. process_cmdline(struct ssh *ssh)
  687. {
  688. void (*handler)(int);
  689. char *s, *cmd;
  690. int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
  691. struct Forward fwd;
  692. memset(&fwd, 0, sizeof(fwd));
  693. leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  694. handler = ssh_signal(SIGINT, SIG_IGN);
  695. cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
  696. if (s == NULL)
  697. goto out;
  698. while (isspace((u_char)*s))
  699. s++;
  700. if (*s == '-')
  701. s++; /* Skip cmdline '-', if any */
  702. if (*s == '\0')
  703. goto out;
  704. if (*s == 'h' || *s == 'H' || *s == '?') {
  705. logit("Commands:");
  706. logit(" -L[bind_address:]port:host:hostport "
  707. "Request local forward");
  708. logit(" -R[bind_address:]port:host:hostport "
  709. "Request remote forward");
  710. logit(" -D[bind_address:]port "
  711. "Request dynamic forward");
  712. logit(" -KL[bind_address:]port "
  713. "Cancel local forward");
  714. logit(" -KR[bind_address:]port "
  715. "Cancel remote forward");
  716. logit(" -KD[bind_address:]port "
  717. "Cancel dynamic forward");
  718. if (!options.permit_local_command)
  719. goto out;
  720. logit(" !args "
  721. "Execute local command");
  722. goto out;
  723. }
  724. if (*s == '!' && options.permit_local_command) {
  725. s++;
  726. ssh_local_cmd(s);
  727. goto out;
  728. }
  729. if (*s == 'K') {
  730. delete = 1;
  731. s++;
  732. }
  733. if (*s == 'L')
  734. local = 1;
  735. else if (*s == 'R')
  736. remote = 1;
  737. else if (*s == 'D')
  738. dynamic = 1;
  739. else {
  740. logit("Invalid command.");
  741. goto out;
  742. }
  743. while (isspace((u_char)*++s))
  744. ;
  745. /* XXX update list of forwards in options */
  746. if (delete) {
  747. /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
  748. if (!parse_forward(&fwd, s, 1, 0)) {
  749. logit("Bad forwarding close specification.");
  750. goto out;
  751. }
  752. if (remote)
  753. ok = channel_request_rforward_cancel(ssh, &fwd) == 0;
  754. else if (dynamic)
  755. ok = channel_cancel_lport_listener(ssh, &fwd,
  756. 0, &options.fwd_opts) > 0;
  757. else
  758. ok = channel_cancel_lport_listener(ssh, &fwd,
  759. CHANNEL_CANCEL_PORT_STATIC,
  760. &options.fwd_opts) > 0;
  761. if (!ok) {
  762. logit("Unknown port forwarding.");
  763. goto out;
  764. }
  765. logit("Canceled forwarding.");
  766. } else {
  767. if (!parse_forward(&fwd, s, dynamic, remote)) {
  768. logit("Bad forwarding specification.");
  769. goto out;
  770. }
  771. if (local || dynamic) {
  772. if (!channel_setup_local_fwd_listener(ssh, &fwd,
  773. &options.fwd_opts)) {
  774. logit("Port forwarding failed.");
  775. goto out;
  776. }
  777. } else {
  778. if (channel_request_remote_forwarding(ssh, &fwd) < 0) {
  779. logit("Port forwarding failed.");
  780. goto out;
  781. }
  782. }
  783. logit("Forwarding port.");
  784. }
  785. out:
  786. ssh_signal(SIGINT, handler);
  787. enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  788. free(cmd);
  789. free(fwd.listen_host);
  790. free(fwd.listen_path);
  791. free(fwd.connect_host);
  792. free(fwd.connect_path);
  793. }
  794. /* reasons to suppress output of an escape command in help output */
  795. #define SUPPRESS_NEVER 0 /* never suppress, always show */
  796. #define SUPPRESS_MUXCLIENT 1 /* don't show in mux client sessions */
  797. #define SUPPRESS_MUXMASTER 2 /* don't show in mux master sessions */
  798. #define SUPPRESS_SYSLOG 4 /* don't show when logging to syslog */
  799. struct escape_help_text {
  800. const char *cmd;
  801. const char *text;
  802. unsigned int flags;
  803. };
  804. static struct escape_help_text esc_txt[] = {
  805. {".", "terminate session", SUPPRESS_MUXMASTER},
  806. {".", "terminate connection (and any multiplexed sessions)",
  807. SUPPRESS_MUXCLIENT},
  808. {"B", "send a BREAK to the remote system", SUPPRESS_NEVER},
  809. {"C", "open a command line", SUPPRESS_MUXCLIENT},
  810. {"R", "request rekey", SUPPRESS_NEVER},
  811. {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
  812. {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
  813. {"#", "list forwarded connections", SUPPRESS_NEVER},
  814. {"&", "background ssh (when waiting for connections to terminate)",
  815. SUPPRESS_MUXCLIENT},
  816. {"?", "this message", SUPPRESS_NEVER},
  817. };
  818. static void
  819. print_escape_help(struct sshbuf *b, int escape_char, int mux_client,
  820. int using_stderr)
  821. {
  822. unsigned int i, suppress_flags;
  823. int r;
  824. if ((r = sshbuf_putf(b,
  825. "%c?\r\nSupported escape sequences:\r\n", escape_char)) != 0)
  826. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  827. suppress_flags =
  828. (mux_client ? SUPPRESS_MUXCLIENT : 0) |
  829. (mux_client ? 0 : SUPPRESS_MUXMASTER) |
  830. (using_stderr ? 0 : SUPPRESS_SYSLOG);
  831. for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
  832. if (esc_txt[i].flags & suppress_flags)
  833. continue;
  834. if ((r = sshbuf_putf(b, " %c%-3s - %s\r\n",
  835. escape_char, esc_txt[i].cmd, esc_txt[i].text)) != 0)
  836. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  837. }
  838. if ((r = sshbuf_putf(b,
  839. " %c%c - send the escape character by typing it twice\r\n"
  840. "(Note that escapes are only recognized immediately after "
  841. "newline.)\r\n", escape_char, escape_char)) != 0)
  842. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  843. }
  844. /*
  845. * Process the characters one by one.
  846. */
  847. static int
  848. process_escapes(struct ssh *ssh, Channel *c,
  849. struct sshbuf *bin, struct sshbuf *bout, struct sshbuf *berr,
  850. char *buf, int len)
  851. {
  852. pid_t pid;
  853. int r, bytes = 0;
  854. u_int i;
  855. u_char ch;
  856. char *s;
  857. struct escape_filter_ctx *efc = c->filter_ctx == NULL ?
  858. NULL : (struct escape_filter_ctx *)c->filter_ctx;
  859. if (c->filter_ctx == NULL)
  860. return 0;
  861. if (len <= 0)
  862. return (0);
  863. for (i = 0; i < (u_int)len; i++) {
  864. /* Get one character at a time. */
  865. ch = buf[i];
  866. if (efc->escape_pending) {
  867. /* We have previously seen an escape character. */
  868. /* Clear the flag now. */
  869. efc->escape_pending = 0;
  870. /* Process the escaped character. */
  871. switch (ch) {
  872. case '.':
  873. /* Terminate the connection. */
  874. if ((r = sshbuf_putf(berr, "%c.\r\n",
  875. efc->escape_char)) != 0)
  876. fatal("%s: buffer error: %s",
  877. __func__, ssh_err(r));
  878. if (c && c->ctl_chan != -1) {
  879. chan_read_failed(ssh, c);
  880. chan_write_failed(ssh, c);
  881. if (c->detach_user) {
  882. c->detach_user(ssh,
  883. c->self, NULL);
  884. }
  885. c->type = SSH_CHANNEL_ABANDONED;
  886. sshbuf_reset(c->input);
  887. chan_ibuf_empty(ssh, c);
  888. return 0;
  889. } else
  890. quit_pending = 1;
  891. return -1;
  892. case 'Z' - 64:
  893. /* XXX support this for mux clients */
  894. if (c && c->ctl_chan != -1) {
  895. char b[16];
  896. noescape:
  897. if (ch == 'Z' - 64)
  898. snprintf(b, sizeof b, "^Z");
  899. else
  900. snprintf(b, sizeof b, "%c", ch);
  901. if ((r = sshbuf_putf(berr,
  902. "%c%s escape not available to "
  903. "multiplexed sessions\r\n",
  904. efc->escape_char, b)) != 0)
  905. fatal("%s: buffer error: %s",
  906. __func__, ssh_err(r));
  907. continue;
  908. }
  909. /* Suspend the program. Inform the user */
  910. if ((r = sshbuf_putf(berr,
  911. "%c^Z [suspend ssh]\r\n",
  912. efc->escape_char)) != 0)
  913. fatal("%s: buffer error: %s",
  914. __func__, ssh_err(r));
  915. /* Restore terminal modes and suspend. */
  916. client_suspend_self(bin, bout, berr);
  917. /* We have been continued. */
  918. continue;
  919. case 'B':
  920. if ((r = sshbuf_putf(berr,
  921. "%cB\r\n", efc->escape_char)) != 0)
  922. fatal("%s: buffer error: %s",
  923. __func__, ssh_err(r));
  924. channel_request_start(ssh, c->self, "break", 0);
  925. if ((r = sshpkt_put_u32(ssh, 1000)) != 0 ||
  926. (r = sshpkt_send(ssh)) != 0)
  927. fatal("%s: send packet: %s", __func__,
  928. ssh_err(r));
  929. continue;
  930. case 'R':
  931. if (ssh->compat & SSH_BUG_NOREKEY)
  932. logit("Server does not "
  933. "support re-keying");
  934. else
  935. need_rekeying = 1;
  936. continue;
  937. case 'V':
  938. /* FALLTHROUGH */
  939. case 'v':
  940. if (c && c->ctl_chan != -1)
  941. goto noescape;
  942. if (!log_is_on_stderr()) {
  943. if ((r = sshbuf_putf(berr,
  944. "%c%c [Logging to syslog]\r\n",
  945. efc->escape_char, ch)) != 0)
  946. fatal("%s: buffer error: %s",
  947. __func__, ssh_err(r));
  948. continue;
  949. }
  950. if (ch == 'V' && options.log_level >
  951. SYSLOG_LEVEL_QUIET)
  952. log_change_level(--options.log_level);
  953. if (ch == 'v' && options.log_level <
  954. SYSLOG_LEVEL_DEBUG3)
  955. log_change_level(++options.log_level);
  956. if ((r = sshbuf_putf(berr,
  957. "%c%c [LogLevel %s]\r\n",
  958. efc->escape_char, ch,
  959. log_level_name(options.log_level))) != 0)
  960. fatal("%s: buffer error: %s",
  961. __func__, ssh_err(r));
  962. continue;
  963. case '&':
  964. if (c && c->ctl_chan != -1)
  965. goto noescape;
  966. /*
  967. * Detach the program (continue to serve
  968. * connections, but put in background and no
  969. * more new connections).
  970. */
  971. /* Restore tty modes. */
  972. leave_raw_mode(
  973. options.request_tty == REQUEST_TTY_FORCE);
  974. /* Stop listening for new connections. */
  975. channel_stop_listening(ssh);
  976. if ((r = sshbuf_putf(berr,
  977. "%c& [backgrounded]\n", efc->escape_char))
  978. != 0)
  979. fatal("%s: buffer error: %s",
  980. __func__, ssh_err(r));
  981. /* Fork into background. */
  982. pid = fork();
  983. if (pid == -1) {
  984. error("fork: %.100s", strerror(errno));
  985. continue;
  986. }
  987. if (pid != 0) { /* This is the parent. */
  988. /* The parent just exits. */
  989. exit(0);
  990. }
  991. /* The child continues serving connections. */
  992. /* fake EOF on stdin */
  993. if ((r = sshbuf_put_u8(bin, 4)) != 0)
  994. fatal("%s: buffer error: %s",
  995. __func__, ssh_err(r));
  996. return -1;
  997. case '?':
  998. print_escape_help(berr, efc->escape_char,
  999. (c && c->ctl_chan != -1),
  1000. log_is_on_stderr());
  1001. continue;
  1002. case '#':
  1003. if ((r = sshbuf_putf(berr, "%c#\r\n",
  1004. efc->escape_char)) != 0)
  1005. fatal("%s: buffer error: %s",
  1006. __func__, ssh_err(r));
  1007. s = channel_open_message(ssh);
  1008. if ((r = sshbuf_put(berr, s, strlen(s))) != 0)
  1009. fatal("%s: buffer error: %s",
  1010. __func__, ssh_err(r));
  1011. free(s);
  1012. continue;
  1013. case 'C':
  1014. if (c && c->ctl_chan != -1)
  1015. goto noescape;
  1016. process_cmdline(ssh);
  1017. continue;
  1018. default:
  1019. if (ch != efc->escape_char) {
  1020. if ((r = sshbuf_put_u8(bin,
  1021. efc->escape_char)) != 0)
  1022. fatal("%s: buffer error: %s",
  1023. __func__, ssh_err(r));
  1024. bytes++;
  1025. }
  1026. /* Escaped characters fall through here */
  1027. break;
  1028. }
  1029. } else {
  1030. /*
  1031. * The previous character was not an escape char.
  1032. * Check if this is an escape.
  1033. */
  1034. if (last_was_cr && ch == efc->escape_char) {
  1035. /*
  1036. * It is. Set the flag and continue to
  1037. * next character.
  1038. */
  1039. efc->escape_pending = 1;
  1040. continue;
  1041. }
  1042. }
  1043. /*
  1044. * Normal character. Record whether it was a newline,
  1045. * and append it to the buffer.
  1046. */
  1047. last_was_cr = (ch == '\r' || ch == '\n');
  1048. if ((r = sshbuf_put_u8(bin, ch)) != 0)
  1049. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1050. bytes++;
  1051. }
  1052. return bytes;
  1053. }
  1054. /*
  1055. * Get packets from the connection input buffer, and process them as long as
  1056. * there are packets available.
  1057. *
  1058. * Any unknown packets received during the actual
  1059. * session cause the session to terminate. This is
  1060. * intended to make debugging easier since no
  1061. * confirmations are sent. Any compatible protocol
  1062. * extensions must be negotiated during the
  1063. * preparatory phase.
  1064. */
  1065. static void
  1066. client_process_buffered_input_packets(struct ssh *ssh)
  1067. {
  1068. ssh_dispatch_run_fatal(ssh, DISPATCH_NONBLOCK, &quit_pending);
  1069. }
  1070. /* scan buf[] for '~' before sending data to the peer */
  1071. /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
  1072. void *
  1073. client_new_escape_filter_ctx(int escape_char)
  1074. {
  1075. struct escape_filter_ctx *ret;
  1076. ret = xcalloc(1, sizeof(*ret));
  1077. ret->escape_pending = 0;
  1078. ret->escape_char = escape_char;
  1079. return (void *)ret;
  1080. }
  1081. /* Free the escape filter context on channel free */
  1082. void
  1083. client_filter_cleanup(struct ssh *ssh, int cid, void *ctx)
  1084. {
  1085. free(ctx);
  1086. }
  1087. int
  1088. client_simple_escape_filter(struct ssh *ssh, Channel *c, char *buf, int len)
  1089. {
  1090. if (c->extended_usage != CHAN_EXTENDED_WRITE)
  1091. return 0;
  1092. return process_escapes(ssh, c, c->input, c->output, c->extended,
  1093. buf, len);
  1094. }
  1095. static void
  1096. client_channel_closed(struct ssh *ssh, int id, void *arg)
  1097. {
  1098. channel_cancel_cleanup(ssh, id);
  1099. session_closed = 1;
  1100. leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  1101. }
  1102. /*
  1103. * Implements the interactive session with the server. This is called after
  1104. * the user has been authenticated, and a command has been started on the
  1105. * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
  1106. * used as an escape character for terminating or suspending the session.
  1107. */
  1108. int
  1109. client_loop(struct ssh *ssh, int have_pty, int escape_char_arg,
  1110. int ssh2_chan_id)
  1111. {
  1112. fd_set *readset = NULL, *writeset = NULL;
  1113. double start_time, total_time;
  1114. int r, max_fd = 0, max_fd2 = 0, len;
  1115. u_int64_t ibytes, obytes;
  1116. u_int nalloc = 0;
  1117. debug("Entering interactive session.");
  1118. if (options.control_master &&
  1119. !option_clear_or_none(options.control_path)) {
  1120. debug("pledge: id");
  1121. if (pledge("stdio rpath wpath cpath unix inet dns recvfd sendfd proc exec id tty",
  1122. NULL) == -1)
  1123. fatal("%s pledge(): %s", __func__, strerror(errno));
  1124. } else if (options.forward_x11 || options.permit_local_command) {
  1125. debug("pledge: exec");
  1126. if (pledge("stdio rpath wpath cpath unix inet dns proc exec tty",
  1127. NULL) == -1)
  1128. fatal("%s pledge(): %s", __func__, strerror(errno));
  1129. } else if (options.update_hostkeys) {
  1130. debug("pledge: filesystem full");
  1131. if (pledge("stdio rpath wpath cpath unix inet dns proc tty",
  1132. NULL) == -1)
  1133. fatal("%s pledge(): %s", __func__, strerror(errno));
  1134. } else if (!option_clear_or_none(options.proxy_command) ||
  1135. options.fork_after_authentication) {
  1136. debug("pledge: proc");
  1137. if (pledge("stdio cpath unix inet dns proc tty", NULL) == -1)
  1138. fatal("%s pledge(): %s", __func__, strerror(errno));
  1139. } else {
  1140. debug("pledge: network");
  1141. if (pledge("stdio unix inet dns proc tty", NULL) == -1)
  1142. fatal("%s pledge(): %s", __func__, strerror(errno));
  1143. }
  1144. start_time = monotime_double();
  1145. /* Initialize variables. */
  1146. last_was_cr = 1;
  1147. exit_status = -1;
  1148. connection_in = ssh_packet_get_connection_in(ssh);
  1149. connection_out = ssh_packet_get_connection_out(ssh);
  1150. max_fd = MAXIMUM(connection_in, connection_out);
  1151. quit_pending = 0;
  1152. /* Initialize buffer. */
  1153. if ((stderr_buffer = sshbuf_new()) == NULL)
  1154. fatal("%s: sshbuf_new failed", __func__);
  1155. client_init_dispatch(ssh);
  1156. /*
  1157. * Set signal handlers, (e.g. to restore non-blocking mode)
  1158. * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
  1159. */
  1160. if (ssh_signal(SIGHUP, SIG_IGN) != SIG_IGN)
  1161. ssh_signal(SIGHUP, signal_handler);
  1162. if (ssh_signal(SIGINT, SIG_IGN) != SIG_IGN)
  1163. ssh_signal(SIGINT, signal_handler);
  1164. if (ssh_signal(SIGQUIT, SIG_IGN) != SIG_IGN)
  1165. ssh_signal(SIGQUIT, signal_handler);
  1166. if (ssh_signal(SIGTERM, SIG_IGN) != SIG_IGN)
  1167. ssh_signal(SIGTERM, signal_handler);
  1168. ssh_signal(SIGWINCH, window_change_handler);
  1169. if (have_pty)
  1170. enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  1171. session_ident = ssh2_chan_id;
  1172. if (session_ident != -1) {
  1173. if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
  1174. channel_register_filter(ssh, session_ident,
  1175. client_simple_escape_filter, NULL,
  1176. client_filter_cleanup,
  1177. client_new_escape_filter_ctx(
  1178. escape_char_arg));
  1179. }
  1180. channel_register_cleanup(ssh, session_ident,
  1181. client_channel_closed, 0);
  1182. }
  1183. schedule_server_alive_check();
  1184. /* Main loop of the client for the interactive session mode. */
  1185. while (!quit_pending) {
  1186. /* Process buffered packets sent by the server. */
  1187. client_process_buffered_input_packets(ssh);
  1188. if (session_closed && !channel_still_open(ssh))
  1189. break;
  1190. if (ssh_packet_is_rekeying(ssh)) {
  1191. debug("rekeying in progress");
  1192. } else if (need_rekeying) {
  1193. /* manual rekey request */
  1194. debug("need rekeying");
  1195. if ((r = kex_start_rekex(ssh)) != 0)
  1196. fatal("%s: kex_start_rekex: %s", __func__,
  1197. ssh_err(r));
  1198. need_rekeying = 0;
  1199. } else {
  1200. /*
  1201. * Make packets from buffered channel data, and
  1202. * enqueue them for sending to the server.
  1203. */
  1204. if (ssh_packet_not_very_much_data_to_write(ssh))
  1205. channel_output_poll(ssh);
  1206. /*
  1207. * Check if the window size has changed, and buffer a
  1208. * message about it to the server if so.
  1209. */
  1210. client_check_window_change(ssh);
  1211. if (quit_pending)
  1212. break;
  1213. }
  1214. /*
  1215. * Wait until we have something to do (something becomes
  1216. * available on one of the descriptors).
  1217. */
  1218. max_fd2 = max_fd;
  1219. client_wait_until_can_do_something(ssh, &readset, &writeset,
  1220. &max_fd2, &nalloc, ssh_packet_is_rekeying(ssh));
  1221. if (quit_pending)
  1222. break;
  1223. /* Do channel operations unless rekeying in progress. */
  1224. if (!ssh_packet_is_rekeying(ssh))
  1225. channel_after_select(ssh, readset, writeset);
  1226. /* Buffer input from the connection. */
  1227. client_process_net_input(ssh, readset);
  1228. if (quit_pending)
  1229. break;
  1230. /*
  1231. * Send as much buffered packet data as possible to the
  1232. * sender.
  1233. */
  1234. if (FD_ISSET(connection_out, writeset)) {
  1235. if ((r = ssh_packet_write_poll(ssh)) != 0) {
  1236. sshpkt_fatal(ssh, r,
  1237. "%s: ssh_packet_write_poll", __func__);
  1238. }
  1239. }
  1240. /*
  1241. * If we are a backgrounded control master, and the
  1242. * timeout has expired without any active client
  1243. * connections, then quit.
  1244. */
  1245. if (control_persist_exit_time > 0) {
  1246. if (monotime() >= control_persist_exit_time) {
  1247. debug("ControlPersist timeout expired");
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. free(readset);
  1253. free(writeset);
  1254. /* Terminate the session. */
  1255. /* Stop watching for window change. */
  1256. ssh_signal(SIGWINCH, SIG_DFL);
  1257. if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
  1258. (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_BY_APPLICATION)) != 0 ||
  1259. (r = sshpkt_put_cstring(ssh, "disconnected by user")) != 0 ||
  1260. (r = sshpkt_put_cstring(ssh, "")) != 0 || /* language tag */
  1261. (r = sshpkt_send(ssh)) != 0 ||
  1262. (r = ssh_packet_write_wait(ssh)) != 0)
  1263. fatal("%s: send disconnect: %s", __func__, ssh_err(r));
  1264. channel_free_all(ssh);
  1265. if (have_pty)
  1266. leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  1267. /* restore blocking io */
  1268. if (!isatty(fileno(stdin)))
  1269. unset_nonblock(fileno(stdin));
  1270. if (!isatty(fileno(stdout)))
  1271. unset_nonblock(fileno(stdout));
  1272. if (!isatty(fileno(stderr)))
  1273. unset_nonblock(fileno(stderr));
  1274. /*
  1275. * If there was no shell or command requested, there will be no remote
  1276. * exit status to be returned. In that case, clear error code if the
  1277. * connection was deliberately terminated at this end.
  1278. */
  1279. if (options.no_shell && received_signal == SIGTERM) {
  1280. received_signal = 0;
  1281. exit_status = 0;
  1282. }
  1283. if (received_signal) {
  1284. verbose("Killed by signal %d.", (int) received_signal);
  1285. cleanup_exit(0);
  1286. }
  1287. /*
  1288. * In interactive mode (with pseudo tty) display a message indicating
  1289. * that the connection has been closed.
  1290. */
  1291. if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
  1292. if ((r = sshbuf_putf(stderr_buffer,
  1293. "Connection to %.64s closed.\r\n", host)) != 0)
  1294. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1295. }
  1296. /* Output any buffered data for stderr. */
  1297. if (sshbuf_len(stderr_buffer) > 0) {
  1298. len = atomicio(vwrite, fileno(stderr),
  1299. (u_char *)sshbuf_ptr(stderr_buffer),
  1300. sshbuf_len(stderr_buffer));
  1301. if (len < 0 || (u_int)len != sshbuf_len(stderr_buffer))
  1302. error("Write failed flushing stderr buffer.");
  1303. else if ((r = sshbuf_consume(stderr_buffer, len)) != 0)
  1304. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  1305. }
  1306. /* Clear and free any buffers. */
  1307. sshbuf_free(stderr_buffer);
  1308. /* Report bytes transferred, and transfer rates. */
  1309. total_time = monotime_double() - start_time;
  1310. ssh_packet_get_bytes(ssh, &ibytes, &obytes);
  1311. verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
  1312. (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
  1313. if (total_time > 0)
  1314. verbose("Bytes per second: sent %.1f, received %.1f",
  1315. obytes / total_time, ibytes / total_time);
  1316. /* Return the exit status of the program. */
  1317. debug("Exit status %d", exit_status);
  1318. return exit_status;
  1319. }
  1320. /*********/
  1321. static Channel *
  1322. client_request_forwarded_tcpip(struct ssh *ssh, const char *request_type,
  1323. int rchan, u_int rwindow, u_int rmaxpack)
  1324. {
  1325. Channel *c = NULL;
  1326. struct sshbuf *b = NULL;
  1327. char *listen_address, *originator_address;
  1328. u_int listen_port, originator_port;
  1329. int r;
  1330. /* Get rest of the packet */
  1331. if ((r = sshpkt_get_cstring(ssh, &listen_address, NULL)) != 0 ||
  1332. (r = sshpkt_get_u32(ssh, &listen_port)) != 0 ||
  1333. (r = sshpkt_get_cstring(ssh, &originator_address, NULL)) != 0 ||
  1334. (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
  1335. (r = sshpkt_get_end(ssh)) != 0)
  1336. fatal("%s: parse packet: %s", __func__, ssh_err(r));
  1337. debug("%s: listen %s port %d, originator %s port %d", __func__,
  1338. listen_address, listen_port, originator_address, originator_port);
  1339. if (listen_port > 0xffff)
  1340. error("%s: invalid listen port", __func__);
  1341. else if (originator_port > 0xffff)
  1342. error("%s: invalid originator port", __func__);
  1343. else {
  1344. c = channel_connect_by_listen_address(ssh,
  1345. listen_address, listen_port, "forwarded-tcpip",
  1346. originator_address);
  1347. }
  1348. if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
  1349. if ((b = sshbuf_new()) == NULL) {
  1350. error("%s: alloc reply", __func__);
  1351. goto out;
  1352. }
  1353. /* reconstruct and send to muxclient */
  1354. if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
  1355. (r = sshbuf_put_u8(b, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
  1356. (r = sshbuf_put_cstring(b, request_type)) != 0 ||
  1357. (r = sshbuf_put_u32(b, rchan)) != 0 ||
  1358. (r = sshbuf_put_u32(b, rwindow)) != 0 ||
  1359. (r = sshbuf_put_u32(b, rmaxpack)) != 0 ||
  1360. (r = sshbuf_put_cstring(b, listen_address)) != 0 ||
  1361. (r = sshbuf_put_u32(b, listen_port)) != 0 ||
  1362. (r = sshbuf_put_cstring(b, originator_address)) != 0 ||
  1363. (r = sshbuf_put_u32(b, originator_port)) != 0 ||
  1364. (r = sshbuf_put_stringb(c->output, b)) != 0) {
  1365. error("%s: compose for muxclient %s", __func__,
  1366. ssh_err(r));
  1367. goto out;
  1368. }
  1369. }
  1370. out:
  1371. sshbuf_free(b);
  1372. free(originator_address);
  1373. free(listen_address);
  1374. return c;
  1375. }
  1376. static Channel *
  1377. client_request_forwarded_streamlocal(struct ssh *ssh,
  1378. const char *request_type, int rchan)
  1379. {
  1380. Channel *c = NULL;
  1381. char *listen_path;
  1382. int r;
  1383. /* Get the remote path. */
  1384. if ((r = sshpkt_get_cstring(ssh, &listen_path, NULL)) != 0 ||
  1385. (r = sshpkt_get_string(ssh, NULL, NULL)) != 0 || /* reserved */
  1386. (r = sshpkt_get_end(ssh)) != 0)
  1387. fatal("%s: parse packet: %s", __func__, ssh_err(r));
  1388. debug("%s: request: %s", __func__, listen_path);
  1389. c = channel_connect_by_listen_path(ssh, listen_path,
  1390. "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
  1391. free(listen_path);
  1392. return c;
  1393. }
  1394. static Channel *
  1395. client_request_x11(struct ssh *ssh, const char *request_type, int rchan)
  1396. {
  1397. Channel *c = NULL;
  1398. char *originator;
  1399. u_int originator_port;
  1400. int r, sock;
  1401. if (!options.forward_x11) {
  1402. error("Warning: ssh server tried X11 forwarding.");
  1403. error("Warning: this is probably a break-in attempt by a "
  1404. "malicious server.");
  1405. return NULL;
  1406. }
  1407. if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
  1408. verbose("Rejected X11 connection after ForwardX11Timeout "
  1409. "expired");
  1410. return NULL;
  1411. }
  1412. if ((r = sshpkt_get_cstring(ssh, &originator, NULL)) != 0 ||
  1413. (r = sshpkt_get_u32(ssh, &originator_port)) != 0 ||
  1414. (r = sshpkt_get_end(ssh)) != 0)
  1415. fatal("%s: parse packet: %s", __func__, ssh_err(r));
  1416. /* XXX check permission */
  1417. /* XXX range check originator port? */
  1418. debug("client_request_x11: request from %s %u", originator,
  1419. originator_port);
  1420. free(originator);
  1421. sock = x11_connect_display(ssh);
  1422. if (sock < 0)
  1423. return NULL;
  1424. c = channel_new(ssh, "x11",
  1425. SSH_CHANNEL_X11_OPEN, sock, sock, -1,
  1426. /* again is this really necessary for X11? */
  1427. options.hpn_disabled ? CHAN_TCP_WINDOW_DEFAULT : options.hpn_buffer_size,
  1428. CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
  1429. c->force_drain = 1;
  1430. return c;
  1431. }
  1432. static Channel *
  1433. client_request_agent(struct ssh *ssh, const char *request_type, int rchan)
  1434. {
  1435. Channel *c = NULL;
  1436. int r, sock;
  1437. if (!options.forward_agent) {
  1438. error("Warning: ssh server tried agent forwarding.");
  1439. error("Warning: this is probably a break-in attempt by a "
  1440. "malicious server.");
  1441. return NULL;
  1442. }
  1443. if (forward_agent_sock_path == NULL) {
  1444. r = ssh_get_authentication_socket(&sock);
  1445. } else {
  1446. r = ssh_get_authentication_socket_path(forward_agent_sock_path, &sock);
  1447. }
  1448. if (r != 0) {
  1449. if (r != SSH_ERR_AGENT_NOT_PRESENT)
  1450. debug("%s: ssh_get_authentication_socket: %s",
  1451. __func__, ssh_err(r));
  1452. return NULL;
  1453. }
  1454. c = channel_new(ssh, "authentication agent connection",
  1455. SSH_CHANNEL_OPEN, sock, sock, -1,
  1456. options.hpn_disabled ? CHAN_X11_WINDOW_DEFAULT : options.hpn_buffer_size,
  1457. CHAN_TCP_PACKET_DEFAULT, 0,
  1458. "authentication agent connection", 1);
  1459. c->force_drain = 1;
  1460. return c;
  1461. }
  1462. char *
  1463. client_request_tun_fwd(struct ssh *ssh, int tun_mode,
  1464. int local_tun, int remote_tun, channel_open_fn *cb, void *cbctx)
  1465. {
  1466. Channel *c;
  1467. int r, fd;
  1468. char *ifname = NULL;
  1469. if (tun_mode == SSH_TUNMODE_NO)
  1470. return 0;
  1471. debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
  1472. /* Open local tunnel device */
  1473. if ((fd = tun_open(local_tun, tun_mode, &ifname)) == -1) {
  1474. error("Tunnel device open failed.");
  1475. return NULL;
  1476. }
  1477. debug("Tunnel forwarding using interface %s", ifname);
  1478. c = channel_new(ssh, "tun", SSH_CHANNEL_OPENING, fd, fd, -1,
  1479. options.hpn_disabled ? CHAN_TCP_WINDOW_DEFAULT : options.hpn_buffer_size,
  1480. CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
  1481. c->datagram = 1;
  1482. #if defined(SSH_TUN_FILTER)
  1483. if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
  1484. channel_register_filter(ssh, c->self, sys_tun_infilter,
  1485. sys_tun_outfilter, NULL, NULL);
  1486. #endif
  1487. if (cb != NULL)
  1488. channel_register_open_confirm(ssh, c->self, cb, cbctx);
  1489. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
  1490. (r = sshpkt_put_cstring(ssh, "tun@openssh.com")) != 0 ||
  1491. (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
  1492. (r = sshpkt_put_u32(ssh, c->local_window_max)) != 0 ||
  1493. (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
  1494. (r = sshpkt_put_u32(ssh, tun_mode)) != 0 ||
  1495. (r = sshpkt_put_u32(ssh, remote_tun)) != 0 ||
  1496. (r = sshpkt_send(ssh)) != 0)
  1497. sshpkt_fatal(ssh, r, "%s: send reply", __func__);
  1498. return ifname;
  1499. }
  1500. /* XXXX move to generic input handler */
  1501. static int
  1502. client_input_channel_open(int type, u_int32_t seq, struct ssh *ssh)
  1503. {
  1504. Channel *c = NULL;
  1505. char *ctype = NULL;
  1506. int r;
  1507. u_int rchan;
  1508. size_t len;
  1509. u_int rmaxpack, rwindow;
  1510. if ((r = sshpkt_get_cstring(ssh, &ctype, &len)) != 0 ||
  1511. (r = sshpkt_get_u32(ssh, &rchan)) != 0 ||
  1512. (r = sshpkt_get_u32(ssh, &rwindow)) != 0 ||
  1513. (r = sshpkt_get_u32(ssh, &rmaxpack)) != 0)
  1514. goto out;
  1515. debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
  1516. ctype, rchan, rwindow, rmaxpack);
  1517. if (strcmp(ctype, "forwarded-tcpip") == 0) {
  1518. c = client_request_forwarded_tcpip(ssh, ctype, rchan, rwindow,
  1519. rmaxpack);
  1520. } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
  1521. c = client_request_forwarded_streamlocal(ssh, ctype, rchan);
  1522. } else if (strcmp(ctype, "x11") == 0) {
  1523. c = client_request_x11(ssh, ctype, rchan);
  1524. } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
  1525. c = client_request_agent(ssh, ctype, rchan);
  1526. }
  1527. if (c != NULL && c->type == SSH_CHANNEL_MUX_CLIENT) {
  1528. debug3("proxied to downstream: %s", ctype);
  1529. } else if (c != NULL) {
  1530. debug("confirm %s", ctype);
  1531. c->remote_id = rchan;
  1532. c->have_remote_id = 1;
  1533. c->remote_window = rwindow;
  1534. c->remote_maxpacket = rmaxpack;
  1535. if (c->type != SSH_CHANNEL_CONNECTING) {
  1536. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
  1537. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  1538. (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
  1539. (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
  1540. (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
  1541. (r = sshpkt_send(ssh)) != 0)
  1542. sshpkt_fatal(ssh, r, "%s: send reply", __func__);
  1543. }
  1544. } else {
  1545. debug("failure %s", ctype);
  1546. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
  1547. (r = sshpkt_put_u32(ssh, rchan)) != 0 ||
  1548. (r = sshpkt_put_u32(ssh, SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED)) != 0 ||
  1549. (r = sshpkt_put_cstring(ssh, "open failed")) != 0 ||
  1550. (r = sshpkt_put_cstring(ssh, "")) != 0 ||
  1551. (r = sshpkt_send(ssh)) != 0)
  1552. sshpkt_fatal(ssh, r, "%s: send failure", __func__);
  1553. }
  1554. r = 0;
  1555. out:
  1556. free(ctype);
  1557. return r;
  1558. }
  1559. static int
  1560. client_input_channel_req(int type, u_int32_t seq, struct ssh *ssh)
  1561. {
  1562. Channel *c = NULL;
  1563. char *rtype = NULL;
  1564. u_char reply;
  1565. u_int id, exitval;
  1566. int r, success = 0;
  1567. if ((r = sshpkt_get_u32(ssh, &id)) != 0)
  1568. return r;
  1569. if (id <= INT_MAX)
  1570. c = channel_lookup(ssh, id);
  1571. if (channel_proxy_upstream(c, type, seq, ssh))
  1572. return 0;
  1573. if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
  1574. (r = sshpkt_get_u8(ssh, &reply)) != 0)
  1575. goto out;
  1576. debug("client_input_channel_req: channel %u rtype %s reply %d",
  1577. id, rtype, reply);
  1578. if (c == NULL) {
  1579. error("client_input_channel_req: channel %d: "
  1580. "unknown channel", id);
  1581. } else if (strcmp(rtype, "eow@openssh.com") == 0) {
  1582. if ((r = sshpkt_get_end(ssh)) != 0)
  1583. goto out;
  1584. chan_rcvd_eow(ssh, c);
  1585. } else if (strcmp(rtype, "exit-status") == 0) {
  1586. if ((r = sshpkt_get_u32(ssh, &exitval)) != 0)
  1587. goto out;
  1588. if (c->ctl_chan != -1) {
  1589. mux_exit_message(ssh, c, exitval);
  1590. success = 1;
  1591. } else if ((int)id == session_ident) {
  1592. /* Record exit value of local session */
  1593. success = 1;
  1594. exit_status = exitval;
  1595. } else {
  1596. /* Probably for a mux channel that has already closed */
  1597. debug("%s: no sink for exit-status on channel %d",
  1598. __func__, id);
  1599. }
  1600. if ((r = sshpkt_get_end(ssh)) != 0)
  1601. goto out;
  1602. }
  1603. if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
  1604. if (!c->have_remote_id)
  1605. fatal("%s: channel %d: no remote_id",
  1606. __func__, c->self);
  1607. if ((r = sshpkt_start(ssh, success ?
  1608. SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE)) != 0 ||
  1609. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  1610. (r = sshpkt_send(ssh)) != 0)
  1611. sshpkt_fatal(ssh, r, "%s: send failure", __func__);
  1612. }
  1613. r = 0;
  1614. out:
  1615. free(rtype);
  1616. return r;
  1617. }
  1618. struct hostkeys_update_ctx {
  1619. /* The hostname and (optionally) IP address string for the server */
  1620. char *host_str, *ip_str;
  1621. /*
  1622. * Keys received from the server and a flag for each indicating
  1623. * whether they already exist in known_hosts.
  1624. * keys_match is filled in by hostkeys_find() and later (for new
  1625. * keys) by client_global_hostkeys_private_confirm().
  1626. */
  1627. struct sshkey **keys;
  1628. u_int *keys_match; /* mask of HKF_MATCH_* from hostfile.h */
  1629. int *keys_verified; /* flag for new keys verified by server */
  1630. size_t nkeys, nnew, nincomplete; /* total, new keys, incomplete match */
  1631. /*
  1632. * Keys that are in known_hosts, but were not present in the update
  1633. * from the server (i.e. scheduled to be deleted).
  1634. * Filled in by hostkeys_find().
  1635. */
  1636. struct sshkey **old_keys;
  1637. size_t nold;
  1638. /* Various special cases. */
  1639. int complex_hostspec; /* wildcard or manual pattern-list host name */
  1640. int ca_available; /* saw CA key for this host */
  1641. };
  1642. static void
  1643. hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
  1644. {
  1645. size_t i;
  1646. if (ctx == NULL)
  1647. return;
  1648. for (i = 0; i < ctx->nkeys; i++)
  1649. sshkey_free(ctx->keys[i]);
  1650. free(ctx->keys);
  1651. free(ctx->keys_match);
  1652. free(ctx->keys_verified);
  1653. for (i = 0; i < ctx->nold; i++)
  1654. sshkey_free(ctx->old_keys[i]);
  1655. free(ctx->old_keys);
  1656. free(ctx->host_str);
  1657. free(ctx->ip_str);
  1658. free(ctx);
  1659. }
  1660. /*
  1661. * Returns non-zero if a known_hosts hostname list is not of a form that
  1662. * can be handled by UpdateHostkeys. These include wildcard hostnames and
  1663. * hostnames lists that do not follow the form host[,ip].
  1664. */
  1665. static int
  1666. hostspec_is_complex(const char *hosts)
  1667. {
  1668. char *cp;
  1669. /* wildcard */
  1670. if (strchr(hosts, '*') != NULL || strchr(hosts, '?') != NULL)
  1671. return 1;
  1672. /* single host/ip = ok */
  1673. if ((cp = strchr(hosts, ',')) == NULL)
  1674. return 0;
  1675. /* more than two entries on the line */
  1676. if (strchr(cp + 1, ',') != NULL)
  1677. return 1;
  1678. /* XXX maybe parse cp+1 and ensure it is an IP? */
  1679. return 0;
  1680. }
  1681. static int
  1682. hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
  1683. {
  1684. struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
  1685. size_t i;
  1686. struct sshkey **tmp;
  1687. if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
  1688. l->marker != MRK_NONE)
  1689. return 0;
  1690. /*
  1691. * UpdateHostkeys is skipped for wildcard host names and hostnames
  1692. * that contain more than two entries (ssh never writes these).
  1693. */
  1694. if (hostspec_is_complex(l->hosts)) {
  1695. debug3("%s: hostkeys file %s:%ld complex host specification",
  1696. __func__, l->path, l->linenum);
  1697. ctx->complex_hostspec = 1;
  1698. return 0;
  1699. }
  1700. /* Mark off keys we've already seen for this host */
  1701. for (i = 0; i < ctx->nkeys; i++) {
  1702. if (!sshkey_equal(l->key, ctx->keys[i]))
  1703. continue;
  1704. debug3("%s: found %s key at %s:%ld", __func__,
  1705. sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
  1706. ctx->keys_match[i] |= l->match;
  1707. return 0;
  1708. }
  1709. /* This line contained a key that not offered by the server */
  1710. debug3("%s: deprecated %s key at %s:%ld", __func__,
  1711. sshkey_ssh_name(l->key), l->path, l->linenum);
  1712. if ((tmp = recallocarray(ctx->old_keys, ctx->nold, ctx->nold + 1,
  1713. sizeof(*ctx->old_keys))) == NULL)
  1714. fatal("%s: recallocarray failed nold = %zu",
  1715. __func__, ctx->nold);
  1716. ctx->old_keys = tmp;
  1717. ctx->old_keys[ctx->nold++] = l->key;
  1718. l->key = NULL;
  1719. return 0;
  1720. }
  1721. static void
  1722. hostkey_change_preamble(LogLevel loglevel)
  1723. {
  1724. do_log2(loglevel, "The server has updated its host keys.");
  1725. do_log2(loglevel, "These changes were verified by the server's "
  1726. "existing trusted key.");
  1727. }
  1728. static void
  1729. update_known_hosts(struct hostkeys_update_ctx *ctx)
  1730. {
  1731. int r, was_raw = 0, first = 1;
  1732. int asking = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK;
  1733. LogLevel loglevel = asking ? SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
  1734. char *fp, *response;
  1735. size_t i;
  1736. struct stat sb;
  1737. for (i = 0; i < ctx->nkeys; i++) {
  1738. if (!ctx->keys_verified[i])
  1739. continue;
  1740. if ((fp = sshkey_fingerprint(ctx->keys[i],
  1741. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
  1742. fatal("%s: sshkey_fingerprint failed", __func__);
  1743. if (first && asking)
  1744. hostkey_change_preamble(loglevel);
  1745. do_log2(loglevel, "Learned new hostkey: %s %s",
  1746. sshkey_type(ctx->keys[i]), fp);
  1747. first = 0;
  1748. free(fp);
  1749. }
  1750. for (i = 0; i < ctx->nold; i++) {
  1751. if ((fp = sshkey_fingerprint(ctx->old_keys[i],
  1752. options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
  1753. fatal("%s: sshkey_fingerprint failed", __func__);
  1754. if (first && asking)
  1755. hostkey_change_preamble(loglevel);
  1756. do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
  1757. sshkey_type(ctx->old_keys[i]), fp);
  1758. first = 0;
  1759. free(fp);
  1760. }
  1761. if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
  1762. if (get_saved_tio() != NULL) {
  1763. leave_raw_mode(1);
  1764. was_raw = 1;
  1765. }
  1766. response = NULL;
  1767. for (i = 0; !quit_pending && i < 3; i++) {
  1768. free(response);
  1769. response = read_passphrase("Accept updated hostkeys? "
  1770. "(yes/no): ", RP_ECHO);
  1771. if (strcasecmp(response, "yes") == 0)
  1772. break;
  1773. else if (quit_pending || response == NULL ||
  1774. strcasecmp(response, "no") == 0) {
  1775. options.update_hostkeys = 0;
  1776. break;
  1777. } else {
  1778. do_log2(loglevel, "Please enter "
  1779. "\"yes\" or \"no\"");
  1780. }
  1781. }
  1782. if (quit_pending || i >= 3 || response == NULL)
  1783. options.update_hostkeys = 0;
  1784. free(response);
  1785. if (was_raw)
  1786. enter_raw_mode(1);
  1787. }
  1788. if (options.update_hostkeys == 0)
  1789. return;
  1790. /*
  1791. * Now that all the keys are verified, we can go ahead and replace
  1792. * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
  1793. * cancel the operation).
  1794. */
  1795. for (i = 0; i < options.num_user_hostfiles; i++) {
  1796. /*
  1797. * NB. keys are only added to hostfiles[0], for the rest we
  1798. * just delete the hostname entries.
  1799. */
  1800. if (stat(options.user_hostfiles[i], &sb) != 0) {
  1801. if (errno == ENOENT) {
  1802. debug("%s: known hosts file %s does not exist",
  1803. __func__, strerror(errno));
  1804. } else {
  1805. error("%s: known hosts file %s inaccessible",
  1806. __func__, strerror(errno));
  1807. }
  1808. continue;
  1809. }
  1810. if ((r = hostfile_replace_entries(options.user_hostfiles[i],
  1811. ctx->host_str, ctx->ip_str,
  1812. i == 0 ? ctx->keys : NULL, i == 0 ? ctx->nkeys : 0,
  1813. options.hash_known_hosts, 0,
  1814. options.fingerprint_hash)) != 0) {
  1815. error("%s: hostfile_replace_entries failed for %s: %s",
  1816. __func__, options.user_hostfiles[i], ssh_err(r));
  1817. }
  1818. }
  1819. }
  1820. static void
  1821. client_global_hostkeys_private_confirm(struct ssh *ssh, int type,
  1822. u_int32_t seq, void *_ctx)
  1823. {
  1824. struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
  1825. size_t i, ndone;
  1826. struct sshbuf *signdata;
  1827. int r, kexsigtype, use_kexsigtype;
  1828. const u_char *sig;
  1829. size_t siglen;
  1830. if (ctx->nnew == 0)
  1831. fatal("%s: ctx->nnew == 0", __func__); /* sanity */
  1832. if (type != SSH2_MSG_REQUEST_SUCCESS) {
  1833. error("Server failed to confirm ownership of "
  1834. "private host keys");
  1835. hostkeys_update_ctx_free(ctx);
  1836. return;
  1837. }
  1838. kexsigtype = sshkey_type_plain(
  1839. sshkey_type_from_name(ssh->kex->hostkey_alg));
  1840. if ((signdata = sshbuf_new()) == NULL)
  1841. fatal("%s: sshbuf_new failed", __func__);
  1842. /*
  1843. * Expect a signature for each of the ctx->nnew private keys we
  1844. * haven't seen before. They will be in the same order as the
  1845. * ctx->keys where the corresponding ctx->keys_match[i] == 0.
  1846. */
  1847. for (ndone = i = 0; i < ctx->nkeys; i++) {
  1848. if (ctx->keys_match[i])
  1849. continue;
  1850. /* Prepare data to be signed: session ID, unique string, key */
  1851. sshbuf_reset(signdata);
  1852. if ( (r = sshbuf_put_cstring(signdata,
  1853. "hostkeys-prove-00@openssh.com")) != 0 ||
  1854. (r = sshbuf_put_stringb(signdata,
  1855. ssh->kex->session_id)) != 0 ||
  1856. (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
  1857. fatal("%s: failed to prepare signature: %s",
  1858. __func__, ssh_err(r));
  1859. /* Extract and verify signature */
  1860. if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
  1861. error("%s: couldn't parse message: %s",
  1862. __func__, ssh_err(r));
  1863. goto out;
  1864. }
  1865. /*
  1866. * For RSA keys, prefer to use the signature type negotiated
  1867. * during KEX to the default (SHA1).
  1868. */
  1869. use_kexsigtype = kexsigtype == KEY_RSA &&
  1870. sshkey_type_plain(ctx->keys[i]->type) == KEY_RSA;
  1871. if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
  1872. sshbuf_ptr(signdata), sshbuf_len(signdata),
  1873. use_kexsigtype ? ssh->kex->hostkey_alg : NULL, 0,
  1874. NULL)) != 0) {
  1875. error("%s: server gave bad signature for %s key %zu",
  1876. __func__, sshkey_type(ctx->keys[i]), i);
  1877. goto out;
  1878. }
  1879. /* Key is good. Mark it as 'seen' */
  1880. ctx->keys_verified[i] = 1;
  1881. ndone++;
  1882. }
  1883. if (ndone != ctx->nnew)
  1884. fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
  1885. ndone, ctx->nnew); /* Shouldn't happen */
  1886. if ((r = sshpkt_get_end(ssh)) != 0) {
  1887. error("%s: protocol error", __func__);
  1888. goto out;
  1889. }
  1890. /* Make the edits to known_hosts */
  1891. update_known_hosts(ctx);
  1892. out:
  1893. hostkeys_update_ctx_free(ctx);
  1894. }
  1895. /*
  1896. * Returns non-zero if the key is accepted by HostkeyAlgorithms.
  1897. * Made slightly less trivial by the multiple RSA signature algorithm names.
  1898. */
  1899. static int
  1900. key_accepted_by_hostkeyalgs(const struct sshkey *key)
  1901. {
  1902. const char *ktype = sshkey_ssh_name(key);
  1903. const char *hostkeyalgs = options.hostkeyalgorithms;
  1904. if (key == NULL || key->type == KEY_UNSPEC)
  1905. return 0;
  1906. if (key->type == KEY_RSA &&
  1907. (match_pattern_list("rsa-sha2-256", hostkeyalgs, 0) == 1 ||
  1908. match_pattern_list("rsa-sha2-512", hostkeyalgs, 0) == 1))
  1909. return 1;
  1910. return match_pattern_list(ktype, hostkeyalgs, 0) == 1;
  1911. }
  1912. /*
  1913. * Handle hostkeys-00@openssh.com global request to inform the client of all
  1914. * the server's hostkeys. The keys are checked against the user's
  1915. * HostkeyAlgorithms preference before they are accepted.
  1916. */
  1917. static int
  1918. client_input_hostkeys(struct ssh *ssh)
  1919. {
  1920. const u_char *blob = NULL;
  1921. size_t i, len = 0;
  1922. struct sshbuf *buf = NULL;
  1923. struct sshkey *key = NULL, **tmp;
  1924. int r;
  1925. char *fp;
  1926. static int hostkeys_seen = 0; /* XXX use struct ssh */
  1927. extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
  1928. struct hostkeys_update_ctx *ctx = NULL;
  1929. u_int want;
  1930. if (hostkeys_seen)
  1931. fatal("%s: server already sent hostkeys", __func__);
  1932. if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
  1933. options.batch_mode)
  1934. return 1; /* won't ask in batchmode, so don't even try */
  1935. if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
  1936. return 1;
  1937. ctx = xcalloc(1, sizeof(*ctx));
  1938. while (ssh_packet_remaining(ssh) > 0) {
  1939. sshkey_free(key);
  1940. key = NULL;
  1941. if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
  1942. error("%s: couldn't parse message: %s",
  1943. __func__, ssh_err(r));
  1944. goto out;
  1945. }
  1946. if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
  1947. do_log2(r == SSH_ERR_KEY_TYPE_UNKNOWN ?
  1948. SYSLOG_LEVEL_DEBUG1 : SYSLOG_LEVEL_ERROR,
  1949. "%s: parse key: %s", __func__, ssh_err(r));
  1950. continue;
  1951. }
  1952. fp = sshkey_fingerprint(key, options.fingerprint_hash,
  1953. SSH_FP_DEFAULT);
  1954. debug3("%s: received %s key %s", __func__,
  1955. sshkey_type(key), fp);
  1956. free(fp);
  1957. if (!key_accepted_by_hostkeyalgs(key)) {
  1958. debug3("%s: %s key not permitted by HostkeyAlgorithms",
  1959. __func__, sshkey_ssh_name(key));
  1960. continue;
  1961. }
  1962. /* Skip certs */
  1963. if (sshkey_is_cert(key)) {
  1964. debug3("%s: %s key is a certificate; skipping",
  1965. __func__, sshkey_ssh_name(key));
  1966. continue;
  1967. }
  1968. /* Ensure keys are unique */
  1969. for (i = 0; i < ctx->nkeys; i++) {
  1970. if (sshkey_equal(key, ctx->keys[i])) {
  1971. error("%s: received duplicated %s host key",
  1972. __func__, sshkey_ssh_name(key));
  1973. goto out;
  1974. }
  1975. }
  1976. /* Key is good, record it */
  1977. if ((tmp = recallocarray(ctx->keys, ctx->nkeys, ctx->nkeys + 1,
  1978. sizeof(*ctx->keys))) == NULL)
  1979. fatal("%s: recallocarray failed nkeys = %zu",
  1980. __func__, ctx->nkeys);
  1981. ctx->keys = tmp;
  1982. ctx->keys[ctx->nkeys++] = key;
  1983. key = NULL;
  1984. }
  1985. if (ctx->nkeys == 0) {
  1986. debug("%s: server sent no hostkeys", __func__);
  1987. goto out;
  1988. }
  1989. if ((ctx->keys_match = calloc(ctx->nkeys,
  1990. sizeof(*ctx->keys_match))) == NULL ||
  1991. (ctx->keys_verified = calloc(ctx->nkeys,
  1992. sizeof(*ctx->keys_verified))) == NULL)
  1993. fatal("%s: calloc failed", __func__);
  1994. get_hostfile_hostname_ipaddr(host,
  1995. options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
  1996. options.port, &ctx->host_str,
  1997. options.check_host_ip ? &ctx->ip_str : NULL);
  1998. /* Find which keys we already know about. */
  1999. for (i = 0; i < options.num_user_hostfiles; i++) {
  2000. debug("%s: searching %s for %s / %s", __func__,
  2001. options.user_hostfiles[i], ctx->host_str,
  2002. ctx->ip_str ? ctx->ip_str : "(none)");
  2003. if ((r = hostkeys_foreach(options.user_hostfiles[i],
  2004. hostkeys_find, ctx, ctx->host_str, ctx->ip_str,
  2005. HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
  2006. if (r == SSH_ERR_SYSTEM_ERROR && errno == ENOENT) {
  2007. debug("%s: hostkeys file %s does not exist",
  2008. __func__, options.user_hostfiles[i]);
  2009. continue;
  2010. }
  2011. error("%s: hostkeys_foreach failed for %s: %s",
  2012. __func__, options.user_hostfiles[i], ssh_err(r));
  2013. goto out;
  2014. }
  2015. }
  2016. /* Figure out if we have any new keys to add */
  2017. ctx->nnew = ctx->nincomplete = 0;
  2018. want = HKF_MATCH_HOST | ( options.check_host_ip ? HKF_MATCH_IP : 0);
  2019. for (i = 0; i < ctx->nkeys; i++) {
  2020. if (ctx->keys_match[i] == 0)
  2021. ctx->nnew++;
  2022. if ((ctx->keys_match[i] & want) != want)
  2023. ctx->nincomplete++;
  2024. }
  2025. debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
  2026. __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
  2027. if (ctx->nnew == 0 && ctx->nold != 0) {
  2028. /* We have some keys to remove. Just do it. */
  2029. update_known_hosts(ctx);
  2030. } else if (ctx->nnew != 0) {
  2031. /*
  2032. * We have received hitherto-unseen keys from the server.
  2033. * Ask the server to confirm ownership of the private halves.
  2034. */
  2035. debug3("%s: asking server to prove ownership for %zu keys",
  2036. __func__, ctx->nnew);
  2037. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  2038. (r = sshpkt_put_cstring(ssh,
  2039. "hostkeys-prove-00@openssh.com")) != 0 ||
  2040. (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
  2041. fatal("%s: cannot prepare packet: %s",
  2042. __func__, ssh_err(r));
  2043. if ((buf = sshbuf_new()) == NULL)
  2044. fatal("%s: sshbuf_new", __func__);
  2045. for (i = 0; i < ctx->nkeys; i++) {
  2046. if (ctx->keys_match[i])
  2047. continue;
  2048. sshbuf_reset(buf);
  2049. if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
  2050. fatal("%s: sshkey_putb: %s",
  2051. __func__, ssh_err(r));
  2052. if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
  2053. fatal("%s: sshpkt_put_string: %s",
  2054. __func__, ssh_err(r));
  2055. }
  2056. if ((r = sshpkt_send(ssh)) != 0)
  2057. fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
  2058. client_register_global_confirm(
  2059. client_global_hostkeys_private_confirm, ctx);
  2060. ctx = NULL; /* will be freed in callback */
  2061. }
  2062. /* Success */
  2063. out:
  2064. hostkeys_update_ctx_free(ctx);
  2065. sshkey_free(key);
  2066. sshbuf_free(buf);
  2067. /*
  2068. * NB. Return success for all cases. The server doesn't need to know
  2069. * what the client does with its hosts file.
  2070. */
  2071. return 1;
  2072. }
  2073. static int
  2074. client_input_global_request(int type, u_int32_t seq, struct ssh *ssh)
  2075. {
  2076. char *rtype;
  2077. u_char want_reply;
  2078. int r, success = 0;
  2079. if ((r = sshpkt_get_cstring(ssh, &rtype, NULL)) != 0 ||
  2080. (r = sshpkt_get_u8(ssh, &want_reply)) != 0)
  2081. goto out;
  2082. debug("client_input_global_request: rtype %s want_reply %d",
  2083. rtype, want_reply);
  2084. if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
  2085. success = client_input_hostkeys(ssh);
  2086. if (want_reply) {
  2087. if ((r = sshpkt_start(ssh, success ? SSH2_MSG_REQUEST_SUCCESS :
  2088. SSH2_MSG_REQUEST_FAILURE)) != 0 ||
  2089. (r = sshpkt_send(ssh)) != 0 ||
  2090. (r = ssh_packet_write_wait(ssh)) != 0)
  2091. goto out;
  2092. }
  2093. r = 0;
  2094. out:
  2095. free(rtype);
  2096. return r;
  2097. }
  2098. void
  2099. client_session2_setup(struct ssh *ssh, int id, int want_tty, int want_subsystem,
  2100. const char *term, struct termios *tiop, int in_fd, struct sshbuf *cmd,
  2101. char **env)
  2102. {
  2103. int i, j, matched, len, r;
  2104. char *name, *val;
  2105. Channel *c = NULL;
  2106. debug2("%s: id %d", __func__, id);
  2107. if ((c = channel_lookup(ssh, id)) == NULL)
  2108. fatal("%s: channel %d: unknown channel", __func__, id);
  2109. ssh_packet_set_interactive(ssh, want_tty,
  2110. options.ip_qos_interactive, options.ip_qos_bulk);
  2111. if (want_tty) {
  2112. struct winsize ws;
  2113. /* Store window size in the packet. */
  2114. if (ioctl(in_fd, TIOCGWINSZ, &ws) == -1)
  2115. memset(&ws, 0, sizeof(ws));
  2116. channel_request_start(ssh, id, "pty-req", 1);
  2117. client_expect_confirm(ssh, id, "PTY allocation", CONFIRM_TTY);
  2118. if ((r = sshpkt_put_cstring(ssh, term != NULL ? term : ""))
  2119. != 0 ||
  2120. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
  2121. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
  2122. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
  2123. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0)
  2124. fatal("%s: build packet: %s", __func__, ssh_err(r));
  2125. if (tiop == NULL)
  2126. tiop = get_saved_tio();
  2127. ssh_tty_make_modes(ssh, -1, tiop);
  2128. if ((r = sshpkt_send(ssh)) != 0)
  2129. fatal("%s: send packet: %s", __func__, ssh_err(r));
  2130. /* XXX wait for reply */
  2131. c->client_tty = 1;
  2132. }
  2133. /* Transfer any environment variables from client to server */
  2134. if (options.num_send_env != 0 && env != NULL) {
  2135. debug("Sending environment.");
  2136. for (i = 0; env[i] != NULL; i++) {
  2137. /* Split */
  2138. name = xstrdup(env[i]);
  2139. if ((val = strchr(name, '=')) == NULL) {
  2140. free(name);
  2141. continue;
  2142. }
  2143. *val++ = '\0';
  2144. matched = 0;
  2145. for (j = 0; j < options.num_send_env; j++) {
  2146. if (match_pattern(name, options.send_env[j])) {
  2147. matched = 1;
  2148. break;
  2149. }
  2150. }
  2151. if (!matched) {
  2152. debug3("Ignored env %s", name);
  2153. free(name);
  2154. continue;
  2155. }
  2156. debug("Sending env %s = %s", name, val);
  2157. channel_request_start(ssh, id, "env", 0);
  2158. if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
  2159. (r = sshpkt_put_cstring(ssh, val)) != 0 ||
  2160. (r = sshpkt_send(ssh)) != 0) {
  2161. fatal("%s: send packet: %s",
  2162. __func__, ssh_err(r));
  2163. }
  2164. free(name);
  2165. }
  2166. }
  2167. for (i = 0; i < options.num_setenv; i++) {
  2168. /* Split */
  2169. name = xstrdup(options.setenv[i]);
  2170. if ((val = strchr(name, '=')) == NULL) {
  2171. free(name);
  2172. continue;
  2173. }
  2174. *val++ = '\0';
  2175. debug("Setting env %s = %s", name, val);
  2176. channel_request_start(ssh, id, "env", 0);
  2177. if ((r = sshpkt_put_cstring(ssh, name)) != 0 ||
  2178. (r = sshpkt_put_cstring(ssh, val)) != 0 ||
  2179. (r = sshpkt_send(ssh)) != 0)
  2180. fatal("%s: send packet: %s", __func__, ssh_err(r));
  2181. free(name);
  2182. }
  2183. len = sshbuf_len(cmd);
  2184. if (len > 0) {
  2185. if (len > 900)
  2186. len = 900;
  2187. if (want_subsystem) {
  2188. debug("Sending subsystem: %.*s",
  2189. len, (const u_char*)sshbuf_ptr(cmd));
  2190. channel_request_start(ssh, id, "subsystem", 1);
  2191. client_expect_confirm(ssh, id, "subsystem",
  2192. CONFIRM_CLOSE);
  2193. } else {
  2194. debug("Sending command: %.*s",
  2195. len, (const u_char*)sshbuf_ptr(cmd));
  2196. channel_request_start(ssh, id, "exec", 1);
  2197. client_expect_confirm(ssh, id, "exec", CONFIRM_CLOSE);
  2198. }
  2199. if ((r = sshpkt_put_stringb(ssh, cmd)) != 0 ||
  2200. (r = sshpkt_send(ssh)) != 0)
  2201. fatal("%s: send command: %s", __func__, ssh_err(r));
  2202. } else {
  2203. channel_request_start(ssh, id, "shell", 1);
  2204. client_expect_confirm(ssh, id, "shell", CONFIRM_CLOSE);
  2205. if ((r = sshpkt_send(ssh)) != 0) {
  2206. fatal("%s: send shell request: %s",
  2207. __func__, ssh_err(r));
  2208. }
  2209. }
  2210. }
  2211. static void
  2212. client_init_dispatch(struct ssh *ssh)
  2213. {
  2214. ssh_dispatch_init(ssh, &dispatch_protocol_error);
  2215. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
  2216. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_DATA, &channel_input_data);
  2217. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
  2218. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
  2219. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
  2220. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
  2221. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
  2222. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
  2223. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
  2224. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
  2225. ssh_dispatch_set(ssh, SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
  2226. ssh_dispatch_set(ssh, SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
  2227. /* rekeying */
  2228. ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
  2229. /* global request reply messages */
  2230. ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
  2231. ssh_dispatch_set(ssh, SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
  2232. }
  2233. void
  2234. client_stop_mux(void)
  2235. {
  2236. if (options.control_path != NULL && muxserver_sock != -1)
  2237. unlink(options.control_path);
  2238. /*
  2239. * If we are in persist mode, or don't have a shell, signal that we
  2240. * should close when all active channels are closed.
  2241. */
  2242. if (options.control_persist || options.no_shell) {
  2243. session_closed = 1;
  2244. setproctitle("[stopped mux]");
  2245. }
  2246. }
  2247. /* client specific fatal cleanup */
  2248. void
  2249. cleanup_exit(int i)
  2250. {
  2251. leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
  2252. if (options.control_path != NULL && muxserver_sock != -1)
  2253. unlink(options.control_path);
  2254. ssh_kill_proxy_command();
  2255. _exit(i);
  2256. }