ssh.c 32 KB

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