ssh.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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, ssh->logctx); // WINSCP
  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. ,conf_get_str(ssh->conf, CONF_loghost),
  231. conf_get_bool(ssh->conf, CONF_change_password) // WINSCP
  232. );
  233. ssh_connect_ppl(ssh, userauth_layer);
  234. transport_child_layer = userauth_layer;
  235. sfree(username);
  236. }
  237. ssh->base_layer = ssh2_transport_new(
  238. ssh->conf, ssh->savedhost, ssh->savedport,
  239. ssh->fullhostname,
  240. ssh_verstring_get_local(old_bpp),
  241. ssh_verstring_get_remote(old_bpp),
  242. #ifndef NO_GSSAPI
  243. &ssh->gss_state,
  244. #else
  245. NULL,
  246. #endif
  247. &ssh->stats, transport_child_layer, NULL);
  248. ssh_connect_ppl(ssh, ssh->base_layer);
  249. if (userauth_layer)
  250. ssh2_userauth_set_transport_layer(userauth_layer,
  251. ssh->base_layer);
  252. } else {
  253. ssh->bpp = ssh1_bpp_new(ssh->logctx);
  254. ssh_connect_bpp(ssh);
  255. connection_layer = ssh1_connection_new(ssh, ssh->conf, &ssh->cl);
  256. ssh_connect_ppl(ssh, connection_layer);
  257. ssh->base_layer = ssh1_login_new(
  258. ssh->conf, ssh->savedhost, ssh->savedport, connection_layer);
  259. ssh_connect_ppl(ssh, ssh->base_layer);
  260. }
  261. } else {
  262. ssh->bpp = ssh2_bare_bpp_new(ssh->logctx);
  263. ssh_connect_bpp(ssh);
  264. connection_layer = ssh2_connection_new(
  265. ssh, NULL, false, ssh->conf, ssh_verstring_get_remote(old_bpp),
  266. &ssh->cl);
  267. ssh_connect_ppl(ssh, connection_layer);
  268. ssh->base_layer = connection_layer;
  269. }
  270. /* Connect the base layer - whichever it is - to the BPP, and set
  271. * up its selfptr. */
  272. ssh->base_layer->selfptr = &ssh->base_layer;
  273. ssh_ppl_setup_queues(ssh->base_layer, &ssh->bpp->in_pq, &ssh->bpp->out_pq);
  274. seat_update_specials_menu(ssh->seat);
  275. ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
  276. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  277. ssh_ppl_process_queue(ssh->base_layer);
  278. /* Pass in the initial terminal size, if we knew it already. */
  279. ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
  280. ssh_bpp_free(old_bpp);
  281. }
  282. void ssh_check_frozen(Ssh *ssh)
  283. {
  284. if (!ssh->s)
  285. return;
  286. { // WINSCP
  287. bool prev_frozen = ssh->socket_frozen;
  288. ssh->socket_frozen = (ssh->logically_frozen ||
  289. bufchain_size(&ssh->in_raw) > SSH_MAX_BACKLOG);
  290. sk_set_frozen(ssh->s, ssh->socket_frozen);
  291. if (prev_frozen && !ssh->socket_frozen && ssh->bpp) {
  292. /*
  293. * If we've just unfrozen, process any SSH connection data
  294. * that was stashed in our queue while we were frozen.
  295. */
  296. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  297. }
  298. } // WINSCP
  299. }
  300. void ssh_conn_processed_data(Ssh *ssh)
  301. {
  302. ssh_check_frozen(ssh);
  303. }
  304. static void ssh_bpp_output_raw_data_callback(void *vctx)
  305. {
  306. Ssh *ssh = (Ssh *)vctx;
  307. if (!ssh->s)
  308. return;
  309. while (bufchain_size(&ssh->out_raw) > 0) {
  310. size_t backlog;
  311. ptrlen data = bufchain_prefix(&ssh->out_raw);
  312. if (ssh->logctx)
  313. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data.ptr, data.len,
  314. 0, NULL, NULL, 0, NULL);
  315. backlog = sk_write(ssh->s, data.ptr, data.len);
  316. bufchain_consume(&ssh->out_raw, data.len);
  317. if (backlog > SSH_MAX_BACKLOG) {
  318. ssh_throttle_all(ssh, true, backlog);
  319. return;
  320. }
  321. }
  322. ssh_check_frozen(ssh);
  323. if (ssh->pending_close) {
  324. sk_close(ssh->s);
  325. ssh->s = NULL;
  326. }
  327. }
  328. static void ssh_shutdown_internal(Ssh *ssh)
  329. {
  330. expire_timer_context(ssh);
  331. if (ssh->connshare) {
  332. sharestate_free(ssh->connshare);
  333. ssh->connshare = NULL;
  334. }
  335. if (ssh->pinger) {
  336. pinger_free(ssh->pinger);
  337. ssh->pinger = NULL;
  338. }
  339. /*
  340. * We only need to free the base PPL, which will free the others
  341. * (if any) transitively.
  342. */
  343. if (ssh->base_layer) {
  344. ssh_ppl_free(ssh->base_layer);
  345. ssh->base_layer = NULL;
  346. }
  347. ssh->cl = NULL;
  348. }
  349. static void ssh_shutdown(Ssh *ssh)
  350. {
  351. ssh_shutdown_internal(ssh);
  352. if (ssh->bpp) {
  353. ssh_bpp_free(ssh->bpp);
  354. ssh->bpp = NULL;
  355. }
  356. if (ssh->s) {
  357. sk_close(ssh->s);
  358. ssh->s = NULL;
  359. }
  360. bufchain_clear(&ssh->in_raw);
  361. bufchain_clear(&ssh->out_raw);
  362. bufchain_clear(&ssh->user_input);
  363. }
  364. static void ssh_initiate_connection_close(Ssh *ssh)
  365. {
  366. /* Wind up everything above the BPP. */
  367. ssh_shutdown_internal(ssh);
  368. /* Force any remaining queued SSH packets through the BPP, and
  369. * schedule closing the network socket after they go out. */
  370. ssh_bpp_handle_output(ssh->bpp);
  371. ssh->pending_close = true;
  372. queue_idempotent_callback(&ssh->ic_out_raw);
  373. /* Now we expect the other end to close the connection too in
  374. * response, so arrange that we'll receive notification of that
  375. * via ssh_remote_eof. */
  376. ssh->bpp->expect_close = true;
  377. }
  378. #define GET_FORMATTED_MSG \
  379. char *msg; \
  380. va_list ap; \
  381. va_start(ap, fmt); \
  382. msg = dupvprintf(fmt, ap); \
  383. va_end(ap);
  384. void ssh_remote_error(Ssh *ssh, const char *fmt, ...)
  385. {
  386. if (ssh->base_layer || !ssh->session_started) {
  387. GET_FORMATTED_MSG;
  388. /* Error messages sent by the remote don't count as clean exits */
  389. ssh->exitcode = 128;
  390. /* Close the socket immediately, since the server has already
  391. * closed its end (or is about to). */
  392. ssh_shutdown(ssh);
  393. logevent(ssh->logctx, msg);
  394. seat_connection_fatal(ssh->seat, "%s", msg);
  395. sfree(msg);
  396. }
  397. }
  398. void ssh_remote_eof(Ssh *ssh, const char *fmt, ...)
  399. {
  400. if (ssh->base_layer || !ssh->session_started) {
  401. GET_FORMATTED_MSG;
  402. /* EOF from the remote, if we were expecting it, does count as
  403. * a clean exit */
  404. ssh->exitcode = 0;
  405. /* Close the socket immediately, since the server has already
  406. * closed its end. */
  407. ssh_shutdown(ssh);
  408. logevent(ssh->logctx, msg);
  409. sfree(msg);
  410. seat_notify_remote_exit(ssh->seat);
  411. } else {
  412. /* This is responding to EOF after we've already seen some
  413. * other reason for terminating the session. */
  414. ssh_shutdown(ssh);
  415. }
  416. }
  417. void ssh_proto_error(Ssh *ssh, const char *fmt, ...)
  418. {
  419. if (ssh->base_layer || !ssh->session_started) {
  420. GET_FORMATTED_MSG;
  421. ssh->exitcode = 128;
  422. ssh_bpp_queue_disconnect(ssh->bpp, msg,
  423. SSH2_DISCONNECT_PROTOCOL_ERROR);
  424. ssh_initiate_connection_close(ssh);
  425. logevent(ssh->logctx, msg);
  426. seat_connection_fatal(ssh->seat, "%s", msg);
  427. sfree(msg);
  428. }
  429. }
  430. void ssh_sw_abort(Ssh *ssh, const char *fmt, ...)
  431. {
  432. if (ssh->base_layer || !ssh->session_started) {
  433. GET_FORMATTED_MSG;
  434. ssh->exitcode = 128;
  435. ssh_initiate_connection_close(ssh);
  436. logevent(ssh->logctx, msg);
  437. seat_connection_fatal(ssh->seat, "%s", msg);
  438. sfree(msg);
  439. seat_notify_remote_exit(ssh->seat);
  440. }
  441. }
  442. void ssh_user_close(Ssh *ssh, const char *fmt, ...)
  443. {
  444. if (ssh->base_layer || !ssh->session_started) {
  445. GET_FORMATTED_MSG;
  446. /* Closing the connection due to user action, even if the
  447. * action is the user aborting during authentication prompts,
  448. * does count as a clean exit - except that this is also how
  449. * we signal ordinary session termination, in which case we
  450. * should use the exit status already sent from the main
  451. * session (if any). */
  452. if (ssh->exitcode < 0)
  453. ssh->exitcode = 0;
  454. ssh_initiate_connection_close(ssh);
  455. logevent(ssh->logctx, msg);
  456. sfree(msg);
  457. seat_notify_remote_exit(ssh->seat);
  458. }
  459. }
  460. void ssh_deferred_abort_callback(void *vctx)
  461. {
  462. Ssh *ssh = (Ssh *)vctx;
  463. char *msg = ssh->deferred_abort_message;
  464. ssh->deferred_abort_message = NULL;
  465. ssh_sw_abort(ssh, "%s", msg);
  466. sfree(msg);
  467. }
  468. void ssh_sw_abort_deferred(Ssh *ssh, const char *fmt, ...)
  469. {
  470. if (!ssh->deferred_abort_message) {
  471. GET_FORMATTED_MSG;
  472. ssh->deferred_abort_message = msg;
  473. queue_toplevel_callback(get_seat_callback_set(ssh->seat), ssh_deferred_abort_callback, ssh);
  474. }
  475. }
  476. static void ssh_socket_log(Plug *plug, int type, SockAddr *addr, int port,
  477. const char *error_msg, int error_code)
  478. {
  479. Ssh *ssh = container_of(plug, Ssh, plug);
  480. /*
  481. * While we're attempting connection sharing, don't loudly log
  482. * everything that happens. Real TCP connections need to be logged
  483. * when we _start_ trying to connect, because it might be ages
  484. * before they respond if something goes wrong; but connection
  485. * sharing is local and quick to respond, and it's sufficient to
  486. * simply wait and see whether it worked afterwards.
  487. */
  488. if (!ssh->attempting_connshare)
  489. backend_socket_log(ssh->seat, ssh->logctx, type, addr, port,
  490. error_msg, error_code, ssh->conf,
  491. ssh->session_started);
  492. }
  493. static void ssh_closing(Plug *plug, const char *error_msg, int error_code,
  494. bool calling_back)
  495. {
  496. Ssh *ssh = container_of(plug, Ssh, plug);
  497. if (error_msg) {
  498. ssh_remote_error(ssh, "%s", error_msg);
  499. } else if (ssh->bpp) {
  500. ssh->bpp->input_eof = true;
  501. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  502. }
  503. }
  504. static void ssh_receive(Plug *plug, int urgent, const char *data, size_t len)
  505. {
  506. Ssh *ssh = container_of(plug, Ssh, plug);
  507. /* Log raw data, if we're in that mode. */
  508. if (ssh->logctx)
  509. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len,
  510. 0, NULL, NULL, 0, NULL);
  511. bufchain_add(&ssh->in_raw, data, len);
  512. if (!ssh->logically_frozen && ssh->bpp)
  513. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  514. ssh_check_frozen(ssh);
  515. }
  516. static void ssh_sent(Plug *plug, size_t bufsize)
  517. {
  518. Ssh *ssh = container_of(plug, Ssh, plug);
  519. /*
  520. * If the send backlog on the SSH socket itself clears, we should
  521. * unthrottle the whole world if it was throttled. Also trigger an
  522. * extra call to the consumer of the BPP's output, to try to send
  523. * some more data off its bufchain.
  524. */
  525. if (bufsize < SSH_MAX_BACKLOG) {
  526. ssh_throttle_all(ssh, false, bufsize);
  527. queue_idempotent_callback(&ssh->ic_out_raw);
  528. }
  529. }
  530. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  531. char **savedhost, int *savedport,
  532. char **loghost_ret)
  533. {
  534. char *loghost = conf_get_str(conf, CONF_loghost);
  535. if (loghost_ret)
  536. *loghost_ret = loghost;
  537. if (*loghost) {
  538. char *tmphost;
  539. char *colon;
  540. tmphost = dupstr(loghost);
  541. *savedport = 22; /* default ssh port */
  542. /*
  543. * A colon suffix on the hostname string also lets us affect
  544. * savedport. (Unless there are multiple colons, in which case
  545. * we assume this is an unbracketed IPv6 literal.)
  546. */
  547. colon = host_strrchr(tmphost, ':');
  548. if (colon && colon == host_strchr(tmphost, ':')) {
  549. *colon++ = '\0';
  550. if (*colon)
  551. *savedport = atoi(colon);
  552. }
  553. *savedhost = host_strduptrim(tmphost);
  554. sfree(tmphost);
  555. } else {
  556. *savedhost = host_strduptrim(host);
  557. if (port < 0)
  558. port = 22; /* default ssh port */
  559. *savedport = port;
  560. }
  561. }
  562. static bool ssh_test_for_upstream(const char *host, int port, Conf *conf)
  563. {
  564. char *savedhost;
  565. int savedport;
  566. bool ret;
  567. random_ref(); /* platform may need this to determine share socket name */
  568. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  569. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  570. sfree(savedhost);
  571. random_unref();
  572. return ret;
  573. }
  574. static const PlugVtable Ssh_plugvt = {
  575. ssh_socket_log,
  576. ssh_closing,
  577. ssh_receive,
  578. ssh_sent,
  579. NULL
  580. };
  581. /*
  582. * Connect to specified host and port.
  583. * Returns an error message, or NULL on success.
  584. * Also places the canonical host name into `realhost'. It must be
  585. * freed by the caller.
  586. */
  587. static const char *connect_to_host(
  588. Ssh *ssh, const char *host, int port, char **realhost,
  589. bool nodelay, bool keepalive)
  590. {
  591. SockAddr *addr;
  592. const char *err;
  593. char *loghost;
  594. int addressfamily, sshprot;
  595. ssh_hostport_setup(host, port, ssh->conf,
  596. &ssh->savedhost, &ssh->savedport, &loghost);
  597. ssh->plug.vt = &Ssh_plugvt;
  598. #ifdef MPEXT
  599. // make sure the field is initialized, in case lookup below fails
  600. ssh->fullhostname = NULL;
  601. #endif
  602. /*
  603. * Try connection-sharing, in case that means we don't open a
  604. * socket after all. ssh_connection_sharing_init will connect to a
  605. * previously established upstream if it can, and failing that,
  606. * establish a listening socket for _us_ to be the upstream. In
  607. * the latter case it will return NULL just as if it had done
  608. * nothing, because here we only need to care if we're a
  609. * downstream and need to do our connection setup differently.
  610. */
  611. ssh->connshare = NULL;
  612. ssh->attempting_connshare = true; /* affects socket logging behaviour */
  613. ssh->s = ssh_connection_sharing_init(
  614. ssh->savedhost, ssh->savedport, ssh->conf, ssh->logctx,
  615. &ssh->plug, &ssh->connshare);
  616. if (ssh->connshare)
  617. ssh_connshare_provide_connlayer(ssh->connshare, &ssh->cl_dummy);
  618. ssh->attempting_connshare = false;
  619. if (ssh->s != NULL) {
  620. /*
  621. * We are a downstream.
  622. */
  623. ssh->bare_connection = true;
  624. ssh->fullhostname = NULL;
  625. *realhost = dupstr(host); /* best we can do */
  626. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  627. /* In an interactive session, or in verbose mode, announce
  628. * in the console window that we're a sharing downstream,
  629. * to avoid confusing users as to why this session doesn't
  630. * behave in quite the usual way. */
  631. const char *msg =
  632. "Reusing a shared connection to this server.\r\n";
  633. seat_stderr_pl(ssh->seat, ptrlen_from_asciz(msg));
  634. }
  635. } else {
  636. /*
  637. * We're not a downstream, so open a normal socket.
  638. */
  639. /*
  640. * Try to find host.
  641. */
  642. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  643. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  644. ssh->logctx, "SSH connection");
  645. if ((err = sk_addr_error(addr)) != NULL) {
  646. sk_addr_free(addr);
  647. return err;
  648. }
  649. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  650. ssh->s = new_connection(addr, *realhost, port,
  651. false, true, nodelay, keepalive,
  652. &ssh->plug, ssh->conf);
  653. if ((err = sk_socket_error(ssh->s)) != NULL) {
  654. ssh->s = NULL;
  655. seat_notify_remote_exit(ssh->seat);
  656. return err;
  657. }
  658. }
  659. /*
  660. * The SSH version number is always fixed (since we no longer support
  661. * fallback between versions), so set it now.
  662. */
  663. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  664. assert(sshprot == 0 || sshprot == 3);
  665. if (sshprot == 0)
  666. /* SSH-1 only */
  667. ssh->version = 1;
  668. if (sshprot == 3 || ssh->bare_connection) {
  669. /* SSH-2 only */
  670. ssh->version = 2;
  671. }
  672. /*
  673. * Set up the initial BPP that will do the version string
  674. * exchange, and get it started so that it can send the outgoing
  675. * version string early if it wants to.
  676. */
  677. ssh->version_receiver.got_ssh_version = ssh_got_ssh_version;
  678. ssh->bpp = ssh_verstring_new(
  679. ssh->conf, ssh->logctx, ssh->bare_connection,
  680. ssh->version == 1 ? "1.5" : "2.0", &ssh->version_receiver,
  681. false, ""); // WINSCP (impl_name provided in sshver already)
  682. ssh_connect_bpp(ssh);
  683. queue_idempotent_callback(&ssh->bpp->ic_in_raw);
  684. /*
  685. * loghost, if configured, overrides realhost.
  686. */
  687. if (*loghost) {
  688. sfree(*realhost);
  689. *realhost = dupstr(loghost);
  690. }
  691. return NULL;
  692. }
  693. /*
  694. * Throttle or unthrottle the SSH connection.
  695. */
  696. void ssh_throttle_conn(Ssh *ssh, int adjust)
  697. {
  698. int old_count = ssh->conn_throttle_count;
  699. bool frozen;
  700. ssh->conn_throttle_count += adjust;
  701. assert(ssh->conn_throttle_count >= 0);
  702. if (ssh->conn_throttle_count && !old_count) {
  703. frozen = true;
  704. } else if (!ssh->conn_throttle_count && old_count) {
  705. frozen = false;
  706. } else {
  707. return; /* don't change current frozen state */
  708. }
  709. ssh->logically_frozen = frozen;
  710. ssh_check_frozen(ssh);
  711. }
  712. /*
  713. * Throttle or unthrottle _all_ local data streams (for when sends
  714. * on the SSH connection itself back up).
  715. */
  716. static void ssh_throttle_all(Ssh *ssh, bool enable, size_t bufsize)
  717. {
  718. if (enable == ssh->throttled_all)
  719. return;
  720. ssh->throttled_all = enable;
  721. ssh->overall_bufsize = bufsize;
  722. ssh_throttle_all_channels(ssh->cl, enable);
  723. }
  724. static void ssh_cache_conf_values(Ssh *ssh)
  725. {
  726. ssh->pls.omit_passwords = conf_get_bool(ssh->conf, CONF_logomitpass);
  727. ssh->pls.omit_data = conf_get_bool(ssh->conf, CONF_logomitdata);
  728. }
  729. /*
  730. * Called to set up the connection.
  731. *
  732. * Returns an error message, or NULL on success.
  733. */
  734. static const char *ssh_init(Seat *seat, Backend **backend_handle,
  735. LogContext *logctx, Conf *conf,
  736. const char *host, int port, char **realhost,
  737. bool nodelay, bool keepalive)
  738. {
  739. const char *p;
  740. Ssh *ssh;
  741. ssh = snew(Ssh);
  742. memset(ssh, 0, sizeof(Ssh));
  743. ssh->conf = conf_copy(conf);
  744. ssh_cache_conf_values(ssh);
  745. ssh->exitcode = -1;
  746. ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
  747. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  748. bufchain_init(&ssh->in_raw);
  749. bufchain_init(&ssh->out_raw);
  750. bufchain_init(&ssh->user_input);
  751. ssh->ic_out_raw.fn = ssh_bpp_output_raw_data_callback;
  752. ssh->ic_out_raw.ctx = ssh;
  753. ssh->ic_out_raw.set = get_seat_callback_set(seat);
  754. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  755. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  756. ssh->backend.vt = &ssh_backend;
  757. *backend_handle = &ssh->backend;
  758. ssh->seat = seat;
  759. ssh->cl_dummy.logctx = ssh->logctx = logctx;
  760. random_ref(); /* do this now - may be needed by sharing setup code */
  761. ssh->need_random_unref = true;
  762. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  763. if (p != NULL) {
  764. /* Call random_unref now instead of waiting until the caller
  765. * frees this useless Ssh object, in case the caller is
  766. * impatient and just exits without bothering, in which case
  767. * the random seed won't be re-saved. */
  768. ssh->need_random_unref = false;
  769. random_unref();
  770. return p;
  771. }
  772. return NULL;
  773. }
  774. static void ssh_free(Backend *be)
  775. {
  776. Ssh *ssh = container_of(be, Ssh, backend);
  777. bool need_random_unref;
  778. ssh_shutdown(ssh);
  779. conf_free(ssh->conf);
  780. if (ssh->connshare)
  781. sharestate_free(ssh->connshare);
  782. sfree(ssh->savedhost);
  783. sfree(ssh->fullhostname);
  784. sfree(ssh->specials);
  785. #ifndef NO_GSSAPI
  786. if (ssh->gss_state.srv_name)
  787. ssh->gss_state.lib->release_name(
  788. ssh->gss_state.lib, &ssh->gss_state.srv_name);
  789. if (ssh->gss_state.ctx != NULL)
  790. ssh->gss_state.lib->release_cred(
  791. ssh->gss_state.lib, &ssh->gss_state.ctx);
  792. if (ssh->gss_state.libs)
  793. ssh_gss_cleanup(ssh->gss_state.libs);
  794. #endif
  795. sfree(ssh->deferred_abort_message);
  796. delete_callbacks_for_context(get_seat_callback_set(ssh->seat), ssh); /* likely to catch ic_out_raw */ // WINSCP (seat)
  797. need_random_unref = ssh->need_random_unref;
  798. sfree(ssh);
  799. if (need_random_unref)
  800. random_unref();
  801. }
  802. /*
  803. * Reconfigure the SSH backend.
  804. */
  805. static void ssh_reconfig(Backend *be, Conf *conf)
  806. {
  807. Ssh *ssh = container_of(be, Ssh, backend);
  808. if (ssh->pinger)
  809. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  810. ssh_ppl_reconfigure(ssh->base_layer, conf);
  811. conf_free(ssh->conf);
  812. ssh->conf = conf_copy(conf);
  813. ssh_cache_conf_values(ssh);
  814. }
  815. /*
  816. * Called to send data down the SSH connection.
  817. */
  818. static size_t ssh_send(Backend *be, const char *buf, size_t len)
  819. {
  820. Ssh *ssh = container_of(be, Ssh, backend);
  821. if (ssh == NULL || ssh->s == NULL)
  822. return 0;
  823. bufchain_add(&ssh->user_input, buf, len);
  824. if (ssh->base_layer)
  825. ssh_ppl_got_user_input(ssh->base_layer);
  826. return backend_sendbuffer(&ssh->backend);
  827. }
  828. /*
  829. * Called to query the current amount of buffered stdin data.
  830. */
  831. static size_t ssh_sendbuffer(Backend *be)
  832. {
  833. Ssh *ssh = container_of(be, Ssh, backend);
  834. size_t backlog;
  835. if (!ssh || !ssh->s || !ssh->cl)
  836. return 0;
  837. backlog = ssh_stdin_backlog(ssh->cl);
  838. #ifndef WINSCP
  839. // This throttles WinSCP unnecessarily, as it uses its own throttling mechanism.
  840. // This value is used only by WinSCP, never directly by PuTTY code.
  841. if (ssh->base_layer)
  842. backlog += ssh_ppl_queued_data_size(ssh->base_layer);
  843. #endif
  844. /*
  845. * If the SSH socket itself has backed up, add the total backup
  846. * size on that to any individual buffer on the stdin channel.
  847. */
  848. if (ssh->throttled_all)
  849. backlog += ssh->overall_bufsize;
  850. return backlog;
  851. }
  852. /*
  853. * Called to set the size of the window from SSH's POV.
  854. */
  855. static void ssh_size(Backend *be, int width, int height)
  856. {
  857. Ssh *ssh = container_of(be, Ssh, backend);
  858. ssh->term_width = width;
  859. ssh->term_height = height;
  860. if (ssh->cl)
  861. ssh_terminal_size(ssh->cl, ssh->term_width, ssh->term_height);
  862. }
  863. struct ssh_add_special_ctx {
  864. SessionSpecial *specials;
  865. size_t nspecials, specials_size;
  866. };
  867. static void ssh_add_special(void *vctx, const char *text,
  868. SessionSpecialCode code, int arg)
  869. {
  870. struct ssh_add_special_ctx *ctx = (struct ssh_add_special_ctx *)vctx;
  871. SessionSpecial *spec;
  872. sgrowarray(ctx->specials, ctx->specials_size, ctx->nspecials);
  873. spec = &ctx->specials[ctx->nspecials++];
  874. spec->name = text;
  875. spec->code = code;
  876. spec->arg = arg;
  877. }
  878. /*
  879. * Return a list of the special codes that make sense in this
  880. * protocol.
  881. */
  882. static const SessionSpecial *ssh_get_specials(Backend *be)
  883. {
  884. Ssh *ssh = container_of(be, Ssh, backend);
  885. /*
  886. * Ask all our active protocol layers what specials they've got,
  887. * and amalgamate the list into one combined one.
  888. */
  889. struct ssh_add_special_ctx ctx;
  890. ctx.specials = NULL;
  891. ctx.nspecials = ctx.specials_size = 0;
  892. if (ssh->base_layer)
  893. ssh_ppl_get_specials(ssh->base_layer, ssh_add_special, &ctx);
  894. if (ctx.specials) {
  895. /* If the list is non-empty, terminate it with a SS_EXITMENU. */
  896. ssh_add_special(&ctx, NULL, SS_EXITMENU, 0);
  897. }
  898. sfree(ssh->specials);
  899. ssh->specials = ctx.specials;
  900. return ssh->specials;
  901. }
  902. /*
  903. * Send special codes.
  904. */
  905. static void ssh_special(Backend *be, SessionSpecialCode code, int arg)
  906. {
  907. Ssh *ssh = container_of(be, Ssh, backend);
  908. if (ssh->base_layer)
  909. ssh_ppl_special_cmd(ssh->base_layer, code, arg);
  910. }
  911. /*
  912. * This is called when the seat's output channel manages to clear some
  913. * backlog.
  914. */
  915. static void ssh_unthrottle(Backend *be, size_t bufsize)
  916. {
  917. Ssh *ssh = container_of(be, Ssh, backend);
  918. if (ssh->cl)
  919. ssh_stdout_unthrottle(ssh->cl, bufsize);
  920. }
  921. static bool ssh_connected(Backend *be)
  922. {
  923. Ssh *ssh = container_of(be, Ssh, backend);
  924. return ssh->s != NULL;
  925. }
  926. static bool ssh_sendok(Backend *be)
  927. {
  928. Ssh *ssh = container_of(be, Ssh, backend);
  929. return ssh->base_layer && ssh_ppl_want_user_input(ssh->base_layer);
  930. }
  931. void ssh_ldisc_update(Ssh *ssh)
  932. {
  933. /* Called when the connection layer wants to propagate an update
  934. * to the line discipline options */
  935. if (ssh->ldisc)
  936. ldisc_echoedit_update(ssh->ldisc);
  937. }
  938. static bool ssh_ldisc(Backend *be, int option)
  939. {
  940. Ssh *ssh = container_of(be, Ssh, backend);
  941. return ssh->cl ? ssh_ldisc_option(ssh->cl, option) : false;
  942. }
  943. static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
  944. {
  945. Ssh *ssh = container_of(be, Ssh, backend);
  946. ssh->ldisc = ldisc;
  947. }
  948. void ssh_got_exitcode(Ssh *ssh, int exitcode)
  949. {
  950. ssh->exitcode = exitcode;
  951. }
  952. static int ssh_return_exitcode(Backend *be)
  953. {
  954. Ssh *ssh = container_of(be, Ssh, backend);
  955. if (ssh->s && (!ssh->session_started || ssh->base_layer))
  956. return -1;
  957. else
  958. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  959. }
  960. /*
  961. * cfg_info for SSH is the protocol running in this session.
  962. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  963. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  964. */
  965. static int ssh_cfg_info(Backend *be)
  966. {
  967. Ssh *ssh = container_of(be, Ssh, backend);
  968. if (ssh->version == 0)
  969. return 0; /* don't know yet */
  970. else if (ssh->bare_connection)
  971. return -1;
  972. else
  973. return ssh->version;
  974. }
  975. /*
  976. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  977. * that fails. This variable is the means by which scp.c can reach
  978. * into the SSH code and find out which one it got.
  979. */
  980. extern bool ssh_fallback_cmd(Backend *be)
  981. {
  982. Ssh *ssh = container_of(be, Ssh, backend);
  983. return ssh->fallback_cmd;
  984. }
  985. void ssh_got_fallback_cmd(Ssh *ssh)
  986. {
  987. ssh->fallback_cmd = true;
  988. }
  989. const struct BackendVtable ssh_backend = {
  990. ssh_init,
  991. ssh_free,
  992. ssh_reconfig,
  993. ssh_send,
  994. ssh_sendbuffer,
  995. ssh_size,
  996. ssh_special,
  997. ssh_get_specials,
  998. ssh_connected,
  999. ssh_return_exitcode,
  1000. ssh_sendok,
  1001. ssh_ldisc,
  1002. ssh_provide_ldisc,
  1003. ssh_unthrottle,
  1004. ssh_cfg_info,
  1005. ssh_test_for_upstream,
  1006. "ssh",
  1007. PROT_SSH,
  1008. 22
  1009. };
  1010. #ifdef MPEXT
  1011. #include "puttyexp.h"
  1012. int is_ssh(Plug * plug)
  1013. {
  1014. return plug->vt->closing == ssh_closing;
  1015. }
  1016. int get_ssh_version(Backend * be)
  1017. {
  1018. Ssh * ssh = container_of(be, Ssh, backend);
  1019. return ssh->version;
  1020. }
  1021. Seat * get_ssh_seat(Plug * plug)
  1022. {
  1023. return container_of(plug, Ssh, plug)->seat;
  1024. }
  1025. const ssh_cipher * get_cipher(Backend * be)
  1026. {
  1027. Ssh * ssh = container_of(be, Ssh, backend);
  1028. return ssh1_bpp_get_cipher(ssh->bpp);
  1029. }
  1030. const ssh_cipher * get_cscipher(Backend * be)
  1031. {
  1032. Ssh * ssh = container_of(be, Ssh, backend);
  1033. return ssh2_bpp_get_cscipher(ssh->bpp);
  1034. }
  1035. const ssh_cipher * get_sccipher(Backend * be)
  1036. {
  1037. Ssh * ssh = container_of(be, Ssh, backend);
  1038. return ssh2_bpp_get_sccipher(ssh->bpp);
  1039. }
  1040. const struct ssh_compressor * get_cscomp(Backend * be)
  1041. {
  1042. Ssh * ssh = container_of(be, Ssh, backend);
  1043. return ssh2_bpp_get_cscomp(ssh->bpp);
  1044. }
  1045. const struct ssh_decompressor * get_sccomp(Backend * be)
  1046. {
  1047. Ssh * ssh = container_of(be, Ssh, backend);
  1048. return ssh2_bpp_get_sccomp(ssh->bpp);
  1049. }
  1050. unsigned int winscp_query(Backend * be, int query)
  1051. {
  1052. Ssh * ssh = container_of(be, Ssh, backend);
  1053. if ((ssh->base_layer != NULL) && (ssh->base_layer->vt->winscp_query != NULL))
  1054. {
  1055. return ssh_ppl_winscp_query(ssh->base_layer, query);
  1056. }
  1057. else
  1058. {
  1059. return 0;
  1060. }
  1061. }
  1062. void md5checksum(const char * buffer, int len, unsigned char output[16])
  1063. {
  1064. hash_simple(&ssh_md5, make_ptrlen(buffer, len), output);
  1065. }
  1066. #endif