ssh2bpp.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. } while (0)
  234. #define userauth_range(pkttype) ((unsigned)((pkttype) - 50) < 20)
  235. static void ssh2_bpp_handle_input(BinaryPacketProtocol *bpp)
  236. {
  237. struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
  238. crBegin(s->crState);
  239. while (1) {
  240. s->maxlen = 0;
  241. s->length = 0;
  242. if (s->in.cipher)
  243. s->cipherblk = ssh_cipher_alg(s->in.cipher)->blksize;
  244. else
  245. s->cipherblk = 8;
  246. if (s->cipherblk < 8)
  247. s->cipherblk = 8;
  248. s->maclen = s->in.mac ? ssh2_mac_alg(s->in.mac)->len : 0;
  249. if (s->in.cipher &&
  250. (ssh_cipher_alg(s->in.cipher)->flags & SSH_CIPHER_IS_CBC) &&
  251. s->in.mac && !s->in.etm_mode) {
  252. /*
  253. * When dealing with a CBC-mode cipher, we want to avoid the
  254. * possibility of an attacker's tweaking the ciphertext stream
  255. * so as to cause us to feed the same block to the block
  256. * cipher more than once and thus leak information
  257. * (VU#958563). The way we do this is not to take any
  258. * decisions on the basis of anything we've decrypted until
  259. * we've verified it with a MAC. That includes the packet
  260. * length, so we just read data and check the MAC repeatedly,
  261. * and when the MAC passes, see if the length we've got is
  262. * plausible.
  263. *
  264. * This defence is unnecessary in OpenSSH ETM mode, because
  265. * the whole point of ETM mode is that the attacker can't
  266. * tweak the ciphertext stream at all without the MAC
  267. * detecting it before we decrypt anything.
  268. */
  269. /*
  270. * Make sure we have buffer space for a maximum-size packet.
  271. */
  272. unsigned buflimit = OUR_V2_PACKETLIMIT + s->maclen;
  273. if (s->bufsize < buflimit) {
  274. s->bufsize = buflimit;
  275. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  276. }
  277. /* Read an amount corresponding to the MAC. */
  278. BPP_READ(s->buf, s->maclen);
  279. s->packetlen = 0;
  280. ssh2_mac_start(s->in.mac);
  281. put_uint32(s->in.mac, s->in.sequence);
  282. for (;;) { /* Once around this loop per cipher block. */
  283. /* Read another cipher-block's worth, and tack it on to
  284. * the end. */
  285. BPP_READ(s->buf + (s->packetlen + s->maclen), s->cipherblk);
  286. /* Decrypt one more block (a little further back in
  287. * the stream). */
  288. ssh_cipher_decrypt(s->in.cipher,
  289. s->buf + s->packetlen, s->cipherblk);
  290. /* Feed that block to the MAC. */
  291. put_data(s->in.mac,
  292. s->buf + s->packetlen, s->cipherblk);
  293. s->packetlen += s->cipherblk;
  294. /* See if that gives us a valid packet. */
  295. if (ssh2_mac_verresult(s->in.mac, s->buf + s->packetlen) &&
  296. ((s->len = toint(GET_32BIT(s->buf))) ==
  297. s->packetlen-4))
  298. break;
  299. if (s->packetlen >= (long)OUR_V2_PACKETLIMIT) {
  300. ssh_sw_abort(s->bpp.ssh,
  301. "No valid incoming packet found");
  302. crStopV;
  303. }
  304. }
  305. s->maxlen = s->packetlen + s->maclen;
  306. /*
  307. * Now transfer the data into an output packet.
  308. */
  309. s->pktin = snew_plus(PktIn, s->maxlen);
  310. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  311. s->pktin->type = 0;
  312. s->pktin->qnode.on_free_queue = false;
  313. s->data = snew_plus_get_aux(s->pktin);
  314. memcpy(s->data, s->buf, s->maxlen);
  315. } else if (s->in.mac && s->in.etm_mode) {
  316. if (s->bufsize < 4) {
  317. s->bufsize = 4;
  318. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  319. }
  320. /*
  321. * OpenSSH encrypt-then-MAC mode: the packet length is
  322. * unencrypted, unless the cipher supports length encryption.
  323. */
  324. BPP_READ(s->buf, 4);
  325. /* Cipher supports length decryption, so do it */
  326. if (s->in.cipher && (ssh_cipher_alg(s->in.cipher)->flags &
  327. SSH_CIPHER_SEPARATE_LENGTH)) {
  328. /* Keep the packet the same though, so the MAC passes */
  329. unsigned char len[4];
  330. memcpy(len, s->buf, 4);
  331. ssh_cipher_decrypt_length(
  332. s->in.cipher, len, 4, s->in.sequence);
  333. s->len = toint(GET_32BIT(len));
  334. } else {
  335. s->len = toint(GET_32BIT(s->buf));
  336. }
  337. /*
  338. * _Completely_ silly lengths should be stomped on before they
  339. * do us any more damage.
  340. */
  341. if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
  342. s->len % s->cipherblk != 0) {
  343. ssh_sw_abort(s->bpp.ssh,
  344. "Incoming packet length field was garbled");
  345. crStopV;
  346. }
  347. /*
  348. * So now we can work out the total packet length.
  349. */
  350. s->packetlen = s->len + 4;
  351. /*
  352. * Allocate the packet to return, now we know its length.
  353. */
  354. s->pktin = snew_plus(PktIn, OUR_V2_PACKETLIMIT + s->maclen);
  355. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  356. s->pktin->type = 0;
  357. s->pktin->qnode.on_free_queue = false;
  358. s->data = snew_plus_get_aux(s->pktin);
  359. memcpy(s->data, s->buf, 4);
  360. /*
  361. * Read the remainder of the packet.
  362. */
  363. BPP_READ(s->data + 4, s->packetlen + s->maclen - 4);
  364. /*
  365. * Check the MAC.
  366. */
  367. if (s->in.mac && !ssh2_mac_verify(
  368. s->in.mac, s->data, s->len + 4, s->in.sequence)) {
  369. ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
  370. crStopV;
  371. }
  372. /* Decrypt everything between the length field and the MAC. */
  373. if (s->in.cipher)
  374. ssh_cipher_decrypt(
  375. s->in.cipher, s->data + 4, s->packetlen - 4);
  376. } else {
  377. if (s->bufsize < s->cipherblk) {
  378. s->bufsize = s->cipherblk;
  379. s->buf = sresize(s->buf, s->bufsize, unsigned char);
  380. }
  381. /*
  382. * Acquire and decrypt the first block of the packet. This will
  383. * contain the length and padding details.
  384. */
  385. BPP_READ(s->buf, s->cipherblk);
  386. if (s->in.cipher)
  387. ssh_cipher_decrypt(s->in.cipher, s->buf, s->cipherblk);
  388. /*
  389. * Now get the length figure.
  390. */
  391. s->len = toint(GET_32BIT(s->buf));
  392. /*
  393. * _Completely_ silly lengths should be stomped on before they
  394. * do us any more damage.
  395. */
  396. if (s->len < 0 || s->len > (long)OUR_V2_PACKETLIMIT ||
  397. (s->len + 4) % s->cipherblk != 0) {
  398. ssh_sw_abort(s->bpp.ssh,
  399. "Incoming packet was garbled on decryption");
  400. crStopV;
  401. }
  402. /*
  403. * So now we can work out the total packet length.
  404. */
  405. s->packetlen = s->len + 4;
  406. /*
  407. * Allocate the packet to return, now we know its length.
  408. */
  409. s->maxlen = s->packetlen + s->maclen;
  410. s->pktin = snew_plus(PktIn, s->maxlen);
  411. s->pktin->qnode.prev = s->pktin->qnode.next = NULL;
  412. s->pktin->type = 0;
  413. s->pktin->qnode.on_free_queue = false;
  414. s->data = snew_plus_get_aux(s->pktin);
  415. memcpy(s->data, s->buf, s->cipherblk);
  416. /*
  417. * Read and decrypt the remainder of the packet.
  418. */
  419. BPP_READ(s->data + s->cipherblk,
  420. s->packetlen + s->maclen - s->cipherblk);
  421. /* Decrypt everything _except_ the MAC. */
  422. if (s->in.cipher)
  423. ssh_cipher_decrypt(
  424. s->in.cipher,
  425. s->data + s->cipherblk, s->packetlen - s->cipherblk);
  426. /*
  427. * Check the MAC.
  428. */
  429. if (s->in.mac && !ssh2_mac_verify(
  430. s->in.mac, s->data, s->len + 4, s->in.sequence)) {
  431. ssh_sw_abort(s->bpp.ssh, "Incorrect MAC received on packet");
  432. crStopV;
  433. }
  434. }
  435. /* Get and sanity-check the amount of random padding. */
  436. s->pad = s->data[4];
  437. if (s->pad < 4 || s->len - s->pad < 1) {
  438. ssh_sw_abort(s->bpp.ssh,
  439. "Invalid padding length on received packet");
  440. crStopV;
  441. }
  442. /*
  443. * This enables us to deduce the payload length.
  444. */
  445. s->payload = s->len - s->pad - 1;
  446. s->length = s->payload + 5;
  447. DTS_CONSUME(s->stats, in, s->packetlen);
  448. s->pktin->sequence = s->in.sequence++;
  449. s->length = s->packetlen - s->pad;
  450. assert(s->length >= 0);
  451. /*
  452. * Decompress packet payload.
  453. */
  454. {
  455. unsigned char *newpayload;
  456. int newlen;
  457. if (s->in_decomp && ssh_decompressor_decompress(
  458. s->in_decomp, s->data + 5, s->length - 5,
  459. &newpayload, &newlen)) {
  460. if (s->maxlen < newlen + 5) {
  461. PktIn *old_pktin = s->pktin;
  462. s->maxlen = newlen + 5;
  463. s->pktin = snew_plus(PktIn, s->maxlen);
  464. *s->pktin = *old_pktin; /* structure copy */
  465. s->data = snew_plus_get_aux(s->pktin);
  466. smemclr(old_pktin, s->packetlen + s->maclen);
  467. sfree(old_pktin);
  468. }
  469. s->length = 5 + newlen;
  470. memcpy(s->data + 5, newpayload, newlen);
  471. sfree(newpayload);
  472. }
  473. }
  474. /*
  475. * Now we can identify the semantic content of the packet,
  476. * and also the initial type byte.
  477. */
  478. if (s->length <= 5) { /* == 5 we hope, but robustness */
  479. /*
  480. * RFC 4253 doesn't explicitly say that completely empty
  481. * packets with no type byte are forbidden. We handle them
  482. * here by giving them a type code larger than 0xFF, which
  483. * will be picked up at the next layer and trigger
  484. * SSH_MSG_UNIMPLEMENTED.
  485. */
  486. s->pktin->type = SSH_MSG_NO_TYPE_CODE;
  487. s->data += 5;
  488. s->length = 0;
  489. } else {
  490. s->pktin->type = s->data[5];
  491. s->data += 6;
  492. s->length -= 6;
  493. }
  494. BinarySource_INIT(s->pktin, s->data, s->length);
  495. if (s->bpp.logctx) {
  496. logblank_t blanks[MAX_BLANKS];
  497. int nblanks = ssh2_censor_packet(
  498. s->bpp.pls, s->pktin->type, false,
  499. make_ptrlen(s->data, s->length), blanks);
  500. log_packet(s->bpp.logctx, PKT_INCOMING, s->pktin->type,
  501. ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
  502. s->pktin->type),
  503. s->data, s->length, nblanks, blanks,
  504. &s->pktin->sequence, 0, NULL);
  505. }
  506. if (ssh2_bpp_check_unimplemented(&s->bpp, s->pktin)) {
  507. sfree(s->pktin);
  508. s->pktin = NULL;
  509. continue;
  510. }
  511. pq_push(&s->bpp.in_pq, s->pktin);
  512. {
  513. int type = s->pktin->type;
  514. s->pktin = NULL;
  515. if (type == SSH2_MSG_NEWKEYS) {
  516. /*
  517. * Mild layer violation: in this situation we must
  518. * suspend processing of the input byte stream until
  519. * the transport layer has initialised the new keys by
  520. * calling ssh2_bpp_new_incoming_crypto above.
  521. */
  522. s->pending_newkeys = true;
  523. crWaitUntilV(!s->pending_newkeys);
  524. continue;
  525. }
  526. if (type == SSH2_MSG_USERAUTH_SUCCESS && !s->is_server) {
  527. /*
  528. * Another one: if we were configured with OpenSSH's
  529. * deferred compression which is triggered on receipt
  530. * of USERAUTH_SUCCESS, then this is the moment to
  531. * turn on compression.
  532. */
  533. ssh2_bpp_enable_pending_compression(s);
  534. /*
  535. * Whether or not we were doing delayed compression in
  536. * _this_ set of crypto parameters, we should set a
  537. * flag indicating that we're now authenticated, so
  538. * that a delayed compression method enabled in any
  539. * future rekey will be treated as un-delayed.
  540. */
  541. s->seen_userauth_success = true;
  542. }
  543. if (s->pending_compression && userauth_range(type)) {
  544. /*
  545. * Receiving any userauth message at all indicates
  546. * that we're not about to turn on delayed compression
  547. * - either because we just _have_ done, or because
  548. * this message is a USERAUTH_FAILURE or some kind of
  549. * intermediate 'please send more data' continuation
  550. * message. Either way, we turn off the outgoing
  551. * packet blockage for now, and release any queued
  552. * output packets, so that we can make another attempt
  553. * to authenticate. The next userauth packet we send
  554. * will re-block the output direction.
  555. */
  556. s->pending_compression = false;
  557. queue_idempotent_callback(&s->bpp.ic_out_pq);
  558. }
  559. }
  560. }
  561. eof:
  562. if (!s->bpp.expect_close) {
  563. ssh_remote_error(s->bpp.ssh,
  564. "Remote side unexpectedly closed network connection");
  565. } else {
  566. ssh_remote_eof(s->bpp.ssh, "Remote side closed network connection");
  567. }
  568. return; /* avoid touching s now it's been freed */
  569. crFinishV;
  570. }
  571. static PktOut *ssh2_bpp_new_pktout(int pkt_type)
  572. {
  573. PktOut *pkt = ssh_new_packet();
  574. pkt->length = 5; /* space for packet length + padding length */
  575. pkt->minlen = 0;
  576. pkt->type = pkt_type;
  577. put_byte(pkt, pkt_type);
  578. pkt->prefix = pkt->length;
  579. return pkt;
  580. }
  581. static void ssh2_bpp_format_packet_inner(struct ssh2_bpp_state *s, PktOut *pkt)
  582. {
  583. int origlen, cipherblk, maclen, padding, unencrypted_prefix, i;
  584. if (s->bpp.logctx) {
  585. ptrlen pktdata = make_ptrlen(pkt->data + pkt->prefix,
  586. pkt->length - pkt->prefix);
  587. logblank_t blanks[MAX_BLANKS];
  588. int nblanks = ssh2_censor_packet(
  589. s->bpp.pls, pkt->type, true, pktdata, blanks);
  590. log_packet(s->bpp.logctx, PKT_OUTGOING, pkt->type,
  591. ssh2_pkt_type(s->bpp.pls->kctx, s->bpp.pls->actx,
  592. pkt->type),
  593. pktdata.ptr, pktdata.len, nblanks, blanks, &s->out.sequence,
  594. pkt->downstream_id, pkt->additional_log_text);
  595. }
  596. cipherblk = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 8;
  597. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  598. if (s->out_comp) {
  599. unsigned char *newpayload;
  600. int minlen, newlen;
  601. /*
  602. * Compress packet payload.
  603. */
  604. minlen = pkt->minlen;
  605. if (minlen) {
  606. /*
  607. * Work out how much compressed data we need (at least) to
  608. * make the overall packet length come to pkt->minlen.
  609. */
  610. if (s->out.mac)
  611. minlen -= ssh2_mac_alg(s->out.mac)->len;
  612. minlen -= 8; /* length field + min padding */
  613. }
  614. ssh_compressor_compress(s->out_comp, pkt->data + 5, pkt->length - 5,
  615. &newpayload, &newlen, minlen);
  616. pkt->length = 5;
  617. put_data(pkt, newpayload, newlen);
  618. sfree(newpayload);
  619. }
  620. /*
  621. * Add padding. At least four bytes, and must also bring total
  622. * length (minus MAC) up to a multiple of the block size.
  623. * If pkt->forcepad is set, make sure the packet is at least that size
  624. * after padding.
  625. */
  626. padding = 4;
  627. unencrypted_prefix = (s->out.mac && s->out.etm_mode) ? 4 : 0;
  628. padding +=
  629. (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
  630. % cipherblk;
  631. assert(padding <= 255);
  632. maclen = s->out.mac ? ssh2_mac_alg(s->out.mac)->len : 0;
  633. origlen = pkt->length;
  634. for (i = 0; i < padding; i++)
  635. put_byte(pkt, 0); /* make space for random padding */
  636. random_read(pkt->data + origlen, padding);
  637. pkt->data[4] = padding;
  638. PUT_32BIT(pkt->data, origlen + padding - 4);
  639. /* Encrypt length if the scheme requires it */
  640. if (s->out.cipher &&
  641. (ssh_cipher_alg(s->out.cipher)->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  642. ssh_cipher_encrypt_length(s->out.cipher, pkt->data, 4,
  643. s->out.sequence);
  644. }
  645. put_padding(pkt, maclen, 0);
  646. if (s->out.mac && s->out.etm_mode) {
  647. /*
  648. * OpenSSH-defined encrypt-then-MAC protocol.
  649. */
  650. if (s->out.cipher)
  651. ssh_cipher_encrypt(s->out.cipher,
  652. pkt->data + 4, origlen + padding - 4);
  653. ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
  654. s->out.sequence);
  655. } else {
  656. /*
  657. * SSH-2 standard protocol.
  658. */
  659. if (s->out.mac)
  660. ssh2_mac_generate(s->out.mac, pkt->data, origlen + padding,
  661. s->out.sequence);
  662. if (s->out.cipher)
  663. ssh_cipher_encrypt(s->out.cipher, pkt->data, origlen + padding);
  664. }
  665. s->out.sequence++; /* whether or not we MACed */
  666. DTS_CONSUME(s->stats, out, origlen + padding);
  667. }
  668. static void ssh2_bpp_format_packet(struct ssh2_bpp_state *s, PktOut *pkt)
  669. {
  670. if (pkt->minlen > 0 && !s->out_comp) {
  671. /*
  672. * If we've been told to pad the packet out to a given minimum
  673. * length, but we're not compressing (and hence can't get the
  674. * compression to do the padding by pointlessly opening and
  675. * closing zlib blocks), then our other strategy is to precede
  676. * this message with an SSH_MSG_IGNORE that makes it up to the
  677. * right length.
  678. *
  679. * A third option in principle, and the most obviously
  680. * sensible, would be to set the explicit padding field in the
  681. * packet to more than its minimum value. Sadly, that turns
  682. * out to break some servers (our institutional memory thinks
  683. * Cisco in particular) and so we abandoned that idea shortly
  684. * after trying it.
  685. */
  686. /*
  687. * Calculate the length we expect the real packet to have.
  688. */
  689. int block, length;
  690. PktOut *ignore_pkt;
  691. block = s->out.cipher ? ssh_cipher_alg(s->out.cipher)->blksize : 0;
  692. if (block < 8)
  693. block = 8;
  694. length = pkt->length;
  695. length += 4; /* minimum 4 byte padding */
  696. length += block-1;
  697. length -= (length % block);
  698. if (s->out.mac)
  699. length += ssh2_mac_alg(s->out.mac)->len;
  700. if (length < pkt->minlen) {
  701. /*
  702. * We need an ignore message. Calculate its length.
  703. */
  704. length = pkt->minlen - length;
  705. /*
  706. * And work backwards from that to the length of the
  707. * contained string.
  708. */
  709. if (s->out.mac)
  710. length -= ssh2_mac_alg(s->out.mac)->len;
  711. length -= 8; /* length field + min padding */
  712. length -= 5; /* type code + string length prefix */
  713. if (length < 0)
  714. length = 0;
  715. ignore_pkt = ssh2_bpp_new_pktout(SSH2_MSG_IGNORE);
  716. put_uint32(ignore_pkt, length);
  717. { // WINSCP
  718. size_t origlen = ignore_pkt->length;
  719. size_t i; // WINSCP
  720. for (i = 0; i < length; i++)
  721. put_byte(ignore_pkt, 0); /* make space for random padding */
  722. random_read(ignore_pkt->data + origlen, length);
  723. ssh2_bpp_format_packet_inner(s, ignore_pkt);
  724. bufchain_add(s->bpp.out_raw, ignore_pkt->data, ignore_pkt->length);
  725. ssh_free_pktout(ignore_pkt);
  726. } // WINSCP
  727. }
  728. }
  729. ssh2_bpp_format_packet_inner(s, pkt);
  730. bufchain_add(s->bpp.out_raw, pkt->data, pkt->length);
  731. }
  732. static void ssh2_bpp_handle_output(BinaryPacketProtocol *bpp)
  733. {
  734. struct ssh2_bpp_state *s = container_of(bpp, struct ssh2_bpp_state, bpp);
  735. PktOut *pkt;
  736. int n_userauth;
  737. /*
  738. * Count the userauth packets in the queue.
  739. */
  740. n_userauth = 0;
  741. for (pkt = pq_first(&s->bpp.out_pq); pkt != NULL;
  742. pkt = pq_next(&s->bpp.out_pq, pkt))
  743. if (userauth_range(pkt->type))
  744. n_userauth++;
  745. if (s->pending_compression && !n_userauth) {
  746. /*
  747. * We're currently blocked from sending any outgoing packets
  748. * until the other end tells us whether we're going to have to
  749. * enable compression or not.
  750. *
  751. * If our end has pushed a userauth packet on the queue, that
  752. * must mean it knows that a USERAUTH_SUCCESS is not
  753. * immediately forthcoming, so we unblock ourselves and send
  754. * up to and including that packet. But in this if statement,
  755. * there aren't any, so we're still blocked.
  756. */
  757. return;
  758. }
  759. if (s->cbc_ignore_workaround) {
  760. /*
  761. * When using a CBC-mode cipher in SSH-2, it's necessary to
  762. * ensure that an attacker can't provide data to be encrypted
  763. * using an IV that they know. We ensure this by inserting an
  764. * SSH_MSG_IGNORE if the last cipher block of the previous
  765. * packet has already been sent to the network (which we
  766. * approximate conservatively by checking if it's vanished
  767. * from out_raw).
  768. */
  769. if (bufchain_size(s->bpp.out_raw) <
  770. (ssh_cipher_alg(s->out.cipher)->blksize +
  771. ssh2_mac_alg(s->out.mac)->len)) {
  772. /*
  773. * There's less data in out_raw than the MAC size plus the
  774. * cipher block size, which means at least one byte of
  775. * that cipher block must already have left. Add an
  776. * IGNORE.
  777. */
  778. pkt = ssh_bpp_new_pktout(&s->bpp, SSH2_MSG_IGNORE);
  779. put_stringz(pkt, "");
  780. ssh2_bpp_format_packet(s, pkt);
  781. }
  782. }
  783. while ((pkt = pq_pop(&s->bpp.out_pq)) != NULL) {
  784. int type = pkt->type;
  785. if (userauth_range(type))
  786. n_userauth--;
  787. ssh2_bpp_format_packet(s, pkt);
  788. ssh_free_pktout(pkt);
  789. if (n_userauth == 0 && s->out.pending_compression && !s->is_server) {
  790. /*
  791. * This is the last userauth packet in the queue, so
  792. * unless our side decides to send another one in future,
  793. * we have to assume will potentially provoke
  794. * USERAUTH_SUCCESS. Block (non-userauth) outgoing packets
  795. * until we see the reply.
  796. */
  797. s->pending_compression = true;
  798. return;
  799. } else if (type == SSH2_MSG_USERAUTH_SUCCESS && s->is_server) {
  800. ssh2_bpp_enable_pending_compression(s);
  801. }
  802. }
  803. }
  804. #ifdef MPEXT
  805. const ssh_cipher * ssh2_bpp_get_cscipher(BinaryPacketProtocol *bpp)
  806. {
  807. return container_of(bpp, struct ssh2_bpp_state, bpp)->out.cipher;
  808. }
  809. const ssh_cipher * ssh2_bpp_get_sccipher(BinaryPacketProtocol *bpp)
  810. {
  811. return container_of(bpp, struct ssh2_bpp_state, bpp)->in.cipher;
  812. }
  813. const struct ssh_compressor * ssh2_bpp_get_cscomp(BinaryPacketProtocol *bpp)
  814. {
  815. return container_of(bpp, struct ssh2_bpp_state, bpp)->out_comp;
  816. }
  817. const struct ssh_decompressor * ssh2_bpp_get_sccomp(BinaryPacketProtocol *bpp)
  818. {
  819. return container_of(bpp, struct ssh2_bpp_state, bpp)->in_decomp;
  820. }
  821. #endif