sshcommon.c 31 KB

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