ssh2bpp.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. /*
  2. * Binary packet protocol for SSH-2.
  3. */
  4. #include <assert.h>
  5. #include "putty.h"
  6. #include "ssh.h"
  7. #include "sshbpp.h"
  8. #include "sshcr.h"
  9. struct ssh2_bpp_direction {
  10. unsigned long sequence;
  11. ssh_cipher *cipher;
  12. ssh2_mac *mac;
  13. bool etm_mode;
  14. const ssh_compression_alg *pending_compression;
  15. };
  16. struct ssh2_bpp_state {
  17. int crState;
  18. long len, pad, payload, packetlen, maclen, length, maxlen;
  19. unsigned char *buf;
  20. size_t bufsize;
  21. unsigned char *data;
  22. unsigned cipherblk;
  23. PktIn *pktin;
  24. struct DataTransferStats *stats;
  25. bool cbc_ignore_workaround;
  26. struct ssh2_bpp_direction in, out;
  27. /* comp and decomp logically belong in the per-direction
  28. * substructure, except that they have different types */
  29. ssh_decompressor *in_decomp;
  30. ssh_compressor *out_comp;
  31. bool is_server;
  32. bool pending_newkeys;
  33. bool pending_compression, seen_userauth_success;
  34. BinaryPacketProtocol bpp;
  35. };
  36. static void ssh2_bpp_free(BinaryPacketProtocol *bpp);
  37. static void ssh2_bpp_handle_input(BinaryPacketProtocol *bpp);
  38. static void ssh2_bpp_handle_output(BinaryPacketProtocol *bpp);
  39. static PktOut *ssh2_bpp_new_pktout(int type);
  40. static const struct BinaryPacketProtocolVtable ssh2_bpp_vtable = {
  41. ssh2_bpp_free,
  42. ssh2_bpp_handle_input,
  43. ssh2_bpp_handle_output,
  44. ssh2_bpp_new_pktout,
  45. ssh2_bpp_queue_disconnect, /* in sshcommon.c */
  46. };
  47. BinaryPacketProtocol *ssh2_bpp_new(
  48. LogContext *logctx, struct DataTransferStats *stats, bool is_server)
  49. {
  50. struct ssh2_bpp_state *s = snew(struct ssh2_bpp_state);
  51. memset(s, 0, sizeof(*s));
  52. s->bpp.vt = &ssh2_bpp_vtable;
  53. s->bpp.logctx = logctx;
  54. s->stats = stats;
  55. s->is_server = is_server;
  56. ssh_bpp_common_setup(&s->bpp);
  57. return &s->bpp;
  58. }
  59. static void ssh2_bpp_free_outgoing_crypto(struct ssh2_bpp_state *s)
  60. {
  61. /*
  62. * We must free the MAC before the cipher, because sometimes the
  63. * MAC is not actually separately allocated but just a different
  64. * facet of the same object as the cipher, in which case
  65. * ssh2_mac_free does nothing and ssh_cipher_free does the actual
  66. * freeing. So if we freed the cipher first and then tried to
  67. * dereference the MAC's vtable pointer to find out how to free
  68. * that too, we'd be accessing freed memory.
  69. */
  70. if (s->out.mac)
  71. ssh2_mac_free(s->out.mac);
  72. if (s->out.cipher)
  73. ssh_cipher_free(s->out.cipher);
  74. if (s->out_comp)
  75. ssh_compressor_free(s->out_comp);
  76. }
  77. static void ssh2_bpp_free_incoming_crypto(struct ssh2_bpp_state *s)
  78. {
  79. /* As above, take care to free in.mac before in.cipher */
  80. if (s->in.mac)
  81. ssh2_mac_free(s->in.mac);
  82. if (s->in.cipher)
  83. ssh_cipher_free(s->in.cipher);
  84. if (s->in_decomp)
  85. ssh_decompressor_free(s->in_decomp);
  86. }
  87. static void ssh2_bpp_free(BinaryPacketProtocol *bpp)
  88. {
  89. struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
  90. sfree(s->buf);
  91. ssh2_bpp_free_outgoing_crypto(s);
  92. ssh2_bpp_free_incoming_crypto(s);
  93. sfree(s->pktin);
  94. sfree(s);
  95. }
  96. void ssh2_bpp_new_outgoing_crypto(
  97. BinaryPacketProtocol *bpp,
  98. const ssh_cipheralg *cipher, const void *ckey, const void *iv,
  99. const ssh2_macalg *mac, bool etm_mode, const void *mac_key,
  100. const ssh_compression_alg *compression, bool delayed_compression)
  101. {
  102. struct ssh2_bpp_state *s;
  103. assert(bpp->vt == &ssh2_bpp_vtable);
  104. s = container_of(bpp, struct ssh2_bpp_state, bpp);
  105. ssh2_bpp_free_outgoing_crypto(s);
  106. if (cipher) {
  107. s->out.cipher = ssh_cipher_new(cipher);
  108. ssh_cipher_setkey(s->out.cipher, ckey);
  109. ssh_cipher_setiv(s->out.cipher, iv);
  110. s->cbc_ignore_workaround = (
  111. (ssh_cipher_alg(s->out.cipher)->flags & SSH_CIPHER_IS_CBC) &&
  112. !(s->bpp.remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE));
  113. bpp_logevent("Initialised %s outbound encryption",
  114. ssh_cipher_alg(s->out.cipher)->text_name);
  115. } else {
  116. s->out.cipher = NULL;
  117. s->cbc_ignore_workaround = false;
  118. }
  119. s->out.etm_mode = etm_mode;
  120. if (mac) {
  121. s->out.mac = ssh2_mac_new(mac, s->out.cipher);
  122. ssh2_mac_setkey(s->out.mac, make_ptrlen(mac_key, mac->keylen));
  123. bpp_logevent("Initialised %s outbound MAC algorithm%s%s",
  124. ssh2_mac_text_name(s->out.mac),
  125. etm_mode ? " (in ETM mode)" : "",
  126. (s->out.cipher &&
  127. ssh_cipher_alg(s->out.cipher)->required_mac ?
  128. " (required by cipher)" : ""));
  129. } else {
  130. s->out.mac = NULL;
  131. }
  132. if (delayed_compression && !s->seen_userauth_success) {
  133. s->out.pending_compression = compression;
  134. s->out_comp = NULL;
  135. bpp_logevent("Will enable %s compression after user authentication",
  136. s->out.pending_compression->text_name);
  137. } else {
  138. s->out.pending_compression = NULL;
  139. /* 'compression' is always non-NULL, because no compression is
  140. * indicated by ssh_comp_none. But this setup call may return a
  141. * null out_comp. */
  142. s->out_comp = ssh_compressor_new(compression);
  143. if (s->out_comp)
  144. bpp_logevent("Initialised %s compression",
  145. ssh_compressor_alg(s->out_comp)->text_name);
  146. }
  147. }
  148. void ssh2_bpp_new_incoming_crypto(
  149. BinaryPacketProtocol *bpp,
  150. const ssh_cipheralg *cipher, const void *ckey, const void *iv,
  151. const ssh2_macalg *mac, bool etm_mode, const void *mac_key,
  152. const ssh_compression_alg *compression, bool delayed_compression)
  153. {
  154. struct ssh2_bpp_state *s;
  155. assert(bpp->vt == &ssh2_bpp_vtable);
  156. s = container_of(bpp, struct ssh2_bpp_state, bpp);
  157. ssh2_bpp_free_incoming_crypto(s);
  158. if (cipher) {
  159. s->in.cipher = ssh_cipher_new(cipher);
  160. ssh_cipher_setkey(s->in.cipher, ckey);
  161. ssh_cipher_setiv(s->in.cipher, iv);
  162. bpp_logevent("Initialised %s inbound encryption",
  163. ssh_cipher_alg(s->in.cipher)->text_name);
  164. } else {
  165. s->in.cipher = NULL;
  166. }
  167. s->in.etm_mode = etm_mode;
  168. if (mac) {
  169. s->in.mac = ssh2_mac_new(mac, s->in.cipher);
  170. ssh2_mac_setkey(s->in.mac, make_ptrlen(mac_key, mac->keylen));
  171. bpp_logevent("Initialised %s inbound MAC algorithm%s%s",
  172. ssh2_mac_text_name(s->in.mac),
  173. etm_mode ? " (in ETM mode)" : "",
  174. (s->in.cipher &&
  175. ssh_cipher_alg(s->in.cipher)->required_mac ?
  176. " (required by cipher)" : ""));
  177. } else {
  178. s->in.mac = NULL;
  179. }
  180. if (delayed_compression && !s->seen_userauth_success) {
  181. s->in.pending_compression = compression;
  182. s->in_decomp = NULL;
  183. bpp_logevent("Will enable %s decompression after user authentication",
  184. s->in.pending_compression->text_name);
  185. } else {
  186. s->in.pending_compression = NULL;
  187. /* 'compression' is always non-NULL, because no compression is
  188. * indicated by ssh_comp_none. But this setup call may return a
  189. * null in_decomp. */
  190. s->in_decomp = ssh_decompressor_new(compression);
  191. if (s->in_decomp)
  192. bpp_logevent("Initialised %s decompression",
  193. ssh_decompressor_alg(s->in_decomp)->text_name);
  194. }
  195. /* Clear the pending_newkeys flag, so that handle_input below will
  196. * start consuming the input data again. */
  197. s->pending_newkeys = false;
  198. /* And schedule a run of handle_input, in case there's already
  199. * input data in the queue. */
  200. queue_idempotent_callback(&s->bpp.ic_in_raw);
  201. }
  202. bool ssh2_bpp_rekey_inadvisable(BinaryPacketProtocol *bpp)
  203. {
  204. struct ssh2_bpp_state *s;
  205. assert(bpp->vt == &ssh2_bpp_vtable);
  206. s = container_of(bpp, struct ssh2_bpp_state, bpp);
  207. return s->pending_compression;
  208. }
  209. static void ssh2_bpp_enable_pending_compression(struct ssh2_bpp_state *s)
  210. {
  211. BinaryPacketProtocol *bpp = &s->bpp; /* for bpp_logevent */
  212. if (s->in.pending_compression) {
  213. s->in_decomp = ssh_decompressor_new(s->in.pending_compression);
  214. bpp_logevent("Initialised delayed %s decompression",
  215. ssh_decompressor_alg(s->in_decomp)->text_name);
  216. s->in.pending_compression = NULL;
  217. }
  218. if (s->out.pending_compression) {
  219. s->out_comp = ssh_compressor_new(s->out.pending_compression);
  220. bpp_logevent("Initialised delayed %s compression",
  221. ssh_compressor_alg(s->out_comp)->text_name);
  222. s->out.pending_compression = NULL;
  223. }
  224. }
  225. #define BPP_READ(ptr, len) do \
  226. { \
  227. bool success; \
  228. crMaybeWaitUntilV((success = bufchain_try_fetch_consume( \
  229. s->bpp.in_raw, ptr, len)) || \
  230. s->bpp.input_eof); \
  231. if (!success) \
  232. goto eof; \
  233. ssh_check_frozen(s->bpp.ssh); \
  234. } while (0)
  235. #define userauth_range(pkttype) ((unsigned)((pkttype) - 50) < 20)
  236. static void ssh2_bpp_handle_input(BinaryPacketProtocol *bpp)
  237. {
  238. struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
  239. crBegin(s->crState);
  240. while (1) {
  241. s->maxlen = 0;
  242. s->length = 0;
  243. if (s->in.cipher)
  244. s->cipherblk = ssh_cipher_alg(s->in.cipher)->blksize;
  245. else
  246. s->cipherblk = 8;
  247. if (s->cipherblk < 8)
  248. s->cipherblk = 8;
  249. s->maclen = s->in.mac ? ssh2_mac_alg(s->in.mac)->len : 0;
  250. if (s->in.cipher &&
  251. (ssh_cipher_alg(s->in.cipher)->flags & SSH_CIPHER_IS_CBC) &&
  252. s->in.mac && !s->in.etm_mode) {
  253. /*
  254. * When dealing with a CBC-mode cipher, we want to avoid the
  255. * possibility of an attacker's tweaking the ciphertext stream
  256. * so as to cause us to feed the same block to the block
  257. * cipher more than once and thus leak information
  258. * (VU#958563). The way we do this is not to take any
  259. * decisions on the basis of anything we've decrypted until
  260. * we've verified it with a MAC. That includes the packet
  261. * length, so we just read data and check the MAC repeatedly,
  262. * and when the MAC passes, see if the length we've got is
  263. * plausible.
  264. *
  265. * This defence is unnecessary in OpenSSH ETM mode, because
  266. * the whole point of ETM mode is that the attacker can't
  267. * tweak the ciphertext stream at all without the MAC
  268. * detecting it before we decrypt anything.
  269. */
  270. /*
  271. * Make sure we have buffer space for a maximum-size packet.
  272. */
  273. unsigned buflimit = OUR_V2_PACKETLIMIT + s->maclen;
  274. if (s->bufsize < buflimit) {
  275. s->bufsize = buflimit;
  276. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  277. }
  278. /* Read an amount corresponding to the MAC. */
  279. BPP_READ(s->buf, s->maclen);
  280. s->packetlen = 0;
  281. ssh2_mac_start(s->in.mac);
  282. put_uint32(s->in.mac, s->in.sequence);
  283. for (;;) { /* Once around this loop per cipher block. */
  284. /* Read another cipher-block's worth, and tack it on to
  285. * the end. */
  286. BPP_READ(s->buf + (s->packetlen + s->maclen), s->cipherblk);
  287. /* Decrypt one more block (a little further back in
  288. * the stream). */
  289. ssh_cipher_decrypt(s->in.cipher,
  290. s->buf + s->packetlen, s->cipherblk);
  291. /* Feed that block to the MAC. */
  292. put_data(s->in.mac,
  293. s->buf + s->packetlen, s->cipherblk);
  294. s->packetlen += s->cipherblk;
  295. /* See if that gives us a valid packet. */
  296. if (ssh2_mac_verresult(s->in.mac, s->buf + s->packetlen) &&
  297. ((s->len = toint(GET_32BIT_MSB_FIRST(s->buf))) ==
  298. s->packetlen-4))
  299. break;
  300. if (s->packetlen >= (long)OUR_V2_PACKETLIMIT) {
  301. ssh_sw_abort(s->bpp.ssh,
  302. "No valid incoming packet found");
  303. crStopV;
  304. }
  305. }
  306. s->maxlen = s->packetlen + s->maclen;
  307. /*
  308. * Now transfer the data into an output packet.
  309. */
  310. s->pktin = snew_plus(PktIn, s->maxlen);
  311. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  312. s->pktin->type = 0;
  313. s->pktin->qnode.on_free_queue = false;
  314. s->data = snew_plus_get_aux(s->pktin);
  315. memcpy(s->data, s->buf, s->maxlen);
  316. } else if (s->in.mac && s->in.etm_mode) {
  317. if (s->bufsize < 4) {
  318. s->bufsize = 4;
  319. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  320. }
  321. /*
  322. * OpenSSH encrypt-then-MAC mode: the packet length is
  323. * unencrypted, unless the cipher supports length encryption.
  324. */
  325. BPP_READ(s->buf, 4);
  326. /* Cipher supports length decryption, so do it */
  327. if (s->in.cipher && (ssh_cipher_alg(s->in.cipher)->flags &
  328. SSH_CIPHER_SEPARATE_LENGTH)) {
  329. /* Keep the packet the same though, so the MAC passes */
  330. unsigned char len[4];
  331. memcpy(len, s->buf, 4);
  332. ssh_cipher_decrypt_length(
  333. s->in.cipher, len, 4, s->in.sequence);
  334. s->len = toint(GET_32BIT_MSB_FIRST(len));
  335. } else {
  336. s->len = toint(GET_32BIT_MSB_FIRST(s->buf));
  337. }
  338. /*
  339. * _Completely_ silly lengths should be stomped on before they
  340. * do us any more damage.
  341. */
  342. if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
  343. s->len % s->cipherblk != 0) {
  344. ssh_sw_abort(s->bpp.ssh,
  345. "Incoming packet length field was garbled");
  346. crStopV;
  347. }
  348. /*
  349. * So now we can work out the total packet length.
  350. */
  351. s->packetlen = s->len + 4;
  352. /*
  353. * Allocate the packet to return, now we know its length.
  354. */
  355. s->pktin = snew_plus(PktIn, OUR_V2_PACKETLIMIT + s->maclen);
  356. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  357. s->pktin->type = 0;
  358. s->pktin->qnode.on_free_queue = false;
  359. s->data = snew_plus_get_aux(s->pktin);
  360. memcpy(s->data, s->buf, 4);
  361. /*
  362. * Read the remainder of the packet.
  363. */
  364. BPP_READ(s->data + 4, s->packetlen + s->maclen - 4);
  365. /*
  366. * Check the MAC.
  367. */
  368. if (s->in.mac && !ssh2_mac_verify(
  369. s->in.mac, s->data, s->len + 4, s->in.sequence)) {
  370. ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
  371. crStopV;
  372. }
  373. /* Decrypt everything between the length field and the MAC. */
  374. if (s->in.cipher)
  375. ssh_cipher_decrypt(
  376. s->in.cipher, s->data + 4, s->packetlen - 4);
  377. } else {
  378. if (s->bufsize < s->cipherblk) {
  379. s->bufsize = s->cipherblk;
  380. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  381. }
  382. /*
  383. * Acquire and decrypt the first block of the packet. This will
  384. * contain the length and padding details.
  385. */
  386. BPP_READ(s->buf, s->cipherblk);
  387. if (s->in.cipher)
  388. ssh_cipher_decrypt(s->in.cipher, s->buf, s->cipherblk);
  389. /*
  390. * Now get the length figure.
  391. */
  392. s->len = toint(GET_32BIT_MSB_FIRST(s->buf));
  393. /*
  394. * _Completely_ silly lengths should be stomped on before they
  395. * do us any more damage.
  396. */
  397. if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
  398. (s->len + 4) % s->cipherblk != 0) {
  399. ssh_sw_abort(s->bpp.ssh,
  400. "Incoming packet was garbled on decryption");
  401. crStopV;
  402. }
  403. /*
  404. * So now we can work out the total packet length.
  405. */
  406. s->packetlen = s->len + 4;
  407. /*
  408. * Allocate the packet to return, now we know its length.
  409. */
  410. s->maxlen = s->packetlen + s->maclen;
  411. s->pktin = snew_plus(PktIn, s->maxlen);
  412. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  413. s->pktin->type = 0;
  414. s->pktin->qnode.on_free_queue = false;
  415. s->data = snew_plus_get_aux(s->pktin);
  416. memcpy(s->data, s->buf, s->cipherblk);
  417. /*
  418. * Read and decrypt the remainder of the packet.
  419. */
  420. BPP_READ(s->data + s->cipherblk,
  421. s->packetlen + s->maclen - s->cipherblk);
  422. /* Decrypt everything _except_ the MAC. */
  423. if (s->in.cipher)
  424. ssh_cipher_decrypt(
  425. s->in.cipher,
  426. s->data + s->cipherblk, s->packetlen - s->cipherblk);
  427. /*
  428. * Check the MAC.
  429. */
  430. if (s->in.mac && !ssh2_mac_verify(
  431. s->in.mac, s->data, s->len + 4, s->in.sequence)) {
  432. ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
  433. crStopV;
  434. }
  435. }
  436. /* Get and sanity-check the amount of random padding. */
  437. s->pad = s->data[4];
  438. if (s->pad < 4 || s->len - s->pad < 1) {
  439. ssh_sw_abort(s->bpp.ssh,
  440. "Invalid padding length on received packet");
  441. crStopV;
  442. }
  443. /*
  444. * This enables us to deduce the payload length.
  445. */
  446. s->payload = s->len - s->pad - 1;
  447. s->length = s->payload + 5;
  448. dts_consume(&s->stats->in, s->packetlen);
  449. s->pktin->sequence = s->in.sequence++;
  450. s->length = s->packetlen - s->pad;
  451. assert(s->length >= 0);
  452. /*
  453. * Decompress packet payload.
  454. */
  455. {
  456. unsigned char *newpayload;
  457. int newlen;
  458. if (s->in_decomp && ssh_decompressor_decompress(
  459. s->in_decomp, s->data + 5, s->length - 5,
  460. &newpayload, &newlen)) {
  461. if (s->maxlen < newlen + 5) {
  462. PktIn *old_pktin = s->pktin;
  463. s->maxlen = newlen + 5;
  464. s->pktin = snew_plus(PktIn, s->maxlen);
  465. *s->pktin = *old_pktin; /* structure copy */
  466. s->data = snew_plus_get_aux(s->pktin);
  467. smemclr(old_pktin, s->packetlen + s->maclen);
  468. sfree(old_pktin);
  469. }
  470. s->length = 5 + newlen;
  471. memcpy(s->data + 5, newpayload, newlen);
  472. sfree(newpayload);
  473. }
  474. }
  475. /*
  476. * Now we can identify the semantic content of the packet,
  477. * and also the initial type byte.
  478. */
  479. if (s->length <= 5) { /* == 5 we hope, but robustness */
  480. /*
  481. * RFC 4253 doesn't explicitly say that completely empty
  482. * packets with no type byte are forbidden. We handle them
  483. * here by giving them a type code larger than 0xFF, which
  484. * will be picked up at the next layer and trigger
  485. * SSH_MSG_UNIMPLEMENTED.
  486. */
  487. s->pktin->type = SSH_MSG_NO_TYPE_CODE;
  488. s->data += 5;
  489. s->length = 0;
  490. } else {
  491. s->pktin->type = s->data[5];
  492. s->data += 6;
  493. s->length -= 6;
  494. }
  495. BinarySource_INIT(s->pktin, s->data, s->length);
  496. if (s->bpp.logctx) {
  497. logblank_t blanks[MAX_BLANKS];
  498. int nblanks = ssh2_censor_packet(
  499. s->bpp.pls, s->pktin->type, false,
  500. make_ptrlen(s->data, s->length), blanks);
  501. log_packet(s->bpp.logctx, PKT_INCOMING, s->pktin->type,
  502. ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
  503. s->pktin->type),
  504. s->data, s->length, nblanks, blanks,
  505. &s->pktin->sequence, 0, NULL);
  506. }
  507. if (ssh2_bpp_check_unimplemented(&s->bpp, s->pktin)) {
  508. sfree(s->pktin);
  509. s->pktin = NULL;
  510. continue;
  511. }
  512. pq_push(&s->bpp.in_pq, s->pktin);
  513. {
  514. int type = s->pktin->type;
  515. s->pktin = NULL;
  516. if (type == SSH2_MSG_NEWKEYS) {
  517. /*
  518. * Mild layer violation: in this situation we must
  519. * suspend processing of the input byte stream until
  520. * the transport layer has initialised the new keys by
  521. * calling ssh2_bpp_new_incoming_crypto above.
  522. */
  523. s->pending_newkeys = true;
  524. crWaitUntilV(!s->pending_newkeys);
  525. continue;
  526. }
  527. if (type == SSH2_MSG_USERAUTH_SUCCESS && !s->is_server) {
  528. /*
  529. * Another one: if we were configured with OpenSSH's
  530. * deferred compression which is triggered on receipt
  531. * of USERAUTH_SUCCESS, then this is the moment to
  532. * turn on compression.
  533. */
  534. ssh2_bpp_enable_pending_compression(s);
  535. /*
  536. * Whether or not we were doing delayed compression in
  537. * _this_ set of crypto parameters, we should set a
  538. * flag indicating that we're now authenticated, so
  539. * that a delayed compression method enabled in any
  540. * future rekey will be treated as un-delayed.
  541. */
  542. s->seen_userauth_success = true;
  543. }
  544. if (s->pending_compression && userauth_range(type)) {
  545. /*
  546. * Receiving any userauth message at all indicates
  547. * that we're not about to turn on delayed compression
  548. * - either because we just _have_ done, or because
  549. * this message is a USERAUTH_FAILURE or some kind of
  550. * intermediate 'please send more data' continuation
  551. * message. Either way, we turn off the outgoing
  552. * packet blockage for now, and release any queued
  553. * output packets, so that we can make another attempt
  554. * to authenticate. The next userauth packet we send
  555. * will re-block the output direction.
  556. */
  557. s->pending_compression = false;
  558. queue_idempotent_callback(&s->bpp.ic_out_pq);
  559. }
  560. }
  561. }
  562. eof:
  563. /*
  564. * We've seen EOF. But we might have pushed stuff on the outgoing
  565. * packet queue first, and that stuff _might_ include a DISCONNECT
  566. * message, in which case we'd like to use that as the diagnostic.
  567. * So first wait for the queue to have been processed.
  568. */
  569. crMaybeWaitUntilV(!pq_peek(&s->bpp.in_pq));
  570. if (!s->bpp.expect_close) {
  571. ssh_remote_error(s->bpp.ssh,
  572. "Remote side unexpectedly closed network connection");
  573. } else {
  574. ssh_remote_eof(s->bpp.ssh, "Remote side closed network connection");
  575. }
  576. return; /* avoid touching s now it's been freed */
  577. crFinishV;
  578. }
  579. static PktOut *ssh2_bpp_new_pktout(int pkt_type)
  580. {
  581. PktOut *pkt = ssh_new_packet();
  582. pkt->length = 5; /* space for packet length + padding length */
  583. pkt->minlen = 0;
  584. pkt->type = pkt_type;
  585. put_byte(pkt, pkt_type);
  586. pkt->prefix = pkt->length;
  587. return pkt;
  588. }
  589. static void ssh2_bpp_format_packet_inner(struct ssh2_bpp_state *s, PktOut *pkt)
  590. {
  591. int origlen, cipherblk, maclen, padding, unencrypted_prefix, i;
  592. if (s->bpp.logctx) {
  593. ptrlen pktdata = make_ptrlen(pkt->data + pkt->prefix,
  594. pkt->length - pkt->prefix);
  595. logblank_t blanks[MAX_BLANKS];
  596. int nblanks = ssh2_censor_packet(
  597. s->bpp.pls, pkt->type, true, pktdata, blanks);
  598. log_packet(s->bpp.logctx, PKT_OUTGOING, pkt->type,
  599. ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
  600. pkt->type),
  601. pktdata.ptr, pktdata.len, nblanks, blanks, &s->out.sequence,
  602. pkt->downstream_id, pkt->additional_log_text);
  603. }
  604. cipherblk = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 8;
  605. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  606. if (s->out_comp) {
  607. unsigned char *newpayload;
  608. int minlen, newlen;
  609. /*
  610. * Compress packet payload.
  611. */
  612. minlen = pkt->minlen;
  613. if (minlen) {
  614. /*
  615. * Work out how much compressed data we need (at least) to
  616. * make the overall packet length come to pkt->minlen.
  617. */
  618. if (s->out.mac)
  619. minlen -= ssh2_mac_alg(s->out.mac)->len;
  620. minlen -= 8; /* length field + min padding */
  621. }
  622. ssh_compressor_compress(s->out_comp, pkt->data + 5, pkt->length - 5,
  623. &newpayload, &newlen, minlen);
  624. pkt->length = 5;
  625. put_data(pkt, newpayload, newlen);
  626. sfree(newpayload);
  627. }
  628. /*
  629. * Add padding. At least four bytes, and must also bring total
  630. * length (minus MAC) up to a multiple of the block size.
  631. * If pkt->forcepad is set, make sure the packet is at least that size
  632. * after padding.
  633. */
  634. padding = 4;
  635. unencrypted_prefix = (s->out.mac && s->out.etm_mode) ? 4 : 0;
  636. padding +=
  637. (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
  638. % cipherblk;
  639. assert(padding <= 255);
  640. maclen = s->out.mac ? ssh2_mac_alg(s->out.mac)->len : 0;
  641. origlen = pkt->length;
  642. for (i = 0; i < padding; i++)
  643. put_byte(pkt, 0); /* make space for random padding */
  644. random_read(pkt->data + origlen, padding);
  645. pkt->data[4] = padding;
  646. PUT_32BIT_MSB_FIRST(pkt->data, origlen + padding - 4);
  647. /* Encrypt length if the scheme requires it */
  648. if (s->out.cipher &&
  649. (ssh_cipher_alg(s->out.cipher)->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  650. ssh_cipher_encrypt_length(s->out.cipher, pkt->data, 4,
  651. s->out.sequence);
  652. }
  653. put_padding(pkt, maclen, 0);
  654. if (s->out.mac && s->out.etm_mode) {
  655. /*
  656. * OpenSSH-defined encrypt-then-MAC protocol.
  657. */
  658. if (s->out.cipher)
  659. ssh_cipher_encrypt(s->out.cipher,
  660. pkt->data + 4, origlen + padding - 4);
  661. ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
  662. s->out.sequence);
  663. } else {
  664. /*
  665. * SSH-2 standard protocol.
  666. */
  667. if (s->out.mac)
  668. ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
  669. s->out.sequence);
  670. if (s->out.cipher)
  671. ssh_cipher_encrypt(s->out.cipher, pkt->data, origlen + padding);
  672. }
  673. s->out.sequence++; /* whether or not we MACed */
  674. dts_consume(&s->stats->out, origlen + padding);
  675. }
  676. static void ssh2_bpp_format_packet(struct ssh2_bpp_state *s, PktOut *pkt)
  677. {
  678. if (pkt->minlen > 0 && !s->out_comp) {
  679. /*
  680. * If we've been told to pad the packet out to a given minimum
  681. * length, but we're not compressing (and hence can't get the
  682. * compression to do the padding by pointlessly opening and
  683. * closing zlib blocks), then our other strategy is to precede
  684. * this message with an SSH_MSG_IGNORE that makes it up to the
  685. * right length.
  686. *
  687. * A third option in principle, and the most obviously
  688. * sensible, would be to set the explicit padding field in the
  689. * packet to more than its minimum value. Sadly, that turns
  690. * out to break some servers (our institutional memory thinks
  691. * Cisco in particular) and so we abandoned that idea shortly
  692. * after trying it.
  693. */
  694. /*
  695. * Calculate the length we expect the real packet to have.
  696. */
  697. int block, length;
  698. PktOut *ignore_pkt;
  699. block = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 0;
  700. if (block < 8)
  701. block = 8;
  702. length = pkt->length;
  703. length += 4; /* minimum 4 byte padding */
  704. length += block-1;
  705. length -= (length % block);
  706. if (s->out.mac)
  707. length += ssh2_mac_alg(s->out.mac)->len;
  708. if (length < pkt->minlen) {
  709. /*
  710. * We need an ignore message. Calculate its length.
  711. */
  712. length = pkt->minlen - length;
  713. /*
  714. * And work backwards from that to the length of the
  715. * contained string.
  716. */
  717. if (s->out.mac)
  718. length -= ssh2_mac_alg(s->out.mac)->len;
  719. length -= 8; /* length field + min padding */
  720. length -= 5; /* type code + string length prefix */
  721. if (length < 0)
  722. length = 0;
  723. ignore_pkt = ssh2_bpp_new_pktout(SSH2_MSG_IGNORE);
  724. put_uint32(ignore_pkt, length);
  725. { // WINSCP
  726. size_t origlen = ignore_pkt->length;
  727. size_t i; // WINSCP
  728. for (i = 0; i < length; i++)
  729. put_byte(ignore_pkt, 0); /* make space for random padding */
  730. random_read(ignore_pkt->data + origlen, length);
  731. ssh2_bpp_format_packet_inner(s, ignore_pkt);
  732. bufchain_add(s->bpp.out_raw, ignore_pkt->data, ignore_pkt->length);
  733. ssh_free_pktout(ignore_pkt);
  734. } // WINSCP
  735. }
  736. }
  737. ssh2_bpp_format_packet_inner(s, pkt);
  738. bufchain_add(s->bpp.out_raw, pkt->data, pkt->length);
  739. }
  740. static void ssh2_bpp_handle_output(BinaryPacketProtocol *bpp)
  741. {
  742. struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
  743. PktOut *pkt;
  744. int n_userauth;
  745. /*
  746. * Count the userauth packets in the queue.
  747. */
  748. n_userauth = 0;
  749. for (pkt = pq_first(&s->bpp.out_pq); pkt != NULL;
  750. pkt = pq_next(&s->bpp.out_pq, pkt))
  751. if (userauth_range(pkt->type))
  752. n_userauth++;
  753. if (s->pending_compression && !n_userauth) {
  754. /*
  755. * We're currently blocked from sending any outgoing packets
  756. * until the other end tells us whether we're going to have to
  757. * enable compression or not.
  758. *
  759. * If our end has pushed a userauth packet on the queue, that
  760. * must mean it knows that a USERAUTH_SUCCESS is not
  761. * immediately forthcoming, so we unblock ourselves and send
  762. * up to and including that packet. But in this if statement,
  763. * there aren't any, so we're still blocked.
  764. */
  765. return;
  766. }
  767. if (s->cbc_ignore_workaround) {
  768. /*
  769. * When using a CBC-mode cipher in SSH-2, it's necessary to
  770. * ensure that an attacker can't provide data to be encrypted
  771. * using an IV that they know. We ensure this by inserting an
  772. * SSH_MSG_IGNORE if the last cipher block of the previous
  773. * packet has already been sent to the network (which we
  774. * approximate conservatively by checking if it's vanished
  775. * from out_raw).
  776. */
  777. if (bufchain_size(s->bpp.out_raw) <
  778. (ssh_cipher_alg(s->out.cipher)->blksize +
  779. ssh2_mac_alg(s->out.mac)->len)) {
  780. /*
  781. * There's less data in out_raw than the MAC size plus the
  782. * cipher block size, which means at least one byte of
  783. * that cipher block must already have left. Add an
  784. * IGNORE.
  785. */
  786. pkt = ssh_bpp_new_pktout(&s->bpp, SSH2_MSG_IGNORE);
  787. put_stringz(pkt, "");
  788. ssh2_bpp_format_packet(s, pkt);
  789. }
  790. }
  791. while ((pkt = pq_pop(&s->bpp.out_pq)) != NULL) {
  792. int type = pkt->type;
  793. if (userauth_range(type))
  794. n_userauth--;
  795. ssh2_bpp_format_packet(s, pkt);
  796. ssh_free_pktout(pkt);
  797. if (n_userauth == 0 && s->out.pending_compression && !s->is_server) {
  798. /*
  799. * This is the last userauth packet in the queue, so
  800. * unless our side decides to send another one in future,
  801. * we have to assume will potentially provoke
  802. * USERAUTH_SUCCESS. Block (non-userauth) outgoing packets
  803. * until we see the reply.
  804. */
  805. s->pending_compression = true;
  806. return;
  807. } else if (type == SSH2_MSG_USERAUTH_SUCCESS && s->is_server) {
  808. ssh2_bpp_enable_pending_compression(s);
  809. }
  810. }
  811. }
  812. #ifdef MPEXT
  813. const ssh_cipher * ssh2_bpp_get_cscipher(BinaryPacketProtocol *bpp)
  814. {
  815. return container_of(bpp, struct ssh2_bpp_state, bpp)->out.cipher;
  816. }
  817. const ssh_cipher * ssh2_bpp_get_sccipher(BinaryPacketProtocol *bpp)
  818. {
  819. return container_of(bpp, struct ssh2_bpp_state, bpp)->in.cipher;
  820. }
  821. const struct ssh_compressor * ssh2_bpp_get_cscomp(BinaryPacketProtocol *bpp)
  822. {
  823. return container_of(bpp, struct ssh2_bpp_state, bpp)->out_comp;
  824. }
  825. const struct ssh_decompressor * ssh2_bpp_get_sccomp(BinaryPacketProtocol *bpp)
  826. {
  827. return container_of(bpp, struct ssh2_bpp_state, bpp)->in_decomp;
  828. }
  829. #endif