packet.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. /*
  2. * Dropbear - a SSH2 server
  3. *
  4. * Copyright (c) 2002,2003 Matt Johnston
  5. * All rights reserved.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE. */
  24. #include "includes.h"
  25. #include "packet.h"
  26. #include "session.h"
  27. #include "dbutil.h"
  28. #include "ssh.h"
  29. #include "algo.h"
  30. #include "buffer.h"
  31. #include "kex.h"
  32. #include "dbrandom.h"
  33. #include "service.h"
  34. #include "auth.h"
  35. #include "channel.h"
  36. #include "netio.h"
  37. #include "runopts.h"
  38. static int read_packet_init(void);
  39. static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
  40. buffer * clear_buf, unsigned int clear_len,
  41. unsigned char *output_mac);
  42. static int checkmac(void);
  43. /* For exact details see http://www.zlib.net/zlib_tech.html
  44. * 5 bytes per 16kB block, plus 6 bytes for the stream.
  45. * We might allocate 5 unnecessary bytes here if it's an
  46. * exact multiple. */
  47. #define ZLIB_COMPRESS_EXPANSION (((RECV_MAX_PAYLOAD_LEN/16384)+1)*5 + 6)
  48. #define ZLIB_DECOMPRESS_INCR 1024
  49. #ifndef DISABLE_ZLIB
  50. static buffer* buf_decompress(const buffer* buf, unsigned int len);
  51. static void buf_compress(buffer * dest, buffer * src, unsigned int len);
  52. #endif
  53. /* non-blocking function writing out a current encrypted packet */
  54. void write_packet() {
  55. ssize_t written;
  56. #if defined(HAVE_WRITEV) && (defined(IOV_MAX) || defined(UIO_MAXIOV))
  57. /* 50 is somewhat arbitrary */
  58. unsigned int iov_count = 50;
  59. struct iovec iov[50];
  60. #else
  61. int len;
  62. buffer* writebuf;
  63. #endif
  64. TRACE2(("enter write_packet"))
  65. dropbear_assert(!isempty(&ses.writequeue));
  66. #if defined(HAVE_WRITEV) && (defined(IOV_MAX) || defined(UIO_MAXIOV))
  67. packet_queue_to_iovec(&ses.writequeue, iov, &iov_count);
  68. /* This may return EAGAIN. The main loop sometimes
  69. calls write_packet() without bothering to test with select() since
  70. it's likely to be necessary */
  71. #if DROPBEAR_FUZZ
  72. if (fuzz.fuzzing) {
  73. /* pretend to write one packet at a time */
  74. /* TODO(fuzz): randomise amount written based on the fuzz input */
  75. written = iov[0].iov_len;
  76. }
  77. else
  78. #endif
  79. {
  80. written = writev(ses.sock_out, iov, iov_count);
  81. if (written < 0) {
  82. if (errno == EINTR || errno == EAGAIN) {
  83. TRACE2(("leave write_packet: EINTR"))
  84. return;
  85. } else {
  86. dropbear_exit("Error writing: %s", strerror(errno));
  87. }
  88. }
  89. }
  90. packet_queue_consume(&ses.writequeue, written);
  91. ses.writequeue_len -= written;
  92. if (written == 0) {
  93. ses.remoteclosed();
  94. }
  95. #else /* No writev () */
  96. #if DROPBEAR_FUZZ
  97. _Static_assert(0, "No fuzzing code for no-writev writes");
  98. #endif
  99. /* Get the next buffer in the queue of encrypted packets to write*/
  100. writebuf = (buffer*)examine(&ses.writequeue);
  101. len = writebuf->len - writebuf->pos;
  102. dropbear_assert(len > 0);
  103. /* Try to write as much as possible */
  104. written = write(ses.sock_out, buf_getptr(writebuf, len), len);
  105. if (written < 0) {
  106. if (errno == EINTR || errno == EAGAIN) {
  107. TRACE2(("leave writepacket: EINTR"))
  108. return;
  109. } else {
  110. dropbear_exit("Error writing: %s", strerror(errno));
  111. }
  112. }
  113. if (written == 0) {
  114. ses.remoteclosed();
  115. }
  116. ses.writequeue_len -= written;
  117. if (written == len) {
  118. /* We've finished with the packet, free it */
  119. dequeue(&ses.writequeue);
  120. buf_free(writebuf);
  121. writebuf = NULL;
  122. } else {
  123. /* More packet left to write, leave it in the queue for later */
  124. buf_incrpos(writebuf, written);
  125. }
  126. #endif /* writev */
  127. TRACE2(("leave write_packet"))
  128. }
  129. /* Non-blocking function reading available portion of a packet into the
  130. * ses's buffer, decrypting the length if encrypted, decrypting the
  131. * full portion if possible */
  132. void read_packet() {
  133. int len;
  134. unsigned int maxlen;
  135. unsigned char blocksize;
  136. TRACE2(("enter read_packet"))
  137. blocksize = ses.keys->recv.algo_crypt->blocksize;
  138. if (ses.readbuf == NULL || ses.readbuf->len < blocksize) {
  139. int ret;
  140. /* In the first blocksize of a packet */
  141. /* Read the first blocksize of the packet, so we can decrypt it and
  142. * find the length of the whole packet */
  143. ret = read_packet_init();
  144. if (ret == DROPBEAR_FAILURE) {
  145. /* didn't read enough to determine the length */
  146. TRACE2(("leave read_packet: packetinit done"))
  147. return;
  148. }
  149. }
  150. /* Attempt to read the remainder of the packet, note that there
  151. * mightn't be any available (EAGAIN) */
  152. maxlen = ses.readbuf->len - ses.readbuf->pos;
  153. if (maxlen == 0) {
  154. /* Occurs when the packet is only a single block long and has all
  155. * been read in read_packet_init(). Usually means that MAC is disabled
  156. */
  157. len = 0;
  158. } else {
  159. len = read(ses.sock_in, buf_getptr(ses.readbuf, maxlen), maxlen);
  160. if (len == 0) {
  161. ses.remoteclosed();
  162. }
  163. if (len < 0) {
  164. if (errno == EINTR || errno == EAGAIN) {
  165. TRACE2(("leave read_packet: EINTR or EAGAIN"))
  166. return;
  167. } else {
  168. dropbear_exit("Error reading: %s", strerror(errno));
  169. }
  170. }
  171. buf_incrpos(ses.readbuf, len);
  172. }
  173. if ((unsigned int)len == maxlen) {
  174. /* The whole packet has been read */
  175. decrypt_packet();
  176. /* The main select() loop process_packet() to
  177. * handle the packet contents... */
  178. }
  179. TRACE2(("leave read_packet"))
  180. }
  181. /* Function used to read the initial portion of a packet, and determine the
  182. * length. Only called during the first BLOCKSIZE of a packet. */
  183. /* Returns DROPBEAR_SUCCESS if the length is determined,
  184. * DROPBEAR_FAILURE otherwise */
  185. static int read_packet_init() {
  186. unsigned int maxlen;
  187. int slen;
  188. unsigned int len, plen;
  189. unsigned int blocksize;
  190. unsigned int macsize;
  191. blocksize = ses.keys->recv.algo_crypt->blocksize;
  192. macsize = ses.keys->recv.algo_mac->hashsize;
  193. if (ses.readbuf == NULL) {
  194. /* start of a new packet */
  195. ses.readbuf = buf_new(INIT_READBUF);
  196. }
  197. maxlen = blocksize - ses.readbuf->pos;
  198. /* read the rest of the packet if possible */
  199. slen = read(ses.sock_in, buf_getwriteptr(ses.readbuf, maxlen),
  200. maxlen);
  201. if (slen == 0) {
  202. ses.remoteclosed();
  203. }
  204. if (slen < 0) {
  205. if (errno == EINTR || errno == EAGAIN) {
  206. TRACE2(("leave read_packet_init: EINTR"))
  207. return DROPBEAR_FAILURE;
  208. }
  209. dropbear_exit("Error reading: %s", strerror(errno));
  210. }
  211. buf_incrwritepos(ses.readbuf, slen);
  212. if ((unsigned int)slen != maxlen) {
  213. /* don't have enough bytes to determine length, get next time */
  214. return DROPBEAR_FAILURE;
  215. }
  216. /* now we have the first block, need to get packet length, so we decrypt
  217. * the first block (only need first 4 bytes) */
  218. buf_setpos(ses.readbuf, 0);
  219. #if DROPBEAR_AEAD_MODE
  220. if (ses.keys->recv.crypt_mode->aead_crypt) {
  221. if (ses.keys->recv.crypt_mode->aead_getlength(ses.recvseq,
  222. buf_getptr(ses.readbuf, blocksize), &plen,
  223. blocksize,
  224. &ses.keys->recv.cipher_state) != CRYPT_OK) {
  225. dropbear_exit("Error decrypting");
  226. }
  227. len = plen + 4 + macsize;
  228. } else
  229. #endif
  230. {
  231. if (ses.keys->recv.crypt_mode->decrypt(buf_getptr(ses.readbuf, blocksize),
  232. buf_getwriteptr(ses.readbuf, blocksize),
  233. blocksize,
  234. &ses.keys->recv.cipher_state) != CRYPT_OK) {
  235. dropbear_exit("Error decrypting");
  236. }
  237. plen = buf_getint(ses.readbuf) + 4;
  238. len = plen + macsize;
  239. }
  240. TRACE2(("packet size is %u, block %u mac %u", len, blocksize, macsize))
  241. /* check packet length */
  242. if ((len > RECV_MAX_PACKET_LEN) ||
  243. (plen < blocksize) ||
  244. (plen % blocksize != 0)) {
  245. dropbear_exit("Integrity error (bad packet size %u)", len);
  246. }
  247. if (len > ses.readbuf->size) {
  248. ses.readbuf = buf_resize(ses.readbuf, len);
  249. }
  250. buf_setlen(ses.readbuf, len);
  251. buf_setpos(ses.readbuf, blocksize);
  252. return DROPBEAR_SUCCESS;
  253. }
  254. /* handle the received packet */
  255. void decrypt_packet() {
  256. unsigned char blocksize;
  257. unsigned char macsize;
  258. unsigned int padlen;
  259. unsigned int len;
  260. TRACE2(("enter decrypt_packet"))
  261. blocksize = ses.keys->recv.algo_crypt->blocksize;
  262. macsize = ses.keys->recv.algo_mac->hashsize;
  263. ses.kexstate.datarecv += ses.readbuf->len;
  264. #if DROPBEAR_AEAD_MODE
  265. if (ses.keys->recv.crypt_mode->aead_crypt) {
  266. /* first blocksize is not decrypted yet */
  267. buf_setpos(ses.readbuf, 0);
  268. /* decrypt it in-place */
  269. len = ses.readbuf->len - macsize - ses.readbuf->pos;
  270. if (ses.keys->recv.crypt_mode->aead_crypt(ses.recvseq,
  271. buf_getptr(ses.readbuf, len + macsize),
  272. buf_getwriteptr(ses.readbuf, len),
  273. len, macsize,
  274. &ses.keys->recv.cipher_state, LTC_DECRYPT) != CRYPT_OK) {
  275. dropbear_exit("Error decrypting");
  276. }
  277. buf_incrpos(ses.readbuf, len);
  278. } else
  279. #endif
  280. {
  281. /* we've already decrypted the first blocksize in read_packet_init */
  282. buf_setpos(ses.readbuf, blocksize);
  283. /* decrypt it in-place */
  284. len = ses.readbuf->len - macsize - ses.readbuf->pos;
  285. if (ses.keys->recv.crypt_mode->decrypt(
  286. buf_getptr(ses.readbuf, len),
  287. buf_getwriteptr(ses.readbuf, len),
  288. len,
  289. &ses.keys->recv.cipher_state) != CRYPT_OK) {
  290. dropbear_exit("Error decrypting");
  291. }
  292. buf_incrpos(ses.readbuf, len);
  293. /* check the hmac */
  294. if (checkmac() != DROPBEAR_SUCCESS) {
  295. dropbear_exit("Integrity error");
  296. }
  297. }
  298. #if DROPBEAR_FUZZ
  299. fuzz_dump(ses.readbuf->data, ses.readbuf->len);
  300. #endif
  301. /* get padding length */
  302. buf_setpos(ses.readbuf, PACKET_PADDING_OFF);
  303. padlen = buf_getbyte(ses.readbuf);
  304. /* payload length */
  305. /* - 4 - 1 is for LEN and PADLEN values */
  306. len = ses.readbuf->len - padlen - 4 - 1 - macsize;
  307. if ((len > RECV_MAX_PAYLOAD_LEN+ZLIB_COMPRESS_EXPANSION) || (len < 1)) {
  308. dropbear_exit("Bad packet size %u", len);
  309. }
  310. buf_setpos(ses.readbuf, PACKET_PAYLOAD_OFF);
  311. #ifndef DISABLE_ZLIB
  312. if (is_compress_recv()) {
  313. /* decompress */
  314. ses.payload = buf_decompress(ses.readbuf, len);
  315. buf_setpos(ses.payload, 0);
  316. ses.payload_beginning = 0;
  317. buf_free(ses.readbuf);
  318. } else
  319. #endif
  320. {
  321. ses.payload = ses.readbuf;
  322. ses.payload_beginning = ses.payload->pos;
  323. buf_setlen(ses.payload, ses.payload->pos + len);
  324. }
  325. ses.readbuf = NULL;
  326. ses.recvseq++;
  327. TRACE2(("leave decrypt_packet"))
  328. }
  329. /* Checks the mac at the end of a decrypted readbuf.
  330. * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
  331. static int checkmac() {
  332. unsigned char mac_bytes[MAX_MAC_LEN];
  333. unsigned int mac_size, contents_len;
  334. mac_size = ses.keys->recv.algo_mac->hashsize;
  335. contents_len = ses.readbuf->len - mac_size;
  336. buf_setpos(ses.readbuf, 0);
  337. make_mac(ses.recvseq, &ses.keys->recv, ses.readbuf, contents_len, mac_bytes);
  338. #if DROPBEAR_FUZZ
  339. if (fuzz.fuzzing) {
  340. /* fail 1 in 2000 times to test error path. */
  341. unsigned int value = 0;
  342. if (mac_size > sizeof(value)) {
  343. memcpy(&value, mac_bytes, sizeof(value));
  344. }
  345. if (value % 2000 == 99) {
  346. return DROPBEAR_FAILURE;
  347. }
  348. return DROPBEAR_SUCCESS;
  349. }
  350. #endif
  351. /* compare the hash */
  352. buf_setpos(ses.readbuf, contents_len);
  353. if (constant_time_memcmp(mac_bytes, buf_getptr(ses.readbuf, mac_size), mac_size) != 0) {
  354. return DROPBEAR_FAILURE;
  355. } else {
  356. return DROPBEAR_SUCCESS;
  357. }
  358. }
  359. #ifndef DISABLE_ZLIB
  360. /* returns a pointer to a newly created buffer */
  361. static buffer* buf_decompress(const buffer* buf, unsigned int len) {
  362. int result;
  363. buffer * ret;
  364. z_streamp zstream;
  365. zstream = ses.keys->recv.zstream;
  366. ret = buf_new(len);
  367. zstream->avail_in = len;
  368. zstream->next_in = buf_getptr(buf, len);
  369. /* decompress the payload, incrementally resizing the output buffer */
  370. while (1) {
  371. zstream->avail_out = ret->size - ret->pos;
  372. zstream->next_out = buf_getwriteptr(ret, zstream->avail_out);
  373. result = inflate(zstream, Z_SYNC_FLUSH);
  374. buf_setlen(ret, ret->size - zstream->avail_out);
  375. buf_setpos(ret, ret->len);
  376. if (result != Z_BUF_ERROR && result != Z_OK) {
  377. dropbear_exit("zlib error");
  378. }
  379. if (zstream->avail_in == 0 &&
  380. (zstream->avail_out != 0 || result == Z_BUF_ERROR)) {
  381. /* we can only exit if avail_out hasn't all been used,
  382. * and there's no remaining input */
  383. return ret;
  384. }
  385. if (zstream->avail_out == 0) {
  386. int new_size = 0;
  387. if (ret->size >= RECV_MAX_PAYLOAD_LEN) {
  388. /* Already been increased as large as it can go,
  389. * yet didn't finish up the decompression */
  390. dropbear_exit("bad packet, oversized decompressed");
  391. }
  392. new_size = MIN(RECV_MAX_PAYLOAD_LEN, ret->size + ZLIB_DECOMPRESS_INCR);
  393. ret = buf_resize(ret, new_size);
  394. }
  395. }
  396. }
  397. #endif
  398. /* returns 1 if the packet is a valid type during kex (see 7.1 of rfc4253) */
  399. static int packet_is_okay_kex(unsigned char type) {
  400. if (type >= SSH_MSG_USERAUTH_REQUEST) {
  401. return 0;
  402. }
  403. if (type == SSH_MSG_SERVICE_REQUEST || type == SSH_MSG_SERVICE_ACCEPT) {
  404. return 0;
  405. }
  406. if (type == SSH_MSG_KEXINIT) {
  407. /* XXX should this die horribly if !dataallowed ?? */
  408. return 0;
  409. }
  410. return 1;
  411. }
  412. static void enqueue_reply_packet() {
  413. struct packetlist * new_item = NULL;
  414. new_item = m_malloc(sizeof(struct packetlist));
  415. new_item->next = NULL;
  416. new_item->payload = buf_newcopy(ses.writepayload);
  417. buf_setpos(ses.writepayload, 0);
  418. buf_setlen(ses.writepayload, 0);
  419. if (ses.reply_queue_tail) {
  420. ses.reply_queue_tail->next = new_item;
  421. } else {
  422. ses.reply_queue_head = new_item;
  423. }
  424. ses.reply_queue_tail = new_item;
  425. }
  426. void maybe_flush_reply_queue() {
  427. struct packetlist *tmp_item = NULL, *curr_item = NULL;
  428. if (!ses.dataallowed)
  429. {
  430. TRACE(("maybe_empty_reply_queue - no data allowed"))
  431. return;
  432. }
  433. for (curr_item = ses.reply_queue_head; curr_item; ) {
  434. CHECKCLEARTOWRITE();
  435. buf_putbytes(ses.writepayload,
  436. curr_item->payload->data, curr_item->payload->len);
  437. buf_free(curr_item->payload);
  438. tmp_item = curr_item;
  439. curr_item = curr_item->next;
  440. m_free(tmp_item);
  441. encrypt_packet();
  442. }
  443. ses.reply_queue_head = ses.reply_queue_tail = NULL;
  444. }
  445. /* encrypt the writepayload, putting into writebuf, ready for write_packet()
  446. * to put on the wire */
  447. void encrypt_packet() {
  448. unsigned char padlen;
  449. unsigned char blocksize, mac_size;
  450. buffer * writebuf; /* the packet which will go on the wire. This is
  451. encrypted in-place. */
  452. unsigned char packet_type;
  453. unsigned int len, encrypt_buf_size;
  454. unsigned char mac_bytes[MAX_MAC_LEN];
  455. time_t now;
  456. TRACE2(("enter encrypt_packet()"))
  457. buf_setpos(ses.writepayload, 0);
  458. packet_type = buf_getbyte(ses.writepayload);
  459. buf_setpos(ses.writepayload, 0);
  460. TRACE2(("encrypt_packet type is %d", packet_type))
  461. if ((!ses.dataallowed && !packet_is_okay_kex(packet_type))) {
  462. /* During key exchange only particular packets are allowed.
  463. Since this packet_type isn't OK we just enqueue it to send
  464. after the KEX, see maybe_flush_reply_queue */
  465. enqueue_reply_packet();
  466. return;
  467. }
  468. blocksize = ses.keys->trans.algo_crypt->blocksize;
  469. mac_size = ses.keys->trans.algo_mac->hashsize;
  470. /* Encrypted packet len is payload+5. We need to then make sure
  471. * there is enough space for padding or MIN_PACKET_LEN.
  472. * Add extra 3 since we need at least 4 bytes of padding */
  473. encrypt_buf_size = (ses.writepayload->len+4+1)
  474. + MAX(MIN_PACKET_LEN, blocksize) + 3
  475. /* add space for the MAC at the end */
  476. + mac_size
  477. #ifndef DISABLE_ZLIB
  478. /* some extra in case 'compression' makes it larger */
  479. + ZLIB_COMPRESS_EXPANSION
  480. #endif
  481. /* and an extra cleartext (stripped before transmission) byte for the
  482. * packet type */
  483. + 1;
  484. writebuf = buf_new(encrypt_buf_size);
  485. buf_setlen(writebuf, PACKET_PAYLOAD_OFF);
  486. buf_setpos(writebuf, PACKET_PAYLOAD_OFF);
  487. #ifndef DISABLE_ZLIB
  488. /* compression */
  489. if (is_compress_trans()) {
  490. buf_compress(writebuf, ses.writepayload, ses.writepayload->len);
  491. } else
  492. #endif
  493. {
  494. memcpy(buf_getwriteptr(writebuf, ses.writepayload->len),
  495. buf_getptr(ses.writepayload, ses.writepayload->len),
  496. ses.writepayload->len);
  497. buf_incrwritepos(writebuf, ses.writepayload->len);
  498. }
  499. /* finished with payload */
  500. buf_setpos(ses.writepayload, 0);
  501. buf_setlen(ses.writepayload, 0);
  502. /* length of padding - packet length excluding the packetlength uint32
  503. * field in aead mode must be a multiple of blocksize, with a minimum of
  504. * 4 bytes of padding */
  505. len = writebuf->len;
  506. #if DROPBEAR_AEAD_MODE
  507. if (ses.keys->trans.crypt_mode->aead_crypt) {
  508. len -= 4;
  509. }
  510. #endif
  511. padlen = blocksize - len % blocksize;
  512. if (padlen < 4) {
  513. padlen += blocksize;
  514. }
  515. /* check for min packet length */
  516. if (writebuf->len + padlen < MIN_PACKET_LEN) {
  517. padlen += blocksize;
  518. }
  519. buf_setpos(writebuf, 0);
  520. /* packet length excluding the packetlength uint32 */
  521. buf_putint(writebuf, writebuf->len + padlen - 4);
  522. /* padding len */
  523. buf_putbyte(writebuf, padlen);
  524. /* actual padding */
  525. buf_setpos(writebuf, writebuf->len);
  526. buf_incrlen(writebuf, padlen);
  527. genrandom(buf_getptr(writebuf, padlen), padlen);
  528. #if DROPBEAR_AEAD_MODE
  529. if (ses.keys->trans.crypt_mode->aead_crypt) {
  530. /* do the actual encryption, in-place */
  531. buf_setpos(writebuf, 0);
  532. /* encrypt it in-place*/
  533. len = writebuf->len;
  534. buf_incrlen(writebuf, mac_size);
  535. if (ses.keys->trans.crypt_mode->aead_crypt(ses.transseq,
  536. buf_getptr(writebuf, len),
  537. buf_getwriteptr(writebuf, len + mac_size),
  538. len, mac_size,
  539. &ses.keys->trans.cipher_state, LTC_ENCRYPT) != CRYPT_OK) {
  540. dropbear_exit("Error encrypting");
  541. }
  542. buf_incrpos(writebuf, len + mac_size);
  543. } else
  544. #endif
  545. {
  546. make_mac(ses.transseq, &ses.keys->trans, writebuf, writebuf->len, mac_bytes);
  547. /* do the actual encryption, in-place */
  548. buf_setpos(writebuf, 0);
  549. /* encrypt it in-place*/
  550. len = writebuf->len;
  551. if (ses.keys->trans.crypt_mode->encrypt(
  552. buf_getptr(writebuf, len),
  553. buf_getwriteptr(writebuf, len),
  554. len,
  555. &ses.keys->trans.cipher_state) != CRYPT_OK) {
  556. dropbear_exit("Error encrypting");
  557. }
  558. buf_incrpos(writebuf, len);
  559. /* stick the MAC on it */
  560. buf_putbytes(writebuf, mac_bytes, mac_size);
  561. }
  562. /* Update counts */
  563. ses.kexstate.datatrans += writebuf->len;
  564. writebuf_enqueue(writebuf);
  565. /* Update counts */
  566. ses.transseq++;
  567. now = monotonic_now();
  568. ses.last_packet_time_any_sent = now;
  569. /* idle timeout shouldn't be affected by responses to keepalives.
  570. send_msg_keepalive() itself also does tricks with
  571. ses.last_packet_idle_time - read that if modifying this code */
  572. if (packet_type != SSH_MSG_REQUEST_FAILURE
  573. && packet_type != SSH_MSG_UNIMPLEMENTED
  574. && packet_type != SSH_MSG_IGNORE) {
  575. ses.last_packet_time_idle = now;
  576. }
  577. TRACE2(("leave encrypt_packet()"))
  578. }
  579. void writebuf_enqueue(buffer * writebuf) {
  580. /* enqueue the packet for sending. It will get freed after transmission. */
  581. buf_setpos(writebuf, 0);
  582. enqueue(&ses.writequeue, (void*)writebuf);
  583. ses.writequeue_len += writebuf->len;
  584. }
  585. /* Create the packet mac, and append H(seqno|clearbuf) to the output */
  586. /* output_mac must have ses.keys->trans.algo_mac->hashsize bytes. */
  587. static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
  588. buffer * clear_buf, unsigned int clear_len,
  589. unsigned char *output_mac) {
  590. unsigned char seqbuf[4];
  591. unsigned long bufsize;
  592. hmac_state hmac;
  593. if (key_state->algo_mac->hashsize > 0) {
  594. /* calculate the mac */
  595. if (hmac_init(&hmac,
  596. key_state->hash_index,
  597. key_state->mackey,
  598. key_state->algo_mac->keysize) != CRYPT_OK) {
  599. dropbear_exit("HMAC error");
  600. }
  601. /* sequence number */
  602. STORE32H(seqno, seqbuf);
  603. if (hmac_process(&hmac, seqbuf, 4) != CRYPT_OK) {
  604. dropbear_exit("HMAC error");
  605. }
  606. /* the actual contents */
  607. buf_setpos(clear_buf, 0);
  608. if (hmac_process(&hmac,
  609. buf_getptr(clear_buf, clear_len),
  610. clear_len) != CRYPT_OK) {
  611. dropbear_exit("HMAC error");
  612. }
  613. bufsize = MAX_MAC_LEN;
  614. if (hmac_done(&hmac, output_mac, &bufsize) != CRYPT_OK) {
  615. dropbear_exit("HMAC error");
  616. }
  617. }
  618. TRACE2(("leave writemac"))
  619. }
  620. #ifndef DISABLE_ZLIB
  621. /* compresses len bytes from src, outputting to dest (starting from the
  622. * respective current positions. dest must have sufficient space,
  623. * len+ZLIB_COMPRESS_EXPANSION */
  624. static void buf_compress(buffer * dest, buffer * src, unsigned int len) {
  625. unsigned int endpos = src->pos + len;
  626. int result;
  627. TRACE2(("enter buf_compress"))
  628. dropbear_assert(dest->size - dest->pos >= len+ZLIB_COMPRESS_EXPANSION);
  629. ses.keys->trans.zstream->avail_in = endpos - src->pos;
  630. ses.keys->trans.zstream->next_in =
  631. buf_getptr(src, ses.keys->trans.zstream->avail_in);
  632. ses.keys->trans.zstream->avail_out = dest->size - dest->pos;
  633. ses.keys->trans.zstream->next_out =
  634. buf_getwriteptr(dest, ses.keys->trans.zstream->avail_out);
  635. result = deflate(ses.keys->trans.zstream, Z_SYNC_FLUSH);
  636. buf_setpos(src, endpos - ses.keys->trans.zstream->avail_in);
  637. buf_setlen(dest, dest->size - ses.keys->trans.zstream->avail_out);
  638. buf_setpos(dest, dest->len);
  639. if (result != Z_OK) {
  640. dropbear_exit("zlib error");
  641. }
  642. /* fails if destination buffer wasn't large enough */
  643. dropbear_assert(ses.keys->trans.zstream->avail_in == 0);
  644. TRACE2(("leave buf_compress"))
  645. }
  646. #endif