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
39 static int read_packet_init();
40 static void make_mac(unsigned int seqno
, const struct key_context_directional
* key_state
,
41 buffer
* clear_buf
, unsigned int clear_len
,
42 unsigned char *output_mac
);
43 static int checkmac();
45 /* For exact details see http://www.zlib.net/zlib_tech.html
46 * 5 bytes per 16kB block, plus 6 bytes for the stream.
47 * We might allocate 5 unnecessary bytes here if it's an
49 #define ZLIB_COMPRESS_EXPANSION (((RECV_MAX_PAYLOAD_LEN/16384)+1)*5 + 6)
50 #define ZLIB_DECOMPRESS_INCR 1024
52 static buffer
* buf_decompress(buffer
* buf
, unsigned int len
);
53 static void buf_compress(buffer
* dest
, buffer
* src
, unsigned int len
);
56 /* non-blocking function writing out a current encrypted packet */
61 /* 50 is somewhat arbitrary */
62 unsigned int iov_count
= 50;
70 TRACE2(("enter write_packet"))
71 dropbear_assert(!isempty(&ses
.writequeue
));
73 #if defined(HAVE_WRITEV) && (defined(IOV_MAX) || defined(UIO_MAXIOV))
75 packet_queue_to_iovec(&ses
.writequeue
, iov
, &iov_count
);
76 /* This may return EAGAIN. The main loop sometimes
77 calls write_packet() without bothering to test with select() since
78 it's likely to be necessary */
79 written
= writev(ses
.sock_out
, iov
, iov_count
);
81 if (errno
== EINTR
|| errno
== EAGAIN
) {
82 TRACE2(("leave write_packet: EINTR"))
85 dropbear_exit("Error writing: %s", strerror(errno
));
89 packet_queue_consume(&ses
.writequeue
, written
);
90 ses
.writequeue_len
-= written
;
96 #else /* No writev () */
97 /* Get the next buffer in the queue of encrypted packets to write*/
98 writebuf
= (buffer
*)examine(&ses
.writequeue
);
100 /* The last byte of the buffer is not to be transmitted, but is
101 * a cleartext packet_type indicator */
102 packet_type
= writebuf
->data
[writebuf
->len
-1];
103 len
= writebuf
->len
- 1 - writebuf
->pos
;
104 TRACE2(("write_packet type %d len %d/%d", packet_type
,
105 len
, writebuf
->len
-1))
106 dropbear_assert(len
> 0);
107 /* Try to write as much as possible */
108 written
= write(ses
.sock_out
, buf_getptr(writebuf
, len
), len
);
111 if (errno
== EINTR
|| errno
== EAGAIN
) {
112 TRACE2(("leave writepacket: EINTR"))
115 dropbear_exit("Error writing: %s", strerror(errno
));
123 ses
.writequeue_len
-= written
;
125 if (written
== len
) {
126 /* We've finished with the packet, free it */
127 dequeue(&ses
.writequeue
);
131 /* More packet left to write, leave it in the queue for later */
132 buf_incrpos(writebuf
, written
);
136 TRACE2(("leave write_packet"))
139 /* Non-blocking function reading available portion of a packet into the
140 * ses's buffer, decrypting the length if encrypted, decrypting the
141 * full portion if possible */
146 unsigned char blocksize
;
148 TRACE2(("enter read_packet"))
149 blocksize
= ses
.keys
->recv
.algo_crypt
->blocksize
;
151 if (ses
.readbuf
== NULL
|| ses
.readbuf
->len
< blocksize
) {
153 /* In the first blocksize of a packet */
155 /* Read the first blocksize of the packet, so we can decrypt it and
156 * find the length of the whole packet */
157 ret
= read_packet_init();
159 if (ret
== DROPBEAR_FAILURE
) {
160 /* didn't read enough to determine the length */
161 TRACE2(("leave read_packet: packetinit done"))
166 /* Attempt to read the remainder of the packet, note that there
167 * mightn't be any available (EAGAIN) */
168 maxlen
= ses
.readbuf
->len
- ses
.readbuf
->pos
;
170 /* Occurs when the packet is only a single block long and has all
171 * been read in read_packet_init(). Usually means that MAC is disabled
175 len
= read(ses
.sock_in
, buf_getptr(ses
.readbuf
, maxlen
), maxlen
);
182 if (errno
== EINTR
|| errno
== EAGAIN
) {
183 TRACE2(("leave read_packet: EINTR or EAGAIN"))
186 dropbear_exit("Error reading: %s", strerror(errno
));
190 buf_incrpos(ses
.readbuf
, len
);
193 if ((unsigned int)len
== maxlen
) {
194 /* The whole packet has been read */
196 /* The main select() loop process_packet() to
197 * handle the packet contents... */
199 TRACE2(("leave read_packet"))
202 /* Function used to read the initial portion of a packet, and determine the
203 * length. Only called during the first BLOCKSIZE of a packet. */
204 /* Returns DROPBEAR_SUCCESS if the length is determined,
205 * DROPBEAR_FAILURE otherwise */
206 static int read_packet_init() {
211 unsigned int blocksize
;
212 unsigned int macsize
;
215 blocksize
= ses
.keys
->recv
.algo_crypt
->blocksize
;
216 macsize
= ses
.keys
->recv
.algo_mac
->hashsize
;
218 if (ses
.readbuf
== NULL
) {
219 /* start of a new packet */
220 ses
.readbuf
= buf_new(INIT_READBUF
);
223 maxlen
= blocksize
- ses
.readbuf
->pos
;
225 /* read the rest of the packet if possible */
226 slen
= read(ses
.sock_in
, buf_getwriteptr(ses
.readbuf
, maxlen
),
232 if (errno
== EINTR
|| errno
== EAGAIN
) {
233 TRACE2(("leave read_packet_init: EINTR"))
234 return DROPBEAR_FAILURE
;
236 dropbear_exit("Error reading: %s", strerror(errno
));
239 buf_incrwritepos(ses
.readbuf
, slen
);
241 if ((unsigned int)slen
!= maxlen
) {
242 /* don't have enough bytes to determine length, get next time */
243 return DROPBEAR_FAILURE
;
246 /* now we have the first block, need to get packet length, so we decrypt
247 * the first block (only need first 4 bytes) */
248 buf_setpos(ses
.readbuf
, 0);
249 if (ses
.keys
->recv
.crypt_mode
->decrypt(buf_getptr(ses
.readbuf
, blocksize
),
250 buf_getwriteptr(ses
.readbuf
, blocksize
),
252 &ses
.keys
->recv
.cipher_state
) != CRYPT_OK
) {
253 dropbear_exit("Error decrypting");
255 len
= buf_getint(ses
.readbuf
) + 4 + macsize
;
257 TRACE2(("packet size is %u, block %u mac %u", len
, blocksize
, macsize
))
260 /* check packet length */
261 if ((len
> RECV_MAX_PACKET_LEN
) ||
262 (len
< MIN_PACKET_LEN
+ macsize
) ||
263 ((len
- macsize
) % blocksize
!= 0)) {
264 dropbear_exit("Integrity error (bad packet size %u)", len
);
267 if (len
> ses
.readbuf
->size
) {
268 ses
.readbuf
= buf_resize(ses
.readbuf
, len
);
270 buf_setlen(ses
.readbuf
, len
);
271 buf_setpos(ses
.readbuf
, blocksize
);
272 return DROPBEAR_SUCCESS
;
275 /* handle the received packet */
276 void decrypt_packet() {
278 unsigned char blocksize
;
279 unsigned char macsize
;
283 TRACE2(("enter decrypt_packet"))
284 blocksize
= ses
.keys
->recv
.algo_crypt
->blocksize
;
285 macsize
= ses
.keys
->recv
.algo_mac
->hashsize
;
287 ses
.kexstate
.datarecv
+= ses
.readbuf
->len
;
289 /* we've already decrypted the first blocksize in read_packet_init */
290 buf_setpos(ses
.readbuf
, blocksize
);
292 /* decrypt it in-place */
293 len
= ses
.readbuf
->len
- macsize
- ses
.readbuf
->pos
;
294 if (ses
.keys
->recv
.crypt_mode
->decrypt(
295 buf_getptr(ses
.readbuf
, len
),
296 buf_getwriteptr(ses
.readbuf
, len
),
298 &ses
.keys
->recv
.cipher_state
) != CRYPT_OK
) {
299 dropbear_exit("Error decrypting");
301 buf_incrpos(ses
.readbuf
, len
);
304 if (checkmac() != DROPBEAR_SUCCESS
) {
305 dropbear_exit("Integrity error");
308 /* get padding length */
309 buf_setpos(ses
.readbuf
, PACKET_PADDING_OFF
);
310 padlen
= buf_getbyte(ses
.readbuf
);
313 /* - 4 - 1 is for LEN and PADLEN values */
314 len
= ses
.readbuf
->len
- padlen
- 4 - 1 - macsize
;
315 if ((len
> RECV_MAX_PAYLOAD_LEN
+ZLIB_COMPRESS_EXPANSION
) || (len
< 1)) {
316 dropbear_exit("Bad packet size %u", len
);
319 buf_setpos(ses
.readbuf
, PACKET_PAYLOAD_OFF
);
322 if (is_compress_recv()) {
324 ses
.payload
= buf_decompress(ses
.readbuf
, len
);
325 buf_setpos(ses
.payload
, 0);
326 ses
.payload_beginning
= 0;
327 buf_free(ses
.readbuf
);
331 ses
.payload
= ses
.readbuf
;
332 ses
.payload_beginning
= ses
.payload
->pos
;
333 buf_setlen(ses
.payload
, ses
.payload
->pos
+ len
);
335 //ses.payload = buf_new(len);
336 //memcpy(ses.payload->data, buf_getptr(ses.readbuf, len), len);
337 //buf_incrlen(ses.payload, len);
343 TRACE2(("leave decrypt_packet"))
346 /* Checks the mac at the end of a decrypted readbuf.
347 * Returns DROPBEAR_SUCCESS or DROPBEAR_FAILURE */
348 static int checkmac() {
350 unsigned char mac_bytes
[MAX_MAC_LEN
];
351 unsigned int mac_size
, contents_len
;
353 mac_size
= ses
.keys
->recv
.algo_mac
->hashsize
;
354 contents_len
= ses
.readbuf
->len
- mac_size
;
356 buf_setpos(ses
.readbuf
, 0);
357 make_mac(ses
.recvseq
, &ses
.keys
->recv
, ses
.readbuf
, contents_len
, mac_bytes
);
359 /* compare the hash */
360 buf_setpos(ses
.readbuf
, contents_len
);
361 if (constant_time_memcmp(mac_bytes
, buf_getptr(ses
.readbuf
, mac_size
), mac_size
) != 0) {
362 return DROPBEAR_FAILURE
;
364 return DROPBEAR_SUCCESS
;
369 /* returns a pointer to a newly created buffer */
370 static buffer
* buf_decompress(buffer
* buf
, unsigned int len
) {
376 zstream
= ses
.keys
->recv
.zstream
;
379 zstream
->avail_in
= len
;
380 zstream
->next_in
= buf_getptr(buf
, len
);
382 /* decompress the payload, incrementally resizing the output buffer */
385 zstream
->avail_out
= ret
->size
- ret
->pos
;
386 zstream
->next_out
= buf_getwriteptr(ret
, zstream
->avail_out
);
388 result
= inflate(zstream
, Z_SYNC_FLUSH
);
390 buf_setlen(ret
, ret
->size
- zstream
->avail_out
);
391 buf_setpos(ret
, ret
->len
);
393 if (result
!= Z_BUF_ERROR
&& result
!= Z_OK
) {
394 dropbear_exit("zlib error");
397 if (zstream
->avail_in
== 0 &&
398 (zstream
->avail_out
!= 0 || result
== Z_BUF_ERROR
)) {
399 /* we can only exit if avail_out hasn't all been used,
400 * and there's no remaining input */
404 if (zstream
->avail_out
== 0) {
406 if (ret
->size
>= RECV_MAX_PAYLOAD_LEN
) {
407 /* Already been increased as large as it can go,
408 * yet didn't finish up the decompression */
409 dropbear_exit("bad packet, oversized decompressed");
411 new_size
= MIN(RECV_MAX_PAYLOAD_LEN
, ret
->size
+ ZLIB_DECOMPRESS_INCR
);
412 ret
= buf_resize(ret
, new_size
);
419 /* returns 1 if the packet is a valid type during kex (see 7.1 of rfc4253) */
420 static int packet_is_okay_kex(unsigned char type
) {
421 if (type
>= SSH_MSG_USERAUTH_REQUEST
) {
424 if (type
== SSH_MSG_SERVICE_REQUEST
|| type
== SSH_MSG_SERVICE_ACCEPT
) {
427 if (type
== SSH_MSG_KEXINIT
) {
428 /* XXX should this die horribly if !dataallowed ?? */
434 static void enqueue_reply_packet() {
435 struct packetlist
* new_item
= NULL
;
436 new_item
= m_malloc(sizeof(struct packetlist
));
437 new_item
->next
= NULL
;
439 new_item
->payload
= buf_newcopy(ses
.writepayload
);
440 buf_setpos(ses
.writepayload
, 0);
441 buf_setlen(ses
.writepayload
, 0);
443 if (ses
.reply_queue_tail
) {
444 ses
.reply_queue_tail
->next
= new_item
;
446 ses
.reply_queue_head
= new_item
;
448 ses
.reply_queue_tail
= new_item
;
451 void maybe_flush_reply_queue() {
452 struct packetlist
*tmp_item
= NULL
, *curr_item
= NULL
;
453 if (!ses
.dataallowed
)
455 TRACE(("maybe_empty_reply_queue - no data allowed"))
459 for (curr_item
= ses
.reply_queue_head
; curr_item
; ) {
461 buf_putbytes(ses
.writepayload
,
462 curr_item
->payload
->data
, curr_item
->payload
->len
);
464 buf_free(curr_item
->payload
);
465 tmp_item
= curr_item
;
466 curr_item
= curr_item
->next
;
470 ses
.reply_queue_head
= ses
.reply_queue_tail
= NULL
;
473 /* encrypt the writepayload, putting into writebuf, ready for write_packet()
474 * to put on the wire */
475 void encrypt_packet() {
477 unsigned char padlen
;
478 unsigned char blocksize
, mac_size
;
479 buffer
* writebuf
; /* the packet which will go on the wire. This is
480 encrypted in-place. */
481 unsigned char packet_type
;
482 unsigned int len
, encrypt_buf_size
;
483 unsigned char mac_bytes
[MAX_MAC_LEN
];
487 TRACE2(("enter encrypt_packet()"))
489 buf_setpos(ses
.writepayload
, 0);
490 packet_type
= buf_getbyte(ses
.writepayload
);
491 buf_setpos(ses
.writepayload
, 0);
493 TRACE2(("encrypt_packet type is %d", packet_type
))
495 if ((!ses
.dataallowed
&& !packet_is_okay_kex(packet_type
))) {
496 /* During key exchange only particular packets are allowed.
497 Since this packet_type isn't OK we just enqueue it to send
498 after the KEX, see maybe_flush_reply_queue */
499 enqueue_reply_packet();
503 blocksize
= ses
.keys
->trans
.algo_crypt
->blocksize
;
504 mac_size
= ses
.keys
->trans
.algo_mac
->hashsize
;
506 /* Encrypted packet len is payload+5. We need to then make sure
507 * there is enough space for padding or MIN_PACKET_LEN.
508 * Add extra 3 since we need at least 4 bytes of padding */
509 encrypt_buf_size
= (ses
.writepayload
->len
+4+1)
510 + MAX(MIN_PACKET_LEN
, blocksize
) + 3
511 /* add space for the MAC at the end */
514 /* some extra in case 'compression' makes it larger */
515 + ZLIB_COMPRESS_EXPANSION
517 /* and an extra cleartext (stripped before transmission) byte for the
521 writebuf
= buf_new(encrypt_buf_size
);
522 buf_setlen(writebuf
, PACKET_PAYLOAD_OFF
);
523 buf_setpos(writebuf
, PACKET_PAYLOAD_OFF
);
527 if (is_compress_trans()) {
528 buf_compress(writebuf
, ses
.writepayload
, ses
.writepayload
->len
);
532 memcpy(buf_getwriteptr(writebuf
, ses
.writepayload
->len
),
533 buf_getptr(ses
.writepayload
, ses
.writepayload
->len
),
534 ses
.writepayload
->len
);
535 buf_incrwritepos(writebuf
, ses
.writepayload
->len
);
538 /* finished with payload */
539 buf_setpos(ses
.writepayload
, 0);
540 buf_setlen(ses
.writepayload
, 0);
542 /* length of padding - packet length must be a multiple of blocksize,
543 * with a minimum of 4 bytes of padding */
544 padlen
= blocksize
- (writebuf
->len
) % blocksize
;
548 /* check for min packet length */
549 if (writebuf
->len
+ padlen
< MIN_PACKET_LEN
) {
553 buf_setpos(writebuf
, 0);
554 /* packet length excluding the packetlength uint32 */
555 buf_putint(writebuf
, writebuf
->len
+ padlen
- 4);
558 buf_putbyte(writebuf
, padlen
);
560 buf_setpos(writebuf
, writebuf
->len
);
561 buf_incrlen(writebuf
, padlen
);
562 genrandom(buf_getptr(writebuf
, padlen
), padlen
);
564 make_mac(ses
.transseq
, &ses
.keys
->trans
, writebuf
, writebuf
->len
, mac_bytes
);
566 /* do the actual encryption, in-place */
567 buf_setpos(writebuf
, 0);
568 /* encrypt it in-place*/
570 if (ses
.keys
->trans
.crypt_mode
->encrypt(
571 buf_getptr(writebuf
, len
),
572 buf_getwriteptr(writebuf
, len
),
574 &ses
.keys
->trans
.cipher_state
) != CRYPT_OK
) {
575 dropbear_exit("Error encrypting");
577 buf_incrpos(writebuf
, len
);
579 /* stick the MAC on it */
580 buf_putbytes(writebuf
, mac_bytes
, mac_size
);
583 ses
.kexstate
.datatrans
+= writebuf
->len
;
585 writebuf_enqueue(writebuf
, packet_type
);
590 now
= monotonic_now();
591 ses
.last_packet_time_any_sent
= now
;
592 /* idle timeout shouldn't be affected by responses to keepalives.
593 send_msg_keepalive() itself also does tricks with
594 ses.last_packet_idle_time - read that if modifying this code */
595 if (packet_type
!= SSH_MSG_REQUEST_FAILURE
596 && packet_type
!= SSH_MSG_UNIMPLEMENTED
597 && packet_type
!= SSH_MSG_IGNORE
) {
598 ses
.last_packet_time_idle
= now
;
602 TRACE2(("leave encrypt_packet()"))
605 void writebuf_enqueue(buffer
* writebuf
, unsigned char packet_type
) {
606 /* The last byte of the buffer stores the cleartext packet_type. It is not
607 * transmitted but is used for transmit timeout purposes */
608 buf_putbyte(writebuf
, packet_type
);
609 /* enqueue the packet for sending. It will get freed after transmission. */
610 buf_setpos(writebuf
, 0);
611 enqueue(&ses
.writequeue
, (void*)writebuf
);
612 ses
.writequeue_len
+= writebuf
->len
-1;
616 /* Create the packet mac, and append H(seqno|clearbuf) to the output */
617 /* output_mac must have ses.keys->trans.algo_mac->hashsize bytes. */
618 static void make_mac(unsigned int seqno
, const struct key_context_directional
* key_state
,
619 buffer
* clear_buf
, unsigned int clear_len
,
620 unsigned char *output_mac
) {
621 unsigned char seqbuf
[4];
622 unsigned long bufsize
;
625 if (key_state
->algo_mac
->hashsize
> 0) {
626 /* calculate the mac */
628 key_state
->hash_index
,
630 key_state
->algo_mac
->keysize
) != CRYPT_OK
) {
631 dropbear_exit("HMAC error");
634 /* sequence number */
635 STORE32H(seqno
, seqbuf
);
636 if (hmac_process(&hmac
, seqbuf
, 4) != CRYPT_OK
) {
637 dropbear_exit("HMAC error");
640 /* the actual contents */
641 buf_setpos(clear_buf
, 0);
642 if (hmac_process(&hmac
,
643 buf_getptr(clear_buf
, clear_len
),
644 clear_len
) != CRYPT_OK
) {
645 dropbear_exit("HMAC error");
648 bufsize
= MAX_MAC_LEN
;
649 if (hmac_done(&hmac
, output_mac
, &bufsize
) != CRYPT_OK
) {
650 dropbear_exit("HMAC error");
653 TRACE2(("leave writemac"))
657 /* compresses len bytes from src, outputting to dest (starting from the
658 * respective current positions. dest must have sufficient space,
659 * len+ZLIB_COMPRESS_EXPANSION */
660 static void buf_compress(buffer
* dest
, buffer
* src
, unsigned int len
) {
662 unsigned int endpos
= src
->pos
+ len
;
665 TRACE2(("enter buf_compress"))
667 dropbear_assert(dest
->size
- dest
->pos
>= len
+ZLIB_COMPRESS_EXPANSION
);
669 ses
.keys
->trans
.zstream
->avail_in
= endpos
- src
->pos
;
670 ses
.keys
->trans
.zstream
->next_in
=
671 buf_getptr(src
, ses
.keys
->trans
.zstream
->avail_in
);
673 ses
.keys
->trans
.zstream
->avail_out
= dest
->size
- dest
->pos
;
674 ses
.keys
->trans
.zstream
->next_out
=
675 buf_getwriteptr(dest
, ses
.keys
->trans
.zstream
->avail_out
);
677 result
= deflate(ses
.keys
->trans
.zstream
, Z_SYNC_FLUSH
);
679 buf_setpos(src
, endpos
- ses
.keys
->trans
.zstream
->avail_in
);
680 buf_setlen(dest
, dest
->size
- ses
.keys
->trans
.zstream
->avail_out
);
681 buf_setpos(dest
, dest
->len
);
683 if (result
!= Z_OK
) {
684 dropbear_exit("zlib error");
687 /* fails if destination buffer wasn't large enough */
688 dropbear_assert(ses
.keys
->trans
.zstream
->avail_in
== 0);
689 TRACE2(("leave buf_compress"))