ssh.c 34 KB

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