ssh.c 34 KB

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