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

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