ssh.c 36 KB

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