1
0

common_p.c 33 KB

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