[BACK]Return to packet.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/packet.c, Revision 1.118

1.1       deraadt     1: /*
1.15      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
1.35      deraadt     5:  * This file contains code implementing the packet protocol and communication
                      6:  * with the other side.  This same code is used both on client and server side.
1.29      markus      7:  *
1.35      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
1.29      markus     13:  *
1.25      markus     14:  *
                     15:  * SSH2 packet format added by Markus Friedl.
1.69      markus     16:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.25      markus     17:  *
1.35      deraadt    18:  * Redistribution and use in source and binary forms, with or without
                     19:  * modification, are permitted provided that the following conditions
                     20:  * are met:
                     21:  * 1. Redistributions of source code must retain the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer.
                     23:  * 2. Redistributions in binary form must reproduce the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer in the
                     25:  *    documentation and/or other materials provided with the distribution.
                     26:  *
                     27:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     28:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     29:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     30:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     31:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     32:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     33:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     34:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     35:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     36:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.15      deraadt    37:  */
1.1       deraadt    38:
                     39: #include "includes.h"
1.118   ! markus     40: RCSID("$OpenBSD: packet.c,v 1.117 2005/06/17 02:44:32 djm Exp $");
1.105     markus     41:
                     42: #include <sys/queue.h>
1.1       deraadt    43:
                     44: #include "xmalloc.h"
                     45: #include "buffer.h"
                     46: #include "packet.h"
                     47: #include "bufaux.h"
                     48: #include "crc32.h"
                     49: #include "getput.h"
                     50:
                     51: #include "compress.h"
1.9       dugsong    52: #include "deattack.h"
1.64      markus     53: #include "channels.h"
1.1       deraadt    54:
1.25      markus     55: #include "compat.h"
1.45      markus     56: #include "ssh1.h"
1.25      markus     57: #include "ssh2.h"
                     58:
1.37      markus     59: #include "cipher.h"
1.25      markus     60: #include "kex.h"
1.50      markus     61: #include "mac.h"
1.46      markus     62: #include "log.h"
                     63: #include "canohost.h"
1.87      stevesk    64: #include "misc.h"
1.95      markus     65: #include "ssh.h"
1.25      markus     66:
                     67: #ifdef PACKET_DEBUG
                     68: #define DBG(x) x
                     69: #else
                     70: #define DBG(x)
                     71: #endif
                     72:
1.16      markus     73: /*
                     74:  * This variable contains the file descriptors used for communicating with
                     75:  * the other side.  connection_in is used for reading; connection_out for
                     76:  * writing.  These can be the same descriptor, in which case it is assumed to
                     77:  * be a socket.
                     78:  */
1.1       deraadt    79: static int connection_in = -1;
                     80: static int connection_out = -1;
                     81:
                     82: /* Protocol flags for the remote side. */
1.40      markus     83: static u_int remote_protocol_flags = 0;
1.1       deraadt    84:
                     85: /* Encryption context for receiving data.  This is only used for decryption. */
                     86: static CipherContext receive_context;
1.14      markus     87:
                     88: /* Encryption context for sending data.  This is only used for encryption. */
1.1       deraadt    89: static CipherContext send_context;
                     90:
                     91: /* Buffer for raw input data from the socket. */
1.91      markus     92: Buffer input;
1.1       deraadt    93:
                     94: /* Buffer for raw output data going to the socket. */
1.91      markus     95: Buffer output;
1.1       deraadt    96:
                     97: /* Buffer for the partial outgoing packet being constructed. */
                     98: static Buffer outgoing_packet;
                     99:
                    100: /* Buffer for the incoming packet currently being processed. */
                    101: static Buffer incoming_packet;
                    102:
                    103: /* Scratch buffer for packet compression/decompression. */
                    104: static Buffer compression_buffer;
1.60      markus    105: static int compression_buffer_ready = 0;
1.1       deraadt   106:
                    107: /* Flag indicating whether packet compression/decompression is enabled. */
                    108: static int packet_compression = 0;
                    109:
1.12      markus    110: /* default maximum packet size */
1.108     markus    111: u_int max_packet_size = 32768;
1.12      markus    112:
1.1       deraadt   113: /* Flag indicating whether this module has been initialized. */
                    114: static int initialized = 0;
                    115:
                    116: /* Set to true if the connection is interactive. */
                    117: static int interactive_mode = 0;
                    118:
1.118   ! markus    119: /* Set to true if we are the server side. */
        !           120: static int server_side = 0;
        !           121:
        !           122: /* Set to true if we are authenticated. */
        !           123: static int after_authentication = 0;
        !           124:
1.25      markus    125: /* Session key information for Encryption and MAC */
1.57      markus    126: Newkeys *newkeys[MODE_MAX];
1.105     markus    127: static struct packet_state {
                    128:        u_int32_t seqnr;
                    129:        u_int32_t packets;
                    130:        u_int64_t blocks;
                    131: } p_read, p_send;
                    132:
                    133: static u_int64_t max_blocks_in, max_blocks_out;
                    134: static u_int32_t rekey_limit;
1.25      markus    135:
1.95      markus    136: /* Session key for protocol v1 */
                    137: static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
                    138: static u_int ssh1_keylen;
                    139:
1.71      markus    140: /* roundup current message to extra_pad bytes */
                    141: static u_char extra_pad = 0;
                    142:
1.105     markus    143: struct packet {
                    144:        TAILQ_ENTRY(packet) next;
                    145:        u_char type;
                    146:        Buffer payload;
                    147: };
                    148: TAILQ_HEAD(, packet) outgoing;
                    149:
1.16      markus    150: /*
                    151:  * Sets the descriptors used for communication.  Disables encryption until
                    152:  * packet_set_encryption_key is called.
                    153:  */
1.2       provos    154: void
                    155: packet_set_connection(int fd_in, int fd_out)
1.1       deraadt   156: {
1.37      markus    157:        Cipher *none = cipher_by_name("none");
1.97      deraadt   158:
1.37      markus    159:        if (none == NULL)
                    160:                fatal("packet_set_connection: cannot load cipher 'none'");
1.14      markus    161:        connection_in = fd_in;
                    162:        connection_out = fd_out;
1.113     deraadt   163:        cipher_init(&send_context, none, (const u_char *)"",
                    164:            0, NULL, 0, CIPHER_ENCRYPT);
                    165:        cipher_init(&receive_context, none, (const u_char *)"",
                    166:            0, NULL, 0, CIPHER_DECRYPT);
1.62      markus    167:        newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
1.14      markus    168:        if (!initialized) {
                    169:                initialized = 1;
                    170:                buffer_init(&input);
                    171:                buffer_init(&output);
                    172:                buffer_init(&outgoing_packet);
                    173:                buffer_init(&incoming_packet);
1.105     markus    174:                TAILQ_INIT(&outgoing);
1.14      markus    175:        }
1.1       deraadt   176: }
                    177:
1.19      markus    178: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    179:
                    180: int
1.73      itojun    181: packet_connection_is_on_socket(void)
1.19      markus    182: {
                    183:        struct sockaddr_storage from, to;
                    184:        socklen_t fromlen, tolen;
                    185:
                    186:        /* filedescriptors in and out are the same, so it's a socket */
                    187:        if (connection_in == connection_out)
                    188:                return 1;
                    189:        fromlen = sizeof(from);
                    190:        memset(&from, 0, sizeof(from));
1.20      markus    191:        if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
1.19      markus    192:                return 0;
                    193:        tolen = sizeof(to);
                    194:        memset(&to, 0, sizeof(to));
1.20      markus    195:        if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
1.19      markus    196:                return 0;
                    197:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    198:                return 0;
                    199:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    200:                return 0;
                    201:        return 1;
                    202: }
                    203:
1.92      markus    204: /*
1.91      markus    205:  * Exports an IV from the CipherContext required to export the key
                    206:  * state back from the unprivileged child to the privileged parent
                    207:  * process.
                    208:  */
                    209:
                    210: void
                    211: packet_get_keyiv(int mode, u_char *iv, u_int len)
                    212: {
                    213:        CipherContext *cc;
                    214:
                    215:        if (mode == MODE_OUT)
                    216:                cc = &send_context;
                    217:        else
                    218:                cc = &receive_context;
                    219:
                    220:        cipher_get_keyiv(cc, iv, len);
                    221: }
                    222:
                    223: int
                    224: packet_get_keycontext(int mode, u_char *dat)
                    225: {
                    226:        CipherContext *cc;
1.92      markus    227:
1.91      markus    228:        if (mode == MODE_OUT)
                    229:                cc = &send_context;
                    230:        else
                    231:                cc = &receive_context;
                    232:
                    233:        return (cipher_get_keycontext(cc, dat));
                    234: }
                    235:
                    236: void
                    237: packet_set_keycontext(int mode, u_char *dat)
                    238: {
                    239:        CipherContext *cc;
1.92      markus    240:
1.91      markus    241:        if (mode == MODE_OUT)
                    242:                cc = &send_context;
                    243:        else
                    244:                cc = &receive_context;
                    245:
                    246:        cipher_set_keycontext(cc, dat);
                    247: }
                    248:
                    249: int
                    250: packet_get_keyiv_len(int mode)
                    251: {
                    252:        CipherContext *cc;
                    253:
                    254:        if (mode == MODE_OUT)
                    255:                cc = &send_context;
                    256:        else
                    257:                cc = &receive_context;
                    258:
                    259:        return (cipher_get_keyiv_len(cc));
                    260: }
                    261: void
                    262: packet_set_iv(int mode, u_char *dat)
                    263: {
                    264:        CipherContext *cc;
                    265:
                    266:        if (mode == MODE_OUT)
                    267:                cc = &send_context;
                    268:        else
                    269:                cc = &receive_context;
                    270:
                    271:        cipher_set_keyiv(cc, dat);
                    272: }
                    273: int
1.107     deraadt   274: packet_get_ssh1_cipher(void)
1.91      markus    275: {
                    276:        return (cipher_get_number(receive_context.cipher));
                    277: }
                    278:
1.105     markus    279: void
                    280: packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
                    281: {
                    282:        struct packet_state *state;
1.104     markus    283:
1.105     markus    284:        state = (mode == MODE_IN) ? &p_read : &p_send;
                    285:        *seqnr = state->seqnr;
                    286:        *blocks = state->blocks;
                    287:        *packets = state->packets;
1.91      markus    288: }
                    289:
                    290: void
1.105     markus    291: packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
1.91      markus    292: {
1.105     markus    293:        struct packet_state *state;
                    294:
                    295:        state = (mode == MODE_IN) ? &p_read : &p_send;
                    296:        state->seqnr = seqnr;
                    297:        state->blocks = blocks;
                    298:        state->packets = packets;
1.91      markus    299: }
                    300:
1.19      markus    301: /* returns 1 if connection is via ipv4 */
                    302:
                    303: int
1.73      itojun    304: packet_connection_is_ipv4(void)
1.19      markus    305: {
                    306:        struct sockaddr_storage to;
1.21      deraadt   307:        socklen_t tolen = sizeof(to);
1.19      markus    308:
                    309:        memset(&to, 0, sizeof(to));
                    310:        if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
                    311:                return 0;
                    312:        if (to.ss_family != AF_INET)
                    313:                return 0;
                    314:        return 1;
                    315: }
                    316:
1.1       deraadt   317: /* Sets the connection into non-blocking mode. */
                    318:
1.2       provos    319: void
1.73      itojun    320: packet_set_nonblocking(void)
1.1       deraadt   321: {
1.14      markus    322:        /* Set the socket into non-blocking mode. */
1.114     djm       323:        set_nonblock(connection_in);
1.14      markus    324:
1.114     djm       325:        if (connection_out != connection_in)
                    326:                set_nonblock(connection_out);
1.1       deraadt   327: }
                    328:
                    329: /* Returns the socket used for reading. */
                    330:
1.2       provos    331: int
1.73      itojun    332: packet_get_connection_in(void)
1.1       deraadt   333: {
1.14      markus    334:        return connection_in;
1.1       deraadt   335: }
                    336:
                    337: /* Returns the descriptor used for writing. */
                    338:
1.2       provos    339: int
1.73      itojun    340: packet_get_connection_out(void)
1.1       deraadt   341: {
1.14      markus    342:        return connection_out;
1.1       deraadt   343: }
                    344:
                    345: /* Closes the connection and clears and frees internal data structures. */
                    346:
1.2       provos    347: void
1.73      itojun    348: packet_close(void)
1.1       deraadt   349: {
1.14      markus    350:        if (!initialized)
                    351:                return;
                    352:        initialized = 0;
                    353:        if (connection_in == connection_out) {
                    354:                shutdown(connection_out, SHUT_RDWR);
                    355:                close(connection_out);
                    356:        } else {
                    357:                close(connection_in);
                    358:                close(connection_out);
                    359:        }
                    360:        buffer_free(&input);
                    361:        buffer_free(&output);
                    362:        buffer_free(&outgoing_packet);
                    363:        buffer_free(&incoming_packet);
1.60      markus    364:        if (compression_buffer_ready) {
1.14      markus    365:                buffer_free(&compression_buffer);
                    366:                buffer_compress_uninit();
                    367:        }
1.88      markus    368:        cipher_cleanup(&send_context);
                    369:        cipher_cleanup(&receive_context);
1.1       deraadt   370: }
                    371:
                    372: /* Sets remote side protocol flags. */
                    373:
1.2       provos    374: void
1.40      markus    375: packet_set_protocol_flags(u_int protocol_flags)
1.1       deraadt   376: {
1.14      markus    377:        remote_protocol_flags = protocol_flags;
1.1       deraadt   378: }
                    379:
                    380: /* Returns the remote protocol flags set earlier by the above function. */
                    381:
1.40      markus    382: u_int
1.73      itojun    383: packet_get_protocol_flags(void)
1.1       deraadt   384: {
1.14      markus    385:        return remote_protocol_flags;
1.1       deraadt   386: }
                    387:
1.16      markus    388: /*
                    389:  * Starts packet compression from the next packet on in both directions.
                    390:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    391:  */
1.1       deraadt   392:
1.68      itojun    393: static void
                    394: packet_init_compression(void)
1.60      markus    395: {
                    396:        if (compression_buffer_ready == 1)
                    397:                return;
                    398:        compression_buffer_ready = 1;
                    399:        buffer_init(&compression_buffer);
                    400: }
                    401:
1.2       provos    402: void
                    403: packet_start_compression(int level)
1.1       deraadt   404: {
1.62      markus    405:        if (packet_compression && !compat20)
1.14      markus    406:                fatal("Compression already enabled.");
                    407:        packet_compression = 1;
1.60      markus    408:        packet_init_compression();
                    409:        buffer_compress_init_send(level);
                    410:        buffer_compress_init_recv();
1.1       deraadt   411: }
                    412:
1.16      markus    413: /*
                    414:  * Causes any further packets to be encrypted using the given key.  The same
                    415:  * key is used for both sending and reception.  However, both directions are
                    416:  * encrypted independently of each other.
                    417:  */
1.95      markus    418:
1.2       provos    419: void
1.40      markus    420: packet_set_encryption_key(const u_char *key, u_int keylen,
1.37      markus    421:     int number)
1.1       deraadt   422: {
1.37      markus    423:        Cipher *cipher = cipher_by_number(number);
1.97      deraadt   424:
1.37      markus    425:        if (cipher == NULL)
                    426:                fatal("packet_set_encryption_key: unknown cipher number %d", number);
1.25      markus    427:        if (keylen < 20)
1.37      markus    428:                fatal("packet_set_encryption_key: keylen too small: %d", keylen);
1.95      markus    429:        if (keylen > SSH_SESSION_KEY_LENGTH)
                    430:                fatal("packet_set_encryption_key: keylen too big: %d", keylen);
                    431:        memcpy(ssh1_key, key, keylen);
                    432:        ssh1_keylen = keylen;
1.88      markus    433:        cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
                    434:        cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
1.95      markus    435: }
                    436:
                    437: u_int
                    438: packet_get_encryption_key(u_char *key)
                    439: {
                    440:        if (key == NULL)
                    441:                return (ssh1_keylen);
                    442:        memcpy(key, ssh1_key, ssh1_keylen);
                    443:        return (ssh1_keylen);
1.1       deraadt   444: }
                    445:
1.62      markus    446: /* Start constructing a packet to send. */
1.2       provos    447: void
1.62      markus    448: packet_start(u_char type)
1.1       deraadt   449: {
1.62      markus    450:        u_char buf[9];
                    451:        int len;
1.1       deraadt   452:
1.62      markus    453:        DBG(debug("packet_start[%d]", type));
                    454:        len = compat20 ? 6 : 9;
                    455:        memset(buf, 0, len - 1);
                    456:        buf[len - 1] = type;
1.14      markus    457:        buffer_clear(&outgoing_packet);
1.62      markus    458:        buffer_append(&outgoing_packet, buf, len);
1.25      markus    459: }
                    460:
1.62      markus    461: /* Append payload. */
1.2       provos    462: void
                    463: packet_put_char(int value)
1.1       deraadt   464: {
1.14      markus    465:        char ch = value;
1.97      deraadt   466:
1.14      markus    467:        buffer_append(&outgoing_packet, &ch, 1);
1.1       deraadt   468: }
1.2       provos    469: void
1.40      markus    470: packet_put_int(u_int value)
1.1       deraadt   471: {
1.14      markus    472:        buffer_put_int(&outgoing_packet, value);
1.1       deraadt   473: }
1.2       provos    474: void
1.76      stevesk   475: packet_put_string(const void *buf, u_int len)
1.1       deraadt   476: {
1.14      markus    477:        buffer_put_string(&outgoing_packet, buf, len);
1.1       deraadt   478: }
1.24      markus    479: void
                    480: packet_put_cstring(const char *str)
                    481: {
1.65      markus    482:        buffer_put_cstring(&outgoing_packet, str);
1.24      markus    483: }
                    484: void
1.76      stevesk   485: packet_put_raw(const void *buf, u_int len)
1.24      markus    486: {
                    487:        buffer_append(&outgoing_packet, buf, len);
                    488: }
1.2       provos    489: void
1.14      markus    490: packet_put_bignum(BIGNUM * value)
1.1       deraadt   491: {
1.14      markus    492:        buffer_put_bignum(&outgoing_packet, value);
1.1       deraadt   493: }
1.24      markus    494: void
                    495: packet_put_bignum2(BIGNUM * value)
                    496: {
                    497:        buffer_put_bignum2(&outgoing_packet, value);
                    498: }
1.1       deraadt   499:
1.16      markus    500: /*
                    501:  * Finalizes and sends the packet.  If the encryption key has been set,
                    502:  * encrypts the packet before sending.
                    503:  */
1.14      markus    504:
1.68      itojun    505: static void
1.49      itojun    506: packet_send1(void)
1.1       deraadt   507: {
1.89      markus    508:        u_char buf[8], *cp;
1.14      markus    509:        int i, padding, len;
1.40      markus    510:        u_int checksum;
1.115     avsm      511:        u_int32_t rnd = 0;
1.14      markus    512:
1.16      markus    513:        /*
                    514:         * If using packet compression, compress the payload of the outgoing
                    515:         * packet.
                    516:         */
1.14      markus    517:        if (packet_compression) {
                    518:                buffer_clear(&compression_buffer);
                    519:                /* Skip padding. */
                    520:                buffer_consume(&outgoing_packet, 8);
                    521:                /* padding */
                    522:                buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
                    523:                buffer_compress(&outgoing_packet, &compression_buffer);
                    524:                buffer_clear(&outgoing_packet);
                    525:                buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
1.75      deraadt   526:                    buffer_len(&compression_buffer));
1.14      markus    527:        }
                    528:        /* Compute packet length without padding (add checksum, remove padding). */
                    529:        len = buffer_len(&outgoing_packet) + 4 - 8;
                    530:
1.32      markus    531:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    532:        padding = 8 - len % 8;
1.88      markus    533:        if (!send_context.plaintext) {
1.14      markus    534:                cp = buffer_ptr(&outgoing_packet);
                    535:                for (i = 0; i < padding; i++) {
                    536:                        if (i % 4 == 0)
1.115     avsm      537:                                rnd = arc4random();
                    538:                        cp[7 - i] = rnd & 0xff;
                    539:                        rnd >>= 8;
1.14      markus    540:                }
                    541:        }
                    542:        buffer_consume(&outgoing_packet, 8 - padding);
                    543:
                    544:        /* Add check bytes. */
1.83      stevesk   545:        checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
1.34      deraadt   546:            buffer_len(&outgoing_packet));
1.14      markus    547:        PUT_32BIT(buf, checksum);
                    548:        buffer_append(&outgoing_packet, buf, 4);
1.1       deraadt   549:
                    550: #ifdef PACKET_DEBUG
1.14      markus    551:        fprintf(stderr, "packet_send plain: ");
                    552:        buffer_dump(&outgoing_packet);
1.1       deraadt   553: #endif
                    554:
1.14      markus    555:        /* Append to output. */
                    556:        PUT_32BIT(buf, len);
                    557:        buffer_append(&output, buf, 4);
1.76      stevesk   558:        cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
1.88      markus    559:        cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
1.75      deraadt   560:            buffer_len(&outgoing_packet));
1.14      markus    561:
1.1       deraadt   562: #ifdef PACKET_DEBUG
1.14      markus    563:        fprintf(stderr, "encrypted: ");
                    564:        buffer_dump(&output);
1.1       deraadt   565: #endif
                    566:
1.14      markus    567:        buffer_clear(&outgoing_packet);
1.1       deraadt   568:
1.16      markus    569:        /*
                    570:         * Note that the packet is now only buffered in output.  It won\'t be
                    571:         * actually sent until packet_write_wait or packet_write_poll is
                    572:         * called.
                    573:         */
1.1       deraadt   574: }
                    575:
1.91      markus    576: void
1.57      markus    577: set_newkeys(int mode)
                    578: {
                    579:        Enc *enc;
                    580:        Mac *mac;
                    581:        Comp *comp;
                    582:        CipherContext *cc;
1.105     markus    583:        u_int64_t *max_blocks;
1.115     avsm      584:        int crypt_type;
1.57      markus    585:
1.100     markus    586:        debug2("set_newkeys: mode %d", mode);
1.57      markus    587:
1.88      markus    588:        if (mode == MODE_OUT) {
                    589:                cc = &send_context;
1.115     avsm      590:                crypt_type = CIPHER_ENCRYPT;
1.105     markus    591:                p_send.packets = p_send.blocks = 0;
                    592:                max_blocks = &max_blocks_out;
1.88      markus    593:        } else {
                    594:                cc = &receive_context;
1.115     avsm      595:                crypt_type = CIPHER_DECRYPT;
1.105     markus    596:                p_read.packets = p_read.blocks = 0;
                    597:                max_blocks = &max_blocks_in;
1.88      markus    598:        }
1.57      markus    599:        if (newkeys[mode] != NULL) {
1.100     markus    600:                debug("set_newkeys: rekeying");
1.88      markus    601:                cipher_cleanup(cc);
1.59      markus    602:                enc  = &newkeys[mode]->enc;
                    603:                mac  = &newkeys[mode]->mac;
                    604:                comp = &newkeys[mode]->comp;
1.61      markus    605:                memset(mac->key, 0, mac->key_len);
1.59      markus    606:                xfree(enc->name);
                    607:                xfree(enc->iv);
                    608:                xfree(enc->key);
                    609:                xfree(mac->name);
                    610:                xfree(mac->key);
                    611:                xfree(comp->name);
1.58      markus    612:                xfree(newkeys[mode]);
1.57      markus    613:        }
                    614:        newkeys[mode] = kex_get_newkeys(mode);
                    615:        if (newkeys[mode] == NULL)
                    616:                fatal("newkeys: no keys for mode %d", mode);
                    617:        enc  = &newkeys[mode]->enc;
                    618:        mac  = &newkeys[mode]->mac;
                    619:        comp = &newkeys[mode]->comp;
                    620:        if (mac->md != NULL)
                    621:                mac->enabled = 1;
                    622:        DBG(debug("cipher_init_context: %d", mode));
1.88      markus    623:        cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1.115     avsm      624:            enc->iv, enc->block_size, crypt_type);
1.91      markus    625:        /* Deleting the keys does not gain extra security */
                    626:        /* memset(enc->iv,  0, enc->block_size);
                    627:           memset(enc->key, 0, enc->key_len); */
1.118   ! markus    628:        if ((comp->type == COMP_ZLIB ||
        !           629:            (comp->type == COMP_DELAYED && after_authentication)) &&
        !           630:            comp->enabled == 0) {
1.60      markus    631:                packet_init_compression();
                    632:                if (mode == MODE_OUT)
                    633:                        buffer_compress_init_send(6);
                    634:                else
                    635:                        buffer_compress_init_recv();
1.57      markus    636:                comp->enabled = 1;
                    637:        }
1.109     markus    638:        /*
                    639:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    640:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    641:         */
                    642:        if (enc->block_size >= 16)
                    643:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    644:        else
                    645:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.105     markus    646:        if (rekey_limit)
                    647:                *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
1.57      markus    648: }
                    649:
1.16      markus    650: /*
1.118   ! markus    651:  * Delayed compression for SSH2 is enabled after authentication:
        !           652:  * This happans on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
        !           653:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
        !           654:  */
        !           655: static void
        !           656: packet_enable_delayed_compress(void)
        !           657: {
        !           658:        Comp *comp = NULL;
        !           659:        int mode;
        !           660:
        !           661:        /*
        !           662:         * Remember that we are past the authentication step, so rekeying
        !           663:         * with COMP_DELAYED will turn on compression immediately.
        !           664:         */
        !           665:        after_authentication = 1;
        !           666:        for (mode = 0; mode < MODE_MAX; mode++) {
        !           667:                comp = &newkeys[mode]->comp;
        !           668:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
        !           669:                        if (mode == MODE_OUT)
        !           670:                                buffer_compress_init_send(6);
        !           671:                        else
        !           672:                                buffer_compress_init_recv();
        !           673:                        comp->enabled = 1;
        !           674:                }
        !           675:        }
        !           676: }
        !           677:
        !           678: /*
1.25      markus    679:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                    680:  */
1.68      itojun    681: static void
1.105     markus    682: packet_send2_wrapped(void)
1.25      markus    683: {
1.89      markus    684:        u_char type, *cp, *macbuf = NULL;
1.71      markus    685:        u_char padlen, pad;
1.40      markus    686:        u_int packet_length = 0;
1.71      markus    687:        u_int i, len;
1.115     avsm      688:        u_int32_t rnd = 0;
1.25      markus    689:        Enc *enc   = NULL;
                    690:        Mac *mac   = NULL;
                    691:        Comp *comp = NULL;
                    692:        int block_size;
                    693:
1.57      markus    694:        if (newkeys[MODE_OUT] != NULL) {
                    695:                enc  = &newkeys[MODE_OUT]->enc;
                    696:                mac  = &newkeys[MODE_OUT]->mac;
                    697:                comp = &newkeys[MODE_OUT]->comp;
1.25      markus    698:        }
1.88      markus    699:        block_size = enc ? enc->block_size : 8;
1.25      markus    700:
1.89      markus    701:        cp = buffer_ptr(&outgoing_packet);
                    702:        type = cp[5];
1.25      markus    703:
                    704: #ifdef PACKET_DEBUG
                    705:        fprintf(stderr, "plain:     ");
                    706:        buffer_dump(&outgoing_packet);
                    707: #endif
                    708:
                    709:        if (comp && comp->enabled) {
                    710:                len = buffer_len(&outgoing_packet);
                    711:                /* skip header, compress only payload */
                    712:                buffer_consume(&outgoing_packet, 5);
                    713:                buffer_clear(&compression_buffer);
                    714:                buffer_compress(&outgoing_packet, &compression_buffer);
                    715:                buffer_clear(&outgoing_packet);
                    716:                buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
                    717:                buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
                    718:                    buffer_len(&compression_buffer));
                    719:                DBG(debug("compression: raw %d compressed %d", len,
                    720:                    buffer_len(&outgoing_packet)));
                    721:        }
                    722:
                    723:        /* sizeof (packet_len + pad_len + payload) */
                    724:        len = buffer_len(&outgoing_packet);
                    725:
                    726:        /*
                    727:         * calc size of padding, alloc space, get random data,
                    728:         * minimum padding is 4 bytes
                    729:         */
                    730:        padlen = block_size - (len % block_size);
                    731:        if (padlen < 4)
                    732:                padlen += block_size;
1.71      markus    733:        if (extra_pad) {
                    734:                /* will wrap if extra_pad+padlen > 255 */
                    735:                extra_pad  = roundup(extra_pad, block_size);
                    736:                pad = extra_pad - ((len + padlen) % extra_pad);
1.93      markus    737:                debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
1.71      markus    738:                    pad, len, padlen, extra_pad);
                    739:                padlen += pad;
                    740:                extra_pad = 0;
                    741:        }
1.76      stevesk   742:        cp = buffer_append_space(&outgoing_packet, padlen);
1.88      markus    743:        if (enc && !send_context.plaintext) {
1.32      markus    744:                /* random padding */
1.25      markus    745:                for (i = 0; i < padlen; i++) {
                    746:                        if (i % 4 == 0)
1.115     avsm      747:                                rnd = arc4random();
                    748:                        cp[i] = rnd & 0xff;
                    749:                        rnd >>= 8;
1.25      markus    750:                }
1.32      markus    751:        } else {
                    752:                /* clear padding */
                    753:                memset(cp, 0, padlen);
1.25      markus    754:        }
                    755:        /* packet_length includes payload, padding and padding length field */
                    756:        packet_length = buffer_len(&outgoing_packet) - 4;
1.89      markus    757:        cp = buffer_ptr(&outgoing_packet);
                    758:        PUT_32BIT(cp, packet_length);
                    759:        cp[4] = padlen;
1.25      markus    760:        DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
                    761:
                    762:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
                    763:        if (mac && mac->enabled) {
1.105     markus    764:                macbuf = mac_compute(mac, p_send.seqnr,
1.83      stevesk   765:                    buffer_ptr(&outgoing_packet),
1.50      markus    766:                    buffer_len(&outgoing_packet));
1.105     markus    767:                DBG(debug("done calc MAC out #%d", p_send.seqnr));
1.25      markus    768:        }
                    769:        /* encrypt packet and append to output buffer. */
1.76      stevesk   770:        cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
1.88      markus    771:        cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
1.25      markus    772:            buffer_len(&outgoing_packet));
                    773:        /* append unencrypted MAC */
                    774:        if (mac && mac->enabled)
                    775:                buffer_append(&output, (char *)macbuf, mac->mac_len);
                    776: #ifdef PACKET_DEBUG
                    777:        fprintf(stderr, "encrypted: ");
                    778:        buffer_dump(&output);
                    779: #endif
1.29      markus    780:        /* increment sequence number for outgoing packets */
1.105     markus    781:        if (++p_send.seqnr == 0)
1.106     itojun    782:                logit("outgoing seqnr wraps around");
1.105     markus    783:        if (++p_send.packets == 0)
                    784:                if (!(datafellows & SSH_BUG_NOREKEY))
                    785:                        fatal("XXX too many packets with same key");
                    786:        p_send.blocks += (packet_length + 4) / block_size;
1.25      markus    787:        buffer_clear(&outgoing_packet);
                    788:
1.57      markus    789:        if (type == SSH2_MSG_NEWKEYS)
                    790:                set_newkeys(MODE_OUT);
1.118   ! markus    791:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
        !           792:                packet_enable_delayed_compress();
1.25      markus    793: }
                    794:
1.105     markus    795: static void
                    796: packet_send2(void)
                    797: {
                    798:        static int rekeying = 0;
                    799:        struct packet *p;
                    800:        u_char type, *cp;
                    801:
                    802:        cp = buffer_ptr(&outgoing_packet);
                    803:        type = cp[5];
                    804:
                    805:        /* during rekeying we can only send key exchange messages */
                    806:        if (rekeying) {
                    807:                if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
                    808:                    (type <= SSH2_MSG_TRANSPORT_MAX))) {
                    809:                        debug("enqueue packet: %u", type);
                    810:                        p = xmalloc(sizeof(*p));
                    811:                        p->type = type;
                    812:                        memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
                    813:                        buffer_init(&outgoing_packet);
                    814:                        TAILQ_INSERT_TAIL(&outgoing, p, next);
                    815:                        return;
                    816:                }
                    817:        }
                    818:
                    819:        /* rekeying starts with sending KEXINIT */
                    820:        if (type == SSH2_MSG_KEXINIT)
                    821:                rekeying = 1;
                    822:
                    823:        packet_send2_wrapped();
                    824:
                    825:        /* after a NEWKEYS message we can send the complete queue */
                    826:        if (type == SSH2_MSG_NEWKEYS) {
                    827:                rekeying = 0;
                    828:                while ((p = TAILQ_FIRST(&outgoing))) {
                    829:                        type = p->type;
                    830:                        debug("dequeue packet: %u", type);
                    831:                        buffer_free(&outgoing_packet);
                    832:                        memcpy(&outgoing_packet, &p->payload,
                    833:                            sizeof(Buffer));
                    834:                        TAILQ_REMOVE(&outgoing, p, next);
                    835:                        xfree(p);
                    836:                        packet_send2_wrapped();
                    837:                }
                    838:        }
                    839: }
                    840:
1.25      markus    841: void
1.73      itojun    842: packet_send(void)
1.25      markus    843: {
1.62      markus    844:        if (compat20)
1.25      markus    845:                packet_send2();
                    846:        else
                    847:                packet_send1();
                    848:        DBG(debug("packet_send done"));
                    849: }
                    850:
                    851: /*
1.16      markus    852:  * Waits until a packet has been received, and returns its type.  Note that
                    853:  * no other data is processed until this returns, so this function should not
                    854:  * be used during the interactive session.
                    855:  */
1.1       deraadt   856:
1.2       provos    857: int
1.82      markus    858: packet_read_seqnr(u_int32_t *seqnr_p)
1.1       deraadt   859: {
1.14      markus    860:        int type, len;
1.56      millert   861:        fd_set *setp;
1.14      markus    862:        char buf[8192];
1.25      markus    863:        DBG(debug("packet_read()"));
1.14      markus    864:
1.56      millert   865:        setp = (fd_set *)xmalloc(howmany(connection_in+1, NFDBITS) *
                    866:            sizeof(fd_mask));
                    867:
1.14      markus    868:        /* Since we are blocking, ensure that all written packets have been sent. */
                    869:        packet_write_wait();
                    870:
                    871:        /* Stay in the loop until we have received a complete packet. */
                    872:        for (;;) {
                    873:                /* Try to read a packet from the buffer. */
1.82      markus    874:                type = packet_read_poll_seqnr(seqnr_p);
1.62      markus    875:                if (!compat20 && (
1.32      markus    876:                    type == SSH_SMSG_SUCCESS
1.14      markus    877:                    || type == SSH_SMSG_FAILURE
                    878:                    || type == SSH_CMSG_EOF
1.32      markus    879:                    || type == SSH_CMSG_EXIT_CONFIRMATION))
1.79      markus    880:                        packet_check_eom();
1.14      markus    881:                /* If we got a packet, return it. */
1.56      millert   882:                if (type != SSH_MSG_NONE) {
                    883:                        xfree(setp);
1.14      markus    884:                        return type;
1.56      millert   885:                }
1.16      markus    886:                /*
                    887:                 * Otherwise, wait for some data to arrive, add it to the
                    888:                 * buffer, and try again.
                    889:                 */
1.56      millert   890:                memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
                    891:                    sizeof(fd_mask));
                    892:                FD_SET(connection_in, setp);
1.16      markus    893:
1.14      markus    894:                /* Wait for some data to arrive. */
1.56      millert   895:                while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
1.51      deraadt   896:                    (errno == EAGAIN || errno == EINTR))
                    897:                        ;
1.16      markus    898:
1.14      markus    899:                /* Read data from the socket. */
                    900:                len = read(connection_in, buf, sizeof(buf));
1.18      markus    901:                if (len == 0) {
1.106     itojun    902:                        logit("Connection closed by %.200s", get_remote_ipaddr());
1.112     markus    903:                        cleanup_exit(255);
1.18      markus    904:                }
1.14      markus    905:                if (len < 0)
                    906:                        fatal("Read from socket failed: %.100s", strerror(errno));
                    907:                /* Append it to the buffer. */
                    908:                packet_process_incoming(buf, len);
                    909:        }
                    910:        /* NOTREACHED */
1.1       deraadt   911: }
                    912:
1.77      djm       913: int
1.82      markus    914: packet_read(void)
1.77      djm       915: {
1.82      markus    916:        return packet_read_seqnr(NULL);
1.77      djm       917: }
                    918:
1.16      markus    919: /*
                    920:  * Waits until a packet has been received, verifies that its type matches
                    921:  * that given, and gives a fatal error and exits if there is a mismatch.
                    922:  */
1.1       deraadt   923:
1.2       provos    924: void
1.82      markus    925: packet_read_expect(int expected_type)
1.1       deraadt   926: {
1.14      markus    927:        int type;
1.1       deraadt   928:
1.82      markus    929:        type = packet_read();
1.14      markus    930:        if (type != expected_type)
                    931:                packet_disconnect("Protocol error: expected packet type %d, got %d",
1.25      markus    932:                    expected_type, type);
1.1       deraadt   933: }
                    934:
                    935: /* Checks if a full packet is available in the data received so far via
1.14      markus    936:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                    937:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                    938:  *
                    939:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                    940:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                    941:  * to higher levels.
                    942:  */
1.1       deraadt   943:
1.68      itojun    944: static int
1.82      markus    945: packet_read_poll1(void)
1.1       deraadt   946: {
1.40      markus    947:        u_int len, padded_len;
1.89      markus    948:        u_char *cp, type;
1.40      markus    949:        u_int checksum, stored_checksum;
1.14      markus    950:
                    951:        /* Check if input size is less than minimum packet size. */
                    952:        if (buffer_len(&input) < 4 + 8)
                    953:                return SSH_MSG_NONE;
                    954:        /* Get length of incoming packet. */
1.89      markus    955:        cp = buffer_ptr(&input);
                    956:        len = GET_32BIT(cp);
1.14      markus    957:        if (len < 1 + 2 + 2 || len > 256 * 1024)
1.98      markus    958:                packet_disconnect("Bad packet length %u.", len);
1.14      markus    959:        padded_len = (len + 8) & ~7;
                    960:
                    961:        /* Check if the packet has been entirely received. */
                    962:        if (buffer_len(&input) < 4 + padded_len)
                    963:                return SSH_MSG_NONE;
                    964:
                    965:        /* The entire packet is in buffer. */
                    966:
                    967:        /* Consume packet length. */
                    968:        buffer_consume(&input, 4);
                    969:
1.62      markus    970:        /*
                    971:         * Cryptographic attack detector for ssh
                    972:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                    973:         * Ariel Futoransky(futo@core-sdi.com)
                    974:         */
1.88      markus    975:        if (!receive_context.plaintext &&
1.62      markus    976:            detect_attack(buffer_ptr(&input), padded_len, NULL) == DEATTACK_DETECTED)
                    977:                packet_disconnect("crc32 compensation attack: network attack detected");
                    978:
                    979:        /* Decrypt data to incoming_packet. */
1.14      markus    980:        buffer_clear(&incoming_packet);
1.76      stevesk   981:        cp = buffer_append_space(&incoming_packet, padded_len);
1.88      markus    982:        cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1.62      markus    983:
1.14      markus    984:        buffer_consume(&input, padded_len);
1.1       deraadt   985:
                    986: #ifdef PACKET_DEBUG
1.14      markus    987:        fprintf(stderr, "read_poll plain: ");
                    988:        buffer_dump(&incoming_packet);
1.1       deraadt   989: #endif
                    990:
1.14      markus    991:        /* Compute packet checksum. */
1.83      stevesk   992:        checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1.25      markus    993:            buffer_len(&incoming_packet) - 4);
1.14      markus    994:
                    995:        /* Skip padding. */
                    996:        buffer_consume(&incoming_packet, 8 - len % 8);
                    997:
                    998:        /* Test check bytes. */
                    999:        if (len != buffer_len(&incoming_packet))
1.77      djm      1000:                packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1.25      markus   1001:                    len, buffer_len(&incoming_packet));
1.14      markus   1002:
1.89      markus   1003:        cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
                   1004:        stored_checksum = GET_32BIT(cp);
1.14      markus   1005:        if (checksum != stored_checksum)
                   1006:                packet_disconnect("Corrupted check bytes on input.");
                   1007:        buffer_consume_end(&incoming_packet, 4);
                   1008:
                   1009:        if (packet_compression) {
                   1010:                buffer_clear(&compression_buffer);
                   1011:                buffer_uncompress(&incoming_packet, &compression_buffer);
                   1012:                buffer_clear(&incoming_packet);
                   1013:                buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1.25      markus   1014:                    buffer_len(&compression_buffer));
1.14      markus   1015:        }
1.62      markus   1016:        type = buffer_get_char(&incoming_packet);
1.116     markus   1017:        if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
                   1018:                packet_disconnect("Invalid ssh1 packet type: %d", type);
1.62      markus   1019:        return type;
1.1       deraadt  1020: }
1.14      markus   1021:
1.68      itojun   1022: static int
1.82      markus   1023: packet_read_poll2(u_int32_t *seqnr_p)
1.25      markus   1024: {
1.50      markus   1025:        static u_int packet_length = 0;
1.40      markus   1026:        u_int padlen, need;
1.89      markus   1027:        u_char *macbuf, *cp, type;
1.117     djm      1028:        u_int maclen, block_size;
1.25      markus   1029:        Enc *enc   = NULL;
                   1030:        Mac *mac   = NULL;
                   1031:        Comp *comp = NULL;
                   1032:
1.57      markus   1033:        if (newkeys[MODE_IN] != NULL) {
                   1034:                enc  = &newkeys[MODE_IN]->enc;
                   1035:                mac  = &newkeys[MODE_IN]->mac;
                   1036:                comp = &newkeys[MODE_IN]->comp;
1.25      markus   1037:        }
                   1038:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1039:        block_size = enc ? enc->block_size : 8;
1.25      markus   1040:
                   1041:        if (packet_length == 0) {
                   1042:                /*
                   1043:                 * check if input size is less than the cipher block size,
                   1044:                 * decrypt first block and extract length of incoming packet
                   1045:                 */
                   1046:                if (buffer_len(&input) < block_size)
                   1047:                        return SSH_MSG_NONE;
                   1048:                buffer_clear(&incoming_packet);
1.76      stevesk  1049:                cp = buffer_append_space(&incoming_packet, block_size);
1.88      markus   1050:                cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1.25      markus   1051:                    block_size);
1.89      markus   1052:                cp = buffer_ptr(&incoming_packet);
                   1053:                packet_length = GET_32BIT(cp);
1.25      markus   1054:                if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1.110     markus   1055: #ifdef PACKET_DEBUG
1.25      markus   1056:                        buffer_dump(&incoming_packet);
1.110     markus   1057: #endif
1.98      markus   1058:                        packet_disconnect("Bad packet length %u.", packet_length);
1.25      markus   1059:                }
1.98      markus   1060:                DBG(debug("input: packet len %u", packet_length+4));
1.25      markus   1061:                buffer_consume(&input, block_size);
                   1062:        }
                   1063:        /* we have a partial packet of block_size bytes */
                   1064:        need = 4 + packet_length - block_size;
                   1065:        DBG(debug("partial packet %d, need %d, maclen %d", block_size,
                   1066:            need, maclen));
                   1067:        if (need % block_size != 0)
                   1068:                fatal("padding error: need %d block %d mod %d",
                   1069:                    need, block_size, need % block_size);
                   1070:        /*
                   1071:         * check if the entire packet has been received and
                   1072:         * decrypt into incoming_packet
                   1073:         */
                   1074:        if (buffer_len(&input) < need + maclen)
                   1075:                return SSH_MSG_NONE;
                   1076: #ifdef PACKET_DEBUG
                   1077:        fprintf(stderr, "read_poll enc/full: ");
                   1078:        buffer_dump(&input);
                   1079: #endif
1.76      stevesk  1080:        cp = buffer_append_space(&incoming_packet, need);
1.88      markus   1081:        cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1.25      markus   1082:        buffer_consume(&input, need);
                   1083:        /*
                   1084:         * compute MAC over seqnr and packet,
                   1085:         * increment sequence number for incoming packet
                   1086:         */
1.29      markus   1087:        if (mac && mac->enabled) {
1.105     markus   1088:                macbuf = mac_compute(mac, p_read.seqnr,
1.83      stevesk  1089:                    buffer_ptr(&incoming_packet),
1.50      markus   1090:                    buffer_len(&incoming_packet));
1.25      markus   1091:                if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1.36      markus   1092:                        packet_disconnect("Corrupted MAC on input.");
1.105     markus   1093:                DBG(debug("MAC #%d ok", p_read.seqnr));
1.25      markus   1094:                buffer_consume(&input, mac->mac_len);
                   1095:        }
1.77      djm      1096:        if (seqnr_p != NULL)
1.105     markus   1097:                *seqnr_p = p_read.seqnr;
                   1098:        if (++p_read.seqnr == 0)
1.106     itojun   1099:                logit("incoming seqnr wraps around");
1.105     markus   1100:        if (++p_read.packets == 0)
                   1101:                if (!(datafellows & SSH_BUG_NOREKEY))
                   1102:                        fatal("XXX too many packets with same key");
                   1103:        p_read.blocks += (packet_length + 4) / block_size;
1.25      markus   1104:
                   1105:        /* get padlen */
1.76      stevesk  1106:        cp = buffer_ptr(&incoming_packet);
1.89      markus   1107:        padlen = cp[4];
1.25      markus   1108:        DBG(debug("input: padlen %d", padlen));
                   1109:        if (padlen < 4)
                   1110:                packet_disconnect("Corrupted padlen %d on input.", padlen);
                   1111:
                   1112:        /* skip packet size + padlen, discard padding */
                   1113:        buffer_consume(&incoming_packet, 4 + 1);
                   1114:        buffer_consume_end(&incoming_packet, padlen);
                   1115:
                   1116:        DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
                   1117:        if (comp && comp->enabled) {
                   1118:                buffer_clear(&compression_buffer);
                   1119:                buffer_uncompress(&incoming_packet, &compression_buffer);
                   1120:                buffer_clear(&incoming_packet);
                   1121:                buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
                   1122:                    buffer_len(&compression_buffer));
1.97      deraadt  1123:                DBG(debug("input: len after de-compress %d",
                   1124:                    buffer_len(&incoming_packet)));
1.25      markus   1125:        }
                   1126:        /*
                   1127:         * get packet type, implies consume.
                   1128:         * return length of payload (without type field)
                   1129:         */
1.62      markus   1130:        type = buffer_get_char(&incoming_packet);
1.116     markus   1131:        if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
                   1132:                packet_disconnect("Invalid ssh2 packet type: %d", type);
1.57      markus   1133:        if (type == SSH2_MSG_NEWKEYS)
                   1134:                set_newkeys(MODE_IN);
1.118   ! markus   1135:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
        !          1136:                packet_enable_delayed_compress();
1.25      markus   1137: #ifdef PACKET_DEBUG
1.55      deraadt  1138:        fprintf(stderr, "read/plain[%d]:\r\n", type);
1.25      markus   1139:        buffer_dump(&incoming_packet);
                   1140: #endif
1.62      markus   1141:        /* reset for next packet */
                   1142:        packet_length = 0;
                   1143:        return type;
1.25      markus   1144: }
                   1145:
                   1146: int
1.82      markus   1147: packet_read_poll_seqnr(u_int32_t *seqnr_p)
1.25      markus   1148: {
1.96      deraadt  1149:        u_int reason, seqnr;
1.62      markus   1150:        u_char type;
1.25      markus   1151:        char *msg;
1.62      markus   1152:
1.25      markus   1153:        for (;;) {
1.62      markus   1154:                if (compat20) {
1.82      markus   1155:                        type = packet_read_poll2(seqnr_p);
1.62      markus   1156:                        if (type)
1.25      markus   1157:                                DBG(debug("received packet type %d", type));
1.74      deraadt  1158:                        switch (type) {
1.25      markus   1159:                        case SSH2_MSG_IGNORE:
                   1160:                                break;
                   1161:                        case SSH2_MSG_DEBUG:
                   1162:                                packet_get_char();
                   1163:                                msg = packet_get_string(NULL);
                   1164:                                debug("Remote: %.900s", msg);
                   1165:                                xfree(msg);
                   1166:                                msg = packet_get_string(NULL);
                   1167:                                xfree(msg);
                   1168:                                break;
                   1169:                        case SSH2_MSG_DISCONNECT:
                   1170:                                reason = packet_get_int();
                   1171:                                msg = packet_get_string(NULL);
1.106     itojun   1172:                                logit("Received disconnect from %s: %u: %.400s",
1.96      deraadt  1173:                                    get_remote_ipaddr(), reason, msg);
1.25      markus   1174:                                xfree(msg);
1.112     markus   1175:                                cleanup_exit(255);
1.84      markus   1176:                                break;
                   1177:                        case SSH2_MSG_UNIMPLEMENTED:
                   1178:                                seqnr = packet_get_int();
1.96      deraadt  1179:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1180:                                    seqnr);
1.25      markus   1181:                                break;
                   1182:                        default:
                   1183:                                return type;
                   1184:                                break;
1.48      stevesk  1185:                        }
1.25      markus   1186:                } else {
1.82      markus   1187:                        type = packet_read_poll1();
1.74      deraadt  1188:                        switch (type) {
1.25      markus   1189:                        case SSH_MSG_IGNORE:
                   1190:                                break;
                   1191:                        case SSH_MSG_DEBUG:
                   1192:                                msg = packet_get_string(NULL);
                   1193:                                debug("Remote: %.900s", msg);
                   1194:                                xfree(msg);
                   1195:                                break;
                   1196:                        case SSH_MSG_DISCONNECT:
                   1197:                                msg = packet_get_string(NULL);
1.106     itojun   1198:                                logit("Received disconnect from %s: %.400s",
1.96      deraadt  1199:                                    get_remote_ipaddr(), msg);
1.112     markus   1200:                                cleanup_exit(255);
1.25      markus   1201:                                xfree(msg);
                   1202:                                break;
                   1203:                        default:
1.62      markus   1204:                                if (type)
1.25      markus   1205:                                        DBG(debug("received packet type %d", type));
                   1206:                                return type;
                   1207:                                break;
1.48      stevesk  1208:                        }
1.25      markus   1209:                }
                   1210:        }
1.77      djm      1211: }
                   1212:
                   1213: int
1.82      markus   1214: packet_read_poll(void)
1.77      djm      1215: {
1.82      markus   1216:        return packet_read_poll_seqnr(NULL);
1.25      markus   1217: }
                   1218:
1.16      markus   1219: /*
                   1220:  * Buffers the given amount of input characters.  This is intended to be used
                   1221:  * together with packet_read_poll.
                   1222:  */
1.1       deraadt  1223:
1.2       provos   1224: void
1.40      markus   1225: packet_process_incoming(const char *buf, u_int len)
1.1       deraadt  1226: {
1.14      markus   1227:        buffer_append(&input, buf, len);
1.1       deraadt  1228: }
                   1229:
                   1230: /* Returns a character from the packet. */
                   1231:
1.40      markus   1232: u_int
1.73      itojun   1233: packet_get_char(void)
1.1       deraadt  1234: {
1.14      markus   1235:        char ch;
1.97      deraadt  1236:
1.14      markus   1237:        buffer_get(&incoming_packet, &ch, 1);
1.40      markus   1238:        return (u_char) ch;
1.1       deraadt  1239: }
                   1240:
                   1241: /* Returns an integer from the packet data. */
                   1242:
1.40      markus   1243: u_int
1.73      itojun   1244: packet_get_int(void)
1.1       deraadt  1245: {
1.14      markus   1246:        return buffer_get_int(&incoming_packet);
1.1       deraadt  1247: }
                   1248:
1.16      markus   1249: /*
                   1250:  * Returns an arbitrary precision integer from the packet data.  The integer
                   1251:  * must have been initialized before this call.
                   1252:  */
1.1       deraadt  1253:
1.2       provos   1254: void
1.80      markus   1255: packet_get_bignum(BIGNUM * value)
1.1       deraadt  1256: {
1.81      markus   1257:        buffer_get_bignum(&incoming_packet, value);
1.24      markus   1258: }
                   1259:
                   1260: void
1.80      markus   1261: packet_get_bignum2(BIGNUM * value)
1.24      markus   1262: {
1.81      markus   1263:        buffer_get_bignum2(&incoming_packet, value);
1.24      markus   1264: }
                   1265:
1.76      stevesk  1266: void *
1.117     djm      1267: packet_get_raw(u_int *length_ptr)
1.24      markus   1268: {
1.117     djm      1269:        u_int bytes = buffer_len(&incoming_packet);
1.97      deraadt  1270:
1.24      markus   1271:        if (length_ptr != NULL)
                   1272:                *length_ptr = bytes;
                   1273:        return buffer_ptr(&incoming_packet);
1.28      markus   1274: }
                   1275:
                   1276: int
                   1277: packet_remaining(void)
                   1278: {
                   1279:        return buffer_len(&incoming_packet);
1.1       deraadt  1280: }
                   1281:
1.16      markus   1282: /*
                   1283:  * Returns a string from the packet data.  The string is allocated using
                   1284:  * xmalloc; it is the responsibility of the calling program to free it when
                   1285:  * no longer needed.  The length_ptr argument may be NULL, or point to an
                   1286:  * integer into which the length of the string is stored.
                   1287:  */
1.1       deraadt  1288:
1.76      stevesk  1289: void *
1.40      markus   1290: packet_get_string(u_int *length_ptr)
1.1       deraadt  1291: {
1.14      markus   1292:        return buffer_get_string(&incoming_packet, length_ptr);
1.1       deraadt  1293: }
                   1294:
1.16      markus   1295: /*
                   1296:  * Sends a diagnostic message from the server to the client.  This message
                   1297:  * can be sent at any time (but not while constructing another message). The
                   1298:  * message is printed immediately, but only if the client is being executed
                   1299:  * in verbose mode.  These messages are primarily intended to ease debugging
                   1300:  * authentication problems.   The length of the formatted message must not
                   1301:  * exceed 1024 bytes.  This will automatically call packet_write_wait.
                   1302:  */
1.1       deraadt  1303:
1.2       provos   1304: void
1.14      markus   1305: packet_send_debug(const char *fmt,...)
1.1       deraadt  1306: {
1.14      markus   1307:        char buf[1024];
                   1308:        va_list args;
1.39      markus   1309:
                   1310:        if (compat20 && (datafellows & SSH_BUG_DEBUG))
                   1311:                return;
1.14      markus   1312:
                   1313:        va_start(args, fmt);
                   1314:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1315:        va_end(args);
                   1316:
1.30      markus   1317:        if (compat20) {
                   1318:                packet_start(SSH2_MSG_DEBUG);
                   1319:                packet_put_char(0);     /* bool: always display */
                   1320:                packet_put_cstring(buf);
                   1321:                packet_put_cstring("");
                   1322:        } else {
                   1323:                packet_start(SSH_MSG_DEBUG);
                   1324:                packet_put_cstring(buf);
                   1325:        }
1.14      markus   1326:        packet_send();
                   1327:        packet_write_wait();
1.1       deraadt  1328: }
                   1329:
1.16      markus   1330: /*
                   1331:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1332:  * connection, and exits.  This function never returns. The error message
                   1333:  * should not contain a newline.  The length of the formatted message must
                   1334:  * not exceed 1024 bytes.
                   1335:  */
1.1       deraadt  1336:
1.2       provos   1337: void
1.14      markus   1338: packet_disconnect(const char *fmt,...)
1.1       deraadt  1339: {
1.14      markus   1340:        char buf[1024];
                   1341:        va_list args;
                   1342:        static int disconnecting = 0;
1.97      deraadt  1343:
1.14      markus   1344:        if (disconnecting)      /* Guard against recursive invocations. */
                   1345:                fatal("packet_disconnect called recursively.");
                   1346:        disconnecting = 1;
                   1347:
1.16      markus   1348:        /*
                   1349:         * Format the message.  Note that the caller must make sure the
                   1350:         * message is of limited size.
                   1351:         */
1.14      markus   1352:        va_start(args, fmt);
                   1353:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1354:        va_end(args);
                   1355:
1.99      markus   1356:        /* Display the error locally */
1.106     itojun   1357:        logit("Disconnecting: %.100s", buf);
1.99      markus   1358:
1.14      markus   1359:        /* Send the disconnect message to the other side, and wait for it to get sent. */
1.25      markus   1360:        if (compat20) {
                   1361:                packet_start(SSH2_MSG_DISCONNECT);
                   1362:                packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
                   1363:                packet_put_cstring(buf);
                   1364:                packet_put_cstring("");
                   1365:        } else {
                   1366:                packet_start(SSH_MSG_DISCONNECT);
1.65      markus   1367:                packet_put_cstring(buf);
1.25      markus   1368:        }
1.14      markus   1369:        packet_send();
                   1370:        packet_write_wait();
                   1371:
                   1372:        /* Stop listening for connections. */
1.67      markus   1373:        channel_close_all();
1.14      markus   1374:
                   1375:        /* Close the connection. */
                   1376:        packet_close();
1.112     markus   1377:        cleanup_exit(255);
1.1       deraadt  1378: }
                   1379:
1.16      markus   1380: /* Checks if there is any buffered output, and tries to write some of the output. */
1.1       deraadt  1381:
1.2       provos   1382: void
1.73      itojun   1383: packet_write_poll(void)
1.1       deraadt  1384: {
1.14      markus   1385:        int len = buffer_len(&output);
1.97      deraadt  1386:
1.14      markus   1387:        if (len > 0) {
                   1388:                len = write(connection_out, buffer_ptr(&output), len);
                   1389:                if (len <= 0) {
                   1390:                        if (errno == EAGAIN)
                   1391:                                return;
                   1392:                        else
                   1393:                                fatal("Write failed: %.100s", strerror(errno));
                   1394:                }
                   1395:                buffer_consume(&output, len);
                   1396:        }
1.1       deraadt  1397: }
                   1398:
1.16      markus   1399: /*
                   1400:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1401:  * written.
                   1402:  */
1.1       deraadt  1403:
1.2       provos   1404: void
1.73      itojun   1405: packet_write_wait(void)
1.1       deraadt  1406: {
1.56      millert  1407:        fd_set *setp;
                   1408:
                   1409:        setp = (fd_set *)xmalloc(howmany(connection_out + 1, NFDBITS) *
                   1410:            sizeof(fd_mask));
1.14      markus   1411:        packet_write_poll();
                   1412:        while (packet_have_data_to_write()) {
1.56      millert  1413:                memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
                   1414:                    sizeof(fd_mask));
                   1415:                FD_SET(connection_out, setp);
                   1416:                while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1.51      deraadt  1417:                    (errno == EAGAIN || errno == EINTR))
                   1418:                        ;
1.14      markus   1419:                packet_write_poll();
                   1420:        }
1.56      millert  1421:        xfree(setp);
1.1       deraadt  1422: }
                   1423:
                   1424: /* Returns true if there is buffered data to write to the connection. */
                   1425:
1.2       provos   1426: int
1.73      itojun   1427: packet_have_data_to_write(void)
1.1       deraadt  1428: {
1.14      markus   1429:        return buffer_len(&output) != 0;
1.1       deraadt  1430: }
                   1431:
                   1432: /* Returns true if there is not too much data to write to the connection. */
                   1433:
1.2       provos   1434: int
1.73      itojun   1435: packet_not_very_much_data_to_write(void)
1.1       deraadt  1436: {
1.14      markus   1437:        if (interactive_mode)
                   1438:                return buffer_len(&output) < 16384;
                   1439:        else
                   1440:                return buffer_len(&output) < 128 * 1024;
1.1       deraadt  1441: }
                   1442:
1.102     markus   1443: static void
1.101     markus   1444: packet_set_tos(int interactive)
                   1445: {
                   1446:        int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
                   1447:
                   1448:        if (!packet_connection_is_on_socket() ||
                   1449:            !packet_connection_is_ipv4())
                   1450:                return;
                   1451:        if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
                   1452:            sizeof(tos)) < 0)
                   1453:                error("setsockopt IP_TOS %d: %.100s:",
                   1454:                    tos, strerror(errno));
                   1455: }
                   1456:
1.1       deraadt  1457: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   1458:
1.2       provos   1459: void
1.43      markus   1460: packet_set_interactive(int interactive)
1.1       deraadt  1461: {
1.43      markus   1462:        static int called = 0;
1.44      markus   1463:
1.43      markus   1464:        if (called)
                   1465:                return;
                   1466:        called = 1;
1.1       deraadt  1467:
1.14      markus   1468:        /* Record that we are in interactive mode. */
                   1469:        interactive_mode = interactive;
1.1       deraadt  1470:
1.19      markus   1471:        /* Only set socket options if using a socket.  */
                   1472:        if (!packet_connection_is_on_socket())
1.14      markus   1473:                return;
1.101     markus   1474:        if (interactive)
1.86      stevesk  1475:                set_nodelay(connection_in);
1.101     markus   1476:        packet_set_tos(interactive);
1.1       deraadt  1477: }
                   1478:
                   1479: /* Returns true if the current connection is interactive. */
                   1480:
1.2       provos   1481: int
1.73      itojun   1482: packet_is_interactive(void)
1.1       deraadt  1483: {
1.14      markus   1484:        return interactive_mode;
1.12      markus   1485: }
                   1486:
1.113     deraadt  1487: int
1.108     markus   1488: packet_set_maxsize(u_int s)
1.12      markus   1489: {
1.14      markus   1490:        static int called = 0;
1.97      deraadt  1491:
1.14      markus   1492:        if (called) {
1.106     itojun   1493:                logit("packet_set_maxsize: called twice: old %d new %d",
1.25      markus   1494:                    max_packet_size, s);
1.14      markus   1495:                return -1;
                   1496:        }
                   1497:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   1498:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   1499:                return -1;
                   1500:        }
1.70      markus   1501:        called = 1;
1.66      markus   1502:        debug("packet_set_maxsize: setting to %d", s);
1.14      markus   1503:        max_packet_size = s;
                   1504:        return s;
1.53      markus   1505: }
                   1506:
1.71      markus   1507: /* roundup current message to pad bytes */
                   1508: void
                   1509: packet_add_padding(u_char pad)
                   1510: {
                   1511:        extra_pad = pad;
                   1512: }
                   1513:
1.53      markus   1514: /*
                   1515:  * 9.2.  Ignored Data Message
1.61      markus   1516:  *
1.53      markus   1517:  *   byte      SSH_MSG_IGNORE
                   1518:  *   string    data
1.61      markus   1519:  *
1.53      markus   1520:  * All implementations MUST understand (and ignore) this message at any
                   1521:  * time (after receiving the protocol version). No implementation is
                   1522:  * required to send them. This message can be used as an additional
                   1523:  * protection measure against advanced traffic analysis techniques.
                   1524:  */
1.54      markus   1525: void
                   1526: packet_send_ignore(int nbytes)
                   1527: {
1.115     avsm     1528:        u_int32_t rnd = 0;
1.54      markus   1529:        int i;
                   1530:
                   1531:        packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1.53      markus   1532:        packet_put_int(nbytes);
1.75      deraadt  1533:        for (i = 0; i < nbytes; i++) {
1.53      markus   1534:                if (i % 4 == 0)
1.115     avsm     1535:                        rnd = arc4random();
                   1536:                packet_put_char(rnd & 0xff);
                   1537:                rnd >>= 8;
1.53      markus   1538:        }
1.105     markus   1539: }
                   1540:
1.113     deraadt  1541: #define MAX_PACKETS    (1U<<31)
1.105     markus   1542: int
                   1543: packet_need_rekeying(void)
                   1544: {
                   1545:        if (datafellows & SSH_BUG_NOREKEY)
                   1546:                return 0;
                   1547:        return
                   1548:            (p_send.packets > MAX_PACKETS) ||
                   1549:            (p_read.packets > MAX_PACKETS) ||
                   1550:            (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
                   1551:            (max_blocks_in  && (p_read.blocks > max_blocks_in));
                   1552: }
                   1553:
                   1554: void
                   1555: packet_set_rekey_limit(u_int32_t bytes)
                   1556: {
                   1557:        rekey_limit = bytes;
1.118   ! markus   1558: }
        !          1559:
        !          1560: void
        !          1561: packet_set_server(void)
        !          1562: {
        !          1563:        server_side = 1;
        !          1564: }
        !          1565:
        !          1566: void
        !          1567: packet_set_authenticated(void)
        !          1568: {
        !          1569:        after_authentication = 1;
1.1       deraadt  1570: }