2 * Dropbear - a SSH2 server
4 * Copyright (c) 2002,2003 Matt Johnston
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
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
47 static buffer
* buf_decompress(buffer
* buf
, unsigned int len
);
48 static void buf_compress(buffer
* dest
, buffer
* src
, unsigned int len
);
51 /* non-blocking function writing out a current encrypted packet */
55 buffer
* writebuf
= NULL
;
60 struct iovec
*iov
= NULL
;
65 TRACE2(("enter write_packet"))
66 dropbear_assert(!isempty(&ses
.writequeue
));
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
);
82 written
= writev(ses
.sock_out
, iov
, ses
.writequeue
.count
);
86 TRACE2(("leave writepacket: EINTR"))
89 dropbear_exit("Error writing");
98 writebuf
= (buffer
*)examine(&ses
.writequeue
);
99 len
= writebuf
->len
- 1 - writebuf
->pos
;
101 /* partial buffer write */
102 buf_incrpos(writebuf
, written
);
106 dequeue(&ses
.writequeue
);
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
);
126 if (errno
== EINTR
) {
127 TRACE2(("leave writepacket: EINTR"))
130 dropbear_exit("Error writing");
133 all_ignore
= (packet_type
== SSH_MSG_IGNORE
);
139 if (written
== len
) {
140 /* We've finished with the packet, free it */
141 dequeue(&ses
.writequeue
);
145 /* More packet left to write, leave it in the queue for later */
146 buf_incrpos(writebuf
, written
);
151 ses
.last_trx_packet_time
= now
;
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 */
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
) {
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"))
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
;
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
196 len
= read(ses
.sock_in
, buf_getptr(ses
.readbuf
, maxlen
), maxlen
);
203 if (errno
== EINTR
|| errno
== EAGAIN
) {
204 TRACE2(("leave read_packet: EINTR or EAGAIN"))
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 */
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() {
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
),
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
),
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
;
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
),
319 &ses
.keys
->recv
.cipher_state
) != CRYPT_OK
) {
320 dropbear_exit("Error decrypting");
322 buf_incrpos(ses
.readbuf
, len
);
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
);
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
);
343 if (is_compress_recv()) {
345 ses
.payload
= buf_decompress(ses
.readbuf
, len
);
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
);
357 buf_setpos(ses
.payload
, 0);
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
;
382 return DROPBEAR_SUCCESS
;
387 /* returns a pointer to a newly created buffer */
388 static buffer
* buf_decompress(buffer
* buf
, unsigned int len
) {
394 zstream
= ses
.keys
->recv
.zstream
;
397 zstream
->avail_in
= len
;
398 zstream
->next_in
= buf_getptr(buf
, len
);
400 /* decompress the payload, incrementally resizing the output buffer */
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 */
422 if (zstream
->avail_out
== 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
);
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
) {
440 if (type
== SSH_MSG_SERVICE_REQUEST
|| type
== SSH_MSG_SERVICE_ACCEPT
) {
443 if (type
== SSH_MSG_KEXINIT
) {
444 /* XXX should this die horribly if !dataallowed ?? */
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
;
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"))
475 for (curr_item
= ses
.reply_queue_head
; curr_item
; ) {
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
;
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();
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 */
528 /* some extra in case 'compression' makes it larger */
531 /* and an extra cleartext (stripped before transmission) byte for the
535 writebuf
= buf_new(encrypt_buf_size
);
536 buf_setlen(writebuf
, PACKET_PAYLOAD_OFF
);
537 buf_setpos(writebuf
, PACKET_PAYLOAD_OFF
);
541 if (is_compress_trans()) {
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
);
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
;
569 /* check for min packet length */
570 if (writebuf
->len
+ padlen
< MIN_PACKET_LEN
) {
574 buf_setpos(writebuf
, 0);
575 /* packet length excluding the packetlength uint32 */
576 buf_putint(writebuf
, writebuf
->len
+ padlen
- 4);
579 buf_putbyte(writebuf
, padlen
);
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*/
591 if (ses
.keys
->trans
.crypt_mode
->encrypt(
592 buf_getptr(writebuf
, len
),
593 buf_getwriteptr(writebuf
, 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
);
611 ses
.kexstate
.datatrans
+= writebuf
->len
;
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
;
627 if (key_state
->algo_mac
->hashsize
> 0) {
628 /* calculate the mac */
630 key_state
->hash_index
,
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"))
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
;
666 TRACE2(("enter buf_compress"))
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) {
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"))