ssh.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*
  2. * SSH backend.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. #include <assert.h>
  8. #include <limits.h>
  9. #include <signal.h>
  10. #include "putty.h"
  11. #include "pageant.h" /* for AGENT_MAX_MSGLEN */
  12. #include "tree234.h"
  13. #include "storage.h"
  14. #include "marshal.h"
  15. #include "ssh.h"
  16. #include "sshcr.h"
  17. #include "sshbpp.h"
  18. #include "sshppl.h"
  19. #include "sshchan.h"
  20. #ifndef NO_GSSAPI
  21. #include "sshgssc.h"
  22. #include "sshgss.h"
  23. #define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */
  24. #define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */
  25. #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
  26. #define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
  27. #define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
  28. #endif
  29. struct Ssh {
  30. Socket *s;
  31. Seat *seat;
  32. Conf *conf;
  33. struct ssh_version_receiver version_receiver;
  34. int remote_bugs;
  35. Plug plug;
  36. Backend backend;
  37. Ldisc *ldisc;
  38. LogContext *logctx;
  39. /* The last list returned from get_specials. */
  40. SessionSpecial *specials;
  41. bool bare_connection;
  42. ssh_sharing_state *connshare;
  43. bool attempting_connshare;
  44. #ifndef NO_GSSAPI
  45. struct ssh_connection_shared_gss_state gss_state;
  46. #endif
  47. char *savedhost;
  48. int savedport;
  49. char *fullhostname;
  50. bool fallback_cmd;
  51. int exitcode;
  52. int version;
  53. int conn_throttle_count;
  54. size_t overall_bufsize;
  55. bool throttled_all;
  56. /*
  57. * logically_frozen is true if we're not currently _processing_
  58. * data from the SSH socket (e.g. because a higher layer has asked
  59. * us not to due to ssh_throttle_conn). socket_frozen is true if
  60. * we're not even _reading_ data from the socket (i.e. it should
  61. * always match the value we last passed to sk_set_frozen).
  62. *
  63. * The two differ in that socket_frozen can also become
  64. * temporarily true because of a large backlog in the in_raw
  65. * bufchain, to force no further plug_receive events until the BPP
  66. * input function has had a chance to run. (Some front ends, like
  67. * GTK, can persistently call the network and never get round to
  68. * the toplevel callbacks.) If we've stopped reading from the
  69. * socket for that reason, we absolutely _do_ want to carry on
  70. * processing our input bufchain, because that's the only way
  71. * it'll ever get cleared!
  72. *
  73. * ssh_check_frozen() resets socket_frozen, and should be called
  74. * whenever either of logically_frozen and the bufchain size
  75. * changes.
  76. */
  77. bool logically_frozen, socket_frozen;
  78. /* in case we find these out before we have a ConnectionLayer to tell */
  79. int term_width, term_height;
  80. bufchain in_raw, out_raw, user_input;
  81. bool pending_close;
  82. IdempotentCallback ic_out_raw;
  83. PacketLogSettings pls;
  84. struct DataTransferStats stats;
  85. BinaryPacketProtocol *bpp;
  86. /*
  87. * base_layer identifies the bottommost packet protocol layer, the
  88. * one connected directly to the BPP's packet queues. Any
  89. * operation that needs to talk to all layers (e.g. free, or
  90. * get_specials) will do it by talking to this, which will
  91. * recursively propagate it if necessary.
  92. */
  93. PacketProtocolLayer *base_layer;
  94. /*
  95. * The ConnectionLayer vtable from our connection layer.
  96. */
  97. ConnectionLayer *cl;
  98. /*
  99. * A dummy ConnectionLayer that can be used for logging sharing
  100. * downstreams that connect before the real one is ready.
  101. */
  102. ConnectionLayer cl_dummy;
  103. /*
  104. * session_started is false until we initialise the main protocol
  105. * layers. So it distinguishes between base_layer==NULL meaning
  106. * that the SSH protocol hasn't been set up _yet_, and
  107. * base_layer==NULL meaning the SSH protocol has run and finished.
  108. * It's also used to mark the point where we stop counting proxy
  109. * command diagnostics as pre-session-startup.
  110. */
  111. bool session_started;
  112. Pinger *pinger;
  113. char *deferred_abort_message;
  114. bool need_random_unref;
  115. };
  116. #define ssh_logevent(params) ( \
  117. logevent_and_free((ssh)->logctx, dupprintf params))
  118. static void ssh_shutdown(Ssh *ssh);
  119. static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize);
  120. static void ssh_bpp_output_raw_data_callback(void *vctx);
  121. LogContext *ssh_get_logctx(Ssh *ssh)
  122. {
  123. return ssh->logctx;
  124. }
  125. static void ssh_connect_bpp(Ssh *ssh)
  126. {
  127. ssh->bpp->ssh = ssh;
  128. ssh->bpp->in_raw = &ssh->in_raw;
  129. ssh->bpp->out_raw = &ssh->out_raw;
  130. bufchain_set_callback(ssh->bpp->out_raw, &ssh->ic_out_raw);
  131. ssh->bpp->pls = &ssh->pls;
  132. ssh->bpp->logctx = ssh->logctx;
  133. ssh->bpp->remote_bugs = ssh->remote_bugs;
  134. }
  135. static void ssh_connect_ppl(Ssh *ssh, PacketProtocolLayer *ppl)
  136. {
  137. ppl->bpp = ssh->bpp;
  138. ppl->user_input = &ssh->user_input;
  139. ppl->seat = ssh->seat;
  140. ppl->ssh = ssh;
  141. ppl->logctx = ssh->logctx;
  142. ppl->remote_bugs = ssh->remote_bugs;
  143. }
  144. static void ssh_got_ssh_version(struct ssh_version_receiver *rcv,
  145. int major_version)
  146. {
  147. Ssh *ssh = container_of(rcv, Ssh, version_receiver);
  148. BinaryPacketProtocol *old_bpp;
  149. PacketProtocolLayer *connection_layer;
  150. ssh->session_started = true;
  151. /*
  152. * We don't support choosing a major protocol version dynamically,
  153. * so this should always be the same value we set up in
  154. * connect_to_host().
  155. */
  156. assert(ssh->version == major_version);
  157. old_bpp = ssh->bpp;
  158. ssh->remote_bugs = ssh_verstring_get_bugs(old_bpp);
  159. if (!ssh->bare_connection) {
  160. if (ssh->version == 2) {
  161. PacketProtocolLayer *userauth_layer, *transport_child_layer;
  162. /*
  163. * We use the 'simple' variant of the SSH protocol if
  164. * we're asked to, except not if we're also doing
  165. * connection-sharing (either tunnelling our packets over
  166. * an upstream or expecting to be tunnelled over
  167. * ourselves), since then the assumption that we have only
  168. * one channel to worry about is not true after all.
  169. */
  170. bool is_simple =
  171. (conf_get_bool(ssh->conf, CONF_ssh_simple) && !ssh->connshare);
  172. ssh->bpp = ssh2_bpp_new(ssh->logctx, &ssh->stats, false);
  173. ssh_connect_bpp(ssh);
  174. #ifndef NO_GSSAPI
  175. /* Load and pick the highest GSS library on the preference
  176. * list. */
  177. if (!ssh->gss_state.libs)
  178. ssh->gss_state.libs = ssh_gss_setup(ssh->conf);
  179. ssh->gss_state.lib = NULL;
  180. if (ssh->gss_state.libs->nlibraries > 0) {
  181. int i, j;
  182. for (i = 0; i < ngsslibs; i++) {
  183. int want_id = conf_get_int_int(ssh->conf,
  184. CONF_ssh_gsslist, i);
  185. for (j = 0; j < ssh->gss_state.libs->nlibraries; j++)
  186. if (ssh->gss_state.libs->libraries[j].id == want_id) {
  187. ssh->gss_state.lib =
  188. &ssh->gss_state.libs->libraries[j];
  189. goto got_gsslib; /* double break */
  190. }
  191. }
  192. got_gsslib:
  193. /*
  194. * We always expect to have found something in
  195. * the above loop: we only came here if there
  196. * was at least one viable GSS library, and the
  197. * preference list should always mention
  198. * everything and only change the order.
  199. */
  200. assert(ssh->gss_state.lib);
  201. }
  202. #endif
  203. connection_layer = ssh2_connection_new(
  204. ssh, ssh->connshare, is_simple, ssh->conf,
  205. ssh_verstring_get_remote(old_bpp), &ssh->cl);
  206. ssh_connect_ppl(ssh, connection_layer);
  207. if (conf_get_bool(ssh->conf, CONF_ssh_no_userauth)) {
  208. userauth_layer = NULL;
  209. transport_child_layer = connection_layer;
  210. } else {
  211. char *username = get_remote_username(ssh->conf);
  212. userauth_layer = ssh2_userauth_new(
  213. connection_layer, ssh->savedhost, ssh->fullhostname,
  214. conf_get_filename(ssh->conf, CONF_keyfile),
  215. conf_get_bool(ssh->conf, CONF_ssh_show_banner),
  216. conf_get_bool(ssh->conf, CONF_tryagent), username,
  217. conf_get_bool(ssh->conf, CONF_change_username),
  218. conf_get_bool(ssh->conf, CONF_try_ki_auth),
  219. #ifndef NO_GSSAPI
  220. conf_get_bool(ssh->conf, CONF_try_gssapi_auth),
  221. conf_get_bool(ssh->conf, CONF_try_gssapi_kex),
  222. conf_get_bool(ssh->conf, CONF_gssapifwd),
  223. &ssh->gss_state
  224. #else
  225. false,
  226. false,
  227. false,
  228. NULL
  229. #endif
  230. );
  231. ssh_connect_ppl(ssh, userauth_layer);
  232. transport_child_layer = userauth_layer;
  233. sfree(username);
  234. }
  235. ssh->base_layer = ssh2_transport_new(
  236. ssh->conf, ssh->savedhost, ssh->savedport,
  237. ssh->fullhostname,
  238. ssh_verstring_get_local(old_bpp),
  239. ssh_verstring_get_remote(old_bpp),
  240. #ifndef NO_GSSAPI
  241. &ssh->gss_state,
  242. #else
  243. NULL,
  244. #endif
  245. &ssh->stats, transport_child_layer, NULL);
  246. ssh_connect_ppl(ssh, ssh->base_layer);
  247. if (userauth_layer)
  248. ssh2_userauth_set_transport_layer(userauth_layer,
  249. ssh->base_layer);
  250. } else {
  251. ssh->bpp = ssh1_bpp_new(ssh->logctx);
  252. ssh_connect_bpp(ssh);
  253. connection_layer = ssh1_connection_new(ssh, ssh->conf, &ssh->cl);
  254. ssh_connect_ppl(ssh, connection_layer);
  255. ssh->base_layer = ssh1_login_new(
  256. ssh->conf, ssh->savedhost, ssh->savedport, connection_layer);
  257. ssh_connect_ppl(ssh, ssh->base_layer);
  258. }
  259. } else {
  260. ssh->bpp = ssh2_bare_bpp_new(ssh->logctx);
  261. ssh_connect_bpp(ssh);
  262. connection_layer = ssh2_connection_new(
  263. ssh, ssh->connshare, false, ssh->conf,
  264. ssh_verstring_get_remote(old_bpp), &ssh->cl);
  265. ssh_connect_ppl(ssh, connection_layer);
  266. ssh->base_layer = connection_layer;
  267. }
  268. /* Connect the base layer - whichever it is - to the BPP, and set
  269. * up its selfptr. */
  270. ssh->base_layer->selfptr = &ssh->base_layer;
  271. ssh_ppl_setup_queues(ssh->base_layer, &ssh->bpp->in_pq, &ssh->bpp->out_pq);
  272. seat_update_specials_menu(ssh->seat);
  273. ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
  274. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  275. ssh_ppl_process_queue(ssh->base_layer);
  276. /* Pass in the initial terminal size, if we knew it already. */
  277. ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
  278. ssh_bpp_free(old_bpp);
  279. }
  280. void ssh_check_frozen(Ssh *ssh)
  281. {
  282. if (!ssh->s)
  283. return;
  284. bool prev_frozen = ssh->socket_frozen;
  285. ssh->socket_frozen = (ssh->logically_frozen ||
  286. bufchain_size(&ssh->in_raw) > SSH_MAX_BACKLOG);
  287. sk_set_frozen(ssh->s, ssh->socket_frozen);
  288. if (prev_frozen && !ssh->socket_frozen && ssh->bpp) {
  289. /*
  290. * If we've just unfrozen, process any SSH connection data
  291. * that was stashed in our queue while we were frozen.
  292. */
  293. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  294. }
  295. }
  296. void ssh_conn_processed_data(Ssh *ssh)
  297. {
  298. ssh_check_frozen(ssh);
  299. }
  300. static void ssh_bpp_output_raw_data_callback(void *vctx)
  301. {
  302. Ssh *ssh = (Ssh *)vctx;
  303. if (!ssh->s)
  304. return;
  305. while (bufchain_size(&ssh->out_raw) > 0) {
  306. size_t backlog;
  307. ptrlen data = bufchain_prefix(&ssh->out_raw);
  308. if (ssh->logctx)
  309. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data.ptr, data.len,
  310. 0, NULL, NULL, 0, NULL);
  311. backlog = sk_write(ssh->s, data.ptr, data.len);
  312. bufchain_consume(&ssh->out_raw, data.len);
  313. if (backlog > SSH_MAX_BACKLOG) {
  314. ssh_throttle_all(ssh, true, backlog);
  315. return;
  316. }
  317. }
  318. ssh_check_frozen(ssh);
  319. if (ssh->pending_close) {
  320. sk_close(ssh->s);
  321. ssh->s = NULL;
  322. }
  323. }
  324. static void ssh_shutdown_internal(Ssh *ssh)
  325. {
  326. expire_timer_context(ssh);
  327. if (ssh->connshare) {
  328. sharestate_free(ssh->connshare);
  329. ssh->connshare = NULL;
  330. }
  331. if (ssh->pinger) {
  332. pinger_free(ssh->pinger);
  333. ssh->pinger = NULL;
  334. }
  335. /*
  336. * We only need to free the base PPL, which will free the others
  337. * (if any) transitively.
  338. */
  339. if (ssh->base_layer) {
  340. ssh_ppl_free(ssh->base_layer);
  341. ssh->base_layer = NULL;
  342. }
  343. ssh->cl = NULL;
  344. }
  345. static void ssh_shutdown(Ssh *ssh)
  346. {
  347. ssh_shutdown_internal(ssh);
  348. if (ssh->bpp) {
  349. ssh_bpp_free(ssh->bpp);
  350. ssh->bpp = NULL;
  351. }
  352. if (ssh->s) {
  353. sk_close(ssh->s);
  354. ssh->s = NULL;
  355. }
  356. bufchain_clear(&ssh->in_raw);
  357. bufchain_clear(&ssh->out_raw);
  358. bufchain_clear(&ssh->user_input);
  359. }
  360. static void ssh_initiate_connection_close(Ssh *ssh)
  361. {
  362. /* Wind up everything above the BPP. */
  363. ssh_shutdown_internal(ssh);
  364. /* Force any remaining queued SSH packets through the BPP, and
  365. * schedule closing the network socket after they go out. */
  366. ssh_bpp_handle_output(ssh->bpp);
  367. ssh->pending_close = true;
  368. queue_idempotent_callback(&ssh->ic_out_raw);
  369. /* Now we expect the other end to close the connection too in
  370. * response, so arrange that we'll receive notification of that
  371. * via ssh_remote_eof. */
  372. ssh->bpp->expect_close = true;
  373. }
  374. #define GET_FORMATTED_MSG \
  375. char *msg; \
  376. va_list ap; \
  377. va_start(ap, fmt); \
  378. msg = dupvprintf(fmt, ap); \
  379. va_end(ap); \
  380. ((void)0) /* eat trailing semicolon */
  381. void ssh_remote_error(Ssh *ssh, const char *fmt, ...)
  382. {
  383. if (ssh->base_layer || !ssh->session_started) {
  384. GET_FORMATTED_MSG;
  385. /* Error messages sent by the remote don't count as clean exits */
  386. ssh->exitcode = 128;
  387. /* Close the socket immediately, since the server has already
  388. * closed its end (or is about to). */
  389. ssh_shutdown(ssh);
  390. logevent(ssh->logctx, msg);
  391. seat_connection_fatal(ssh->seat, "%s", msg);
  392. sfree(msg);
  393. }
  394. }
  395. void ssh_remote_eof(Ssh *ssh, const char *fmt, ...)
  396. {
  397. if (ssh->base_layer || !ssh->session_started) {
  398. GET_FORMATTED_MSG;
  399. /* EOF from the remote, if we were expecting it, does count as
  400. * a clean exit */
  401. ssh->exitcode = 0;
  402. /* Close the socket immediately, since the server has already
  403. * closed its end. */
  404. ssh_shutdown(ssh);
  405. logevent(ssh->logctx, msg);
  406. sfree(msg);
  407. seat_notify_remote_exit(ssh->seat);
  408. } else {
  409. /* This is responding to EOF after we've already seen some
  410. * other reason for terminating the session. */
  411. ssh_shutdown(ssh);
  412. }
  413. }
  414. void ssh_proto_error(Ssh *ssh, const char *fmt, ...)
  415. {
  416. if (ssh->base_layer || !ssh->session_started) {
  417. GET_FORMATTED_MSG;
  418. ssh->exitcode = 128;
  419. ssh_bpp_queue_disconnect(ssh->bpp, msg,
  420. SSH2_DISCONNECT_PROTOCOL_ERROR);
  421. ssh_initiate_connection_close(ssh);
  422. logevent(ssh->logctx, msg);
  423. seat_connection_fatal(ssh->seat, "%s", msg);
  424. sfree(msg);
  425. }
  426. }
  427. void ssh_sw_abort(Ssh *ssh, const char *fmt, ...)
  428. {
  429. if (ssh->base_layer || !ssh->session_started) {
  430. GET_FORMATTED_MSG;
  431. ssh->exitcode = 128;
  432. ssh_initiate_connection_close(ssh);
  433. logevent(ssh->logctx, msg);
  434. seat_connection_fatal(ssh->seat, "%s", msg);
  435. sfree(msg);
  436. seat_notify_remote_exit(ssh->seat);
  437. }
  438. }
  439. void ssh_user_close(Ssh *ssh, const char *fmt, ...)
  440. {
  441. if (ssh->base_layer || !ssh->session_started) {
  442. GET_FORMATTED_MSG;
  443. /* Closing the connection due to user action, even if the
  444. * action is the user aborting during authentication prompts,
  445. * does count as a clean exit - except that this is also how
  446. * we signal ordinary session termination, in which case we
  447. * should use the exit status already sent from the main
  448. * session (if any). */
  449. if (ssh->exitcode < 0)
  450. ssh->exitcode = 0;
  451. ssh_initiate_connection_close(ssh);
  452. logevent(ssh->logctx, msg);
  453. sfree(msg);
  454. seat_notify_remote_exit(ssh->seat);
  455. }
  456. }
  457. static void ssh_deferred_abort_callback(void *vctx)
  458. {
  459. Ssh *ssh = (Ssh *)vctx;
  460. char *msg = ssh->deferred_abort_message;
  461. ssh->deferred_abort_message = NULL;
  462. ssh_sw_abort(ssh, "%s", msg);
  463. sfree(msg);
  464. }
  465. void ssh_sw_abort_deferred(Ssh *ssh, const char *fmt, ...)
  466. {
  467. if (!ssh->deferred_abort_message) {
  468. GET_FORMATTED_MSG;
  469. ssh->deferred_abort_message = msg;
  470. queue_toplevel_callback(ssh_deferred_abort_callback, ssh);
  471. }
  472. }
  473. static void ssh_socket_log(Plug *plug, PlugLogType type, SockAddr *addr,
  474. int port, const char *error_msg, int error_code)
  475. {
  476. Ssh *ssh = container_of(plug, Ssh, plug);
  477. /*
  478. * While we're attempting connection sharing, don't loudly log
  479. * everything that happens. Real TCP connections need to be logged
  480. * when we _start_ trying to connect, because it might be ages
  481. * before they respond if something goes wrong; but connection
  482. * sharing is local and quick to respond, and it's sufficient to
  483. * simply wait and see whether it worked afterwards.
  484. */
  485. if (!ssh->attempting_connshare)
  486. backend_socket_log(ssh->seat, ssh->logctx, type, addr, port,
  487. error_msg, error_code, ssh->conf,
  488. ssh->session_started);
  489. }
  490. static void ssh_closing(Plug *plug, const char *error_msg, int error_code,
  491. bool calling_back)
  492. {
  493. Ssh *ssh = container_of(plug, Ssh, plug);
  494. if (error_msg) {
  495. ssh_remote_error(ssh, "%s", error_msg);
  496. } else if (ssh->bpp) {
  497. ssh->bpp->input_eof = true;
  498. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  499. }
  500. }
  501. static void ssh_receive(Plug *plug, int urgent, const char *data, size_t len)
  502. {
  503. Ssh *ssh = container_of(plug, Ssh, plug);
  504. /* Log raw data, if we're in that mode. */
  505. if (ssh->logctx)
  506. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len,
  507. 0, NULL, NULL, 0, NULL);
  508. bufchain_add(&ssh->in_raw, data, len);
  509. if (!ssh->logically_frozen && ssh->bpp)
  510. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  511. ssh_check_frozen(ssh);
  512. }
  513. static void ssh_sent(Plug *plug, size_t bufsize)
  514. {
  515. Ssh *ssh = container_of(plug, Ssh, plug);
  516. /*
  517. * If the send backlog on the SSH socket itself clears, we should
  518. * unthrottle the whole world if it was throttled. Also trigger an
  519. * extra call to the consumer of the BPP's output, to try to send
  520. * some more data off its bufchain.
  521. */
  522. if (bufsize < SSH_MAX_BACKLOG) {
  523. ssh_throttle_all(ssh, false, bufsize);
  524. queue_idempotent_callback(&ssh->ic_out_raw);
  525. }
  526. }
  527. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  528. char **savedhost, int *savedport,
  529. char **loghost_ret)
  530. {
  531. char *loghost = conf_get_str(conf, CONF_loghost);
  532. if (loghost_ret)
  533. *loghost_ret = loghost;
  534. if (*loghost) {
  535. char *tmphost;
  536. char *colon;
  537. tmphost = dupstr(loghost);
  538. *savedport = 22; /* default ssh port */
  539. /*
  540. * A colon suffix on the hostname string also lets us affect
  541. * savedport. (Unless there are multiple colons, in which case
  542. * we assume this is an unbracketed IPv6 literal.)
  543. */
  544. colon = host_strrchr(tmphost, ':');
  545. if (colon && colon == host_strchr(tmphost, ':')) {
  546. *colon++ = '\0';
  547. if (*colon)
  548. *savedport = atoi(colon);
  549. }
  550. *savedhost = host_strduptrim(tmphost);
  551. sfree(tmphost);
  552. } else {
  553. *savedhost = host_strduptrim(host);
  554. if (port < 0)
  555. port = 22; /* default ssh port */
  556. *savedport = port;
  557. }
  558. }
  559. static bool ssh_test_for_upstream(const char *host, int port, Conf *conf)
  560. {
  561. char *savedhost;
  562. int savedport;
  563. bool ret;
  564. random_ref(); /* platform may need this to determine share socket name */
  565. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  566. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  567. sfree(savedhost);
  568. random_unref();
  569. return ret;
  570. }
  571. static char *ssh_close_warn_text(Backend *be)
  572. {
  573. Ssh *ssh = container_of(be, Ssh, backend);
  574. if (!ssh->connshare)
  575. return NULL;
  576. int ndowns = share_ndownstreams(ssh->connshare);
  577. if (ndowns == 0)
  578. return NULL;
  579. char *msg = dupprintf("This will also close %d downstream connection%s.",
  580. ndowns, ndowns==1 ? "" : "s");
  581. return msg;
  582. }
  583. static const PlugVtable Ssh_plugvt = {
  584. .log = ssh_socket_log,
  585. .closing = ssh_closing,
  586. .receive = ssh_receive,
  587. .sent = ssh_sent,
  588. };
  589. /*
  590. * Connect to specified host and port.
  591. * Returns an error message, or NULL on success.
  592. * Also places the canonical host name into `realhost'. It must be
  593. * freed by the caller.
  594. */
  595. static char *connect_to_host(
  596. Ssh *ssh, const char *host, int port, char **realhost,
  597. bool nodelay, bool keepalive)
  598. {
  599. SockAddr *addr;
  600. const char *err;
  601. char *loghost;
  602. int addressfamily, sshprot;
  603. ssh_hostport_setup(host, port, ssh->conf,
  604. &ssh->savedhost, &ssh->savedport, &loghost);
  605. ssh->plug.vt = &Ssh_plugvt;
  606. /*
  607. * Try connection-sharing, in case that means we don't open a
  608. * socket after all. ssh_connection_sharing_init will connect to a
  609. * previously established upstream if it can, and failing that,
  610. * establish a listening socket for _us_ to be the upstream. In
  611. * the latter case it will return NULL just as if it had done
  612. * nothing, because here we only need to care if we're a
  613. * downstream and need to do our connection setup differently.
  614. */
  615. ssh->connshare = NULL;
  616. ssh->attempting_connshare = true; /* affects socket logging behaviour */
  617. ssh->s = ssh_connection_sharing_init(
  618. ssh->savedhost, ssh->savedport, ssh->conf, ssh->logctx,
  619. &ssh->plug, &ssh->connshare);
  620. if (ssh->connshare)
  621. ssh_connshare_provide_connlayer(ssh->connshare, &ssh->cl_dummy);
  622. ssh->attempting_connshare = false;
  623. if (ssh->s != NULL) {
  624. /*
  625. * We are a downstream.
  626. */
  627. ssh->bare_connection = true;
  628. ssh->fullhostname = NULL;
  629. *realhost = dupstr(host); /* best we can do */
  630. if (seat_verbose(ssh->seat) || seat_interactive(ssh->seat)) {
  631. /* In an interactive session, or in verbose mode, announce
  632. * in the console window that we're a sharing downstream,
  633. * to avoid confusing users as to why this session doesn't
  634. * behave in quite the usual way. */
  635. const char *msg =
  636. "Reusing a shared connection to this server.\r\n";
  637. seat_stderr_pl(ssh->seat, ptrlen_from_asciz(msg));
  638. }
  639. } else {
  640. /*
  641. * We're not a downstream, so open a normal socket.
  642. */
  643. /*
  644. * Try to find host.
  645. */
  646. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  647. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  648. ssh->logctx, "SSH connection");
  649. if ((err = sk_addr_error(addr)) != NULL) {
  650. sk_addr_free(addr);
  651. return dupstr(err);
  652. }
  653. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  654. ssh->s = new_connection(addr, *realhost, port,
  655. false, true, nodelay, keepalive,
  656. &ssh->plug, ssh->conf);
  657. if ((err = sk_socket_error(ssh->s)) != NULL) {
  658. ssh->s = NULL;
  659. seat_notify_remote_exit(ssh->seat);
  660. return dupstr(err);
  661. }
  662. }
  663. /*
  664. * The SSH version number is always fixed (since we no longer support
  665. * fallback between versions), so set it now.
  666. */
  667. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  668. assert(sshprot == 0 || sshprot == 3);
  669. if (sshprot == 0)
  670. /* SSH-1 only */
  671. ssh->version = 1;
  672. if (sshprot == 3 || ssh->bare_connection) {
  673. /* SSH-2 only */
  674. ssh->version = 2;
  675. }
  676. /*
  677. * Set up the initial BPP that will do the version string
  678. * exchange, and get it started so that it can send the outgoing
  679. * version string early if it wants to.
  680. */
  681. ssh->version_receiver.got_ssh_version = ssh_got_ssh_version;
  682. ssh->bpp = ssh_verstring_new(
  683. ssh->conf, ssh->logctx, ssh->bare_connection,
  684. ssh->version == 1 ? "1.5" : "2.0", &ssh->version_receiver,
  685. false, "PuTTY");
  686. ssh_connect_bpp(ssh);
  687. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  688. /*
  689. * loghost, if configured, overrides realhost.
  690. */
  691. if (*loghost) {
  692. sfree(*realhost);
  693. *realhost = dupstr(loghost);
  694. }
  695. return NULL;
  696. }
  697. /*
  698. * Throttle or unthrottle the SSH connection.
  699. */
  700. void ssh_throttle_conn(Ssh *ssh, int adjust)
  701. {
  702. int old_count = ssh->conn_throttle_count;
  703. bool frozen;
  704. ssh->conn_throttle_count += adjust;
  705. assert(ssh->conn_throttle_count >= 0);
  706. if (ssh->conn_throttle_count && !old_count) {
  707. frozen = true;
  708. } else if (!ssh->conn_throttle_count && old_count) {
  709. frozen = false;
  710. } else {
  711. return; /* don't change current frozen state */
  712. }
  713. ssh->logically_frozen = frozen;
  714. ssh_check_frozen(ssh);
  715. }
  716. /*
  717. * Throttle or unthrottle _all_ local data streams (for when sends
  718. * on the SSH connection itself back up).
  719. */
  720. static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize)
  721. {
  722. if (enable == ssh->throttled_all)
  723. return;
  724. ssh->throttled_all = enable;
  725. ssh->overall_bufsize = bufsize;
  726. ssh_throttle_all_channels(ssh->cl, enable);
  727. }
  728. static void ssh_cache_conf_values(Ssh *ssh)
  729. {
  730. ssh->pls.omit_passwords = conf_get_bool(ssh->conf, CONF_logomitpass);
  731. ssh->pls.omit_data = conf_get_bool(ssh->conf, CONF_logomitdata);
  732. }
  733. bool ssh_is_bare(Ssh *ssh)
  734. {
  735. return ssh->backend.vt->protocol == PROT_SSHCONN;
  736. }
  737. /* Dummy connlayer must provide ssh_sharing_no_more_downstreams,
  738. * because it might be called early due to plink -shareexists */
  739. static void dummy_sharing_no_more_downstreams(ConnectionLayer *cl) {}
  740. static const ConnectionLayerVtable dummy_connlayer_vtable = {
  741. .sharing_no_more_downstreams = dummy_sharing_no_more_downstreams,
  742. };
  743. /*
  744. * Called to set up the connection.
  745. *
  746. * Returns an error message, or NULL on success.
  747. */
  748. static char *ssh_init(const BackendVtable *vt, Seat *seat,
  749. Backend **backend_handle, LogContext *logctx,
  750. Conf *conf, const char *host, int port,
  751. char **realhost, bool nodelay, bool keepalive)
  752. {
  753. Ssh *ssh;
  754. ssh = snew(Ssh);
  755. memset(ssh, 0, sizeof(Ssh));
  756. ssh->conf = conf_copy(conf);
  757. ssh_cache_conf_values(ssh);
  758. ssh->exitcode = -1;
  759. ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
  760. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  761. bufchain_init(&ssh->in_raw);
  762. bufchain_init(&ssh->out_raw);
  763. bufchain_init(&ssh->user_input);
  764. ssh->ic_out_raw.fn = ssh_bpp_output_raw_data_callback;
  765. ssh->ic_out_raw.ctx = ssh;
  766. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  767. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  768. ssh->backend.vt = vt;
  769. *backend_handle = &ssh->backend;
  770. ssh->bare_connection = (vt->protocol == PROT_SSHCONN);
  771. ssh->seat = seat;
  772. ssh->cl_dummy.vt = &dummy_connlayer_vtable;
  773. ssh->cl_dummy.logctx = ssh->logctx = logctx;
  774. random_ref(); /* do this now - may be needed by sharing setup code */
  775. ssh->need_random_unref = true;
  776. char *conn_err = connect_to_host(
  777. ssh, host, port, realhost, nodelay, keepalive);
  778. if (conn_err) {
  779. /* Call random_unref now instead of waiting until the caller
  780. * frees this useless Ssh object, in case the caller is
  781. * impatient and just exits without bothering, in which case
  782. * the random seed won't be re-saved. */
  783. ssh->need_random_unref = false;
  784. random_unref();
  785. return conn_err;
  786. }
  787. return NULL;
  788. }
  789. static void ssh_free(Backend *be)
  790. {
  791. Ssh *ssh = container_of(be, Ssh, backend);
  792. bool need_random_unref;
  793. ssh_shutdown(ssh);
  794. conf_free(ssh->conf);
  795. if (ssh->connshare)
  796. sharestate_free(ssh->connshare);
  797. sfree(ssh->savedhost);
  798. sfree(ssh->fullhostname);
  799. sfree(ssh->specials);
  800. #ifndef NO_GSSAPI
  801. if (ssh->gss_state.srv_name)
  802. ssh->gss_state.lib->release_name(
  803. ssh->gss_state.lib, &ssh->gss_state.srv_name);
  804. if (ssh->gss_state.ctx != NULL)
  805. ssh->gss_state.lib->release_cred(
  806. ssh->gss_state.lib, &ssh->gss_state.ctx);
  807. if (ssh->gss_state.libs)
  808. ssh_gss_cleanup(ssh->gss_state.libs);
  809. #endif
  810. sfree(ssh->deferred_abort_message);
  811. delete_callbacks_for_context(ssh); /* likely to catch ic_out_raw */
  812. need_random_unref = ssh->need_random_unref;
  813. sfree(ssh);
  814. if (need_random_unref)
  815. random_unref();
  816. }
  817. /*
  818. * Reconfigure the SSH backend.
  819. */
  820. static void ssh_reconfig(Backend *be, Conf *conf)
  821. {
  822. Ssh *ssh = container_of(be, Ssh, backend);
  823. if (ssh->pinger)
  824. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  825. ssh_ppl_reconfigure(ssh->base_layer, conf);
  826. conf_free(ssh->conf);
  827. ssh->conf = conf_copy(conf);
  828. ssh_cache_conf_values(ssh);
  829. }
  830. /*
  831. * Called to send data down the SSH connection.
  832. */
  833. static size_t ssh_send(Backend *be, const char *buf, size_t len)
  834. {
  835. Ssh *ssh = container_of(be, Ssh, backend);
  836. if (ssh == NULL || ssh->s == NULL)
  837. return 0;
  838. bufchain_add(&ssh->user_input, buf, len);
  839. if (ssh->base_layer)
  840. ssh_ppl_got_user_input(ssh->base_layer);
  841. return backend_sendbuffer(&ssh->backend);
  842. }
  843. /*
  844. * Called to query the current amount of buffered stdin data.
  845. */
  846. static size_t ssh_sendbuffer(Backend *be)
  847. {
  848. Ssh *ssh = container_of(be, Ssh, backend);
  849. size_t backlog;
  850. if (!ssh || !ssh->s || !ssh->cl)
  851. return 0;
  852. backlog = ssh_stdin_backlog(ssh->cl);
  853. if (ssh->base_layer)
  854. backlog += ssh_ppl_queued_data_size(ssh->base_layer);
  855. /*
  856. * If the SSH socket itself has backed up, add the total backup
  857. * size on that to any individual buffer on the stdin channel.
  858. */
  859. if (ssh->throttled_all)
  860. backlog += ssh->overall_bufsize;
  861. return backlog;
  862. }
  863. /*
  864. * Called to set the size of the window from SSH's POV.
  865. */
  866. static void ssh_size(Backend *be, int width, int height)
  867. {
  868. Ssh *ssh = container_of(be, Ssh, backend);
  869. ssh->term_width = width;
  870. ssh->term_height = height;
  871. if (ssh->cl)
  872. ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
  873. }
  874. struct ssh_add_special_ctx {
  875. SessionSpecial *specials;
  876. size_t nspecials, specials_size;
  877. };
  878. static void ssh_add_special(void *vctx, const char *text,
  879. SessionSpecialCode code, int arg)
  880. {
  881. struct ssh_add_special_ctx *ctx = (struct ssh_add_special_ctx *)vctx;
  882. SessionSpecial *spec;
  883. sgrowarray(ctx->specials, ctx->specials_size, ctx->nspecials);
  884. spec = &ctx->specials[ctx->nspecials++];
  885. spec->name = text;
  886. spec->code = code;
  887. spec->arg = arg;
  888. }
  889. /*
  890. * Return a list of the special codes that make sense in this
  891. * protocol.
  892. */
  893. static const SessionSpecial *ssh_get_specials(Backend *be)
  894. {
  895. Ssh *ssh = container_of(be, Ssh, backend);
  896. /*
  897. * Ask all our active protocol layers what specials they've got,
  898. * and amalgamate the list into one combined one.
  899. */
  900. struct ssh_add_special_ctx ctx[1];
  901. ctx->specials = NULL;
  902. ctx->nspecials = ctx->specials_size = 0;
  903. if (ssh->base_layer)
  904. ssh_ppl_get_specials(ssh->base_layer, ssh_add_special, ctx);
  905. if (ctx->specials) {
  906. /* If the list is non-empty, terminate it with a SS_EXITMENU. */
  907. ssh_add_special(ctx, NULL, SS_EXITMENU, 0);
  908. }
  909. sfree(ssh->specials);
  910. ssh->specials = ctx->specials;
  911. return ssh->specials;
  912. }
  913. /*
  914. * Send special codes.
  915. */
  916. static void ssh_special(Backend *be, SessionSpecialCode code, int arg)
  917. {
  918. Ssh *ssh = container_of(be, Ssh, backend);
  919. if (ssh->base_layer)
  920. ssh_ppl_special_cmd(ssh->base_layer, code, arg);
  921. }
  922. /*
  923. * This is called when the seat's output channel manages to clear some
  924. * backlog.
  925. */
  926. static void ssh_unthrottle(Backend *be, size_t bufsize)
  927. {
  928. Ssh *ssh = container_of(be, Ssh, backend);
  929. if (ssh->cl)
  930. ssh_stdout_unthrottle(ssh->cl, bufsize);
  931. }
  932. static bool ssh_connected(Backend *be)
  933. {
  934. Ssh *ssh = container_of(be, Ssh, backend);
  935. return ssh->s != NULL;
  936. }
  937. static bool ssh_sendok(Backend *be)
  938. {
  939. Ssh *ssh = container_of(be, Ssh, backend);
  940. return ssh->base_layer && ssh_ppl_want_user_input(ssh->base_layer);
  941. }
  942. void ssh_ldisc_update(Ssh *ssh)
  943. {
  944. /* Called when the connection layer wants to propagate an update
  945. * to the line discipline options */
  946. if (ssh->ldisc)
  947. ldisc_echoedit_update(ssh->ldisc);
  948. }
  949. static bool ssh_ldisc(Backend *be, int option)
  950. {
  951. Ssh *ssh = container_of(be, Ssh, backend);
  952. return ssh->cl ? ssh_ldisc_option(ssh->cl, option) : false;
  953. }
  954. static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
  955. {
  956. Ssh *ssh = container_of(be, Ssh, backend);
  957. ssh->ldisc = ldisc;
  958. }
  959. void ssh_got_exitcode(Ssh *ssh, int exitcode)
  960. {
  961. ssh->exitcode = exitcode;
  962. }
  963. static int ssh_return_exitcode(Backend *be)
  964. {
  965. Ssh *ssh = container_of(be, Ssh, backend);
  966. if (ssh->s && (!ssh->session_started || ssh->base_layer))
  967. return -1;
  968. else
  969. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  970. }
  971. /*
  972. * cfg_info for SSH is the protocol running in this session.
  973. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  974. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  975. */
  976. static int ssh_cfg_info(Backend *be)
  977. {
  978. Ssh *ssh = container_of(be, Ssh, backend);
  979. if (ssh->version == 0)
  980. return 0; /* don't know yet */
  981. else if (ssh->bare_connection)
  982. return -1;
  983. else
  984. return ssh->version;
  985. }
  986. /*
  987. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  988. * that fails. This variable is the means by which scp.c can reach
  989. * into the SSH code and find out which one it got.
  990. */
  991. extern bool ssh_fallback_cmd(Backend *be)
  992. {
  993. Ssh *ssh = container_of(be, Ssh, backend);
  994. return ssh->fallback_cmd;
  995. }
  996. void ssh_got_fallback_cmd(Ssh *ssh)
  997. {
  998. ssh->fallback_cmd = true;
  999. }
  1000. const BackendVtable ssh_backend = {
  1001. .init = ssh_init,
  1002. .free = ssh_free,
  1003. .reconfig = ssh_reconfig,
  1004. .send = ssh_send,
  1005. .sendbuffer = ssh_sendbuffer,
  1006. .size = ssh_size,
  1007. .special = ssh_special,
  1008. .get_specials = ssh_get_specials,
  1009. .connected = ssh_connected,
  1010. .exitcode = ssh_return_exitcode,
  1011. .sendok = ssh_sendok,
  1012. .ldisc_option_state = ssh_ldisc,
  1013. .provide_ldisc = ssh_provide_ldisc,
  1014. .unthrottle = ssh_unthrottle,
  1015. .cfg_info = ssh_cfg_info,
  1016. .test_for_upstream = ssh_test_for_upstream,
  1017. .close_warn_text = ssh_close_warn_text,
  1018. .id = "ssh",
  1019. .displayname = "SSH",
  1020. .protocol = PROT_SSH,
  1021. .default_port = 22,
  1022. };
  1023. const BackendVtable sshconn_backend = {
  1024. .init = ssh_init,
  1025. .free = ssh_free,
  1026. .reconfig = ssh_reconfig,
  1027. .send = ssh_send,
  1028. .sendbuffer = ssh_sendbuffer,
  1029. .size = ssh_size,
  1030. .special = ssh_special,
  1031. .get_specials = ssh_get_specials,
  1032. .connected = ssh_connected,
  1033. .exitcode = ssh_return_exitcode,
  1034. .sendok = ssh_sendok,
  1035. .ldisc_option_state = ssh_ldisc,
  1036. .provide_ldisc = ssh_provide_ldisc,
  1037. .unthrottle = ssh_unthrottle,
  1038. .cfg_info = ssh_cfg_info,
  1039. .test_for_upstream = ssh_test_for_upstream,
  1040. .close_warn_text = ssh_close_warn_text,
  1041. .id = "ssh-connection",
  1042. .displayname = "Bare ssh-connection",
  1043. .protocol = PROT_SSHCONN,
  1044. };