sshcommon.c 30 KB

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