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

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