common.c 31 KB

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