ssh.c 37 KB

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