ssh2bpp.c 36 KB

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