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

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