sshcommon.c 32 KB

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