ssh.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. /*
  2. * SSH backend.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. #include <assert.h>
  8. #include <limits.h>
  9. #include <signal.h>
  10. #include "putty.h"
  11. #include "pageant.h" /* for AGENT_MAX_MSGLEN */
  12. #include "tree234.h"
  13. #include "storage.h"
  14. #include "marshal.h"
  15. #include "ssh.h"
  16. #include "sshcr.h"
  17. #include "sshbpp.h"
  18. #include "sshppl.h"
  19. #include "sshchan.h"
  20. #ifndef NO_GSSAPI
  21. #include "sshgssc.h"
  22. #include "sshgss.h"
  23. #define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */
  24. #define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */
  25. #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
  26. #define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
  27. #define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
  28. #endif
  29. struct Ssh {
  30. Socket *s;
  31. Seat *seat;
  32. Conf *conf;
  33. struct ssh_version_receiver version_receiver;
  34. int remote_bugs;
  35. Plug plug;
  36. Backend backend;
  37. Ldisc *ldisc;
  38. LogContext *logctx;
  39. /* The last list returned from get_specials. */
  40. SessionSpecial *specials;
  41. bool bare_connection;
  42. ssh_sharing_state *connshare;
  43. bool attempting_connshare;
  44. 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, "PuTTY");
  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. ssh_stdout_unthrottle(ssh->cl, bufsize);
  845. }
  846. static bool ssh_connected(Backend *be)
  847. {
  848. Ssh *ssh = container_of(be, Ssh, backend);
  849. return ssh->s != NULL;
  850. }
  851. static bool ssh_sendok(Backend *be)
  852. {
  853. Ssh *ssh = container_of(be, Ssh, backend);
  854. return ssh->base_layer && ssh_ppl_want_user_input(ssh->base_layer);
  855. }
  856. void ssh_ldisc_update(Ssh *ssh)
  857. {
  858. /* Called when the connection layer wants to propagate an update
  859. * to the line discipline options */
  860. if (ssh->ldisc)
  861. ldisc_echoedit_update(ssh->ldisc);
  862. }
  863. static bool ssh_ldisc(Backend *be, int option)
  864. {
  865. Ssh *ssh = container_of(be, Ssh, backend);
  866. return ssh->cl ? ssh_ldisc_option(ssh->cl, option) : false;
  867. }
  868. static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
  869. {
  870. Ssh *ssh = container_of(be, Ssh, backend);
  871. ssh->ldisc = ldisc;
  872. }
  873. void ssh_got_exitcode(Ssh *ssh, int exitcode)
  874. {
  875. ssh->exitcode = exitcode;
  876. }
  877. static int ssh_return_exitcode(Backend *be)
  878. {
  879. Ssh *ssh = container_of(be, Ssh, backend);
  880. if (ssh->s && (!ssh->session_started || ssh->base_layer))
  881. return -1;
  882. else
  883. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  884. }
  885. /*
  886. * cfg_info for SSH is the protocol running in this session.
  887. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  888. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  889. */
  890. static int ssh_cfg_info(Backend *be)
  891. {
  892. Ssh *ssh = container_of(be, Ssh, backend);
  893. if (ssh->version == 0)
  894. return 0; /* don't know yet */
  895. else if (ssh->bare_connection)
  896. return -1;
  897. else
  898. return ssh->version;
  899. }
  900. /*
  901. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  902. * that fails. This variable is the means by which scp.c can reach
  903. * into the SSH code and find out which one it got.
  904. */
  905. extern bool ssh_fallback_cmd(Backend *be)
  906. {
  907. Ssh *ssh = container_of(be, Ssh, backend);
  908. return ssh->fallback_cmd;
  909. }
  910. void ssh_got_fallback_cmd(Ssh *ssh)
  911. {
  912. ssh->fallback_cmd = true;
  913. }
  914. const struct BackendVtable ssh_backend = {
  915. ssh_init,
  916. ssh_free,
  917. ssh_reconfig,
  918. ssh_send,
  919. ssh_sendbuffer,
  920. ssh_size,
  921. ssh_special,
  922. ssh_get_specials,
  923. ssh_connected,
  924. ssh_return_exitcode,
  925. ssh_sendok,
  926. ssh_ldisc,
  927. ssh_provide_ldisc,
  928. ssh_unthrottle,
  929. ssh_cfg_info,
  930. ssh_test_for_upstream,
  931. "ssh",
  932. PROT_SSH,
  933. 22
  934. };
  935. #ifdef MPEXT
  936. #include "puttyexp.h"
  937. int is_ssh(Plug * plug)
  938. {
  939. return plug->vt->closing == ssh_closing;
  940. }
  941. int get_ssh_version(Backend * be)
  942. {
  943. Ssh * ssh = container_of(be, Ssh, backend);
  944. return ssh->version;
  945. }
  946. Seat * get_ssh_seat(Plug * plug)
  947. {
  948. return container_of(plug, Ssh, plug)->seat;
  949. }
  950. const ssh1_cipher * get_cipher(Backend * be)
  951. {
  952. Ssh * ssh = container_of(be, Ssh, backend);
  953. return ssh1_bpp_get_cipher(ssh->bpp);
  954. }
  955. const ssh2_cipher * get_cscipher(Backend * be)
  956. {
  957. Ssh * ssh = container_of(be, Ssh, backend);
  958. return ssh2_bpp_get_cscipher(ssh->bpp);
  959. }
  960. const ssh2_cipher * get_sccipher(Backend * be)
  961. {
  962. Ssh * ssh = container_of(be, Ssh, backend);
  963. return ssh2_bpp_get_sccipher(ssh->bpp);
  964. }
  965. const struct ssh_compressor * get_cscomp(Backend * be)
  966. {
  967. Ssh * ssh = container_of(be, Ssh, backend);
  968. return ssh2_bpp_get_cscomp(ssh->bpp);
  969. }
  970. const struct ssh_decompressor * get_sccomp(Backend * be)
  971. {
  972. Ssh * ssh = container_of(be, Ssh, backend);
  973. return ssh2_bpp_get_sccomp(ssh->bpp);
  974. }
  975. unsigned int winscp_query(Backend * be, int query)
  976. {
  977. Ssh * ssh = container_of(be, Ssh, backend);
  978. if ((ssh->base_layer != NULL) && (ssh->base_layer->vt->winscp_query != NULL))
  979. {
  980. return ssh_ppl_winscp_query(ssh->base_layer, query);
  981. }
  982. else
  983. {
  984. return 0;
  985. }
  986. }
  987. void md5checksum(const char * buffer, int len, unsigned char output[16])
  988. {
  989. MD5Simple(buffer, len, output);
  990. }
  991. #endif