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

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