ssh.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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, NULL, false, ssh->conf, ssh_verstring_get_remote(old_bpp),
  264. &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 ssh_remote_error(Ssh *ssh, const char *fmt, ...)
  381. {
  382. if (ssh->base_layer || !ssh->session_started) {
  383. GET_FORMATTED_MSG;
  384. /* Error messages sent by the remote don't count as clean exits */
  385. ssh->exitcode = 128;
  386. /* Close the socket immediately, since the server has already
  387. * closed its end (or is about to). */
  388. ssh_shutdown(ssh);
  389. logevent(ssh->logctx, msg);
  390. seat_connection_fatal(ssh->seat, "%s", msg);
  391. sfree(msg);
  392. }
  393. }
  394. void ssh_remote_eof(Ssh *ssh, const char *fmt, ...)
  395. {
  396. if (ssh->base_layer || !ssh->session_started) {
  397. GET_FORMATTED_MSG;
  398. /* EOF from the remote, if we were expecting it, does count as
  399. * a clean exit */
  400. ssh->exitcode = 0;
  401. /* Close the socket immediately, since the server has already
  402. * closed its end. */
  403. ssh_shutdown(ssh);
  404. logevent(ssh->logctx, msg);
  405. sfree(msg);
  406. seat_notify_remote_exit(ssh->seat);
  407. } else {
  408. /* This is responding to EOF after we've already seen some
  409. * other reason for terminating the session. */
  410. ssh_shutdown(ssh);
  411. }
  412. }
  413. void ssh_proto_error(Ssh *ssh, const char *fmt, ...)
  414. {
  415. if (ssh->base_layer || !ssh->session_started) {
  416. GET_FORMATTED_MSG;
  417. ssh->exitcode = 128;
  418. ssh_bpp_queue_disconnect(ssh->bpp, msg,
  419. SSH2_DISCONNECT_PROTOCOL_ERROR);
  420. ssh_initiate_connection_close(ssh);
  421. logevent(ssh->logctx, msg);
  422. seat_connection_fatal(ssh->seat, "%s", msg);
  423. sfree(msg);
  424. }
  425. }
  426. void ssh_sw_abort(Ssh *ssh, const char *fmt, ...)
  427. {
  428. if (ssh->base_layer || !ssh->session_started) {
  429. GET_FORMATTED_MSG;
  430. ssh->exitcode = 128;
  431. ssh_initiate_connection_close(ssh);
  432. logevent(ssh->logctx, msg);
  433. seat_connection_fatal(ssh->seat, "%s", msg);
  434. sfree(msg);
  435. seat_notify_remote_exit(ssh->seat);
  436. }
  437. }
  438. void ssh_user_close(Ssh *ssh, const char *fmt, ...)
  439. {
  440. if (ssh->base_layer || !ssh->session_started) {
  441. GET_FORMATTED_MSG;
  442. /* Closing the connection due to user action, even if the
  443. * action is the user aborting during authentication prompts,
  444. * does count as a clean exit - except that this is also how
  445. * we signal ordinary session termination, in which case we
  446. * should use the exit status already sent from the main
  447. * session (if any). */
  448. if (ssh->exitcode < 0)
  449. ssh->exitcode = 0;
  450. ssh_initiate_connection_close(ssh);
  451. logevent(ssh->logctx, msg);
  452. sfree(msg);
  453. seat_notify_remote_exit(ssh->seat);
  454. }
  455. }
  456. void ssh_deferred_abort_callback(void *vctx)
  457. {
  458. Ssh *ssh = (Ssh *)vctx;
  459. char *msg = ssh->deferred_abort_message;
  460. ssh->deferred_abort_message = NULL;
  461. ssh_sw_abort(ssh, msg);
  462. sfree(msg);
  463. }
  464. void ssh_sw_abort_deferred(Ssh *ssh, const char *fmt, ...)
  465. {
  466. if (!ssh->deferred_abort_message) {
  467. GET_FORMATTED_MSG;
  468. ssh->deferred_abort_message = msg;
  469. queue_toplevel_callback(ssh_deferred_abort_callback, ssh);
  470. }
  471. }
  472. static void ssh_socket_log(Plug *plug, int type, SockAddr *addr, int port,
  473. const char *error_msg, int error_code)
  474. {
  475. Ssh *ssh = container_of(plug, Ssh, plug);
  476. /*
  477. * While we're attempting connection sharing, don't loudly log
  478. * everything that happens. Real TCP connections need to be logged
  479. * when we _start_ trying to connect, because it might be ages
  480. * before they respond if something goes wrong; but connection
  481. * sharing is local and quick to respond, and it's sufficient to
  482. * simply wait and see whether it worked afterwards.
  483. */
  484. if (!ssh->attempting_connshare)
  485. backend_socket_log(ssh->seat, ssh->logctx, type, addr, port,
  486. error_msg, error_code, ssh->conf,
  487. ssh->session_started);
  488. }
  489. static void ssh_closing(Plug *plug, const char *error_msg, int error_code,
  490. bool calling_back)
  491. {
  492. Ssh *ssh = container_of(plug, Ssh, plug);
  493. if (error_msg) {
  494. ssh_remote_error(ssh, "%s", error_msg);
  495. } else if (ssh->bpp) {
  496. ssh->bpp->input_eof = true;
  497. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  498. }
  499. }
  500. static void ssh_receive(Plug *plug, int urgent, const char *data, size_t len)
  501. {
  502. Ssh *ssh = container_of(plug, Ssh, plug);
  503. /* Log raw data, if we're in that mode. */
  504. if (ssh->logctx)
  505. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len,
  506. 0, NULL, NULL, 0, NULL);
  507. bufchain_add(&ssh->in_raw, data, len);
  508. if (!ssh->logically_frozen && ssh->bpp)
  509. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  510. ssh_check_frozen(ssh);
  511. }
  512. static void ssh_sent(Plug *plug, size_t bufsize)
  513. {
  514. Ssh *ssh = container_of(plug, Ssh, plug);
  515. /*
  516. * If the send backlog on the SSH socket itself clears, we should
  517. * unthrottle the whole world if it was throttled. Also trigger an
  518. * extra call to the consumer of the BPP's output, to try to send
  519. * some more data off its bufchain.
  520. */
  521. if (bufsize < SSH_MAX_BACKLOG) {
  522. ssh_throttle_all(ssh, false, bufsize);
  523. queue_idempotent_callback(&ssh->ic_out_raw);
  524. }
  525. }
  526. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  527. char **savedhost, int *savedport,
  528. char **loghost_ret)
  529. {
  530. char *loghost = conf_get_str(conf, CONF_loghost);
  531. if (loghost_ret)
  532. *loghost_ret = loghost;
  533. if (*loghost) {
  534. char *tmphost;
  535. char *colon;
  536. tmphost = dupstr(loghost);
  537. *savedport = 22; /* default ssh port */
  538. /*
  539. * A colon suffix on the hostname string also lets us affect
  540. * savedport. (Unless there are multiple colons, in which case
  541. * we assume this is an unbracketed IPv6 literal.)
  542. */
  543. colon = host_strrchr(tmphost, ':');
  544. if (colon && colon == host_strchr(tmphost, ':')) {
  545. *colon++ = '\0';
  546. if (*colon)
  547. *savedport = atoi(colon);
  548. }
  549. *savedhost = host_strduptrim(tmphost);
  550. sfree(tmphost);
  551. } else {
  552. *savedhost = host_strduptrim(host);
  553. if (port < 0)
  554. port = 22; /* default ssh port */
  555. *savedport = port;
  556. }
  557. }
  558. static bool ssh_test_for_upstream(const char *host, int port, Conf *conf)
  559. {
  560. char *savedhost;
  561. int savedport;
  562. bool ret;
  563. random_ref(); /* platform may need this to determine share socket name */
  564. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  565. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  566. sfree(savedhost);
  567. random_unref();
  568. return ret;
  569. }
  570. static const PlugVtable Ssh_plugvt = {
  571. ssh_socket_log,
  572. ssh_closing,
  573. ssh_receive,
  574. ssh_sent,
  575. NULL
  576. };
  577. /*
  578. * Connect to specified host and port.
  579. * Returns an error message, or NULL on success.
  580. * Also places the canonical host name into `realhost'. It must be
  581. * freed by the caller.
  582. */
  583. static const char *connect_to_host(
  584. Ssh *ssh, const char *host, int port, char **realhost,
  585. bool nodelay, bool keepalive)
  586. {
  587. SockAddr *addr;
  588. const char *err;
  589. char *loghost;
  590. int addressfamily, sshprot;
  591. ssh_hostport_setup(host, port, ssh->conf,
  592. &ssh->savedhost, &ssh->savedport, &loghost);
  593. ssh->plug.vt = &Ssh_plugvt;
  594. /*
  595. * Try connection-sharing, in case that means we don't open a
  596. * socket after all. ssh_connection_sharing_init will connect to a
  597. * previously established upstream if it can, and failing that,
  598. * establish a listening socket for _us_ to be the upstream. In
  599. * the latter case it will return NULL just as if it had done
  600. * nothing, because here we only need to care if we're a
  601. * downstream and need to do our connection setup differently.
  602. */
  603. ssh->connshare = NULL;
  604. ssh->attempting_connshare = true; /* affects socket logging behaviour */
  605. ssh->s = ssh_connection_sharing_init(
  606. ssh->savedhost, ssh->savedport, ssh->conf, ssh->logctx,
  607. &ssh->plug, &ssh->connshare);
  608. if (ssh->connshare)
  609. ssh_connshare_provide_connlayer(ssh->connshare, &ssh->cl_dummy);
  610. ssh->attempting_connshare = false;
  611. if (ssh->s != NULL) {
  612. /*
  613. * We are a downstream.
  614. */
  615. ssh->bare_connection = true;
  616. ssh->fullhostname = NULL;
  617. *realhost = dupstr(host); /* best we can do */
  618. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  619. /* In an interactive session, or in verbose mode, announce
  620. * in the console window that we're a sharing downstream,
  621. * to avoid confusing users as to why this session doesn't
  622. * behave in quite the usual way. */
  623. const char *msg =
  624. "Reusing a shared connection to this server.\r\n";
  625. seat_stderr_pl(ssh->seat, ptrlen_from_asciz(msg));
  626. }
  627. } else {
  628. /*
  629. * We're not a downstream, so open a normal socket.
  630. */
  631. /*
  632. * Try to find host.
  633. */
  634. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  635. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  636. ssh->logctx, "SSH connection");
  637. if ((err = sk_addr_error(addr)) != NULL) {
  638. sk_addr_free(addr);
  639. return err;
  640. }
  641. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  642. ssh->s = new_connection(addr, *realhost, port,
  643. false, true, nodelay, keepalive,
  644. &ssh->plug, ssh->conf);
  645. if ((err = sk_socket_error(ssh->s)) != NULL) {
  646. ssh->s = NULL;
  647. seat_notify_remote_exit(ssh->seat);
  648. return err;
  649. }
  650. }
  651. /*
  652. * The SSH version number is always fixed (since we no longer support
  653. * fallback between versions), so set it now.
  654. */
  655. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  656. assert(sshprot == 0 || sshprot == 3);
  657. if (sshprot == 0)
  658. /* SSH-1 only */
  659. ssh->version = 1;
  660. if (sshprot == 3 || ssh->bare_connection) {
  661. /* SSH-2 only */
  662. ssh->version = 2;
  663. }
  664. /*
  665. * Set up the initial BPP that will do the version string
  666. * exchange, and get it started so that it can send the outgoing
  667. * version string early if it wants to.
  668. */
  669. ssh->version_receiver.got_ssh_version = ssh_got_ssh_version;
  670. ssh->bpp = ssh_verstring_new(
  671. ssh->conf, ssh->logctx, ssh->bare_connection,
  672. ssh->version == 1 ? "1.5" : "2.0", &ssh->version_receiver,
  673. false, "PuTTY");
  674. ssh_connect_bpp(ssh);
  675. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  676. /*
  677. * loghost, if configured, overrides realhost.
  678. */
  679. if (*loghost) {
  680. sfree(*realhost);
  681. *realhost = dupstr(loghost);
  682. }
  683. return NULL;
  684. }
  685. /*
  686. * Throttle or unthrottle the SSH connection.
  687. */
  688. void ssh_throttle_conn(Ssh *ssh, int adjust)
  689. {
  690. int old_count = ssh->conn_throttle_count;
  691. bool frozen;
  692. ssh->conn_throttle_count += adjust;
  693. assert(ssh->conn_throttle_count >= 0);
  694. if (ssh->conn_throttle_count && !old_count) {
  695. frozen = true;
  696. } else if (!ssh->conn_throttle_count && old_count) {
  697. frozen = false;
  698. } else {
  699. return; /* don't change current frozen state */
  700. }
  701. ssh->logically_frozen = frozen;
  702. ssh_check_frozen(ssh);
  703. }
  704. /*
  705. * Throttle or unthrottle _all_ local data streams (for when sends
  706. * on the SSH connection itself back up).
  707. */
  708. static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize)
  709. {
  710. if (enable == ssh->throttled_all)
  711. return;
  712. ssh->throttled_all = enable;
  713. ssh->overall_bufsize = bufsize;
  714. ssh_throttle_all_channels(ssh->cl, enable);
  715. }
  716. static void ssh_cache_conf_values(Ssh *ssh)
  717. {
  718. ssh->pls.omit_passwords = conf_get_bool(ssh->conf, CONF_logomitpass);
  719. ssh->pls.omit_data = conf_get_bool(ssh->conf, CONF_logomitdata);
  720. }
  721. /*
  722. * Called to set up the connection.
  723. *
  724. * Returns an error message, or NULL on success.
  725. */
  726. static const char *ssh_init(Seat *seat, Backend **backend_handle,
  727. LogContext *logctx, Conf *conf,
  728. const char *host, int port, char **realhost,
  729. bool nodelay, bool keepalive)
  730. {
  731. const char *p;
  732. Ssh *ssh;
  733. ssh = snew(Ssh);
  734. memset(ssh, 0, sizeof(Ssh));
  735. ssh->conf = conf_copy(conf);
  736. ssh_cache_conf_values(ssh);
  737. ssh->exitcode = -1;
  738. ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
  739. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  740. bufchain_init(&ssh->in_raw);
  741. bufchain_init(&ssh->out_raw);
  742. bufchain_init(&ssh->user_input);
  743. ssh->ic_out_raw.fn = ssh_bpp_output_raw_data_callback;
  744. ssh->ic_out_raw.ctx = ssh;
  745. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  746. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  747. ssh->backend.vt = &ssh_backend;
  748. *backend_handle = &ssh->backend;
  749. ssh->seat = seat;
  750. ssh->cl_dummy.logctx = ssh->logctx = logctx;
  751. random_ref(); /* do this now - may be needed by sharing setup code */
  752. ssh->need_random_unref = true;
  753. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  754. if (p != NULL) {
  755. /* Call random_unref now instead of waiting until the caller
  756. * frees this useless Ssh object, in case the caller is
  757. * impatient and just exits without bothering, in which case
  758. * the random seed won't be re-saved. */
  759. ssh->need_random_unref = false;
  760. random_unref();
  761. return p;
  762. }
  763. return NULL;
  764. }
  765. static void ssh_free(Backend *be)
  766. {
  767. Ssh *ssh = container_of(be, Ssh, backend);
  768. bool need_random_unref;
  769. ssh_shutdown(ssh);
  770. conf_free(ssh->conf);
  771. if (ssh->connshare)
  772. sharestate_free(ssh->connshare);
  773. sfree(ssh->savedhost);
  774. sfree(ssh->fullhostname);
  775. sfree(ssh->specials);
  776. #ifndef NO_GSSAPI
  777. if (ssh->gss_state.srv_name)
  778. ssh->gss_state.lib->release_name(
  779. ssh->gss_state.lib, &ssh->gss_state.srv_name);
  780. if (ssh->gss_state.ctx != NULL)
  781. ssh->gss_state.lib->release_cred(
  782. ssh->gss_state.lib, &ssh->gss_state.ctx);
  783. if (ssh->gss_state.libs)
  784. ssh_gss_cleanup(ssh->gss_state.libs);
  785. #endif
  786. sfree(ssh->deferred_abort_message);
  787. delete_callbacks_for_context(ssh); /* likely to catch ic_out_raw */
  788. need_random_unref = ssh->need_random_unref;
  789. sfree(ssh);
  790. if (need_random_unref)
  791. random_unref();
  792. }
  793. /*
  794. * Reconfigure the SSH backend.
  795. */
  796. static void ssh_reconfig(Backend *be, Conf *conf)
  797. {
  798. Ssh *ssh = container_of(be, Ssh, backend);
  799. if (ssh->pinger)
  800. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  801. ssh_ppl_reconfigure(ssh->base_layer, conf);
  802. conf_free(ssh->conf);
  803. ssh->conf = conf_copy(conf);
  804. ssh_cache_conf_values(ssh);
  805. }
  806. /*
  807. * Called to send data down the SSH connection.
  808. */
  809. static size_t ssh_send(Backend *be, const char *buf, size_t len)
  810. {
  811. Ssh *ssh = container_of(be, Ssh, backend);
  812. if (ssh == NULL || ssh->s == NULL)
  813. return 0;
  814. bufchain_add(&ssh->user_input, buf, len);
  815. if (ssh->base_layer)
  816. ssh_ppl_got_user_input(ssh->base_layer);
  817. return backend_sendbuffer(&ssh->backend);
  818. }
  819. /*
  820. * Called to query the current amount of buffered stdin data.
  821. */
  822. static size_t ssh_sendbuffer(Backend *be)
  823. {
  824. Ssh *ssh = container_of(be, Ssh, backend);
  825. size_t backlog;
  826. if (!ssh || !ssh->s || !ssh->cl)
  827. return 0;
  828. backlog = ssh_stdin_backlog(ssh->cl);
  829. /* FIXME: also include sizes of pqs */
  830. /*
  831. * If the SSH socket itself has backed up, add the total backup
  832. * size on that to any individual buffer on the stdin channel.
  833. */
  834. if (ssh->throttled_all)
  835. backlog += ssh->overall_bufsize;
  836. return backlog;
  837. }
  838. /*
  839. * Called to set the size of the window from SSH's POV.
  840. */
  841. static void ssh_size(Backend *be, int width, int height)
  842. {
  843. Ssh *ssh = container_of(be, Ssh, backend);
  844. ssh->term_width = width;
  845. ssh->term_height = height;
  846. if (ssh->cl)
  847. ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
  848. }
  849. struct ssh_add_special_ctx {
  850. SessionSpecial *specials;
  851. size_t nspecials, specials_size;
  852. };
  853. static void ssh_add_special(void *vctx, const char *text,
  854. SessionSpecialCode code, int arg)
  855. {
  856. struct ssh_add_special_ctx *ctx = (struct ssh_add_special_ctx *)vctx;
  857. SessionSpecial *spec;
  858. sgrowarray(ctx->specials, ctx->specials_size, ctx->nspecials);
  859. spec = &ctx->specials[ctx->nspecials++];
  860. spec->name = text;
  861. spec->code = code;
  862. spec->arg = arg;
  863. }
  864. /*
  865. * Return a list of the special codes that make sense in this
  866. * protocol.
  867. */
  868. static const SessionSpecial *ssh_get_specials(Backend *be)
  869. {
  870. Ssh *ssh = container_of(be, Ssh, backend);
  871. /*
  872. * Ask all our active protocol layers what specials they've got,
  873. * and amalgamate the list into one combined one.
  874. */
  875. struct ssh_add_special_ctx ctx;
  876. ctx.specials = NULL;
  877. ctx.nspecials = ctx.specials_size = 0;
  878. if (ssh->base_layer)
  879. ssh_ppl_get_specials(ssh->base_layer, ssh_add_special, &ctx);
  880. if (ctx.specials) {
  881. /* If the list is non-empty, terminate it with a SS_EXITMENU. */
  882. ssh_add_special(&ctx, NULL, SS_EXITMENU, 0);
  883. }
  884. sfree(ssh->specials);
  885. ssh->specials = ctx.specials;
  886. return ssh->specials;
  887. }
  888. /*
  889. * Send special codes.
  890. */
  891. static void ssh_special(Backend *be, SessionSpecialCode code, int arg)
  892. {
  893. Ssh *ssh = container_of(be, Ssh, backend);
  894. if (ssh->base_layer)
  895. ssh_ppl_special_cmd(ssh->base_layer, code, arg);
  896. }
  897. /*
  898. * This is called when the seat's output channel manages to clear some
  899. * backlog.
  900. */
  901. static void ssh_unthrottle(Backend *be, size_t bufsize)
  902. {
  903. Ssh *ssh = container_of(be, Ssh, backend);
  904. if (ssh->cl)
  905. ssh_stdout_unthrottle(ssh->cl, bufsize);
  906. }
  907. static bool ssh_connected(Backend *be)
  908. {
  909. Ssh *ssh = container_of(be, Ssh, backend);
  910. return ssh->s != NULL;
  911. }
  912. static bool ssh_sendok(Backend *be)
  913. {
  914. Ssh *ssh = container_of(be, Ssh, backend);
  915. return ssh->base_layer && ssh_ppl_want_user_input(ssh->base_layer);
  916. }
  917. void ssh_ldisc_update(Ssh *ssh)
  918. {
  919. /* Called when the connection layer wants to propagate an update
  920. * to the line discipline options */
  921. if (ssh->ldisc)
  922. ldisc_echoedit_update(ssh->ldisc);
  923. }
  924. static bool ssh_ldisc(Backend *be, int option)
  925. {
  926. Ssh *ssh = container_of(be, Ssh, backend);
  927. return ssh->cl ? ssh_ldisc_option(ssh->cl, option) : false;
  928. }
  929. static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
  930. {
  931. Ssh *ssh = container_of(be, Ssh, backend);
  932. ssh->ldisc = ldisc;
  933. }
  934. void ssh_got_exitcode(Ssh *ssh, int exitcode)
  935. {
  936. ssh->exitcode = exitcode;
  937. }
  938. static int ssh_return_exitcode(Backend *be)
  939. {
  940. Ssh *ssh = container_of(be, Ssh, backend);
  941. if (ssh->s && (!ssh->session_started || ssh->base_layer))
  942. return -1;
  943. else
  944. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  945. }
  946. /*
  947. * cfg_info for SSH is the protocol running in this session.
  948. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  949. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  950. */
  951. static int ssh_cfg_info(Backend *be)
  952. {
  953. Ssh *ssh = container_of(be, Ssh, backend);
  954. if (ssh->version == 0)
  955. return 0; /* don't know yet */
  956. else if (ssh->bare_connection)
  957. return -1;
  958. else
  959. return ssh->version;
  960. }
  961. /*
  962. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  963. * that fails. This variable is the means by which scp.c can reach
  964. * into the SSH code and find out which one it got.
  965. */
  966. extern bool ssh_fallback_cmd(Backend *be)
  967. {
  968. Ssh *ssh = container_of(be, Ssh, backend);
  969. return ssh->fallback_cmd;
  970. }
  971. void ssh_got_fallback_cmd(Ssh *ssh)
  972. {
  973. ssh->fallback_cmd = true;
  974. }
  975. const struct BackendVtable ssh_backend = {
  976. ssh_init,
  977. ssh_free,
  978. ssh_reconfig,
  979. ssh_send,
  980. ssh_sendbuffer,
  981. ssh_size,
  982. ssh_special,
  983. ssh_get_specials,
  984. ssh_connected,
  985. ssh_return_exitcode,
  986. ssh_sendok,
  987. ssh_ldisc,
  988. ssh_provide_ldisc,
  989. ssh_unthrottle,
  990. ssh_cfg_info,
  991. ssh_test_for_upstream,
  992. "ssh",
  993. PROT_SSH,
  994. 22
  995. };