packet.c 19 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 * Dropbear - a SSH2 server
 * 
 * Copyright (c) 2002,2003 Matt Johnston
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. */

#include "includes.h"
#include "packet.h"
#include "session.h"
#include "dbutil.h"
#include "ssh.h"
#include "algo.h"
#include "buffer.h"
#include "kex.h"
33
#include "dbrandom.h"
34
35
36
37
#include "service.h"
#include "auth.h"
#include "channel.h"

38
39
40
41
42
static int read_packet_init();
static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
		buffer * clear_buf, unsigned int clear_len, 
		unsigned char *output_mac);
static int checkmac();
43

44
45
46
47
48
/* For exact details see http://www.zlib.net/zlib_tech.html
 * 5 bytes per 16kB block, plus 6 bytes for the stream.
 * We might allocate 5 unnecessary bytes here if it's an
 * exact multiple. */
#define ZLIB_COMPRESS_EXPANSION (((RECV_MAX_PAYLOAD_LEN/16384)+1)*5 + 6)
Matt Johnston's avatar
Matt Johnston committed
49
#define ZLIB_DECOMPRESS_INCR 1024
50
51
52
53
54
#ifndef DISABLE_ZLIB
static buffer* buf_decompress(buffer* buf, unsigned int len);
static void buf_compress(buffer * dest, buffer * src, unsigned int len);
#endif

55
56
/* non-blocking function writing out a current encrypted packet */
void write_packet() {
57
58

	int len, written;
59
	buffer * writebuf = NULL;
60
61
	time_t now;
	unsigned packet_type;
62
63
64
65
66
67
	int all_ignore = 1;
#ifdef HAVE_WRITEV
	struct iovec *iov = NULL;
	int i;
	struct Link *l;
#endif
68
	
69
	TRACE2(("enter write_packet"))
70
	dropbear_assert(!isempty(&ses.writequeue));
71

72
73
74
75
76
77
78
79
80
#ifdef HAVE_WRITEV
	iov = m_malloc(sizeof(*iov) * ses.writequeue.count);
	for (l = ses.writequeue.head, i = 0; l; l = l->link, i++)
	{
		writebuf = (buffer*)l->item;
		packet_type = writebuf->data[writebuf->len-1];
		len = writebuf->len - 1 - writebuf->pos;
		dropbear_assert(len > 0);
		all_ignore &= (packet_type == SSH_MSG_IGNORE);
81
82
		TRACE2(("write_packet writev #%d  type %d len %d/%d", i, packet_type,
				len, writebuf->len-1))
83
84
85
86
87
88
89
		iov[i].iov_base = buf_getptr(writebuf, len);
		iov[i].iov_len = len;
	}
	written = writev(ses.sock_out, iov, ses.writequeue.count);
	if (written < 0) {
		if (errno == EINTR) {
			m_free(iov);
90
			TRACE2(("leave write_packet: EINTR"))
91
92
			return;
		} else {
93
			dropbear_exit("Error writing: %s", strerror(errno));
94
		}
95
	}
96
97
98
99
100
101
102
103
104

	if (written == 0) {
		ses.remoteclosed();
	}

	while (written > 0) {
		writebuf = (buffer*)examine(&ses.writequeue);
		len = writebuf->len - 1 - writebuf->pos;
		if (len > written) {
Matt Johnston's avatar
Matt Johnston committed
105
			/* partial buffer write */
106
107
108
109
110
111
112
113
114
115
116
117
			buf_incrpos(writebuf, written);
			written = 0;
		} else {
			written -= len;
			dequeue(&ses.writequeue);
			buf_free(writebuf);
		}
	}

	m_free(iov);

#else
118
119
120
	/* Get the next buffer in the queue of encrypted packets to write*/
	writebuf = (buffer*)examine(&ses.writequeue);

121
122
123
124
	/* The last byte of the buffer is not to be transmitted, but is 
	 * a cleartext packet_type indicator */
	packet_type = writebuf->data[writebuf->len-1];
	len = writebuf->len - 1 - writebuf->pos;
125
	dropbear_assert(len > 0);
126
	/* Try to write as much as possible */
127
	written = write(ses.sock_out, buf_getptr(writebuf, len), len);
128
129
130

	if (written < 0) {
		if (errno == EINTR) {
131
			TRACE2(("leave writepacket: EINTR"))
132
133
			return;
		} else {
134
			dropbear_exit("Error writing: %s", strerror(errno));
135
136
		}
	} 
137
	all_ignore = (packet_type == SSH_MSG_IGNORE);
138
139

	if (written == 0) {
Matt Johnston's avatar
Matt Johnston committed
140
		ses.remoteclosed();
141
142
143
144
145
146
	}

	if (written == len) {
		/* We've finished with the packet, free it */
		dequeue(&ses.writequeue);
		buf_free(writebuf);
147
		writebuf = NULL;
148
149
150
151
152
	} else {
		/* More packet left to write, leave it in the queue for later */
		buf_incrpos(writebuf, written);
	}

153
#endif
154
	now = monotonic_now();
155
156
157
158
159
160
	ses.last_trx_packet_time = now;

	if (!all_ignore) {
		ses.last_packet_time = now;
	}

161
	TRACE2(("leave write_packet"))
162
163
164
165
166
167
168
169
170
171
172
}

/* Non-blocking function reading available portion of a packet into the
 * ses's buffer, decrypting the length if encrypted, decrypting the
 * full portion if possible */
void read_packet() {

	int len;
	unsigned int maxlen;
	unsigned char blocksize;

173
	TRACE2(("enter read_packet"))
174
	blocksize = ses.keys->recv.algo_crypt->blocksize;
175
176
	
	if (ses.readbuf == NULL || ses.readbuf->len < blocksize) {
177
		int ret;
178
179
180
181
		/* In the first blocksize of a packet */

		/* Read the first blocksize of the packet, so we can decrypt it and
		 * find the length of the whole packet */
182
		ret = read_packet_init();
183

184
185
		if (ret == DROPBEAR_FAILURE) {
			/* didn't read enough to determine the length */
186
			TRACE2(("leave read_packet: packetinit done"))
187
188
189
190
191
192
193
			return;
		}
	}

	/* Attempt to read the remainder of the packet, note that there
	 * mightn't be any available (EAGAIN) */
	maxlen = ses.readbuf->len - ses.readbuf->pos;
194
195
196
197
198
199
200
	if (maxlen == 0) {
		/* Occurs when the packet is only a single block long and has all
		 * been read in read_packet_init().  Usually means that MAC is disabled
		 */
		len = 0;
	} else {
		len = read(ses.sock_in, buf_getptr(ses.readbuf, maxlen), maxlen);
201

202
203
204
		if (len == 0) {
			ses.remoteclosed();
		}
205

206
207
		if (len < 0) {
			if (errno == EINTR || errno == EAGAIN) {
208
				TRACE2(("leave read_packet: EINTR or EAGAIN"))
209
210
211
212
				return;
			} else {
				dropbear_exit("Error reading: %s", strerror(errno));
			}
213
214
		}

215
216
		buf_incrpos(ses.readbuf, len);
	}
217
218
219
220
221
222
223

	if ((unsigned int)len == maxlen) {
		/* The whole packet has been read */
		decrypt_packet();
		/* The main select() loop process_packet() to
		 * handle the packet contents... */
	}
224
	TRACE2(("leave read_packet"))
225
226
227
228
}

/* Function used to read the initial portion of a packet, and determine the
 * length. Only called during the first BLOCKSIZE of a packet. */
229
230
231
/* Returns DROPBEAR_SUCCESS if the length is determined, 
 * DROPBEAR_FAILURE otherwise */
static int read_packet_init() {
232
233

	unsigned int maxlen;
Matt Johnston's avatar
Matt Johnston committed
234
235
236
237
	int slen;
	unsigned int len;
	unsigned int blocksize;
	unsigned int macsize;
238
239


240
241
	blocksize = ses.keys->recv.algo_crypt->blocksize;
	macsize = ses.keys->recv.algo_mac->hashsize;
242
243
244
245
246
247
248
249
250

	if (ses.readbuf == NULL) {
		/* start of a new packet */
		ses.readbuf = buf_new(INIT_READBUF);
	}

	maxlen = blocksize - ses.readbuf->pos;
			
	/* read the rest of the packet if possible */
Matt Johnston's avatar
Matt Johnston committed
251
	slen = read(ses.sock_in, buf_getwriteptr(ses.readbuf, maxlen),
252
			maxlen);
Matt Johnston's avatar
Matt Johnston committed
253
	if (slen == 0) {
Matt Johnston's avatar
Matt Johnston committed
254
		ses.remoteclosed();
255
	}
Matt Johnston's avatar
Matt Johnston committed
256
	if (slen < 0) {
257
		if (errno == EINTR) {
258
			TRACE2(("leave read_packet_init: EINTR"))
259
			return DROPBEAR_FAILURE;
260
		}
261
		dropbear_exit("Error reading: %s", strerror(errno));
262
263
	}

Matt Johnston's avatar
Matt Johnston committed
264
	buf_incrwritepos(ses.readbuf, slen);
265

Matt Johnston's avatar
Matt Johnston committed
266
	if ((unsigned int)slen != maxlen) {
267
		/* don't have enough bytes to determine length, get next time */
268
		return DROPBEAR_FAILURE;
269
270
271
272
273
	}

	/* now we have the first block, need to get packet length, so we decrypt
	 * the first block (only need first 4 bytes) */
	buf_setpos(ses.readbuf, 0);
274
275
	if (ses.keys->recv.crypt_mode->decrypt(buf_getptr(ses.readbuf, blocksize), 
				buf_getwriteptr(ses.readbuf, blocksize),
Matt Johnston's avatar
Matt Johnston committed
276
				blocksize,
277
				&ses.keys->recv.cipher_state) != CRYPT_OK) {
278
		dropbear_exit("Error decrypting");
279
	}
280
281
	len = buf_getint(ses.readbuf) + 4 + macsize;

282
	TRACE2(("packet size is %d, block %d mac %d", len, blocksize, macsize))
283
284
285


	/* check packet length */
286
	if ((len > RECV_MAX_PACKET_LEN) ||
287
288
		(len < MIN_PACKET_LEN + macsize) ||
		((len - macsize) % blocksize != 0)) {
289
		dropbear_exit("Integrity error (bad packet size %d)", len);
290
291
	}

292
293
294
	if (len > ses.readbuf->size) {
		buf_resize(ses.readbuf, len);		
	}
295
	buf_setlen(ses.readbuf, len);
296
297
	buf_setpos(ses.readbuf, blocksize);
	return DROPBEAR_SUCCESS;
298
299
300
301
302
303
304
305
306
307
}

/* handle the received packet */
void decrypt_packet() {

	unsigned char blocksize;
	unsigned char macsize;
	unsigned int padlen;
	unsigned int len;

308
	TRACE2(("enter decrypt_packet"))
309
310
	blocksize = ses.keys->recv.algo_crypt->blocksize;
	macsize = ses.keys->recv.algo_mac->hashsize;
311
312
313
314
315
316

	ses.kexstate.datarecv += ses.readbuf->len;

	/* we've already decrypted the first blocksize in read_packet_init */
	buf_setpos(ses.readbuf, blocksize);

317
	/* decrypt it in-place */
318
	len = ses.readbuf->len - macsize - ses.readbuf->pos;
319
	if (ses.keys->recv.crypt_mode->decrypt(
320
				buf_getptr(ses.readbuf, len), 
321
				buf_getwriteptr(ses.readbuf, len),
322
				len,
323
				&ses.keys->recv.cipher_state) != CRYPT_OK) {
324
		dropbear_exit("Error decrypting");
325
	}
326
	buf_incrpos(ses.readbuf, len);
327

328
	/* check the hmac */
329
	if (checkmac() != DROPBEAR_SUCCESS) {
330
331
332
333
		dropbear_exit("Integrity error");
	}

	/* get padding length */
334
335
	buf_setpos(ses.readbuf, PACKET_PADDING_OFF);
	padlen = buf_getbyte(ses.readbuf);
336
337
338
		
	/* payload length */
	/* - 4 - 1 is for LEN and PADLEN values */
339
	len = ses.readbuf->len - padlen - 4 - 1 - macsize;
340
	if ((len > RECV_MAX_PAYLOAD_LEN+ZLIB_COMPRESS_EXPANSION) || (len < 1)) {
341
		dropbear_exit("Bad packet size %d", len);
342
343
	}

344
	buf_setpos(ses.readbuf, PACKET_PAYLOAD_OFF);
345
346

#ifndef DISABLE_ZLIB
347
	if (is_compress_recv()) {
348
		/* decompress */
349
		ses.payload = buf_decompress(ses.readbuf, len);
350
351
352
353
354
	} else 
#endif
	{
		/* copy payload */
		ses.payload = buf_new(len);
355
		memcpy(ses.payload->data, buf_getptr(ses.readbuf, len), len);
356
357
358
		buf_incrlen(ses.payload, len);
	}

359
360
	buf_free(ses.readbuf);
	ses.readbuf = NULL;
361
362
363
364
	buf_setpos(ses.payload, 0);

	ses.recvseq++;

365
	TRACE2(("leave decrypt_packet"))
366
367
}

368
/* Checks the mac at the end of a decrypted readbuf.
369
 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
370
static int checkmac() {
371

372
373
	unsigned char mac_bytes[MAX_MAC_LEN];
	unsigned int mac_size, contents_len;
374
	
375
	mac_size = ses.keys->recv.algo_mac->hashsize;
376
	contents_len = ses.readbuf->len - mac_size;
377

378
379
	buf_setpos(ses.readbuf, 0);
	make_mac(ses.recvseq, &ses.keys->recv, ses.readbuf, contents_len, mac_bytes);
380
381

	/* compare the hash */
382
	buf_setpos(ses.readbuf, contents_len);
383
	if (constant_time_memcmp(mac_bytes, buf_getptr(ses.readbuf, mac_size), mac_size) != 0) {
384
385
386
387
388
389
390
391
392
393
394
395
396
397
		return DROPBEAR_FAILURE;
	} else {
		return DROPBEAR_SUCCESS;
	}
}

#ifndef DISABLE_ZLIB
/* returns a pointer to a newly created buffer */
static buffer* buf_decompress(buffer* buf, unsigned int len) {

	int result;
	buffer * ret;
	z_streamp zstream;

398
	zstream = ses.keys->recv.zstream;
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
	ret = buf_new(len);

	zstream->avail_in = len;
	zstream->next_in = buf_getptr(buf, len);

	/* decompress the payload, incrementally resizing the output buffer */
	while (1) {

		zstream->avail_out = ret->size - ret->pos;
		zstream->next_out = buf_getwriteptr(ret, zstream->avail_out);

		result = inflate(zstream, Z_SYNC_FLUSH);

		buf_setlen(ret, ret->size - zstream->avail_out);
		buf_setpos(ret, ret->len);

		if (result != Z_BUF_ERROR && result != Z_OK) {
			dropbear_exit("zlib error");
		}

		if (zstream->avail_in == 0 &&
		   		(zstream->avail_out != 0 || result == Z_BUF_ERROR)) {
			/* we can only exit if avail_out hasn't all been used,
			 * and there's no remaining input */
			return ret;
		}

		if (zstream->avail_out == 0) {
Matt Johnston's avatar
Matt Johnston committed
427
428
			int new_size = 0;
			if (ret->size >= RECV_MAX_PAYLOAD_LEN) {
429
430
				/* Already been increased as large as it can go,
				 * yet didn't finish up the decompression */
Matt Johnston's avatar
Matt Johnston committed
431
432
433
434
				dropbear_exit("bad packet, oversized decompressed");
			}
			new_size = MIN(RECV_MAX_PAYLOAD_LEN, ret->size + ZLIB_DECOMPRESS_INCR);
			buf_resize(ret, new_size);
435
436
437
438
439
440
		}
	}
}
#endif


441
442
443
444
445
446
447
448
449
450
451
452
453
454
/* returns 1 if the packet is a valid type during kex (see 7.1 of rfc4253) */
static int packet_is_okay_kex(unsigned char type) {
	if (type >= SSH_MSG_USERAUTH_REQUEST) {
		return 0;
	}
	if (type == SSH_MSG_SERVICE_REQUEST || type == SSH_MSG_SERVICE_ACCEPT) {
		return 0;
	}
	if (type == SSH_MSG_KEXINIT) {
		/* XXX should this die horribly if !dataallowed ?? */
		return 0;
	}
	return 1;
}
455

456
457
458
459
460
461
462
463
464
465
466
467
468
469
static void enqueue_reply_packet() {
	struct packetlist * new_item = NULL;
	new_item = m_malloc(sizeof(struct packetlist));
	new_item->next = NULL;
	
	new_item->payload = buf_newcopy(ses.writepayload);
	buf_setpos(ses.writepayload, 0);
	buf_setlen(ses.writepayload, 0);
	
	if (ses.reply_queue_tail) {
		ses.reply_queue_tail->next = new_item;
	} else {
		ses.reply_queue_head = new_item;
	}
470
	ses.reply_queue_tail = new_item;
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
}

void maybe_flush_reply_queue() {
	struct packetlist *tmp_item = NULL, *curr_item = NULL;
	if (!ses.dataallowed)
	{
		TRACE(("maybe_empty_reply_queue - no data allowed"))
		return;
	}
		
	for (curr_item = ses.reply_queue_head; curr_item; ) {
		CHECKCLEARTOWRITE();
		buf_putbytes(ses.writepayload,
			curr_item->payload->data, curr_item->payload->len);
			
		buf_free(curr_item->payload);
		tmp_item = curr_item;
		curr_item = curr_item->next;
		m_free(tmp_item);
		encrypt_packet();
	}
	ses.reply_queue_head = ses.reply_queue_tail = NULL;
}
494
495
496
497
498
499
	
/* encrypt the writepayload, putting into writebuf, ready for write_packet()
 * to put on the wire */
void encrypt_packet() {

	unsigned char padlen;
500
501
502
	unsigned char blocksize, mac_size;
	buffer * writebuf; /* the packet which will go on the wire. This is 
	                      encrypted in-place. */
503
	unsigned char packet_type;
504
505
	unsigned int len, encrypt_buf_size;
	unsigned char mac_bytes[MAX_MAC_LEN];
506
	
507
	TRACE2(("enter encrypt_packet()"))
508
509
510
511
512

	buf_setpos(ses.writepayload, 0);
	packet_type = buf_getbyte(ses.writepayload);
	buf_setpos(ses.writepayload, 0);

513
	TRACE2(("encrypt_packet type is %d", packet_type))
514
	
515
	if ((!ses.dataallowed && !packet_is_okay_kex(packet_type))) {
516
		/* During key exchange only particular packets are allowed.
517
			Since this packet_type isn't OK we just enqueue it to send 
518
519
520
521
522
			after the KEX, see maybe_flush_reply_queue */
		enqueue_reply_packet();
		return;
	}
		
523
524
	blocksize = ses.keys->trans.algo_crypt->blocksize;
	mac_size = ses.keys->trans.algo_mac->hashsize;
525

526
527
528
529
530
	/* Encrypted packet len is payload+5. We need to then make sure
	 * there is enough space for padding or MIN_PACKET_LEN. 
	 * Add extra 3 since we need at least 4 bytes of padding */
	encrypt_buf_size = (ses.writepayload->len+4+1) 
		+ MAX(MIN_PACKET_LEN, blocksize) + 3
531
	/* add space for the MAC at the end */
532
				+ mac_size
533
#ifndef DISABLE_ZLIB
534
	/* some extra in case 'compression' makes it larger */
535
				+ ZLIB_COMPRESS_EXPANSION
536
#endif
537
538
539
540
	/* and an extra cleartext (stripped before transmission) byte for the
	 * packet type */
				+ 1;

541
542
543
	writebuf = buf_new(encrypt_buf_size);
	buf_setlen(writebuf, PACKET_PAYLOAD_OFF);
	buf_setpos(writebuf, PACKET_PAYLOAD_OFF);
544
545
546

#ifndef DISABLE_ZLIB
	/* compression */
547
	if (is_compress_trans()) {
548
		buf_compress(writebuf, ses.writepayload, ses.writepayload->len);
549
550
551
	} else
#endif
	{
552
		memcpy(buf_getwriteptr(writebuf, ses.writepayload->len),
553
554
				buf_getptr(ses.writepayload, ses.writepayload->len),
				ses.writepayload->len);
555
		buf_incrwritepos(writebuf, ses.writepayload->len);
556
557
558
559
560
561
562
563
	}

	/* finished with payload */
	buf_setpos(ses.writepayload, 0);
	buf_setlen(ses.writepayload, 0);

	/* length of padding - packet length must be a multiple of blocksize,
	 * with a minimum of 4 bytes of padding */
564
	padlen = blocksize - (writebuf->len) % blocksize;
565
566
567
568
	if (padlen < 4) {
		padlen += blocksize;
	}
	/* check for min packet length */
569
	if (writebuf->len + padlen < MIN_PACKET_LEN) {
570
571
572
		padlen += blocksize;
	}

573
	buf_setpos(writebuf, 0);
574
	/* packet length excluding the packetlength uint32 */
575
	buf_putint(writebuf, writebuf->len + padlen - 4);
576
577

	/* padding len */
578
	buf_putbyte(writebuf, padlen);
579
	/* actual padding */
580
581
582
583
	buf_setpos(writebuf, writebuf->len);
	buf_incrlen(writebuf, padlen);
	genrandom(buf_getptr(writebuf, padlen), padlen);

584
	make_mac(ses.transseq, &ses.keys->trans, writebuf, writebuf->len, mac_bytes);
585
586
587
588
589

	/* do the actual encryption, in-place */
	buf_setpos(writebuf, 0);
	/* encrypt it in-place*/
	len = writebuf->len;
590
	if (ses.keys->trans.crypt_mode->encrypt(
591
				buf_getptr(writebuf, len),
592
593
				buf_getwriteptr(writebuf, len),
				len,
594
				&ses.keys->trans.cipher_state) != CRYPT_OK) {
595
		dropbear_exit("Error encrypting");
596
	}
597
	buf_incrpos(writebuf, len);
598

599
600
    /* stick the MAC on it */
    buf_putbytes(writebuf, mac_bytes, mac_size);
601

602
603
604
	/* The last byte of the buffer stores the cleartext packet_type. It is not
	 * transmitted but is used for transmit timeout purposes */
	buf_putbyte(writebuf, packet_type);
605
	/* enqueue the packet for sending. It will get freed after transmission. */
606
607
608
609
610
611
612
	buf_setpos(writebuf, 0);
	enqueue(&ses.writequeue, (void*)writebuf);

	/* Update counts */
	ses.kexstate.datatrans += writebuf->len;
	ses.transseq++;

613
	TRACE2(("leave encrypt_packet()"))
614
615
616
617
}


/* Create the packet mac, and append H(seqno|clearbuf) to the output */
618
619
620
621
/* output_mac must have ses.keys->trans.algo_mac->hashsize bytes. */
static void make_mac(unsigned int seqno, const struct key_context_directional * key_state,
		buffer * clear_buf, unsigned int clear_len, 
		unsigned char *output_mac) {
622
	unsigned char seqbuf[4];
623
	unsigned long bufsize;
624
625
	hmac_state hmac;

626
	if (key_state->algo_mac->hashsize > 0) {
627
628
		/* calculate the mac */
		if (hmac_init(&hmac, 
629
630
631
					key_state->hash_index,
					key_state->mackey,
					key_state->algo_mac->keysize) != CRYPT_OK) {
632
633
634
635
			dropbear_exit("HMAC error");
		}
	
		/* sequence number */
636
		STORE32H(seqno, seqbuf);
637
638
639
640
641
		if (hmac_process(&hmac, seqbuf, 4) != CRYPT_OK) {
			dropbear_exit("HMAC error");
		}
	
		/* the actual contents */
642
		buf_setpos(clear_buf, 0);
643
		if (hmac_process(&hmac, 
644
645
					buf_getptr(clear_buf, clear_len),
					clear_len) != CRYPT_OK) {
646
647
648
			dropbear_exit("HMAC error");
		}
	
649
650
        bufsize = MAX_MAC_LEN;
		if (hmac_done(&hmac, output_mac, &bufsize) != CRYPT_OK) {
651
652
653
			dropbear_exit("HMAC error");
		}
	}
654
	TRACE2(("leave writemac"))
655
656
657
658
659
660
661
662
663
664
}

#ifndef DISABLE_ZLIB
/* compresses len bytes from src, outputting to dest (starting from the
 * respective current positions. */
static void buf_compress(buffer * dest, buffer * src, unsigned int len) {

	unsigned int endpos = src->pos + len;
	int result;

665
	TRACE2(("enter buf_compress"))
666
667
668

	while (1) {

669
670
671
		ses.keys->trans.zstream->avail_in = endpos - src->pos;
		ses.keys->trans.zstream->next_in = 
			buf_getptr(src, ses.keys->trans.zstream->avail_in);
672

673
674
675
		ses.keys->trans.zstream->avail_out = dest->size - dest->pos;
		ses.keys->trans.zstream->next_out =
			buf_getwriteptr(dest, ses.keys->trans.zstream->avail_out);
676

677
		result = deflate(ses.keys->trans.zstream, Z_SYNC_FLUSH);
678

679
680
		buf_setpos(src, endpos - ses.keys->trans.zstream->avail_in);
		buf_setlen(dest, dest->size - ses.keys->trans.zstream->avail_out);
681
682
683
684
685
686
		buf_setpos(dest, dest->len);

		if (result != Z_OK) {
			dropbear_exit("zlib error");
		}

687
		if (ses.keys->trans.zstream->avail_in == 0) {
688
689
690
			break;
		}

691
		dropbear_assert(ses.keys->trans.zstream->avail_out == 0);
692
693
694
695

		/* the buffer has been filled, we must extend. This only happens in
		 * unusual circumstances where the data grows in size after deflate(),
		 * but it is possible */
696
		buf_resize(dest, dest->size + ZLIB_COMPRESS_EXPANSION);
697
698

	}
699
	TRACE2(("leave buf_compress"))
700
701
}
#endif