sshcommon.c 31 KB

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