ssh.c 34 KB

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