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

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