ssh.c 34 KB

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