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

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