ssh.c 34 KB

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