ssh2bpp.c 38 KB

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