sshcommon.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. /*
  2. * Supporting routines used in common by all the various components of
  3. * the SSH system.
  4. */
  5. #include <assert.h>
  6. #include <stdlib.h>
  7. #include "putty.h"
  8. #include "mpint.h"
  9. #include "ssh.h"
  10. #include "sshbpp.h"
  11. #include "sshppl.h"
  12. #include "sshchan.h"
  13. /* ----------------------------------------------------------------------
  14. * Implementation of PacketQueue.
  15. */
  16. static void pq_ensure_unlinked(PacketQueueNode *node)
  17. {
  18. if (node->on_free_queue) {
  19. node->next->prev = node->prev;
  20. node->prev->next = node->next;
  21. } else {
  22. assert(!node->next);
  23. assert(!node->prev);
  24. }
  25. }
  26. void pq_base_push(PacketQueueBase *pqb, PacketQueueNode *node)
  27. {
  28. pq_ensure_unlinked(node);
  29. node->next = &pqb->end;
  30. node->prev = pqb->end.prev;
  31. node->next->prev = node;
  32. node->prev->next = node;
  33. if (pqb->ic)
  34. queue_idempotent_callback(pqb->ic);
  35. }
  36. void pq_base_push_front(PacketQueueBase *pqb, PacketQueueNode *node)
  37. {
  38. pq_ensure_unlinked(node);
  39. node->prev = &pqb->end;
  40. node->next = pqb->end.next;
  41. node->next->prev = node;
  42. node->prev->next = node;
  43. if (pqb->ic)
  44. queue_idempotent_callback(pqb->ic);
  45. }
  46. static PacketQueueNode pktin_freeq_head = {
  47. &pktin_freeq_head, &pktin_freeq_head, true
  48. };
  49. static void pktin_free_queue_callback(void *vctx)
  50. {
  51. while (pktin_freeq_head.next != &pktin_freeq_head) {
  52. PacketQueueNode *node = pktin_freeq_head.next;
  53. PktIn *pktin = container_of(node, PktIn, qnode);
  54. pktin_freeq_head.next = node->next;
  55. sfree(pktin);
  56. }
  57. pktin_freeq_head.prev = &pktin_freeq_head;
  58. }
  59. static IdempotentCallback ic_pktin_free = {
  60. pktin_free_queue_callback, NULL, false
  61. };
  62. static PktIn *pq_in_after(PacketQueueBase *pqb,
  63. PacketQueueNode *prev, bool pop)
  64. {
  65. PacketQueueNode *node = prev->next;
  66. if (node == &pqb->end)
  67. return NULL;
  68. if (pop) {
  69. node->next->prev = node->prev;
  70. node->prev->next = node->next;
  71. node->prev = pktin_freeq_head.prev;
  72. node->next = &pktin_freeq_head;
  73. node->next->prev = node;
  74. node->prev->next = node;
  75. node->on_free_queue = true;
  76. queue_idempotent_callback(&ic_pktin_free);
  77. }
  78. return container_of(node, PktIn, qnode);
  79. }
  80. static PktOut *pq_out_after(PacketQueueBase *pqb,
  81. PacketQueueNode *prev, bool pop)
  82. {
  83. PacketQueueNode *node = prev->next;
  84. if (node == &pqb->end)
  85. return NULL;
  86. if (pop) {
  87. node->next->prev = node->prev;
  88. node->prev->next = node->next;
  89. node->prev = node->next = NULL;
  90. }
  91. return container_of(node, PktOut, qnode);
  92. }
  93. void pq_in_init(PktInQueue *pq)
  94. {
  95. pq->pqb.ic = NULL;
  96. pq->pqb.end.next = pq->pqb.end.prev = &pq->pqb.end;
  97. pq->after = pq_in_after;
  98. }
  99. void pq_out_init(PktOutQueue *pq)
  100. {
  101. pq->pqb.ic = NULL;
  102. pq->pqb.end.next = pq->pqb.end.prev = &pq->pqb.end;
  103. pq->after = pq_out_after;
  104. }
  105. void pq_in_clear(PktInQueue *pq)
  106. {
  107. PktIn *pkt;
  108. pq->pqb.ic = NULL;
  109. while ((pkt = pq_pop(pq)) != NULL) {
  110. /* No need to actually free these packets: pq_pop on a
  111. * PktInQueue will automatically move them to the free
  112. * queue. */
  113. }
  114. }
  115. void pq_out_clear(PktOutQueue *pq)
  116. {
  117. PktOut *pkt;
  118. pq->pqb.ic = NULL;
  119. while ((pkt = pq_pop(pq)) != NULL)
  120. ssh_free_pktout(pkt);
  121. }
  122. /*
  123. * Concatenate the contents of the two queues q1 and q2, and leave the
  124. * result in qdest. qdest must be either empty, or one of the input
  125. * queues.
  126. */
  127. void pq_base_concatenate(PacketQueueBase *qdest,
  128. PacketQueueBase *q1, PacketQueueBase *q2)
  129. {
  130. struct PacketQueueNode *head1, *tail1, *head2, *tail2;
  131. /*
  132. * Extract the contents from both input queues, and empty them.
  133. */
  134. head1 = (q1->end.next == &q1->end ? NULL : q1->end.next);
  135. tail1 = (q1->end.prev == &q1->end ? NULL : q1->end.prev);
  136. head2 = (q2->end.next == &q2->end ? NULL : q2->end.next);
  137. tail2 = (q2->end.prev == &q2->end ? NULL : q2->end.prev);
  138. q1->end.next = q1->end.prev = &q1->end;
  139. q2->end.next = q2->end.prev = &q2->end;
  140. /*
  141. * Link the two lists together, handling the case where one or
  142. * both is empty.
  143. */
  144. if (tail1)
  145. tail1->next = head2;
  146. else
  147. head1 = head2;
  148. if (head2)
  149. head2->prev = tail1;
  150. else
  151. tail2 = tail1;
  152. /*
  153. * Check the destination queue is currently empty. (If it was one
  154. * of the input queues, then it will be, because we emptied both
  155. * of those just a moment ago.)
  156. */
  157. assert(qdest->end.next == &qdest->end);
  158. assert(qdest->end.prev == &qdest->end);
  159. /*
  160. * If our concatenated list has anything in it, then put it in
  161. * dest.
  162. */
  163. if (!head1) {
  164. assert(!tail2);
  165. } else {
  166. assert(tail2);
  167. qdest->end.next = head1;
  168. qdest->end.prev = tail2;
  169. head1->prev = &qdest->end;
  170. tail2->next = &qdest->end;
  171. if (qdest->ic)
  172. queue_idempotent_callback(qdest->ic);
  173. }
  174. }
  175. /* ----------------------------------------------------------------------
  176. * Low-level functions for the packet structures themselves.
  177. */
  178. static void ssh_pkt_BinarySink_write(BinarySink *bs,
  179. const void *data, size_t len);
  180. PktOut *ssh_new_packet(void)
  181. {
  182. PktOut *pkt = snew(PktOut);
  183. BinarySink_INIT(pkt, ssh_pkt_BinarySink_write);
  184. pkt->data = NULL;
  185. pkt->length = 0;
  186. pkt->maxlen = 0;
  187. pkt->downstream_id = 0;
  188. pkt->additional_log_text = NULL;
  189. pkt->qnode.next = pkt->qnode.prev = NULL;
  190. pkt->qnode.on_free_queue = false;
  191. return pkt;
  192. }
  193. static void ssh_pkt_adddata(PktOut *pkt, const void *data, int len)
  194. {
  195. sgrowarrayn_nm(pkt->data, pkt->maxlen, pkt->length, len);
  196. memcpy(pkt->data + pkt->length, data, len);
  197. pkt->length += len;
  198. }
  199. static void ssh_pkt_BinarySink_write(BinarySink *bs,
  200. const void *data, size_t len)
  201. {
  202. PktOut *pkt = BinarySink_DOWNCAST(bs, PktOut);
  203. ssh_pkt_adddata(pkt, data, len);
  204. }
  205. void ssh_free_pktout(PktOut *pkt)
  206. {
  207. sfree(pkt->data);
  208. sfree(pkt);
  209. }
  210. /* ----------------------------------------------------------------------
  211. * Implement zombiechan_new() and its trivial vtable.
  212. */
  213. static void zombiechan_free(Channel *chan);
  214. static size_t zombiechan_send(
  215. Channel *chan, bool is_stderr, const void *, size_t);
  216. static void zombiechan_set_input_wanted(Channel *chan, bool wanted);
  217. static void zombiechan_do_nothing(Channel *chan);
  218. static void zombiechan_open_failure(Channel *chan, const char *);
  219. static bool zombiechan_want_close(Channel *chan, bool sent_eof, bool rcvd_eof);
  220. static char *zombiechan_log_close_msg(Channel *chan) { return NULL; }
  221. static const struct ChannelVtable zombiechan_channelvt = {
  222. zombiechan_free,
  223. zombiechan_do_nothing, /* open_confirmation */
  224. zombiechan_open_failure,
  225. zombiechan_send,
  226. zombiechan_do_nothing, /* send_eof */
  227. zombiechan_set_input_wanted,
  228. zombiechan_log_close_msg,
  229. zombiechan_want_close,
  230. chan_no_exit_status,
  231. chan_no_exit_signal,
  232. chan_no_exit_signal_numeric,
  233. chan_no_run_shell,
  234. chan_no_run_command,
  235. chan_no_run_subsystem,
  236. chan_no_enable_x11_forwarding,
  237. chan_no_enable_agent_forwarding,
  238. chan_no_allocate_pty,
  239. chan_no_set_env,
  240. chan_no_send_break,
  241. chan_no_send_signal,
  242. chan_no_change_window_size,
  243. chan_no_request_response,
  244. };
  245. Channel *zombiechan_new(void)
  246. {
  247. Channel *chan = snew(Channel);
  248. chan->vt = &zombiechan_channelvt;
  249. chan->initial_fixed_window_size = 0;
  250. return chan;
  251. }
  252. static void zombiechan_free(Channel *chan)
  253. {
  254. assert(chan->vt == &zombiechan_channelvt);
  255. sfree(chan);
  256. }
  257. static void zombiechan_do_nothing(Channel *chan)
  258. {
  259. assert(chan->vt == &zombiechan_channelvt);
  260. }
  261. static void zombiechan_open_failure(Channel *chan, const char *errtext)
  262. {
  263. assert(chan->vt == &zombiechan_channelvt);
  264. }
  265. static size_t zombiechan_send(Channel *chan, bool is_stderr,
  266. const void *data, size_t length)
  267. {
  268. assert(chan->vt == &zombiechan_channelvt);
  269. return 0;
  270. }
  271. static void zombiechan_set_input_wanted(Channel *chan, bool enable)
  272. {
  273. assert(chan->vt == &zombiechan_channelvt);
  274. }
  275. static bool zombiechan_want_close(Channel *chan, bool sent_eof, bool rcvd_eof)
  276. {
  277. return true;
  278. }
  279. /* ----------------------------------------------------------------------
  280. * Centralised standard methods for other channel implementations to
  281. * borrow.
  282. */
  283. void chan_remotely_opened_confirmation(Channel *chan)
  284. {
  285. unreachable("this channel type should never receive OPEN_CONFIRMATION");
  286. }
  287. void chan_remotely_opened_failure(Channel *chan, const char *errtext)
  288. {
  289. unreachable("this channel type should never receive OPEN_FAILURE");
  290. }
  291. bool chan_default_want_close(
  292. Channel *chan, bool sent_local_eof, bool rcvd_remote_eof)
  293. {
  294. /*
  295. * Default close policy: we start initiating the CHANNEL_CLOSE
  296. * procedure as soon as both sides of the channel have seen EOF.
  297. */
  298. return sent_local_eof && rcvd_remote_eof;
  299. }
  300. bool chan_no_exit_status(Channel *chan, int status)
  301. {
  302. return false;
  303. }
  304. bool chan_no_exit_signal(
  305. Channel *chan, ptrlen signame, bool core_dumped, ptrlen msg)
  306. {
  307. return false;
  308. }
  309. bool chan_no_exit_signal_numeric(
  310. Channel *chan, int signum, bool core_dumped, ptrlen msg)
  311. {
  312. return false;
  313. }
  314. bool chan_no_run_shell(Channel *chan)
  315. {
  316. return false;
  317. }
  318. bool chan_no_run_command(Channel *chan, ptrlen command)
  319. {
  320. return false;
  321. }
  322. bool chan_no_run_subsystem(Channel *chan, ptrlen subsys)
  323. {
  324. return false;
  325. }
  326. bool chan_no_enable_x11_forwarding(
  327. Channel *chan, bool oneshot, ptrlen authproto, ptrlen authdata,
  328. unsigned screen_number)
  329. {
  330. return false;
  331. }
  332. bool chan_no_enable_agent_forwarding(Channel *chan)
  333. {
  334. return false;
  335. }
  336. bool chan_no_allocate_pty(
  337. Channel *chan, ptrlen termtype, unsigned width, unsigned height,
  338. unsigned pixwidth, unsigned pixheight, struct ssh_ttymodes modes)
  339. {
  340. return false;
  341. }
  342. bool chan_no_set_env(Channel *chan, ptrlen var, ptrlen value)
  343. {
  344. return false;
  345. }
  346. bool chan_no_send_break(Channel *chan, unsigned length)
  347. {
  348. return false;
  349. }
  350. bool chan_no_send_signal(Channel *chan, ptrlen signame)
  351. {
  352. return false;
  353. }
  354. bool chan_no_change_window_size(
  355. Channel *chan, unsigned width, unsigned height,
  356. unsigned pixwidth, unsigned pixheight)
  357. {
  358. return false;
  359. }
  360. void chan_no_request_response(Channel *chan, bool success)
  361. {
  362. unreachable("this channel type should never send a want-reply request");
  363. }
  364. /* ----------------------------------------------------------------------
  365. * Common routines for handling SSH tty modes.
  366. */
  367. static unsigned real_ttymode_opcode(unsigned our_opcode, int ssh_version)
  368. {
  369. switch (our_opcode) {
  370. case TTYMODE_ISPEED:
  371. return ssh_version == 1 ? TTYMODE_ISPEED_SSH1 : TTYMODE_ISPEED_SSH2;
  372. case TTYMODE_OSPEED:
  373. return ssh_version == 1 ? TTYMODE_OSPEED_SSH1 : TTYMODE_OSPEED_SSH2;
  374. default:
  375. return our_opcode;
  376. }
  377. }
  378. static unsigned our_ttymode_opcode(unsigned real_opcode, int ssh_version)
  379. {
  380. if (ssh_version == 1) {
  381. switch (real_opcode) {
  382. case TTYMODE_ISPEED_SSH1:
  383. return TTYMODE_ISPEED;
  384. case TTYMODE_OSPEED_SSH1:
  385. return TTYMODE_OSPEED;
  386. default:
  387. return real_opcode;
  388. }
  389. } else {
  390. switch (real_opcode) {
  391. case TTYMODE_ISPEED_SSH2:
  392. return TTYMODE_ISPEED;
  393. case TTYMODE_OSPEED_SSH2:
  394. return TTYMODE_OSPEED;
  395. default:
  396. return real_opcode;
  397. }
  398. }
  399. }
  400. struct ssh_ttymodes get_ttymodes_from_conf(Seat *seat, Conf *conf)
  401. {
  402. struct ssh_ttymodes modes;
  403. size_t i;
  404. static const struct mode_name_type {
  405. const char *mode;
  406. int opcode;
  407. enum { TYPE_CHAR, TYPE_BOOL } type;
  408. } modes_names_types[] = {
  409. #define TTYMODE_CHAR(name, val, index) { #name, val, TYPE_CHAR },
  410. #define TTYMODE_FLAG(name, val, field, mask) { #name, val, TYPE_BOOL },
  411. #include "sshttymodes.h"
  412. #undef TTYMODE_CHAR
  413. #undef TTYMODE_FLAG
  414. };
  415. memset(&modes, 0, sizeof(modes));
  416. for (i = 0; i < lenof(modes_names_types); i++) {
  417. const struct mode_name_type *mode = &modes_names_types[i];
  418. const char *sval = conf_get_str_str(conf, CONF_ttymodes, mode->mode);
  419. char *to_free = NULL;
  420. if (!sval)
  421. sval = "N"; /* just in case */
  422. /*
  423. * sval[0] can be
  424. * - 'V', indicating that an explicit value follows it;
  425. * - 'A', indicating that we should pass the value through from
  426. * the local environment via get_ttymode; or
  427. * - 'N', indicating that we should explicitly not send this
  428. * mode.
  429. */
  430. if (sval[0] == 'A') {
  431. sval = to_free = seat_get_ttymode(seat, mode->mode);
  432. } else if (sval[0] == 'V') {
  433. sval++; /* skip the 'V' */
  434. } else {
  435. /* else 'N', or something from the future we don't understand */
  436. continue;
  437. }
  438. if (sval) {
  439. /*
  440. * Parse the string representation of the tty mode
  441. * into the integer value it will take on the wire.
  442. */
  443. unsigned ival = 0;
  444. switch (mode->type) {
  445. case TYPE_CHAR:
  446. if (*sval) {
  447. char *next = NULL;
  448. /* We know ctrlparse won't write to the string, so
  449. * casting away const is ugly but allowable. */
  450. ival = ctrlparse((char *)sval, &next);
  451. if (!next)
  452. ival = sval[0];
  453. } else {
  454. ival = 255; /* special value meaning "don't set" */
  455. }
  456. break;
  457. case TYPE_BOOL:
  458. if (stricmp(sval, "yes") == 0 ||
  459. stricmp(sval, "on") == 0 ||
  460. stricmp(sval, "true") == 0 ||
  461. stricmp(sval, "+") == 0)
  462. ival = 1; /* true */
  463. else if (stricmp(sval, "no") == 0 ||
  464. stricmp(sval, "off") == 0 ||
  465. stricmp(sval, "false") == 0 ||
  466. stricmp(sval, "-") == 0)
  467. ival = 0; /* false */
  468. else
  469. ival = (atoi(sval) != 0);
  470. break;
  471. default:
  472. unreachable("Bad mode->type");
  473. }
  474. modes.have_mode[mode->opcode] = true;
  475. modes.mode_val[mode->opcode] = ival;
  476. }
  477. sfree(to_free);
  478. }
  479. {
  480. unsigned ospeed, ispeed;
  481. /* Unpick the terminal-speed config string. */
  482. ospeed = ispeed = 38400; /* last-resort defaults */
  483. sscanf(conf_get_str(conf, CONF_termspeed), "%u,%u", &ospeed, &ispeed);
  484. /* Currently we unconditionally set these */
  485. modes.have_mode[TTYMODE_ISPEED] = true;
  486. modes.mode_val[TTYMODE_ISPEED] = ispeed;
  487. modes.have_mode[TTYMODE_OSPEED] = true;
  488. modes.mode_val[TTYMODE_OSPEED] = ospeed;
  489. }
  490. return modes;
  491. }
  492. struct ssh_ttymodes read_ttymodes_from_packet(
  493. BinarySource *bs, int ssh_version)
  494. {
  495. struct ssh_ttymodes modes;
  496. memset(&modes, 0, sizeof(modes));
  497. while (1) {
  498. unsigned real_opcode, our_opcode;
  499. real_opcode = get_byte(bs);
  500. if (real_opcode == TTYMODE_END_OF_LIST)
  501. break;
  502. if (real_opcode >= 160) {
  503. /*
  504. * RFC 4254 (and the SSH 1.5 spec): "Opcodes 160 to 255
  505. * are not yet defined, and cause parsing to stop (they
  506. * should only be used after any other data)."
  507. *
  508. * My interpretation of this is that if one of these
  509. * opcodes appears, it's not a parse _error_, but it is
  510. * something that we don't know how to parse even well
  511. * enough to step over it to find the next opcode, so we
  512. * stop parsing now and assume that the rest of the string
  513. * is composed entirely of things we don't understand and
  514. * (as usual for unsupported terminal modes) silently
  515. * ignore.
  516. */
  517. return modes;
  518. }
  519. our_opcode = our_ttymode_opcode(real_opcode, ssh_version);
  520. assert(our_opcode < TTYMODE_LIMIT);
  521. modes.have_mode[our_opcode] = true;
  522. if (ssh_version == 1 && real_opcode >= 1 && real_opcode <= 127)
  523. modes.mode_val[our_opcode] = get_byte(bs);
  524. else
  525. modes.mode_val[our_opcode] = get_uint32(bs);
  526. }
  527. return modes;
  528. }
  529. void write_ttymodes_to_packet(BinarySink *bs, int ssh_version,
  530. struct ssh_ttymodes modes)
  531. {
  532. unsigned i;
  533. for (i = 0; i < TTYMODE_LIMIT; i++) {
  534. if (modes.have_mode[i]) {
  535. unsigned val = modes.mode_val[i];
  536. unsigned opcode = real_ttymode_opcode(i, ssh_version);
  537. put_byte(bs, opcode);
  538. if (ssh_version == 1 && opcode >= 1 && opcode <= 127)
  539. put_byte(bs, val);
  540. else
  541. put_uint32(bs, val);
  542. }
  543. }
  544. put_byte(bs, TTYMODE_END_OF_LIST);
  545. }
  546. /* ----------------------------------------------------------------------
  547. * Routine for allocating a new channel ID, given a means of finding
  548. * the index field in a given channel structure.
  549. */
  550. unsigned alloc_channel_id_general(tree234 *channels, size_t localid_offset)
  551. {
  552. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  553. search234_state ss;
  554. /*
  555. * First-fit allocation of channel numbers: we always pick the
  556. * lowest unused one.
  557. *
  558. * Every channel before that, and no channel after it, has an ID
  559. * exactly equal to its tree index plus CHANNEL_NUMBER_OFFSET. So
  560. * we can use the search234 system to identify the length of that
  561. * initial sequence, in a single log-time pass down the channels
  562. * tree.
  563. */
  564. search234_start(&ss, channels);
  565. while (ss.element) {
  566. unsigned localid = *(unsigned *)((char *)ss.element + localid_offset);
  567. if (localid == ss.index + CHANNEL_NUMBER_OFFSET)
  568. search234_step(&ss, +1);
  569. else
  570. search234_step(&ss, -1);
  571. }
  572. /*
  573. * Now ss.index gives exactly the number of channels in that
  574. * initial sequence. So adding CHANNEL_NUMBER_OFFSET to it must
  575. * give precisely the lowest unused channel number.
  576. */
  577. return ss.index + CHANNEL_NUMBER_OFFSET;
  578. }
  579. /* ----------------------------------------------------------------------
  580. * Functions for handling the comma-separated strings used to store
  581. * lists of protocol identifiers in SSH-2.
  582. */
  583. void add_to_commasep(strbuf *buf, const char *data)
  584. {
  585. if (buf->len > 0)
  586. put_byte(buf, ',');
  587. put_data(buf, data, strlen(data));
  588. }
  589. bool get_commasep_word(ptrlen *list, ptrlen *word)
  590. {
  591. const char *comma;
  592. /*
  593. * Discard empty list elements, should there be any, because we
  594. * never want to return one as if it was a real string. (This
  595. * introduces a mild tolerance of badly formatted data in lists we
  596. * receive, but I think that's acceptable.)
  597. */
  598. while (list->len > 0 && *(const char *)list->ptr == ',') {
  599. list->ptr = (const char *)list->ptr + 1;
  600. list->len--;
  601. }
  602. if (!list->len)
  603. return false;
  604. comma = memchr(list->ptr, ',', list->len);
  605. if (!comma) {
  606. *word = *list;
  607. list->len = 0;
  608. } else {
  609. size_t wordlen = comma - (const char *)list->ptr;
  610. word->ptr = list->ptr;
  611. word->len = wordlen;
  612. list->ptr = (const char *)list->ptr + wordlen + 1;
  613. list->len -= wordlen + 1;
  614. }
  615. return true;
  616. }
  617. /* ----------------------------------------------------------------------
  618. * Functions for translating SSH packet type codes into their symbolic
  619. * string names.
  620. */
  621. #define TRANSLATE_UNIVERSAL(y, name, value) \
  622. if (type == value) return #name;
  623. #define TRANSLATE_KEX(y, name, value, ctx) \
  624. if (type == value && pkt_kctx == ctx) return #name;
  625. #define TRANSLATE_AUTH(y, name, value, ctx) \
  626. if (type == value && pkt_actx == ctx) return #name;
  627. const char *ssh1_pkt_type(int type)
  628. {
  629. SSH1_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, y);
  630. return "unknown";
  631. }
  632. const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
  633. {
  634. SSH2_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, TRANSLATE_KEX, TRANSLATE_AUTH, y);
  635. return "unknown";
  636. }
  637. #undef TRANSLATE_UNIVERSAL
  638. #undef TRANSLATE_KEX
  639. #undef TRANSLATE_AUTH
  640. /* ----------------------------------------------------------------------
  641. * Common helper function for clients and implementations of
  642. * PacketProtocolLayer.
  643. */
  644. void ssh_ppl_replace(PacketProtocolLayer *old, PacketProtocolLayer *new)
  645. {
  646. new->bpp = old->bpp;
  647. ssh_ppl_setup_queues(new, old->in_pq, old->out_pq);
  648. new->selfptr = old->selfptr;
  649. new->user_input = old->user_input;
  650. new->seat = old->seat;
  651. new->ssh = old->ssh;
  652. *new->selfptr = new;
  653. ssh_ppl_free(old);
  654. /* The new layer might need to be the first one that sends a
  655. * packet, so trigger a call to its main coroutine immediately. If
  656. * it doesn't need to go first, the worst that will do is return
  657. * straight away. */
  658. queue_idempotent_callback(&new->ic_process_queue);
  659. }
  660. void ssh_ppl_free(PacketProtocolLayer *ppl)
  661. {
  662. delete_callbacks_for_context(ppl);
  663. ppl->vt->free(ppl);
  664. }
  665. static void ssh_ppl_ic_process_queue_callback(void *context)
  666. {
  667. PacketProtocolLayer *ppl = (PacketProtocolLayer *)context;
  668. ssh_ppl_process_queue(ppl);
  669. }
  670. void ssh_ppl_setup_queues(PacketProtocolLayer *ppl,
  671. PktInQueue *inq, PktOutQueue *outq)
  672. {
  673. ppl->in_pq = inq;
  674. ppl->out_pq = outq;
  675. ppl->in_pq->pqb.ic = &ppl->ic_process_queue;
  676. ppl->ic_process_queue.fn = ssh_ppl_ic_process_queue_callback;
  677. ppl->ic_process_queue.ctx = ppl;
  678. /* If there's already something on the input queue, it will want
  679. * handling immediately. */
  680. if (pq_peek(ppl->in_pq))
  681. queue_idempotent_callback(&ppl->ic_process_queue);
  682. }
  683. void ssh_ppl_user_output_string_and_free(PacketProtocolLayer *ppl, char *text)
  684. {
  685. /* Messages sent via this function are from the SSH layer, not
  686. * from the server-side process, so they always have the stderr
  687. * flag set. */
  688. seat_stderr_pl(ppl->seat, ptrlen_from_asciz(text));
  689. sfree(text);
  690. }
  691. /* ----------------------------------------------------------------------
  692. * Common helper functions for clients and implementations of
  693. * BinaryPacketProtocol.
  694. */
  695. static void ssh_bpp_input_raw_data_callback(void *context)
  696. {
  697. BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
  698. Ssh *ssh = bpp->ssh; /* in case bpp is about to get freed */
  699. ssh_bpp_handle_input(bpp);
  700. /* If we've now cleared enough backlog on the input connection, we
  701. * may need to unfreeze it. */
  702. ssh_conn_processed_data(ssh);
  703. }
  704. static void ssh_bpp_output_packet_callback(void *context)
  705. {
  706. BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
  707. ssh_bpp_handle_output(bpp);
  708. }
  709. void ssh_bpp_common_setup(BinaryPacketProtocol *bpp)
  710. {
  711. pq_in_init(&bpp->in_pq);
  712. pq_out_init(&bpp->out_pq);
  713. bpp->input_eof = false;
  714. bpp->ic_in_raw.fn = ssh_bpp_input_raw_data_callback;
  715. bpp->ic_in_raw.ctx = bpp;
  716. bpp->ic_out_pq.fn = ssh_bpp_output_packet_callback;
  717. bpp->ic_out_pq.ctx = bpp;
  718. bpp->out_pq.pqb.ic = &bpp->ic_out_pq;
  719. }
  720. void ssh_bpp_free(BinaryPacketProtocol *bpp)
  721. {
  722. delete_callbacks_for_context(bpp);
  723. bpp->vt->free(bpp);
  724. }
  725. void ssh2_bpp_queue_disconnect(BinaryPacketProtocol *bpp,
  726. const char *msg, int category)
  727. {
  728. PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_DISCONNECT);
  729. put_uint32(pkt, category);
  730. put_stringz(pkt, msg);
  731. put_stringz(pkt, "en"); /* language tag */
  732. pq_push(&bpp->out_pq, pkt);
  733. }
  734. #define BITMAP_UNIVERSAL(y, name, value) \
  735. | (value >= y && value < y+32 ? 1UL << (value-y) : 0)
  736. #define BITMAP_CONDITIONAL(y, name, value, ctx) \
  737. BITMAP_UNIVERSAL(y, name, value)
  738. #define SSH2_BITMAP_WORD(y) \
  739. (0 SSH2_MESSAGE_TYPES(BITMAP_UNIVERSAL, BITMAP_CONDITIONAL, \
  740. BITMAP_CONDITIONAL, (32*y)))
  741. bool ssh2_bpp_check_unimplemented(BinaryPacketProtocol *bpp, PktIn *pktin)
  742. {
  743. static const unsigned valid_bitmap[] = {
  744. SSH2_BITMAP_WORD(0),
  745. SSH2_BITMAP_WORD(1),
  746. SSH2_BITMAP_WORD(2),
  747. SSH2_BITMAP_WORD(3),
  748. SSH2_BITMAP_WORD(4),
  749. SSH2_BITMAP_WORD(5),
  750. SSH2_BITMAP_WORD(6),
  751. SSH2_BITMAP_WORD(7),
  752. };
  753. if (pktin->type < 0x100 &&
  754. !((valid_bitmap[pktin->type >> 5] >> (pktin->type & 0x1F)) & 1)) {
  755. PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_UNIMPLEMENTED);
  756. put_uint32(pkt, pktin->sequence);
  757. pq_push(&bpp->out_pq, pkt);
  758. return true;
  759. }
  760. return false;
  761. }
  762. #undef BITMAP_UNIVERSAL
  763. #undef BITMAP_CONDITIONAL
  764. #undef SSH1_BITMAP_WORD
  765. /* ----------------------------------------------------------------------
  766. * Function to check a host key against any manually configured in Conf.
  767. */
  768. int verify_ssh_manual_host_key(
  769. Conf *conf, const char *fingerprint, ssh_key *key)
  770. {
  771. if (!conf_get_str_nthstrkey(conf, CONF_ssh_manual_hostkeys, 0))
  772. return -1; /* no manual keys configured */
  773. if (fingerprint) {
  774. /*
  775. * The fingerprint string we've been given will have things
  776. * like 'ssh-rsa 2048' at the front of it. Strip those off and
  777. * narrow down to just the colon-separated hex block at the
  778. * end of the string.
  779. */
  780. const char *p = strrchr(fingerprint, ' ');
  781. fingerprint = p ? p+1 : fingerprint;
  782. /* Quick sanity checks, including making sure it's in lowercase */
  783. assert(strlen(fingerprint) == 16*3 - 1);
  784. assert(fingerprint[2] == ':');
  785. assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
  786. if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys, fingerprint))
  787. return 1; /* success */
  788. }
  789. if (key) {
  790. /*
  791. * Construct the base64-encoded public key blob and see if
  792. * that's listed.
  793. */
  794. strbuf *binblob;
  795. char *base64blob;
  796. int atoms, i;
  797. binblob = strbuf_new();
  798. ssh_key_public_blob(key, BinarySink_UPCAST(binblob));
  799. atoms = (binblob->len + 2) / 3;
  800. base64blob = snewn(atoms * 4 + 1, char);
  801. for (i = 0; i < atoms; i++)
  802. base64_encode_atom(binblob->u + 3*i,
  803. binblob->len - 3*i, base64blob + 4*i);
  804. base64blob[atoms * 4] = '\0';
  805. strbuf_free(binblob);
  806. if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys, base64blob)) {
  807. sfree(base64blob);
  808. return 1; /* success */
  809. }
  810. sfree(base64blob);
  811. }
  812. return 0;
  813. }
  814. /* ----------------------------------------------------------------------
  815. * Common functions shared between SSH-1 layers.
  816. */
  817. bool ssh1_common_get_specials(
  818. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
  819. {
  820. /*
  821. * Don't bother offering IGNORE if we've decided the remote
  822. * won't cope with it, since we wouldn't bother sending it if
  823. * asked anyway.
  824. */
  825. if (!(ppl->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
  826. add_special(ctx, "IGNORE message", SS_NOP, 0);
  827. return true;
  828. }
  829. return false;
  830. }
  831. bool ssh1_common_filter_queue(PacketProtocolLayer *ppl)
  832. {
  833. PktIn *pktin;
  834. ptrlen msg;
  835. while ((pktin = pq_peek(ppl->in_pq)) != NULL) {
  836. switch (pktin->type) {
  837. case SSH1_MSG_DISCONNECT:
  838. msg = get_string(pktin);
  839. ssh_remote_error(ppl->ssh,
  840. "Remote side sent disconnect message:\n\"%.*s\"",
  841. PTRLEN_PRINTF(msg));
  842. /* don't try to pop the queue, because we've been freed! */
  843. return true; /* indicate that we've been freed */
  844. case SSH1_MSG_DEBUG:
  845. msg = get_string(pktin);
  846. ppl_logevent("Remote debug message: %.*s", PTRLEN_PRINTF(msg));
  847. pq_pop(ppl->in_pq);
  848. break;
  849. case SSH1_MSG_IGNORE:
  850. /* Do nothing, because we're ignoring it! Duhh. */
  851. pq_pop(ppl->in_pq);
  852. break;
  853. default:
  854. return false;
  855. }
  856. }
  857. return false;
  858. }
  859. void ssh1_compute_session_id(
  860. unsigned char *session_id, const unsigned char *cookie,
  861. RSAKey *hostkey, RSAKey *servkey)
  862. {
  863. ssh_hash *hash = ssh_hash_new(&ssh_md5);
  864. for (size_t i = (mp_get_nbits(hostkey->modulus) + 7) / 8; i-- ;)
  865. put_byte(hash, mp_get_byte(hostkey->modulus, i));
  866. for (size_t i = (mp_get_nbits(servkey->modulus) + 7) / 8; i-- ;)
  867. put_byte(hash, mp_get_byte(servkey->modulus, i));
  868. put_data(hash, cookie, 8);
  869. ssh_hash_final(hash, session_id);
  870. }
  871. /* ----------------------------------------------------------------------
  872. * Other miscellaneous utility functions.
  873. */
  874. void free_rportfwd(struct ssh_rportfwd *rpf)
  875. {
  876. if (rpf) {
  877. sfree(rpf->log_description);
  878. sfree(rpf->shost);
  879. sfree(rpf->dhost);
  880. sfree(rpf);
  881. }
  882. }