bpp2.c 38 KB

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