bpp2.c 38 KB

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