usbmodeswitch: Updated to v.1.2.6 from shibby's branch.
[tomato.git] / release / src / router / dropbear / packet.c
blob349ed40073b4a81e7c1d829e12a81b1c4f44150e
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 "random.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 100
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;
59 TRACE(("enter write_packet"))
60 dropbear_assert(!isempty(&ses.writequeue));
62 /* Get the next buffer in the queue of encrypted packets to write*/
63 writebuf = (buffer*)examine(&ses.writequeue);
65 /* The last byte of the buffer is not to be transmitted, but is
66 * a cleartext packet_type indicator */
67 packet_type = writebuf->data[writebuf->len-1];
68 len = writebuf->len - 1 - writebuf->pos;
69 dropbear_assert(len > 0);
70 /* Try to write as much as possible */
71 written = write(ses.sock_out, buf_getptr(writebuf, len), len);
73 if (written < 0) {
74 if (errno == EINTR) {
75 TRACE(("leave writepacket: EINTR"))
76 return;
77 } else {
78 dropbear_exit("Error writing");
82 now = time(NULL);
83 ses.last_trx_packet_time = now;
85 if (packet_type != SSH_MSG_IGNORE) {
86 ses.last_packet_time = now;
89 if (written == 0) {
90 ses.remoteclosed();
93 if (written == len) {
94 /* We've finished with the packet, free it */
95 dequeue(&ses.writequeue);
96 buf_free(writebuf);
97 writebuf = NULL;
98 } else {
99 /* More packet left to write, leave it in the queue for later */
100 buf_incrpos(writebuf, written);
103 TRACE(("leave write_packet"))
106 /* Non-blocking function reading available portion of a packet into the
107 * ses's buffer, decrypting the length if encrypted, decrypting the
108 * full portion if possible */
109 void read_packet() {
111 int len;
112 unsigned int maxlen;
113 unsigned char blocksize;
115 TRACE(("enter read_packet"))
116 blocksize = ses.keys->recv.algo_crypt->blocksize;
118 if (ses.readbuf == NULL || ses.readbuf->len < blocksize) {
119 int ret;
120 /* In the first blocksize of a packet */
122 /* Read the first blocksize of the packet, so we can decrypt it and
123 * find the length of the whole packet */
124 ret = read_packet_init();
126 if (ret == DROPBEAR_FAILURE) {
127 /* didn't read enough to determine the length */
128 TRACE(("leave read_packet: packetinit done"))
129 return;
133 /* Attempt to read the remainder of the packet, note that there
134 * mightn't be any available (EAGAIN) */
135 maxlen = ses.readbuf->len - ses.readbuf->pos;
136 len = read(ses.sock_in, buf_getptr(ses.readbuf, maxlen), maxlen);
138 if (len == 0) {
139 ses.remoteclosed();
142 if (len < 0) {
143 if (errno == EINTR || errno == EAGAIN) {
144 TRACE(("leave read_packet: EINTR or EAGAIN"))
145 return;
146 } else {
147 dropbear_exit("Error reading: %s", strerror(errno));
151 buf_incrpos(ses.readbuf, len);
153 if ((unsigned int)len == maxlen) {
154 /* The whole packet has been read */
155 decrypt_packet();
156 /* The main select() loop process_packet() to
157 * handle the packet contents... */
159 TRACE(("leave read_packet"))
162 /* Function used to read the initial portion of a packet, and determine the
163 * length. Only called during the first BLOCKSIZE of a packet. */
164 /* Returns DROPBEAR_SUCCESS if the length is determined,
165 * DROPBEAR_FAILURE otherwise */
166 static int read_packet_init() {
168 unsigned int maxlen;
169 int slen;
170 unsigned int len;
171 unsigned int blocksize;
172 unsigned int macsize;
175 blocksize = ses.keys->recv.algo_crypt->blocksize;
176 macsize = ses.keys->recv.algo_mac->hashsize;
178 if (ses.readbuf == NULL) {
179 /* start of a new packet */
180 ses.readbuf = buf_new(INIT_READBUF);
183 maxlen = blocksize - ses.readbuf->pos;
185 /* read the rest of the packet if possible */
186 slen = read(ses.sock_in, buf_getwriteptr(ses.readbuf, maxlen),
187 maxlen);
188 if (slen == 0) {
189 ses.remoteclosed();
191 if (slen < 0) {
192 if (errno == EINTR) {
193 TRACE(("leave read_packet_init: EINTR"))
194 return DROPBEAR_FAILURE;
196 dropbear_exit("Error reading: %s", strerror(errno));
199 buf_incrwritepos(ses.readbuf, slen);
201 if ((unsigned int)slen != maxlen) {
202 /* don't have enough bytes to determine length, get next time */
203 return DROPBEAR_FAILURE;
206 /* now we have the first block, need to get packet length, so we decrypt
207 * the first block (only need first 4 bytes) */
208 buf_setpos(ses.readbuf, 0);
209 if (ses.keys->recv.crypt_mode->decrypt(buf_getptr(ses.readbuf, blocksize),
210 buf_getwriteptr(ses.readbuf, blocksize),
211 blocksize,
212 &ses.keys->recv.cipher_state) != CRYPT_OK) {
213 dropbear_exit("Error decrypting");
215 len = buf_getint(ses.readbuf) + 4 + macsize;
217 TRACE(("packet size is %d, block %d mac %d", len, blocksize, macsize))
220 /* check packet length */
221 if ((len > RECV_MAX_PACKET_LEN) ||
222 (len < MIN_PACKET_LEN + macsize) ||
223 ((len - macsize) % blocksize != 0)) {
224 dropbear_exit("Integrity error (bad packet size %d)", len);
227 if (len > ses.readbuf->size) {
228 buf_resize(ses.readbuf, len);
230 buf_setlen(ses.readbuf, len);
231 buf_setpos(ses.readbuf, blocksize);
232 return DROPBEAR_SUCCESS;
235 /* handle the received packet */
236 void decrypt_packet() {
238 unsigned char blocksize;
239 unsigned char macsize;
240 unsigned int padlen;
241 unsigned int len;
243 TRACE(("enter decrypt_packet"))
244 blocksize = ses.keys->recv.algo_crypt->blocksize;
245 macsize = ses.keys->recv.algo_mac->hashsize;
247 ses.kexstate.datarecv += ses.readbuf->len;
249 /* we've already decrypted the first blocksize in read_packet_init */
250 buf_setpos(ses.readbuf, blocksize);
252 /* decrypt it in-place */
253 len = ses.readbuf->len - macsize - ses.readbuf->pos;
254 if (ses.keys->recv.crypt_mode->decrypt(
255 buf_getptr(ses.readbuf, len),
256 buf_getwriteptr(ses.readbuf, len),
257 len,
258 &ses.keys->recv.cipher_state) != CRYPT_OK) {
259 dropbear_exit("Error decrypting");
261 buf_incrpos(ses.readbuf, len);
263 /* check the hmac */
264 if (checkmac() != DROPBEAR_SUCCESS) {
265 dropbear_exit("Integrity error");
268 /* get padding length */
269 buf_setpos(ses.readbuf, PACKET_PADDING_OFF);
270 padlen = buf_getbyte(ses.readbuf);
272 /* payload length */
273 /* - 4 - 1 is for LEN and PADLEN values */
274 len = ses.readbuf->len - padlen - 4 - 1 - macsize;
275 if ((len > RECV_MAX_PAYLOAD_LEN) || (len < 1)) {
276 dropbear_exit("Bad packet size %d", len);
279 buf_setpos(ses.readbuf, PACKET_PAYLOAD_OFF);
281 #ifndef DISABLE_ZLIB
282 if (is_compress_recv()) {
283 /* decompress */
284 ses.payload = buf_decompress(ses.readbuf, len);
285 } else
286 #endif
288 /* copy payload */
289 ses.payload = buf_new(len);
290 memcpy(ses.payload->data, buf_getptr(ses.readbuf, len), len);
291 buf_incrlen(ses.payload, len);
294 buf_free(ses.readbuf);
295 ses.readbuf = NULL;
296 buf_setpos(ses.payload, 0);
298 ses.recvseq++;
300 TRACE(("leave decrypt_packet"))
303 /* Checks the mac at the end of a decrypted readbuf.
304 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
305 static int checkmac() {
307 unsigned char mac_bytes[MAX_MAC_LEN];
308 unsigned int mac_size, contents_len;
310 mac_size = ses.keys->trans.algo_mac->hashsize;
311 contents_len = ses.readbuf->len - mac_size;
313 buf_setpos(ses.readbuf, 0);
314 make_mac(ses.recvseq, &ses.keys->recv, ses.readbuf, contents_len, mac_bytes);
316 /* compare the hash */
317 buf_setpos(ses.readbuf, contents_len);
318 if (memcmp(mac_bytes, buf_getptr(ses.readbuf, mac_size), mac_size) != 0) {
319 return DROPBEAR_FAILURE;
320 } else {
321 return DROPBEAR_SUCCESS;
325 #ifndef DISABLE_ZLIB
326 /* returns a pointer to a newly created buffer */
327 static buffer* buf_decompress(buffer* buf, unsigned int len) {
329 int result;
330 buffer * ret;
331 z_streamp zstream;
333 zstream = ses.keys->recv.zstream;
334 ret = buf_new(len);
336 zstream->avail_in = len;
337 zstream->next_in = buf_getptr(buf, len);
339 /* decompress the payload, incrementally resizing the output buffer */
340 while (1) {
342 zstream->avail_out = ret->size - ret->pos;
343 zstream->next_out = buf_getwriteptr(ret, zstream->avail_out);
345 result = inflate(zstream, Z_SYNC_FLUSH);
347 buf_setlen(ret, ret->size - zstream->avail_out);
348 buf_setpos(ret, ret->len);
350 if (result != Z_BUF_ERROR && result != Z_OK) {
351 dropbear_exit("zlib error");
354 if (zstream->avail_in == 0 &&
355 (zstream->avail_out != 0 || result == Z_BUF_ERROR)) {
356 /* we can only exit if avail_out hasn't all been used,
357 * and there's no remaining input */
358 return ret;
361 if (zstream->avail_out == 0) {
362 buf_resize(ret, ret->size + ZLIB_DECOMPRESS_INCR);
366 #endif
369 /* returns 1 if the packet is a valid type during kex (see 7.1 of rfc4253) */
370 static int packet_is_okay_kex(unsigned char type) {
371 if (type >= SSH_MSG_USERAUTH_REQUEST) {
372 return 0;
374 if (type == SSH_MSG_SERVICE_REQUEST || type == SSH_MSG_SERVICE_ACCEPT) {
375 return 0;
377 if (type == SSH_MSG_KEXINIT) {
378 /* XXX should this die horribly if !dataallowed ?? */
379 return 0;
381 return 1;
384 static void enqueue_reply_packet() {
385 struct packetlist * new_item = NULL;
386 new_item = m_malloc(sizeof(struct packetlist));
387 new_item->next = NULL;
389 new_item->payload = buf_newcopy(ses.writepayload);
390 buf_setpos(ses.writepayload, 0);
391 buf_setlen(ses.writepayload, 0);
393 if (ses.reply_queue_tail) {
394 ses.reply_queue_tail->next = new_item;
395 } else {
396 ses.reply_queue_head = new_item;
398 ses.reply_queue_tail = new_item;
399 TRACE(("leave enqueue_reply_packet"))
402 void maybe_flush_reply_queue() {
403 struct packetlist *tmp_item = NULL, *curr_item = NULL;
404 if (!ses.dataallowed)
406 TRACE(("maybe_empty_reply_queue - no data allowed"))
407 return;
410 for (curr_item = ses.reply_queue_head; curr_item; ) {
411 CHECKCLEARTOWRITE();
412 buf_putbytes(ses.writepayload,
413 curr_item->payload->data, curr_item->payload->len);
415 buf_free(curr_item->payload);
416 tmp_item = curr_item;
417 curr_item = curr_item->next;
418 m_free(tmp_item);
419 encrypt_packet();
421 ses.reply_queue_head = ses.reply_queue_tail = NULL;
424 /* encrypt the writepayload, putting into writebuf, ready for write_packet()
425 * to put on the wire */
426 void encrypt_packet() {
428 unsigned char padlen;
429 unsigned char blocksize, mac_size;
430 buffer * writebuf; /* the packet which will go on the wire. This is
431 encrypted in-place. */
432 unsigned char packet_type;
433 unsigned int len, encrypt_buf_size;
434 unsigned char mac_bytes[MAX_MAC_LEN];
436 TRACE(("enter encrypt_packet()"))
438 buf_setpos(ses.writepayload, 0);
439 packet_type = buf_getbyte(ses.writepayload);
440 buf_setpos(ses.writepayload, 0);
442 TRACE(("encrypt_packet type is %d", packet_type))
444 if ((!ses.dataallowed && !packet_is_okay_kex(packet_type))
445 || ses.kexstate.sentnewkeys) {
446 /* During key exchange only particular packets are allowed.
447 Since this packet_type isn't OK we just enqueue it to send
448 after the KEX, see maybe_flush_reply_queue */
450 /* We also enqueue packets here when we have sent a MSG_NEWKEYS
451 * packet but are yet to received one. For simplicity we just switch
452 * over all the keys at once. This is the 'ses.kexstate.sentnewkeys'
453 * case. */
454 enqueue_reply_packet();
455 return;
458 blocksize = ses.keys->trans.algo_crypt->blocksize;
459 mac_size = ses.keys->trans.algo_mac->hashsize;
461 /* Encrypted packet len is payload+5. We need to then make sure
462 * there is enough space for padding or MIN_PACKET_LEN.
463 * Add extra 3 since we need at least 4 bytes of padding */
464 encrypt_buf_size = (ses.writepayload->len+4+1)
465 + MAX(MIN_PACKET_LEN, blocksize) + 3
466 /* add space for the MAC at the end */
467 + mac_size
468 #ifndef DISABLE_ZLIB
469 /* some extra in case 'compression' makes it larger */
470 + ZLIB_COMPRESS_INCR
471 #endif
472 /* and an extra cleartext (stripped before transmission) byte for the
473 * packet type */
474 + 1;
476 writebuf = buf_new(encrypt_buf_size);
477 buf_setlen(writebuf, PACKET_PAYLOAD_OFF);
478 buf_setpos(writebuf, PACKET_PAYLOAD_OFF);
480 #ifndef DISABLE_ZLIB
481 /* compression */
482 if (is_compress_trans()) {
483 int compress_delta;
484 buf_compress(writebuf, ses.writepayload, ses.writepayload->len);
485 compress_delta = (writebuf->len - PACKET_PAYLOAD_OFF) - ses.writepayload->len;
487 /* Handle the case where 'compress' increased the size. */
488 if (compress_delta > ZLIB_COMPRESS_INCR) {
489 buf_resize(writebuf, writebuf->size + compress_delta);
491 } else
492 #endif
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);
500 /* finished with payload */
501 buf_setpos(ses.writepayload, 0);
502 buf_setlen(ses.writepayload, 0);
504 /* length of padding - packet length must be a multiple of blocksize,
505 * with a minimum of 4 bytes of padding */
506 padlen = blocksize - (writebuf->len) % blocksize;
507 if (padlen < 4) {
508 padlen += blocksize;
510 /* check for min packet length */
511 if (writebuf->len + padlen < MIN_PACKET_LEN) {
512 padlen += blocksize;
515 buf_setpos(writebuf, 0);
516 /* packet length excluding the packetlength uint32 */
517 buf_putint(writebuf, writebuf->len + padlen - 4);
519 /* padding len */
520 buf_putbyte(writebuf, padlen);
521 /* actual padding */
522 buf_setpos(writebuf, writebuf->len);
523 buf_incrlen(writebuf, padlen);
524 genrandom(buf_getptr(writebuf, padlen), padlen);
526 make_mac(ses.transseq, &ses.keys->trans, writebuf, writebuf->len, mac_bytes);
528 /* do the actual encryption, in-place */
529 buf_setpos(writebuf, 0);
530 /* encrypt it in-place*/
531 len = writebuf->len;
532 if (ses.keys->trans.crypt_mode->encrypt(
533 buf_getptr(writebuf, len),
534 buf_getwriteptr(writebuf, len),
535 len,
536 &ses.keys->trans.cipher_state) != CRYPT_OK) {
537 dropbear_exit("Error encrypting");
539 buf_incrpos(writebuf, len);
541 /* stick the MAC on it */
542 buf_putbytes(writebuf, mac_bytes, mac_size);
544 /* The last byte of the buffer stores the cleartext packet_type. It is not
545 * transmitted but is used for transmit timeout purposes */
546 buf_putbyte(writebuf, packet_type);
547 /* enqueue the packet for sending. It will get freed after transmission. */
548 buf_setpos(writebuf, 0);
549 enqueue(&ses.writequeue, (void*)writebuf);
551 /* Update counts */
552 ses.kexstate.datatrans += writebuf->len;
553 ses.transseq++;
555 TRACE(("leave encrypt_packet()"))
559 /* Create the packet mac, and append H(seqno|clearbuf) to the output */
560 /* output_mac must have ses.keys->trans.algo_mac->hashsize bytes. */
561 static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
562 buffer * clear_buf, unsigned int clear_len,
563 unsigned char *output_mac) {
564 unsigned char seqbuf[4];
565 unsigned long bufsize;
566 hmac_state hmac;
568 TRACE(("enter writemac"))
570 if (key_state->algo_mac->hashsize > 0) {
571 /* calculate the mac */
572 if (hmac_init(&hmac,
573 key_state->hash_index,
574 key_state->mackey,
575 key_state->algo_mac->keysize) != CRYPT_OK) {
576 dropbear_exit("HMAC error");
579 /* sequence number */
580 STORE32H(seqno, seqbuf);
581 if (hmac_process(&hmac, seqbuf, 4) != CRYPT_OK) {
582 dropbear_exit("HMAC error");
585 /* the actual contents */
586 buf_setpos(clear_buf, 0);
587 if (hmac_process(&hmac,
588 buf_getptr(clear_buf, clear_len),
589 clear_len) != CRYPT_OK) {
590 dropbear_exit("HMAC error");
593 bufsize = MAX_MAC_LEN;
594 if (hmac_done(&hmac, output_mac, &bufsize) != CRYPT_OK) {
595 dropbear_exit("HMAC error");
598 TRACE(("leave writemac"))
601 #ifndef DISABLE_ZLIB
602 /* compresses len bytes from src, outputting to dest (starting from the
603 * respective current positions. */
604 static void buf_compress(buffer * dest, buffer * src, unsigned int len) {
606 unsigned int endpos = src->pos + len;
607 int result;
609 TRACE(("enter buf_compress"))
611 while (1) {
613 ses.keys->trans.zstream->avail_in = endpos - src->pos;
614 ses.keys->trans.zstream->next_in =
615 buf_getptr(src, ses.keys->trans.zstream->avail_in);
617 ses.keys->trans.zstream->avail_out = dest->size - dest->pos;
618 ses.keys->trans.zstream->next_out =
619 buf_getwriteptr(dest, ses.keys->trans.zstream->avail_out);
621 result = deflate(ses.keys->trans.zstream, Z_SYNC_FLUSH);
623 buf_setpos(src, endpos - ses.keys->trans.zstream->avail_in);
624 buf_setlen(dest, dest->size - ses.keys->trans.zstream->avail_out);
625 buf_setpos(dest, dest->len);
627 if (result != Z_OK) {
628 dropbear_exit("zlib error");
631 if (ses.keys->trans.zstream->avail_in == 0) {
632 break;
635 dropbear_assert(ses.keys->trans.zstream->avail_out == 0);
637 /* the buffer has been filled, we must extend. This only happens in
638 * unusual circumstances where the data grows in size after deflate(),
639 * but it is possible */
640 buf_resize(dest, dest->size + ZLIB_COMPRESS_INCR);
643 TRACE(("leave buf_compress"))
645 #endif