sshcommon.c 29 KB

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