Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / dropbear / packet.c
blob1b5ee93d4f0ba08861d092028f54dcb5924ae7d7
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:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
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. */
25 #include "includes.h"
26 #include "packet.h"
27 #include "session.h"
28 #include "dbutil.h"
29 #include "ssh.h"
30 #include "algo.h"
31 #include "buffer.h"
32 #include "kex.h"
33 #include "dbrandom.h"
34 #include "service.h"
35 #include "auth.h"
36 #include "channel.h"
38 static int read_packet_init();
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();
44 #define ZLIB_COMPRESS_INCR 100
45 #define ZLIB_DECOMPRESS_INCR 1024
46 #ifndef DISABLE_ZLIB
47 static buffer* buf_decompress(buffer* buf, unsigned int len);
48 static void buf_compress(buffer * dest, buffer * src, unsigned int len);
49 #endif
51 /* non-blocking function writing out a current encrypted packet */
52 void write_packet() {
54 int len, written;
55 buffer * writebuf = NULL;
56 time_t now;
57 unsigned packet_type;
58 int all_ignore = 1;
59 #ifdef HAVE_WRITEV
60 struct iovec *iov = NULL;
61 int i;
62 struct Link *l;
63 #endif
65 TRACE2(("enter write_packet"))
66 dropbear_assert(!isempty(&ses.writequeue));
68 #ifdef HAVE_WRITEV
69 iov = m_malloc(sizeof(*iov) * ses.writequeue.count);
70 for (l = ses.writequeue.head, i = 0; l; l = l->link, i++)
72 writebuf = (buffer*)l->item;
73 packet_type = writebuf->data[writebuf->len-1];
74 len = writebuf->len - 1 - writebuf->pos;
75 dropbear_assert(len > 0);
76 all_ignore &= (packet_type == SSH_MSG_IGNORE);
77 TRACE2(("write_packet writev #%d type %d len %d/%d", i, packet_type,
78 len, writebuf->len-1))
79 iov[i].iov_base = buf_getptr(writebuf, len);
80 iov[i].iov_len = len;
82 written = writev(ses.sock_out, iov, ses.writequeue.count);
83 if (written < 0) {
84 if (errno == EINTR) {
85 m_free(iov);
86 TRACE2(("leave writepacket: EINTR"))
87 return;
88 } else {
89 dropbear_exit("Error writing");
93 if (written == 0) {
94 ses.remoteclosed();
97 while (written > 0) {
98 writebuf = (buffer*)examine(&ses.writequeue);
99 len = writebuf->len - 1 - writebuf->pos;
100 if (len > written) {
101 /* partial buffer write */
102 buf_incrpos(writebuf, written);
103 written = 0;
104 } else {
105 written -= len;
106 dequeue(&ses.writequeue);
107 buf_free(writebuf);
111 m_free(iov);
113 #else
114 /* Get the next buffer in the queue of encrypted packets to write*/
115 writebuf = (buffer*)examine(&ses.writequeue);
117 /* The last byte of the buffer is not to be transmitted, but is
118 * a cleartext packet_type indicator */
119 packet_type = writebuf->data[writebuf->len-1];
120 len = writebuf->len - 1 - writebuf->pos;
121 dropbear_assert(len > 0);
122 /* Try to write as much as possible */
123 written = write(ses.sock_out, buf_getptr(writebuf, len), len);
125 if (written < 0) {
126 if (errno == EINTR) {
127 TRACE2(("leave writepacket: EINTR"))
128 return;
129 } else {
130 dropbear_exit("Error writing");
133 all_ignore = (packet_type == SSH_MSG_IGNORE);
135 if (written == 0) {
136 ses.remoteclosed();
139 if (written == len) {
140 /* We've finished with the packet, free it */
141 dequeue(&ses.writequeue);
142 buf_free(writebuf);
143 writebuf = NULL;
144 } else {
145 /* More packet left to write, leave it in the queue for later */
146 buf_incrpos(writebuf, written);
149 #endif
150 now = time(NULL);
151 ses.last_trx_packet_time = now;
153 if (!all_ignore) {
154 ses.last_packet_time = now;
157 TRACE2(("leave write_packet"))
160 /* Non-blocking function reading available portion of a packet into the
161 * ses's buffer, decrypting the length if encrypted, decrypting the
162 * full portion if possible */
163 void read_packet() {
165 int len;
166 unsigned int maxlen;
167 unsigned char blocksize;
169 TRACE2(("enter read_packet"))
170 blocksize = ses.keys->recv.algo_crypt->blocksize;
172 if (ses.readbuf == NULL || ses.readbuf->len < blocksize) {
173 int ret;
174 /* In the first blocksize of a packet */
176 /* Read the first blocksize of the packet, so we can decrypt it and
177 * find the length of the whole packet */
178 ret = read_packet_init();
180 if (ret == DROPBEAR_FAILURE) {
181 /* didn't read enough to determine the length */
182 TRACE2(("leave read_packet: packetinit done"))
183 return;
187 /* Attempt to read the remainder of the packet, note that there
188 * mightn't be any available (EAGAIN) */
189 maxlen = ses.readbuf->len - ses.readbuf->pos;
190 if (maxlen == 0) {
191 /* Occurs when the packet is only a single block long and has all
192 * been read in read_packet_init(). Usually means that MAC is disabled
194 len = 0;
195 } else {
196 len = read(ses.sock_in, buf_getptr(ses.readbuf, maxlen), maxlen);
198 if (len == 0) {
199 ses.remoteclosed();
202 if (len < 0) {
203 if (errno == EINTR || errno == EAGAIN) {
204 TRACE2(("leave read_packet: EINTR or EAGAIN"))
205 return;
206 } else {
207 dropbear_exit("Error reading: %s", strerror(errno));
211 buf_incrpos(ses.readbuf, len);
214 if ((unsigned int)len == maxlen) {
215 /* The whole packet has been read */
216 decrypt_packet();
217 /* The main select() loop process_packet() to
218 * handle the packet contents... */
220 TRACE2(("leave read_packet"))
223 /* Function used to read the initial portion of a packet, and determine the
224 * length. Only called during the first BLOCKSIZE of a packet. */
225 /* Returns DROPBEAR_SUCCESS if the length is determined,
226 * DROPBEAR_FAILURE otherwise */
227 static int read_packet_init() {
229 unsigned int maxlen;
230 int slen;
231 unsigned int len;
232 unsigned int blocksize;
233 unsigned int macsize;
236 blocksize = ses.keys->recv.algo_crypt->blocksize;
237 macsize = ses.keys->recv.algo_mac->hashsize;
239 if (ses.readbuf == NULL) {
240 /* start of a new packet */
241 ses.readbuf = buf_new(INIT_READBUF);
244 maxlen = blocksize - ses.readbuf->pos;
246 /* read the rest of the packet if possible */
247 slen = read(ses.sock_in, buf_getwriteptr(ses.readbuf, maxlen),
248 maxlen);
249 if (slen == 0) {
250 ses.remoteclosed();
252 if (slen < 0) {
253 if (errno == EINTR) {
254 TRACE2(("leave read_packet_init: EINTR"))
255 return DROPBEAR_FAILURE;
257 dropbear_exit("Error reading: %s", strerror(errno));
260 buf_incrwritepos(ses.readbuf, slen);
262 if ((unsigned int)slen != maxlen) {
263 /* don't have enough bytes to determine length, get next time */
264 return DROPBEAR_FAILURE;
267 /* now we have the first block, need to get packet length, so we decrypt
268 * the first block (only need first 4 bytes) */
269 buf_setpos(ses.readbuf, 0);
270 if (ses.keys->recv.crypt_mode->decrypt(buf_getptr(ses.readbuf, blocksize),
271 buf_getwriteptr(ses.readbuf, blocksize),
272 blocksize,
273 &ses.keys->recv.cipher_state) != CRYPT_OK) {
274 dropbear_exit("Error decrypting");
276 len = buf_getint(ses.readbuf) + 4 + macsize;
278 TRACE2(("packet size is %d, block %d mac %d", len, blocksize, macsize))
281 /* check packet length */
282 if ((len > RECV_MAX_PACKET_LEN) ||
283 (len < MIN_PACKET_LEN + macsize) ||
284 ((len - macsize) % blocksize != 0)) {
285 dropbear_exit("Integrity error (bad packet size %d)", len);
288 if (len > ses.readbuf->size) {
289 buf_resize(ses.readbuf, len);
291 buf_setlen(ses.readbuf, len);
292 buf_setpos(ses.readbuf, blocksize);
293 return DROPBEAR_SUCCESS;
296 /* handle the received packet */
297 void decrypt_packet() {
299 unsigned char blocksize;
300 unsigned char macsize;
301 unsigned int padlen;
302 unsigned int len;
304 TRACE2(("enter decrypt_packet"))
305 blocksize = ses.keys->recv.algo_crypt->blocksize;
306 macsize = ses.keys->recv.algo_mac->hashsize;
308 ses.kexstate.datarecv += ses.readbuf->len;
310 /* we've already decrypted the first blocksize in read_packet_init */
311 buf_setpos(ses.readbuf, blocksize);
313 /* decrypt it in-place */
314 len = ses.readbuf->len - macsize - ses.readbuf->pos;
315 if (ses.keys->recv.crypt_mode->decrypt(
316 buf_getptr(ses.readbuf, len),
317 buf_getwriteptr(ses.readbuf, len),
318 len,
319 &ses.keys->recv.cipher_state) != CRYPT_OK) {
320 dropbear_exit("Error decrypting");
322 buf_incrpos(ses.readbuf, len);
324 /* check the hmac */
325 if (checkmac() != DROPBEAR_SUCCESS) {
326 dropbear_exit("Integrity error");
329 /* get padding length */
330 buf_setpos(ses.readbuf, PACKET_PADDING_OFF);
331 padlen = buf_getbyte(ses.readbuf);
333 /* payload length */
334 /* - 4 - 1 is for LEN and PADLEN values */
335 len = ses.readbuf->len - padlen - 4 - 1 - macsize;
336 if ((len > RECV_MAX_PAYLOAD_LEN) || (len < 1)) {
337 dropbear_exit("Bad packet size %d", len);
340 buf_setpos(ses.readbuf, PACKET_PAYLOAD_OFF);
342 #ifndef DISABLE_ZLIB
343 if (is_compress_recv()) {
344 /* decompress */
345 ses.payload = buf_decompress(ses.readbuf, len);
346 } else
347 #endif
349 /* copy payload */
350 ses.payload = buf_new(len);
351 memcpy(ses.payload->data, buf_getptr(ses.readbuf, len), len);
352 buf_incrlen(ses.payload, len);
355 buf_free(ses.readbuf);
356 ses.readbuf = NULL;
357 buf_setpos(ses.payload, 0);
359 ses.recvseq++;
361 TRACE2(("leave decrypt_packet"))
364 /* Checks the mac at the end of a decrypted readbuf.
365 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
366 static int checkmac() {
368 unsigned char mac_bytes[MAX_MAC_LEN];
369 unsigned int mac_size, contents_len;
371 mac_size = ses.keys->recv.algo_mac->hashsize;
372 contents_len = ses.readbuf->len - mac_size;
374 buf_setpos(ses.readbuf, 0);
375 make_mac(ses.recvseq, &ses.keys->recv, ses.readbuf, contents_len, mac_bytes);
377 /* compare the hash */
378 buf_setpos(ses.readbuf, contents_len);
379 if (constant_time_memcmp(mac_bytes, buf_getptr(ses.readbuf, mac_size), mac_size) != 0) {
380 return DROPBEAR_FAILURE;
381 } else {
382 return DROPBEAR_SUCCESS;
386 #ifndef DISABLE_ZLIB
387 /* returns a pointer to a newly created buffer */
388 static buffer* buf_decompress(buffer* buf, unsigned int len) {
390 int result;
391 buffer * ret;
392 z_streamp zstream;
394 zstream = ses.keys->recv.zstream;
395 ret = buf_new(len);
397 zstream->avail_in = len;
398 zstream->next_in = buf_getptr(buf, len);
400 /* decompress the payload, incrementally resizing the output buffer */
401 while (1) {
403 zstream->avail_out = ret->size - ret->pos;
404 zstream->next_out = buf_getwriteptr(ret, zstream->avail_out);
406 result = inflate(zstream, Z_SYNC_FLUSH);
408 buf_setlen(ret, ret->size - zstream->avail_out);
409 buf_setpos(ret, ret->len);
411 if (result != Z_BUF_ERROR && result != Z_OK) {
412 dropbear_exit("zlib error");
415 if (zstream->avail_in == 0 &&
416 (zstream->avail_out != 0 || result == Z_BUF_ERROR)) {
417 /* we can only exit if avail_out hasn't all been used,
418 * and there's no remaining input */
419 return ret;
422 if (zstream->avail_out == 0) {
423 int new_size = 0;
424 if (ret->size >= RECV_MAX_PAYLOAD_LEN) {
425 dropbear_exit("bad packet, oversized decompressed");
427 new_size = MIN(RECV_MAX_PAYLOAD_LEN, ret->size + ZLIB_DECOMPRESS_INCR);
428 buf_resize(ret, new_size);
432 #endif
435 /* returns 1 if the packet is a valid type during kex (see 7.1 of rfc4253) */
436 static int packet_is_okay_kex(unsigned char type) {
437 if (type >= SSH_MSG_USERAUTH_REQUEST) {
438 return 0;
440 if (type == SSH_MSG_SERVICE_REQUEST || type == SSH_MSG_SERVICE_ACCEPT) {
441 return 0;
443 if (type == SSH_MSG_KEXINIT) {
444 /* XXX should this die horribly if !dataallowed ?? */
445 return 0;
447 return 1;
450 static void enqueue_reply_packet() {
451 struct packetlist * new_item = NULL;
452 new_item = m_malloc(sizeof(struct packetlist));
453 new_item->next = NULL;
455 new_item->payload = buf_newcopy(ses.writepayload);
456 buf_setpos(ses.writepayload, 0);
457 buf_setlen(ses.writepayload, 0);
459 if (ses.reply_queue_tail) {
460 ses.reply_queue_tail->next = new_item;
461 } else {
462 ses.reply_queue_head = new_item;
464 ses.reply_queue_tail = new_item;
467 void maybe_flush_reply_queue() {
468 struct packetlist *tmp_item = NULL, *curr_item = NULL;
469 if (!ses.dataallowed)
471 TRACE(("maybe_empty_reply_queue - no data allowed"))
472 return;
475 for (curr_item = ses.reply_queue_head; curr_item; ) {
476 CHECKCLEARTOWRITE();
477 buf_putbytes(ses.writepayload,
478 curr_item->payload->data, curr_item->payload->len);
480 buf_free(curr_item->payload);
481 tmp_item = curr_item;
482 curr_item = curr_item->next;
483 m_free(tmp_item);
484 encrypt_packet();
486 ses.reply_queue_head = ses.reply_queue_tail = NULL;
489 /* encrypt the writepayload, putting into writebuf, ready for write_packet()
490 * to put on the wire */
491 void encrypt_packet() {
493 unsigned char padlen;
494 unsigned char blocksize, mac_size;
495 buffer * writebuf; /* the packet which will go on the wire. This is
496 encrypted in-place. */
497 unsigned char packet_type;
498 unsigned int len, encrypt_buf_size;
499 unsigned char mac_bytes[MAX_MAC_LEN];
501 TRACE2(("enter encrypt_packet()"))
503 buf_setpos(ses.writepayload, 0);
504 packet_type = buf_getbyte(ses.writepayload);
505 buf_setpos(ses.writepayload, 0);
507 TRACE2(("encrypt_packet type is %d", packet_type))
509 if ((!ses.dataallowed && !packet_is_okay_kex(packet_type))) {
510 /* During key exchange only particular packets are allowed.
511 Since this packet_type isn't OK we just enqueue it to send
512 after the KEX, see maybe_flush_reply_queue */
513 enqueue_reply_packet();
514 return;
517 blocksize = ses.keys->trans.algo_crypt->blocksize;
518 mac_size = ses.keys->trans.algo_mac->hashsize;
520 /* Encrypted packet len is payload+5. We need to then make sure
521 * there is enough space for padding or MIN_PACKET_LEN.
522 * Add extra 3 since we need at least 4 bytes of padding */
523 encrypt_buf_size = (ses.writepayload->len+4+1)
524 + MAX(MIN_PACKET_LEN, blocksize) + 3
525 /* add space for the MAC at the end */
526 + mac_size
527 #ifndef DISABLE_ZLIB
528 /* some extra in case 'compression' makes it larger */
529 + ZLIB_COMPRESS_INCR
530 #endif
531 /* and an extra cleartext (stripped before transmission) byte for the
532 * packet type */
533 + 1;
535 writebuf = buf_new(encrypt_buf_size);
536 buf_setlen(writebuf, PACKET_PAYLOAD_OFF);
537 buf_setpos(writebuf, PACKET_PAYLOAD_OFF);
539 #ifndef DISABLE_ZLIB
540 /* compression */
541 if (is_compress_trans()) {
542 int compress_delta;
543 buf_compress(writebuf, ses.writepayload, ses.writepayload->len);
544 compress_delta = (writebuf->len - PACKET_PAYLOAD_OFF) - ses.writepayload->len;
546 /* Handle the case where 'compress' increased the size. */
547 if (compress_delta > ZLIB_COMPRESS_INCR) {
548 buf_resize(writebuf, writebuf->size + compress_delta);
550 } else
551 #endif
553 memcpy(buf_getwriteptr(writebuf, ses.writepayload->len),
554 buf_getptr(ses.writepayload, ses.writepayload->len),
555 ses.writepayload->len);
556 buf_incrwritepos(writebuf, ses.writepayload->len);
559 /* finished with payload */
560 buf_setpos(ses.writepayload, 0);
561 buf_setlen(ses.writepayload, 0);
563 /* length of padding - packet length must be a multiple of blocksize,
564 * with a minimum of 4 bytes of padding */
565 padlen = blocksize - (writebuf->len) % blocksize;
566 if (padlen < 4) {
567 padlen += blocksize;
569 /* check for min packet length */
570 if (writebuf->len + padlen < MIN_PACKET_LEN) {
571 padlen += blocksize;
574 buf_setpos(writebuf, 0);
575 /* packet length excluding the packetlength uint32 */
576 buf_putint(writebuf, writebuf->len + padlen - 4);
578 /* padding len */
579 buf_putbyte(writebuf, padlen);
580 /* actual padding */
581 buf_setpos(writebuf, writebuf->len);
582 buf_incrlen(writebuf, padlen);
583 genrandom(buf_getptr(writebuf, padlen), padlen);
585 make_mac(ses.transseq, &ses.keys->trans, writebuf, writebuf->len, mac_bytes);
587 /* do the actual encryption, in-place */
588 buf_setpos(writebuf, 0);
589 /* encrypt it in-place*/
590 len = writebuf->len;
591 if (ses.keys->trans.crypt_mode->encrypt(
592 buf_getptr(writebuf, len),
593 buf_getwriteptr(writebuf, len),
594 len,
595 &ses.keys->trans.cipher_state) != CRYPT_OK) {
596 dropbear_exit("Error encrypting");
598 buf_incrpos(writebuf, len);
600 /* stick the MAC on it */
601 buf_putbytes(writebuf, mac_bytes, mac_size);
603 /* The last byte of the buffer stores the cleartext packet_type. It is not
604 * transmitted but is used for transmit timeout purposes */
605 buf_putbyte(writebuf, packet_type);
606 /* enqueue the packet for sending. It will get freed after transmission. */
607 buf_setpos(writebuf, 0);
608 enqueue(&ses.writequeue, (void*)writebuf);
610 /* Update counts */
611 ses.kexstate.datatrans += writebuf->len;
612 ses.transseq++;
614 TRACE2(("leave encrypt_packet()"))
618 /* Create the packet mac, and append H(seqno|clearbuf) to the output */
619 /* output_mac must have ses.keys->trans.algo_mac->hashsize bytes. */
620 static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
621 buffer * clear_buf, unsigned int clear_len,
622 unsigned char *output_mac) {
623 unsigned char seqbuf[4];
624 unsigned long bufsize;
625 hmac_state hmac;
627 if (key_state->algo_mac->hashsize > 0) {
628 /* calculate the mac */
629 if (hmac_init(&hmac,
630 key_state->hash_index,
631 key_state->mackey,
632 key_state->algo_mac->keysize) != CRYPT_OK) {
633 dropbear_exit("HMAC error");
636 /* sequence number */
637 STORE32H(seqno, seqbuf);
638 if (hmac_process(&hmac, seqbuf, 4) != CRYPT_OK) {
639 dropbear_exit("HMAC error");
642 /* the actual contents */
643 buf_setpos(clear_buf, 0);
644 if (hmac_process(&hmac,
645 buf_getptr(clear_buf, clear_len),
646 clear_len) != CRYPT_OK) {
647 dropbear_exit("HMAC error");
650 bufsize = MAX_MAC_LEN;
651 if (hmac_done(&hmac, output_mac, &bufsize) != CRYPT_OK) {
652 dropbear_exit("HMAC error");
655 TRACE2(("leave writemac"))
658 #ifndef DISABLE_ZLIB
659 /* compresses len bytes from src, outputting to dest (starting from the
660 * respective current positions. */
661 static void buf_compress(buffer * dest, buffer * src, unsigned int len) {
663 unsigned int endpos = src->pos + len;
664 int result;
666 TRACE2(("enter buf_compress"))
668 while (1) {
670 ses.keys->trans.zstream->avail_in = endpos - src->pos;
671 ses.keys->trans.zstream->next_in =
672 buf_getptr(src, ses.keys->trans.zstream->avail_in);
674 ses.keys->trans.zstream->avail_out = dest->size - dest->pos;
675 ses.keys->trans.zstream->next_out =
676 buf_getwriteptr(dest, ses.keys->trans.zstream->avail_out);
678 result = deflate(ses.keys->trans.zstream, Z_SYNC_FLUSH);
680 buf_setpos(src, endpos - ses.keys->trans.zstream->avail_in);
681 buf_setlen(dest, dest->size - ses.keys->trans.zstream->avail_out);
682 buf_setpos(dest, dest->len);
684 if (result != Z_OK) {
685 dropbear_exit("zlib error");
688 if (ses.keys->trans.zstream->avail_in == 0) {
689 break;
692 dropbear_assert(ses.keys->trans.zstream->avail_out == 0);
694 /* the buffer has been filled, we must extend. This only happens in
695 * unusual circumstances where the data grows in size after deflate(),
696 * but it is possible */
697 buf_resize(dest, dest->size + ZLIB_COMPRESS_INCR);
700 TRACE2(("leave buf_compress"))
702 #endif