bpp2.c 36 KB

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