common.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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_pl(strbuf *buf, ptrlen data)
  520. {
  521. if (buf->len > 0)
  522. put_byte(buf, ',');
  523. put_datapl(buf, data);
  524. }
  525. void add_to_commasep(strbuf *buf, const char *data)
  526. {
  527. add_to_commasep_pl(buf, ptrlen_from_asciz(data));
  528. }
  529. bool get_commasep_word(ptrlen *list, ptrlen *word)
  530. {
  531. const char *comma;
  532. /*
  533. * Discard empty list elements, should there be any, because we
  534. * never want to return one as if it was a real string. (This
  535. * introduces a mild tolerance of badly formatted data in lists we
  536. * receive, but I think that's acceptable.)
  537. */
  538. while (list->len > 0 && *(const char *)list->ptr == ',') {
  539. list->ptr = (const char *)list->ptr + 1;
  540. list->len--;
  541. }
  542. if (!list->len)
  543. return false;
  544. comma = memchr(list->ptr, ',', list->len);
  545. if (!comma) {
  546. *word = *list;
  547. list->len = 0;
  548. } else {
  549. size_t wordlen = comma - (const char *)list->ptr;
  550. word->ptr = list->ptr;
  551. word->len = wordlen;
  552. list->ptr = (const char *)list->ptr + wordlen + 1;
  553. list->len -= wordlen + 1;
  554. }
  555. return true;
  556. }
  557. /* ----------------------------------------------------------------------
  558. * Functions for translating SSH packet type codes into their symbolic
  559. * string names.
  560. */
  561. #define TRANSLATE_UNIVERSAL(y, name, value) \
  562. if (type == value) return #name;
  563. #define TRANSLATE_KEX(y, name, value, ctx) \
  564. if (type == value && pkt_kctx == ctx) return #name;
  565. #define TRANSLATE_AUTH(y, name, value, ctx) \
  566. if (type == value && pkt_actx == ctx) return #name;
  567. const char *ssh1_pkt_type(int type)
  568. {
  569. SSH1_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, y);
  570. return "unknown";
  571. }
  572. const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
  573. {
  574. SSH2_MESSAGE_TYPES(TRANSLATE_UNIVERSAL, TRANSLATE_KEX, TRANSLATE_AUTH, y);
  575. return "unknown";
  576. }
  577. #undef TRANSLATE_UNIVERSAL
  578. #undef TRANSLATE_KEX
  579. #undef TRANSLATE_AUTH
  580. /* ----------------------------------------------------------------------
  581. * Common helper function for clients and implementations of
  582. * PacketProtocolLayer.
  583. */
  584. void ssh_ppl_replace(PacketProtocolLayer *old, PacketProtocolLayer *new)
  585. {
  586. new->bpp = old->bpp;
  587. ssh_ppl_setup_queues(new, old->in_pq, old->out_pq);
  588. new->selfptr = old->selfptr;
  589. new->seat = old->seat;
  590. new->ssh = old->ssh;
  591. *new->selfptr = new;
  592. ssh_ppl_free(old);
  593. /* The new layer might need to be the first one that sends a
  594. * packet, so trigger a call to its main coroutine immediately. If
  595. * it doesn't need to go first, the worst that will do is return
  596. * straight away. */
  597. queue_idempotent_callback(&new->ic_process_queue);
  598. }
  599. void ssh_ppl_free(PacketProtocolLayer *ppl)
  600. {
  601. delete_callbacks_for_context(ppl);
  602. ppl->vt->free(ppl);
  603. }
  604. static void ssh_ppl_ic_process_queue_callback(void *context)
  605. {
  606. PacketProtocolLayer *ppl = (PacketProtocolLayer *)context;
  607. ssh_ppl_process_queue(ppl);
  608. }
  609. void ssh_ppl_setup_queues(PacketProtocolLayer *ppl,
  610. PktInQueue *inq, PktOutQueue *outq)
  611. {
  612. ppl->in_pq = inq;
  613. ppl->out_pq = outq;
  614. ppl->in_pq->pqb.ic = &ppl->ic_process_queue;
  615. ppl->ic_process_queue.fn = ssh_ppl_ic_process_queue_callback;
  616. ppl->ic_process_queue.ctx = ppl;
  617. /* If there's already something on the input queue, it will want
  618. * handling immediately. */
  619. if (pq_peek(ppl->in_pq))
  620. queue_idempotent_callback(&ppl->ic_process_queue);
  621. }
  622. void ssh_ppl_user_output_string_and_free(PacketProtocolLayer *ppl, char *text)
  623. {
  624. /* Messages sent via this function are from the SSH layer, not
  625. * from the server-side process, so they always have the stderr
  626. * flag set. */
  627. seat_stderr_pl(ppl->seat, ptrlen_from_asciz(text));
  628. sfree(text);
  629. }
  630. size_t ssh_ppl_default_queued_data_size(PacketProtocolLayer *ppl)
  631. {
  632. return ppl->out_pq->pqb.total_size;
  633. }
  634. void ssh_ppl_default_final_output(PacketProtocolLayer *ppl)
  635. {
  636. }
  637. static void ssh_ppl_prompts_callback(void *ctx)
  638. {
  639. ssh_ppl_process_queue((PacketProtocolLayer *)ctx);
  640. }
  641. prompts_t *ssh_ppl_new_prompts(PacketProtocolLayer *ppl)
  642. {
  643. prompts_t *p = new_prompts();
  644. p->callback = ssh_ppl_prompts_callback;
  645. p->callback_ctx = ppl;
  646. return p;
  647. }
  648. /* ----------------------------------------------------------------------
  649. * Common helper functions for clients and implementations of
  650. * BinaryPacketProtocol.
  651. */
  652. static void ssh_bpp_input_raw_data_callback(void *context)
  653. {
  654. BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
  655. Ssh *ssh = bpp->ssh; /* in case bpp is about to get freed */
  656. ssh_bpp_handle_input(bpp);
  657. /* If we've now cleared enough backlog on the input connection, we
  658. * may need to unfreeze it. */
  659. ssh_conn_processed_data(ssh);
  660. }
  661. static void ssh_bpp_output_packet_callback(void *context)
  662. {
  663. BinaryPacketProtocol *bpp = (BinaryPacketProtocol *)context;
  664. ssh_bpp_handle_output(bpp);
  665. }
  666. void ssh_bpp_common_setup(BinaryPacketProtocol *bpp)
  667. {
  668. pq_in_init(&bpp->in_pq);
  669. pq_out_init(&bpp->out_pq);
  670. bpp->input_eof = false;
  671. bpp->ic_in_raw.fn = ssh_bpp_input_raw_data_callback;
  672. bpp->ic_in_raw.ctx = bpp;
  673. bpp->ic_out_pq.fn = ssh_bpp_output_packet_callback;
  674. bpp->ic_out_pq.ctx = bpp;
  675. bpp->out_pq.pqb.ic = &bpp->ic_out_pq;
  676. }
  677. void ssh_bpp_free(BinaryPacketProtocol *bpp)
  678. {
  679. delete_callbacks_for_context(bpp);
  680. bpp->vt->free(bpp);
  681. }
  682. void ssh2_bpp_queue_disconnect(BinaryPacketProtocol *bpp,
  683. const char *msg, int category)
  684. {
  685. PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_DISCONNECT);
  686. put_uint32(pkt, category);
  687. put_stringz(pkt, msg);
  688. put_stringz(pkt, "en"); /* language tag */
  689. pq_push(&bpp->out_pq, pkt);
  690. }
  691. #define BITMAP_UNIVERSAL(y, name, value) \
  692. | (value >= y && value < y+32 \
  693. ? 1UL << (value >= y && value < y+32 ? (value-y) : 0) \
  694. : 0)
  695. #define BITMAP_CONDITIONAL(y, name, value, ctx) \
  696. BITMAP_UNIVERSAL(y, name, value)
  697. #define SSH2_BITMAP_WORD(y) \
  698. (0 SSH2_MESSAGE_TYPES(BITMAP_UNIVERSAL, BITMAP_CONDITIONAL, \
  699. BITMAP_CONDITIONAL, (32*y)))
  700. bool ssh2_bpp_check_unimplemented(BinaryPacketProtocol *bpp, PktIn *pktin)
  701. {
  702. static const unsigned valid_bitmap[] = {
  703. SSH2_BITMAP_WORD(0),
  704. SSH2_BITMAP_WORD(1),
  705. SSH2_BITMAP_WORD(2),
  706. SSH2_BITMAP_WORD(3),
  707. SSH2_BITMAP_WORD(4),
  708. SSH2_BITMAP_WORD(5),
  709. SSH2_BITMAP_WORD(6),
  710. SSH2_BITMAP_WORD(7),
  711. };
  712. if (pktin->type < 0x100 &&
  713. !((valid_bitmap[pktin->type >> 5] >> (pktin->type & 0x1F)) & 1)) {
  714. PktOut *pkt = ssh_bpp_new_pktout(bpp, SSH2_MSG_UNIMPLEMENTED);
  715. put_uint32(pkt, pktin->sequence);
  716. pq_push(&bpp->out_pq, pkt);
  717. return true;
  718. }
  719. return false;
  720. }
  721. #undef BITMAP_UNIVERSAL
  722. #undef BITMAP_CONDITIONAL
  723. #undef SSH2_BITMAP_WORD
  724. /* ----------------------------------------------------------------------
  725. * Centralised component of SSH host key verification.
  726. *
  727. * verify_ssh_host_key is called from both the SSH-1 and SSH-2
  728. * transport layers, and does the initial work of checking whether the
  729. * host key is already known. If so, it returns success on its own
  730. * account; otherwise, it calls out to the Seat to give an interactive
  731. * prompt (the nature of which varies depending on the Seat itself).
  732. */
  733. SeatPromptResult verify_ssh_host_key(
  734. InteractionReadySeat iseat, Conf *conf, const char *host, int port,
  735. ssh_key *key, const char *keytype, char *keystr, const char *keydisp,
  736. char **fingerprints, int ca_count,
  737. void (*callback)(void *ctx, SeatPromptResult result), void *ctx)
  738. {
  739. /*
  740. * First, check if the Conf includes a manual specification of the
  741. * expected host key. If so, that completely supersedes everything
  742. * else, including the normal host key cache _and_ including
  743. * manual overrides: we return success or failure immediately,
  744. * entirely based on whether the key matches the Conf.
  745. */
  746. if (conf_get_str_nthstrkey(conf, CONF_ssh_manual_hostkeys, 0)) {
  747. if (fingerprints) {
  748. for (size_t i = 0; i < SSH_N_FPTYPES; i++) {
  749. /*
  750. * Each fingerprint string we've been given will have
  751. * things like 'ssh-rsa 2048' at the front of it. Strip
  752. * those off and narrow down to just the hash at the end
  753. * of the string.
  754. */
  755. const char *fingerprint = fingerprints[i];
  756. if (!fingerprint)
  757. continue;
  758. const char *p = strrchr(fingerprint, ' ');
  759. fingerprint = p ? p+1 : fingerprint;
  760. if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys,
  761. fingerprint))
  762. return SPR_OK;
  763. }
  764. }
  765. if (key) {
  766. /*
  767. * Construct the base64-encoded public key blob and see if
  768. * that's listed.
  769. */
  770. strbuf *binblob;
  771. char *base64blob;
  772. int atoms, i;
  773. binblob = strbuf_new();
  774. ssh_key_public_blob(key, BinarySink_UPCAST(binblob));
  775. atoms = (binblob->len + 2) / 3;
  776. base64blob = snewn(atoms * 4 + 1, char);
  777. for (i = 0; i < atoms; i++)
  778. base64_encode_atom(binblob->u + 3*i,
  779. binblob->len - 3*i, base64blob + 4*i);
  780. base64blob[atoms * 4] = '\0';
  781. strbuf_free(binblob);
  782. if (conf_get_str_str_opt(conf, CONF_ssh_manual_hostkeys,
  783. base64blob)) {
  784. sfree(base64blob);
  785. return SPR_OK;
  786. }
  787. sfree(base64blob);
  788. }
  789. return SPR_SW_ABORT("Host key not in manually configured list");
  790. }
  791. /*
  792. * Next, check the host key cache.
  793. */
  794. int storage_status = check_stored_host_key(host, port, keytype, keystr);
  795. if (storage_status == 0) /* matching key was found in the cache */
  796. return SPR_OK;
  797. /*
  798. * The key is either missing from the cache, or does not match.
  799. * Either way, fall back to an interactive prompt from the Seat.
  800. */
  801. SeatDialogText *text = seat_dialog_text_new();
  802. const SeatDialogPromptDescriptions *pds =
  803. seat_prompt_descriptions(iseat.seat);
  804. FingerprintType fptype_default =
  805. ssh2_pick_default_fingerprint(fingerprints);
  806. seat_dialog_text_append(
  807. text, SDT_TITLE, "%s Security Alert", appname);
  808. HelpCtx helpctx;
  809. if (key && ssh_key_alg(key)->is_certificate) {
  810. seat_dialog_text_append(
  811. text, SDT_SCARY_HEADING, "WARNING - POTENTIAL SECURITY BREACH!");
  812. seat_dialog_text_append(
  813. text, SDT_PARA, "This server presented a certified host key:");
  814. seat_dialog_text_append(
  815. text, SDT_DISPLAY, "%s (port %d)", host, port);
  816. if (ca_count) {
  817. seat_dialog_text_append(
  818. text, SDT_PARA, "which was signed by a different "
  819. "certification authority from the %s %s is configured to "
  820. "trust for this server.", ca_count > 1 ? "ones" : "one",
  821. appname);
  822. if (storage_status == 2) {
  823. seat_dialog_text_append(
  824. text, SDT_PARA, "ALSO, that key does not match the key "
  825. "%s had previously cached for this server.", appname);
  826. seat_dialog_text_append(
  827. text, SDT_PARA, "This means that either another "
  828. "certification authority is operating in this realm AND "
  829. "the server administrator has changed the host key, or "
  830. "you have actually connected to another computer "
  831. "pretending to be the server.");
  832. } else {
  833. seat_dialog_text_append(
  834. text, SDT_PARA, "This means that either another "
  835. "certification authority is operating in this realm, or "
  836. "you have actually connected to another computer "
  837. "pretending to be the server.");
  838. }
  839. } else {
  840. assert(storage_status == 2);
  841. seat_dialog_text_append(
  842. text, SDT_PARA, "which does not match the certified key %s "
  843. "had previously cached for this server.", appname);
  844. seat_dialog_text_append(
  845. text, SDT_PARA, "This means that either the server "
  846. "administrator has changed the host key, or you have actually "
  847. "connected to another computer pretending to be the server.");
  848. }
  849. seat_dialog_text_append(
  850. text, SDT_PARA, "The new %s key fingerprint is:", keytype);
  851. seat_dialog_text_append(
  852. text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
  853. helpctx = HELPCTX(errors_cert_mismatch);
  854. } else if (storage_status == 1) {
  855. seat_dialog_text_append(
  856. text, SDT_PARA, "The host key is not cached for this server:");
  857. seat_dialog_text_append(
  858. text, SDT_DISPLAY, "%s (port %d)", host, port);
  859. seat_dialog_text_append(
  860. text, SDT_PARA, "You have no guarantee that the server is the "
  861. "computer you think it is.");
  862. seat_dialog_text_append(
  863. text, SDT_PARA, "The server's %s key fingerprint is:", keytype);
  864. seat_dialog_text_append(
  865. text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
  866. helpctx = HELPCTX(errors_hostkey_absent);
  867. } else {
  868. seat_dialog_text_append(
  869. text, SDT_SCARY_HEADING, "WARNING - POTENTIAL SECURITY BREACH!");
  870. seat_dialog_text_append(
  871. text, SDT_PARA, "The host key does not match the one %s has "
  872. "cached for this server:", appname);
  873. seat_dialog_text_append(
  874. text, SDT_DISPLAY, "%s (port %d)", host, port);
  875. seat_dialog_text_append(
  876. text, SDT_PARA, "This means that either the server administrator "
  877. "has changed the host key, or you have actually connected to "
  878. "another computer pretending to be the server.");
  879. seat_dialog_text_append(
  880. text, SDT_PARA, "The new %s key fingerprint is:", keytype);
  881. seat_dialog_text_append(
  882. text, SDT_DISPLAY, "%s", fingerprints[fptype_default]);
  883. helpctx = HELPCTX(errors_hostkey_changed);
  884. }
  885. /* The above text is printed even in batch mode. Here's where we stop if
  886. * we can't present interactive prompts. */
  887. seat_dialog_text_append(
  888. text, SDT_BATCH_ABORT, "Connection abandoned.");
  889. if (storage_status == 1) {
  890. seat_dialog_text_append(
  891. text, SDT_PARA, "If you trust this host, %s to add the key to "
  892. "%s's cache and carry on connecting.",
  893. pds->hk_accept_action, appname);
  894. if (key && ssh_key_alg(key)->is_certificate) {
  895. seat_dialog_text_append(
  896. text, SDT_PARA, "(Storing this certified key in the cache "
  897. "will NOT cause its certification authority to be trusted "
  898. "for any other key or host.)");
  899. }
  900. seat_dialog_text_append(
  901. text, SDT_PARA, "If you want to carry on connecting just once, "
  902. "without adding the key to the cache, %s.",
  903. pds->hk_connect_once_action);
  904. seat_dialog_text_append(
  905. text, SDT_PARA, "If you do not trust this host, %s to abandon the "
  906. "connection.", pds->hk_cancel_action);
  907. seat_dialog_text_append(
  908. text, SDT_PROMPT, "Store key in cache?");
  909. } else {
  910. seat_dialog_text_append(
  911. text, SDT_PARA, "If you were expecting this change and trust the "
  912. "new key, %s to update %s's cache and carry on connecting.",
  913. pds->hk_accept_action, appname);
  914. if (key && ssh_key_alg(key)->is_certificate) {
  915. seat_dialog_text_append(
  916. text, SDT_PARA, "(Storing this certified key in the cache "
  917. "will NOT cause its certification authority to be trusted "
  918. "for any other key or host.)");
  919. }
  920. seat_dialog_text_append(
  921. text, SDT_PARA, "If you want to carry on connecting but without "
  922. "updating the cache, %s.", pds->hk_connect_once_action);
  923. seat_dialog_text_append(
  924. text, SDT_PARA, "If you want to abandon the connection "
  925. "completely, %s to cancel. %s is the ONLY guaranteed safe choice.",
  926. pds->hk_cancel_action, pds->hk_cancel_action_Participle);
  927. seat_dialog_text_append(
  928. text, SDT_PROMPT, "Update cached key?");
  929. }
  930. seat_dialog_text_append(text, SDT_MORE_INFO_KEY,
  931. "Full text of host's public key");
  932. seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_BLOB, "%s", keydisp);
  933. if (fingerprints[SSH_FPTYPE_SHA256]) {
  934. seat_dialog_text_append(text, SDT_MORE_INFO_KEY, "SHA256 fingerprint");
  935. seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_SHORT, "%s",
  936. fingerprints[SSH_FPTYPE_SHA256]);
  937. }
  938. if (fingerprints[SSH_FPTYPE_MD5]) {
  939. seat_dialog_text_append(text, SDT_MORE_INFO_KEY, "MD5 fingerprint");
  940. seat_dialog_text_append(text, SDT_MORE_INFO_VALUE_SHORT, "%s",
  941. fingerprints[SSH_FPTYPE_MD5]);
  942. }
  943. SeatPromptResult toret = seat_confirm_ssh_host_key(
  944. iseat, host, port, keytype, keystr, text, helpctx, callback, ctx);
  945. seat_dialog_text_free(text);
  946. return toret;
  947. }
  948. SeatPromptResult confirm_weak_crypto_primitive(
  949. InteractionReadySeat iseat, const char *algtype, const char *algname,
  950. void (*callback)(void *ctx, SeatPromptResult result), void *ctx,
  951. WeakCryptoReason wcr)
  952. {
  953. SeatDialogText *text = seat_dialog_text_new();
  954. const SeatDialogPromptDescriptions *pds =
  955. seat_prompt_descriptions(iseat.seat);
  956. seat_dialog_text_append(text, SDT_TITLE, "%s Security Alert", appname);
  957. switch (wcr) {
  958. case WCR_BELOW_THRESHOLD:
  959. seat_dialog_text_append(
  960. text, SDT_PARA,
  961. "The first %s supported by the server is %s, "
  962. "which is below the configured warning threshold.",
  963. algtype, algname);
  964. break;
  965. case WCR_TERRAPIN:
  966. case WCR_TERRAPIN_AVOIDABLE:
  967. seat_dialog_text_append(
  968. text, SDT_PARA,
  969. "The %s selected for this session is %s, "
  970. "which, with this server, is vulnerable to the 'Terrapin' attack "
  971. "CVE-2023-48795, potentially allowing an attacker to modify "
  972. "the encrypted session.",
  973. algtype, algname);
  974. seat_dialog_text_append(
  975. text, SDT_PARA,
  976. "Upgrading, patching, or reconfiguring this SSH server is the "
  977. "best way to avoid this vulnerability, if possible.");
  978. if (wcr == WCR_TERRAPIN_AVOIDABLE) {
  979. seat_dialog_text_append(
  980. text, SDT_PARA,
  981. "You can also avoid this vulnerability by abandoning "
  982. "this connection, moving ChaCha20 to below the "
  983. "'warn below here' line in PuTTY's SSH cipher "
  984. "configuration (so that an algorithm without the "
  985. "vulnerability will be selected), and starting a new "
  986. "connection.");
  987. }
  988. break;
  989. default:
  990. unreachable("bad WeakCryptoReason");
  991. }
  992. /* In batch mode, we print the above information and then this
  993. * abort message, and stop. */
  994. seat_dialog_text_append(text, SDT_BATCH_ABORT, "Connection abandoned.");
  995. seat_dialog_text_append(
  996. text, SDT_PARA, "To accept the risk and continue, %s. "
  997. "To abandon the connection, %s.",
  998. pds->weak_accept_action, pds->weak_cancel_action);
  999. seat_dialog_text_append(text, SDT_PROMPT, "Continue with connection?");
  1000. SeatPromptResult toret = seat_confirm_weak_crypto_primitive(
  1001. iseat, text, callback, ctx);
  1002. seat_dialog_text_free(text);
  1003. return toret;
  1004. }
  1005. SeatPromptResult confirm_weak_cached_hostkey(
  1006. InteractionReadySeat iseat, const char *algname, const char **betteralgs,
  1007. void (*callback)(void *ctx, SeatPromptResult result), void *ctx)
  1008. {
  1009. SeatDialogText *text = seat_dialog_text_new();
  1010. const SeatDialogPromptDescriptions *pds =
  1011. seat_prompt_descriptions(iseat.seat);
  1012. seat_dialog_text_append(text, SDT_TITLE, "%s Security Alert", appname);
  1013. seat_dialog_text_append(
  1014. text, SDT_PARA,
  1015. "The first host key type we have stored for this server "
  1016. "is %s, which is below the configured warning threshold.", algname);
  1017. seat_dialog_text_append(
  1018. text, SDT_PARA,
  1019. "The server also provides the following types of host key "
  1020. "above the threshold, which we do not have stored:");
  1021. for (const char **p = betteralgs; *p; p++)
  1022. seat_dialog_text_append(text, SDT_DISPLAY, "%s", *p);
  1023. /* In batch mode, we print the above information and then this
  1024. * abort message, and stop. */
  1025. seat_dialog_text_append(text, SDT_BATCH_ABORT, "Connection abandoned.");
  1026. seat_dialog_text_append(
  1027. text, SDT_PARA, "To accept the risk and continue, %s. "
  1028. "To abandon the connection, %s.",
  1029. pds->weak_accept_action, pds->weak_cancel_action);
  1030. seat_dialog_text_append(text, SDT_PROMPT, "Continue with connection?");
  1031. SeatPromptResult toret = seat_confirm_weak_cached_hostkey(
  1032. iseat, text, callback, ctx);
  1033. seat_dialog_text_free(text);
  1034. return toret;
  1035. }
  1036. /* ----------------------------------------------------------------------
  1037. * Common functions shared between SSH-1 layers.
  1038. */
  1039. bool ssh1_common_get_specials(
  1040. PacketProtocolLayer *ppl, add_special_fn_t add_special, void *ctx)
  1041. {
  1042. /*
  1043. * Don't bother offering IGNORE if we've decided the remote
  1044. * won't cope with it, since we wouldn't bother sending it if
  1045. * asked anyway.
  1046. */
  1047. if (!(ppl->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
  1048. add_special(ctx, "IGNORE message", SS_NOP, 0);
  1049. return true;
  1050. }
  1051. return false;
  1052. }
  1053. bool ssh1_common_filter_queue(PacketProtocolLayer *ppl)
  1054. {
  1055. PktIn *pktin;
  1056. ptrlen msg;
  1057. while ((pktin = pq_peek(ppl->in_pq)) != NULL) {
  1058. switch (pktin->type) {
  1059. case SSH1_MSG_DISCONNECT:
  1060. msg = get_string(pktin);
  1061. ssh_remote_error(ppl->ssh,
  1062. "Remote side sent disconnect message:\n\"%.*s\"",
  1063. PTRLEN_PRINTF(msg));
  1064. /* don't try to pop the queue, because we've been freed! */
  1065. return true; /* indicate that we've been freed */
  1066. case SSH1_MSG_DEBUG:
  1067. msg = get_string(pktin);
  1068. ppl_logevent("Remote debug message: %.*s", PTRLEN_PRINTF(msg));
  1069. pq_pop(ppl->in_pq);
  1070. break;
  1071. case SSH1_MSG_IGNORE:
  1072. /* Do nothing, because we're ignoring it! Duhh. */
  1073. pq_pop(ppl->in_pq);
  1074. break;
  1075. default:
  1076. return false;
  1077. }
  1078. }
  1079. return false;
  1080. }
  1081. void ssh1_compute_session_id(
  1082. unsigned char *session_id, const unsigned char *cookie,
  1083. RSAKey *hostkey, RSAKey *servkey)
  1084. {
  1085. ssh_hash *hash = ssh_hash_new(&ssh_md5);
  1086. for (size_t i = (mp_get_nbits(hostkey->modulus) + 7) / 8; i-- ;)
  1087. put_byte(hash, mp_get_byte(hostkey->modulus, i));
  1088. for (size_t i = (mp_get_nbits(servkey->modulus) + 7) / 8; i-- ;)
  1089. put_byte(hash, mp_get_byte(servkey->modulus, i));
  1090. put_data(hash, cookie, 8);
  1091. ssh_hash_final(hash, session_id);
  1092. }
  1093. /* ----------------------------------------------------------------------
  1094. * Wrapper function to handle the abort-connection modes of a
  1095. * SeatPromptResult without a lot of verbiage at every call site.
  1096. *
  1097. * Can become ssh_sw_abort or ssh_user_close, depending on the kind of
  1098. * negative SeatPromptResult.
  1099. */
  1100. void ssh_spr_close(Ssh *ssh, SeatPromptResult spr, const char *context)
  1101. {
  1102. if (spr.kind == SPRK_USER_ABORT) {
  1103. ssh_user_close(ssh, "User aborted at %s", context);
  1104. } else {
  1105. assert(spr.kind == SPRK_SW_ABORT);
  1106. char *err = spr_get_error_message(spr);
  1107. ssh_sw_abort(ssh, "%s", err);
  1108. sfree(err);
  1109. }
  1110. }