ssh.c 37 KB

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