ssh.c 32 KB

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