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

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