ssh.c 34 KB

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