[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.123

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