ssh2bpp.c 35 KB

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