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

1.1       deraadt     1: /*
1.15      deraadt     2:  *
                      3:  * packet.c
                      4:  *
                      5:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      6:  *
                      7:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      8:  *                    All rights reserved
                      9:  *
                     10:  * Created: Sat Mar 18 02:40:40 1995 ylo
                     11:  *
                     12:  * This file contains code implementing the packet protocol and communication
                     13:  * with the other side.  This same code is used both on client and server side.
                     14:  *
                     15:  */
1.1       deraadt    16:
                     17: #include "includes.h"
1.24    ! markus     18: RCSID("$Id: packet.c,v 1.23 2000/03/28 20:31:27 markus Exp $");
1.1       deraadt    19:
                     20: #include "xmalloc.h"
                     21: #include "buffer.h"
                     22: #include "packet.h"
                     23: #include "bufaux.h"
                     24: #include "ssh.h"
                     25: #include "crc32.h"
                     26: #include "cipher.h"
                     27: #include "getput.h"
                     28:
                     29: #include "compress.h"
1.9       dugsong    30: #include "deattack.h"
1.23      markus     31: #include "channels.h"
1.1       deraadt    32:
1.16      markus     33: /*
                     34:  * This variable contains the file descriptors used for communicating with
                     35:  * the other side.  connection_in is used for reading; connection_out for
                     36:  * writing.  These can be the same descriptor, in which case it is assumed to
                     37:  * be a socket.
                     38:  */
1.1       deraadt    39: static int connection_in = -1;
                     40: static int connection_out = -1;
                     41:
1.16      markus     42: /*
                     43:  * Cipher type.  This value is only used to determine whether to pad the
                     44:  * packets with zeroes or random data.
                     45:  */
1.1       deraadt    46: static int cipher_type = SSH_CIPHER_NONE;
                     47:
                     48: /* Protocol flags for the remote side. */
                     49: static unsigned int remote_protocol_flags = 0;
                     50:
                     51: /* Encryption context for receiving data.  This is only used for decryption. */
                     52: static CipherContext receive_context;
1.14      markus     53:
                     54: /* Encryption context for sending data.  This is only used for encryption. */
1.1       deraadt    55: static CipherContext send_context;
                     56:
                     57: /* Buffer for raw input data from the socket. */
                     58: static Buffer input;
                     59:
                     60: /* Buffer for raw output data going to the socket. */
                     61: static Buffer output;
                     62:
                     63: /* Buffer for the partial outgoing packet being constructed. */
                     64: static Buffer outgoing_packet;
                     65:
                     66: /* Buffer for the incoming packet currently being processed. */
                     67: static Buffer incoming_packet;
                     68:
                     69: /* Scratch buffer for packet compression/decompression. */
                     70: static Buffer compression_buffer;
                     71:
                     72: /* Flag indicating whether packet compression/decompression is enabled. */
                     73: static int packet_compression = 0;
                     74:
1.12      markus     75: /* default maximum packet size */
                     76: int max_packet_size = 32768;
                     77:
1.1       deraadt    78: /* Flag indicating whether this module has been initialized. */
                     79: static int initialized = 0;
                     80:
                     81: /* Set to true if the connection is interactive. */
                     82: static int interactive_mode = 0;
                     83:
1.16      markus     84: /*
                     85:  * Sets the descriptors used for communication.  Disables encryption until
                     86:  * packet_set_encryption_key is called.
                     87:  */
1.1       deraadt    88:
1.2       provos     89: void
                     90: packet_set_connection(int fd_in, int fd_out)
1.1       deraadt    91: {
1.14      markus     92:        connection_in = fd_in;
                     93:        connection_out = fd_out;
                     94:        cipher_type = SSH_CIPHER_NONE;
                     95:        cipher_set_key(&send_context, SSH_CIPHER_NONE, (unsigned char *) "", 0, 1);
                     96:        cipher_set_key(&receive_context, SSH_CIPHER_NONE, (unsigned char *) "", 0, 0);
                     97:        if (!initialized) {
                     98:                initialized = 1;
                     99:                buffer_init(&input);
                    100:                buffer_init(&output);
                    101:                buffer_init(&outgoing_packet);
                    102:                buffer_init(&incoming_packet);
                    103:        }
                    104:        /* Kludge: arrange the close function to be called from fatal(). */
                    105:        fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
1.1       deraadt   106: }
                    107:
1.19      markus    108: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    109:
                    110: int
                    111: packet_connection_is_on_socket()
                    112: {
                    113:        struct sockaddr_storage from, to;
                    114:        socklen_t fromlen, tolen;
                    115:
                    116:        /* filedescriptors in and out are the same, so it's a socket */
                    117:        if (connection_in == connection_out)
                    118:                return 1;
                    119:        fromlen = sizeof(from);
                    120:        memset(&from, 0, sizeof(from));
1.20      markus    121:        if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
1.19      markus    122:                return 0;
                    123:        tolen = sizeof(to);
                    124:        memset(&to, 0, sizeof(to));
1.20      markus    125:        if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
1.19      markus    126:                return 0;
                    127:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    128:                return 0;
                    129:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    130:                return 0;
                    131:        return 1;
                    132: }
                    133:
                    134: /* returns 1 if connection is via ipv4 */
                    135:
                    136: int
                    137: packet_connection_is_ipv4()
                    138: {
                    139:        struct sockaddr_storage to;
1.21      deraadt   140:        socklen_t tolen = sizeof(to);
1.19      markus    141:
                    142:        memset(&to, 0, sizeof(to));
                    143:        if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
                    144:                return 0;
                    145:        if (to.ss_family != AF_INET)
                    146:                return 0;
                    147:        return 1;
                    148: }
                    149:
1.1       deraadt   150: /* Sets the connection into non-blocking mode. */
                    151:
1.2       provos    152: void
                    153: packet_set_nonblocking()
1.1       deraadt   154: {
1.14      markus    155:        /* Set the socket into non-blocking mode. */
                    156:        if (fcntl(connection_in, F_SETFL, O_NONBLOCK) < 0)
                    157:                error("fcntl O_NONBLOCK: %.100s", strerror(errno));
                    158:
                    159:        if (connection_out != connection_in) {
                    160:                if (fcntl(connection_out, F_SETFL, O_NONBLOCK) < 0)
                    161:                        error("fcntl O_NONBLOCK: %.100s", strerror(errno));
                    162:        }
1.1       deraadt   163: }
                    164:
                    165: /* Returns the socket used for reading. */
                    166:
1.2       provos    167: int
                    168: packet_get_connection_in()
1.1       deraadt   169: {
1.14      markus    170:        return connection_in;
1.1       deraadt   171: }
                    172:
                    173: /* Returns the descriptor used for writing. */
                    174:
1.2       provos    175: int
                    176: packet_get_connection_out()
1.1       deraadt   177: {
1.14      markus    178:        return connection_out;
1.1       deraadt   179: }
                    180:
                    181: /* Closes the connection and clears and frees internal data structures. */
                    182:
1.2       provos    183: void
                    184: packet_close()
1.1       deraadt   185: {
1.14      markus    186:        if (!initialized)
                    187:                return;
                    188:        initialized = 0;
                    189:        if (connection_in == connection_out) {
                    190:                shutdown(connection_out, SHUT_RDWR);
                    191:                close(connection_out);
                    192:        } else {
                    193:                close(connection_in);
                    194:                close(connection_out);
                    195:        }
                    196:        buffer_free(&input);
                    197:        buffer_free(&output);
                    198:        buffer_free(&outgoing_packet);
                    199:        buffer_free(&incoming_packet);
                    200:        if (packet_compression) {
                    201:                buffer_free(&compression_buffer);
                    202:                buffer_compress_uninit();
                    203:        }
1.1       deraadt   204: }
                    205:
                    206: /* Sets remote side protocol flags. */
                    207:
1.2       provos    208: void
                    209: packet_set_protocol_flags(unsigned int protocol_flags)
1.1       deraadt   210: {
1.14      markus    211:        remote_protocol_flags = protocol_flags;
                    212:        channel_set_options((protocol_flags & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) != 0);
1.1       deraadt   213: }
                    214:
                    215: /* Returns the remote protocol flags set earlier by the above function. */
                    216:
1.2       provos    217: unsigned int
                    218: packet_get_protocol_flags()
1.1       deraadt   219: {
1.14      markus    220:        return remote_protocol_flags;
1.1       deraadt   221: }
                    222:
1.16      markus    223: /*
                    224:  * Starts packet compression from the next packet on in both directions.
                    225:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    226:  */
1.1       deraadt   227:
1.2       provos    228: void
                    229: packet_start_compression(int level)
1.1       deraadt   230: {
1.14      markus    231:        if (packet_compression)
                    232:                fatal("Compression already enabled.");
                    233:        packet_compression = 1;
                    234:        buffer_init(&compression_buffer);
                    235:        buffer_compress_init(level);
1.1       deraadt   236: }
                    237:
1.16      markus    238: /*
                    239:  * Encrypts the given number of bytes, copying from src to dest. bytes is
                    240:  * known to be a multiple of 8.
                    241:  */
1.1       deraadt   242:
1.2       provos    243: void
1.14      markus    244: packet_encrypt(CipherContext * cc, void *dest, void *src,
1.2       provos    245:               unsigned int bytes)
1.1       deraadt   246: {
1.14      markus    247:        cipher_encrypt(cc, dest, src, bytes);
1.1       deraadt   248: }
                    249:
1.16      markus    250: /*
                    251:  * Decrypts the given number of bytes, copying from src to dest. bytes is
                    252:  * known to be a multiple of 8.
                    253:  */
1.1       deraadt   254:
1.2       provos    255: void
1.14      markus    256: packet_decrypt(CipherContext * cc, void *dest, void *src,
1.2       provos    257:               unsigned int bytes)
1.1       deraadt   258: {
1.14      markus    259:        int i;
                    260:
                    261:        if ((bytes % 8) != 0)
                    262:                fatal("packet_decrypt: bad ciphertext length %d", bytes);
                    263:
1.16      markus    264:        /*
                    265:         * Cryptographic attack detector for ssh - Modifications for packet.c
                    266:         * (C)1998 CORE-SDI, Buenos Aires Argentina Ariel Futoransky(futo@core-sdi.com)
                    267:         */
1.14      markus    268:
                    269:        switch (cc->type) {
                    270:        case SSH_CIPHER_NONE:
                    271:                i = DEATTACK_OK;
                    272:                break;
                    273:        default:
                    274:                i = detect_attack(src, bytes, NULL);
                    275:                break;
                    276:        }
                    277:
                    278:        if (i == DEATTACK_DETECTED)
                    279:                packet_disconnect("crc32 compensation attack: network attack detected");
                    280:
                    281:        cipher_decrypt(cc, dest, src, bytes);
1.1       deraadt   282: }
                    283:
1.16      markus    284: /*
                    285:  * Causes any further packets to be encrypted using the given key.  The same
                    286:  * key is used for both sending and reception.  However, both directions are
                    287:  * encrypted independently of each other.
                    288:  */
1.1       deraadt   289:
1.2       provos    290: void
                    291: packet_set_encryption_key(const unsigned char *key, unsigned int keylen,
1.11      markus    292:                          int cipher)
1.1       deraadt   293: {
1.14      markus    294:        /* All other ciphers use the same key in both directions for now. */
                    295:        cipher_set_key(&receive_context, cipher, key, keylen, 0);
                    296:        cipher_set_key(&send_context, cipher, key, keylen, 1);
1.1       deraadt   297: }
                    298:
                    299: /* Starts constructing a packet to send. */
                    300:
1.2       provos    301: void
                    302: packet_start(int type)
1.1       deraadt   303: {
1.14      markus    304:        char buf[9];
1.1       deraadt   305:
1.14      markus    306:        buffer_clear(&outgoing_packet);
                    307:        memset(buf, 0, 8);
                    308:        buf[8] = type;
                    309:        buffer_append(&outgoing_packet, buf, 9);
1.1       deraadt   310: }
                    311:
                    312: /* Appends a character to the packet data. */
                    313:
1.2       provos    314: void
                    315: packet_put_char(int value)
1.1       deraadt   316: {
1.14      markus    317:        char ch = value;
                    318:        buffer_append(&outgoing_packet, &ch, 1);
1.1       deraadt   319: }
                    320:
                    321: /* Appends an integer to the packet data. */
                    322:
1.2       provos    323: void
                    324: packet_put_int(unsigned int value)
1.1       deraadt   325: {
1.14      markus    326:        buffer_put_int(&outgoing_packet, value);
1.1       deraadt   327: }
                    328:
                    329: /* Appends a string to packet data. */
                    330:
1.2       provos    331: void
                    332: packet_put_string(const char *buf, unsigned int len)
1.1       deraadt   333: {
1.14      markus    334:        buffer_put_string(&outgoing_packet, buf, len);
1.1       deraadt   335: }
1.24    ! markus    336: void
        !           337: packet_put_cstring(const char *str)
        !           338: {
        !           339:        buffer_put_string(&outgoing_packet, str, strlen(str));
        !           340: }
        !           341:
        !           342: void
        !           343: packet_put_raw(const char *buf, unsigned int len)
        !           344: {
        !           345:        buffer_append(&outgoing_packet, buf, len);
        !           346: }
        !           347:
1.1       deraadt   348:
                    349: /* Appends an arbitrary precision integer to packet data. */
                    350:
1.2       provos    351: void
1.14      markus    352: packet_put_bignum(BIGNUM * value)
1.1       deraadt   353: {
1.14      markus    354:        buffer_put_bignum(&outgoing_packet, value);
1.1       deraadt   355: }
1.24    ! markus    356: void
        !           357: packet_put_bignum2(BIGNUM * value)
        !           358: {
        !           359:        buffer_put_bignum2(&outgoing_packet, value);
        !           360: }
1.1       deraadt   361:
1.16      markus    362: /*
                    363:  * Finalizes and sends the packet.  If the encryption key has been set,
                    364:  * encrypts the packet before sending.
                    365:  */
1.14      markus    366:
1.2       provos    367: void
                    368: packet_send()
1.1       deraadt   369: {
1.14      markus    370:        char buf[8], *cp;
                    371:        int i, padding, len;
                    372:        unsigned int checksum;
                    373:        u_int32_t rand = 0;
                    374:
1.16      markus    375:        /*
                    376:         * If using packet compression, compress the payload of the outgoing
                    377:         * packet.
                    378:         */
1.14      markus    379:        if (packet_compression) {
                    380:                buffer_clear(&compression_buffer);
                    381:                /* Skip padding. */
                    382:                buffer_consume(&outgoing_packet, 8);
                    383:                /* padding */
                    384:                buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
                    385:                buffer_compress(&outgoing_packet, &compression_buffer);
                    386:                buffer_clear(&outgoing_packet);
                    387:                buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
                    388:                              buffer_len(&compression_buffer));
                    389:        }
                    390:        /* Compute packet length without padding (add checksum, remove padding). */
                    391:        len = buffer_len(&outgoing_packet) + 4 - 8;
                    392:
                    393:        /* Insert padding. */
                    394:        padding = 8 - len % 8;
                    395:        if (cipher_type != SSH_CIPHER_NONE) {
                    396:                cp = buffer_ptr(&outgoing_packet);
                    397:                for (i = 0; i < padding; i++) {
                    398:                        if (i % 4 == 0)
                    399:                                rand = arc4random();
                    400:                        cp[7 - i] = rand & 0xff;
                    401:                        rand >>= 8;
                    402:                }
                    403:        }
                    404:        buffer_consume(&outgoing_packet, 8 - padding);
                    405:
                    406:        /* Add check bytes. */
                    407:        checksum = crc32((unsigned char *) buffer_ptr(&outgoing_packet),
                    408:                         buffer_len(&outgoing_packet));
                    409:        PUT_32BIT(buf, checksum);
                    410:        buffer_append(&outgoing_packet, buf, 4);
1.1       deraadt   411:
                    412: #ifdef PACKET_DEBUG
1.14      markus    413:        fprintf(stderr, "packet_send plain: ");
                    414:        buffer_dump(&outgoing_packet);
1.1       deraadt   415: #endif
                    416:
1.14      markus    417:        /* Append to output. */
                    418:        PUT_32BIT(buf, len);
                    419:        buffer_append(&output, buf, 4);
                    420:        buffer_append_space(&output, &cp, buffer_len(&outgoing_packet));
                    421:        packet_encrypt(&send_context, cp, buffer_ptr(&outgoing_packet),
                    422:                       buffer_len(&outgoing_packet));
                    423:
1.1       deraadt   424: #ifdef PACKET_DEBUG
1.14      markus    425:        fprintf(stderr, "encrypted: ");
                    426:        buffer_dump(&output);
1.1       deraadt   427: #endif
                    428:
1.14      markus    429:        buffer_clear(&outgoing_packet);
1.1       deraadt   430:
1.16      markus    431:        /*
                    432:         * Note that the packet is now only buffered in output.  It won\'t be
                    433:         * actually sent until packet_write_wait or packet_write_poll is
                    434:         * called.
                    435:         */
1.1       deraadt   436: }
                    437:
1.16      markus    438: /*
                    439:  * Waits until a packet has been received, and returns its type.  Note that
                    440:  * no other data is processed until this returns, so this function should not
                    441:  * be used during the interactive session.
                    442:  */
1.1       deraadt   443:
1.2       provos    444: int
                    445: packet_read(int *payload_len_ptr)
1.1       deraadt   446: {
1.14      markus    447:        int type, len;
                    448:        fd_set set;
                    449:        char buf[8192];
                    450:
                    451:        /* Since we are blocking, ensure that all written packets have been sent. */
                    452:        packet_write_wait();
                    453:
                    454:        /* Stay in the loop until we have received a complete packet. */
                    455:        for (;;) {
                    456:                /* Try to read a packet from the buffer. */
                    457:                type = packet_read_poll(payload_len_ptr);
                    458:                if (type == SSH_SMSG_SUCCESS
                    459:                    || type == SSH_SMSG_FAILURE
                    460:                    || type == SSH_CMSG_EOF
                    461:                    || type == SSH_CMSG_EXIT_CONFIRMATION)
                    462:                        packet_integrity_check(*payload_len_ptr, 0, type);
                    463:                /* If we got a packet, return it. */
                    464:                if (type != SSH_MSG_NONE)
                    465:                        return type;
1.16      markus    466:                /*
                    467:                 * Otherwise, wait for some data to arrive, add it to the
                    468:                 * buffer, and try again.
                    469:                 */
1.14      markus    470:                FD_ZERO(&set);
                    471:                FD_SET(connection_in, &set);
1.16      markus    472:
1.14      markus    473:                /* Wait for some data to arrive. */
                    474:                select(connection_in + 1, &set, NULL, NULL, NULL);
1.16      markus    475:
1.14      markus    476:                /* Read data from the socket. */
                    477:                len = read(connection_in, buf, sizeof(buf));
1.18      markus    478:                if (len == 0) {
                    479:                        log("Connection closed by %.200s", get_remote_ipaddr());
                    480:                        fatal_cleanup();
                    481:                }
1.14      markus    482:                if (len < 0)
                    483:                        fatal("Read from socket failed: %.100s", strerror(errno));
                    484:                /* Append it to the buffer. */
                    485:                packet_process_incoming(buf, len);
                    486:        }
                    487:        /* NOTREACHED */
1.1       deraadt   488: }
                    489:
1.16      markus    490: /*
                    491:  * Waits until a packet has been received, verifies that its type matches
                    492:  * that given, and gives a fatal error and exits if there is a mismatch.
                    493:  */
1.1       deraadt   494:
1.2       provos    495: void
                    496: packet_read_expect(int *payload_len_ptr, int expected_type)
1.1       deraadt   497: {
1.14      markus    498:        int type;
1.1       deraadt   499:
1.14      markus    500:        type = packet_read(payload_len_ptr);
                    501:        if (type != expected_type)
                    502:                packet_disconnect("Protocol error: expected packet type %d, got %d",
                    503:                                  expected_type, type);
1.1       deraadt   504: }
                    505:
                    506: /* Checks if a full packet is available in the data received so far via
1.14      markus    507:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                    508:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                    509:  *
                    510:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                    511:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                    512:  * to higher levels.
                    513:  *
                    514:  * The returned payload_len does include space consumed by:
                    515:  *     Packet length
                    516:  *     Padding
                    517:  *     Packet type
                    518:  *     Check bytes
                    519:  */
1.1       deraadt   520:
1.2       provos    521: int
                    522: packet_read_poll(int *payload_len_ptr)
1.1       deraadt   523: {
1.14      markus    524:        unsigned int len, padded_len;
                    525:        unsigned char *ucp;
1.22      markus    526:        char buf[8], *cp, *msg;
1.14      markus    527:        unsigned int checksum, stored_checksum;
                    528:
                    529: restart:
                    530:
                    531:        /* Check if input size is less than minimum packet size. */
                    532:        if (buffer_len(&input) < 4 + 8)
                    533:                return SSH_MSG_NONE;
                    534:        /* Get length of incoming packet. */
                    535:        ucp = (unsigned char *) buffer_ptr(&input);
                    536:        len = GET_32BIT(ucp);
                    537:        if (len < 1 + 2 + 2 || len > 256 * 1024)
                    538:                packet_disconnect("Bad packet length %d.", len);
                    539:        padded_len = (len + 8) & ~7;
                    540:
                    541:        /* Check if the packet has been entirely received. */
                    542:        if (buffer_len(&input) < 4 + padded_len)
                    543:                return SSH_MSG_NONE;
                    544:
                    545:        /* The entire packet is in buffer. */
                    546:
                    547:        /* Consume packet length. */
                    548:        buffer_consume(&input, 4);
                    549:
                    550:        /* Copy data to incoming_packet. */
                    551:        buffer_clear(&incoming_packet);
                    552:        buffer_append_space(&incoming_packet, &cp, padded_len);
                    553:        packet_decrypt(&receive_context, cp, buffer_ptr(&input), padded_len);
                    554:        buffer_consume(&input, padded_len);
1.1       deraadt   555:
                    556: #ifdef PACKET_DEBUG
1.14      markus    557:        fprintf(stderr, "read_poll plain: ");
                    558:        buffer_dump(&incoming_packet);
1.1       deraadt   559: #endif
                    560:
1.14      markus    561:        /* Compute packet checksum. */
                    562:        checksum = crc32((unsigned char *) buffer_ptr(&incoming_packet),
                    563:                         buffer_len(&incoming_packet) - 4);
                    564:
                    565:        /* Skip padding. */
                    566:        buffer_consume(&incoming_packet, 8 - len % 8);
                    567:
                    568:        /* Test check bytes. */
                    569:
                    570:        if (len != buffer_len(&incoming_packet))
                    571:                packet_disconnect("packet_read_poll: len %d != buffer_len %d.",
                    572:                                  len, buffer_len(&incoming_packet));
                    573:
                    574:        ucp = (unsigned char *) buffer_ptr(&incoming_packet) + len - 4;
                    575:        stored_checksum = GET_32BIT(ucp);
                    576:        if (checksum != stored_checksum)
                    577:                packet_disconnect("Corrupted check bytes on input.");
                    578:        buffer_consume_end(&incoming_packet, 4);
                    579:
                    580:        /* If using packet compression, decompress the packet. */
                    581:        if (packet_compression) {
                    582:                buffer_clear(&compression_buffer);
                    583:                buffer_uncompress(&incoming_packet, &compression_buffer);
                    584:                buffer_clear(&incoming_packet);
                    585:                buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
                    586:                              buffer_len(&compression_buffer));
                    587:        }
                    588:        /* Get packet type. */
                    589:        buffer_get(&incoming_packet, &buf[0], 1);
                    590:
                    591:        /* Return length of payload (without type field). */
                    592:        *payload_len_ptr = buffer_len(&incoming_packet);
                    593:
                    594:        /* Handle disconnect message. */
1.17      markus    595:        if ((unsigned char) buf[0] == SSH_MSG_DISCONNECT) {
1.22      markus    596:                msg = packet_get_string(NULL);
                    597:                log("Received disconnect: %.900s", msg);
                    598:                xfree(msg);
1.17      markus    599:                fatal_cleanup();
                    600:        }
1.14      markus    601:
                    602:        /* Ignore ignore messages. */
                    603:        if ((unsigned char) buf[0] == SSH_MSG_IGNORE)
                    604:                goto restart;
                    605:
                    606:        /* Send debug messages as debugging output. */
                    607:        if ((unsigned char) buf[0] == SSH_MSG_DEBUG) {
1.22      markus    608:                msg = packet_get_string(NULL);
                    609:                debug("Remote: %.900s", msg);
                    610:                xfree(msg);
1.14      markus    611:                goto restart;
                    612:        }
                    613:        /* Return type. */
                    614:        return (unsigned char) buf[0];
1.1       deraadt   615: }
1.14      markus    616:
1.16      markus    617: /*
                    618:  * Buffers the given amount of input characters.  This is intended to be used
                    619:  * together with packet_read_poll.
                    620:  */
1.1       deraadt   621:
1.2       provos    622: void
                    623: packet_process_incoming(const char *buf, unsigned int len)
1.1       deraadt   624: {
1.14      markus    625:        buffer_append(&input, buf, len);
1.1       deraadt   626: }
                    627:
                    628: /* Returns a character from the packet. */
                    629:
1.2       provos    630: unsigned int
                    631: packet_get_char()
1.1       deraadt   632: {
1.14      markus    633:        char ch;
                    634:        buffer_get(&incoming_packet, &ch, 1);
                    635:        return (unsigned char) ch;
1.1       deraadt   636: }
                    637:
                    638: /* Returns an integer from the packet data. */
                    639:
1.2       provos    640: unsigned int
                    641: packet_get_int()
1.1       deraadt   642: {
1.14      markus    643:        return buffer_get_int(&incoming_packet);
1.1       deraadt   644: }
                    645:
1.16      markus    646: /*
                    647:  * Returns an arbitrary precision integer from the packet data.  The integer
                    648:  * must have been initialized before this call.
                    649:  */
1.1       deraadt   650:
1.2       provos    651: void
1.14      markus    652: packet_get_bignum(BIGNUM * value, int *length_ptr)
1.1       deraadt   653: {
1.14      markus    654:        *length_ptr = buffer_get_bignum(&incoming_packet, value);
1.24    ! markus    655: }
        !           656:
        !           657: void
        !           658: packet_get_bignum2(BIGNUM * value, int *length_ptr)
        !           659: {
        !           660:        *length_ptr = buffer_get_bignum2(&incoming_packet, value);
        !           661: }
        !           662:
        !           663: char *
        !           664: packet_get_raw(int *length_ptr)
        !           665: {
        !           666:        int bytes = buffer_len(&incoming_packet);
        !           667:        if (length_ptr != NULL)
        !           668:                *length_ptr = bytes;
        !           669:        return buffer_ptr(&incoming_packet);
1.1       deraadt   670: }
                    671:
1.16      markus    672: /*
                    673:  * Returns a string from the packet data.  The string is allocated using
                    674:  * xmalloc; it is the responsibility of the calling program to free it when
                    675:  * no longer needed.  The length_ptr argument may be NULL, or point to an
                    676:  * integer into which the length of the string is stored.
                    677:  */
1.1       deraadt   678:
1.16      markus    679: char *
1.14      markus    680: packet_get_string(unsigned int *length_ptr)
1.1       deraadt   681: {
1.14      markus    682:        return buffer_get_string(&incoming_packet, length_ptr);
1.1       deraadt   683: }
                    684:
1.16      markus    685: /*
                    686:  * Sends a diagnostic message from the server to the client.  This message
                    687:  * can be sent at any time (but not while constructing another message). The
                    688:  * message is printed immediately, but only if the client is being executed
                    689:  * in verbose mode.  These messages are primarily intended to ease debugging
                    690:  * authentication problems.   The length of the formatted message must not
                    691:  * exceed 1024 bytes.  This will automatically call packet_write_wait.
                    692:  */
1.1       deraadt   693:
1.2       provos    694: void
1.14      markus    695: packet_send_debug(const char *fmt,...)
1.1       deraadt   696: {
1.14      markus    697:        char buf[1024];
                    698:        va_list args;
                    699:
                    700:        va_start(args, fmt);
                    701:        vsnprintf(buf, sizeof(buf), fmt, args);
                    702:        va_end(args);
                    703:
                    704:        packet_start(SSH_MSG_DEBUG);
                    705:        packet_put_string(buf, strlen(buf));
                    706:        packet_send();
                    707:        packet_write_wait();
1.1       deraadt   708: }
                    709:
1.16      markus    710: /*
                    711:  * Logs the error plus constructs and sends a disconnect packet, closes the
                    712:  * connection, and exits.  This function never returns. The error message
                    713:  * should not contain a newline.  The length of the formatted message must
                    714:  * not exceed 1024 bytes.
                    715:  */
1.1       deraadt   716:
1.2       provos    717: void
1.14      markus    718: packet_disconnect(const char *fmt,...)
1.1       deraadt   719: {
1.14      markus    720:        char buf[1024];
                    721:        va_list args;
                    722:        static int disconnecting = 0;
                    723:        if (disconnecting)      /* Guard against recursive invocations. */
                    724:                fatal("packet_disconnect called recursively.");
                    725:        disconnecting = 1;
                    726:
1.16      markus    727:        /*
                    728:         * Format the message.  Note that the caller must make sure the
                    729:         * message is of limited size.
                    730:         */
1.14      markus    731:        va_start(args, fmt);
                    732:        vsnprintf(buf, sizeof(buf), fmt, args);
                    733:        va_end(args);
                    734:
                    735:        /* Send the disconnect message to the other side, and wait for it to get sent. */
                    736:        packet_start(SSH_MSG_DISCONNECT);
                    737:        packet_put_string(buf, strlen(buf));
                    738:        packet_send();
                    739:        packet_write_wait();
                    740:
                    741:        /* Stop listening for connections. */
                    742:        channel_stop_listening();
                    743:
                    744:        /* Close the connection. */
                    745:        packet_close();
1.1       deraadt   746:
1.14      markus    747:        /* Display the error locally and exit. */
1.17      markus    748:        log("Disconnecting: %.100s", buf);
                    749:        fatal_cleanup();
1.1       deraadt   750: }
                    751:
1.16      markus    752: /* Checks if there is any buffered output, and tries to write some of the output. */
1.1       deraadt   753:
1.2       provos    754: void
                    755: packet_write_poll()
1.1       deraadt   756: {
1.14      markus    757:        int len = buffer_len(&output);
                    758:        if (len > 0) {
                    759:                len = write(connection_out, buffer_ptr(&output), len);
                    760:                if (len <= 0) {
                    761:                        if (errno == EAGAIN)
                    762:                                return;
                    763:                        else
                    764:                                fatal("Write failed: %.100s", strerror(errno));
                    765:                }
                    766:                buffer_consume(&output, len);
                    767:        }
1.1       deraadt   768: }
                    769:
1.16      markus    770: /*
                    771:  * Calls packet_write_poll repeatedly until all pending output data has been
                    772:  * written.
                    773:  */
1.1       deraadt   774:
1.2       provos    775: void
                    776: packet_write_wait()
1.1       deraadt   777: {
1.14      markus    778:        packet_write_poll();
                    779:        while (packet_have_data_to_write()) {
                    780:                fd_set set;
                    781:                FD_ZERO(&set);
                    782:                FD_SET(connection_out, &set);
                    783:                select(connection_out + 1, NULL, &set, NULL, NULL);
                    784:                packet_write_poll();
                    785:        }
1.1       deraadt   786: }
                    787:
                    788: /* Returns true if there is buffered data to write to the connection. */
                    789:
1.2       provos    790: int
                    791: packet_have_data_to_write()
1.1       deraadt   792: {
1.14      markus    793:        return buffer_len(&output) != 0;
1.1       deraadt   794: }
                    795:
                    796: /* Returns true if there is not too much data to write to the connection. */
                    797:
1.2       provos    798: int
                    799: packet_not_very_much_data_to_write()
1.1       deraadt   800: {
1.14      markus    801:        if (interactive_mode)
                    802:                return buffer_len(&output) < 16384;
                    803:        else
                    804:                return buffer_len(&output) < 128 * 1024;
1.1       deraadt   805: }
                    806:
                    807: /* Informs that the current session is interactive.  Sets IP flags for that. */
                    808:
1.2       provos    809: void
                    810: packet_set_interactive(int interactive, int keepalives)
1.1       deraadt   811: {
1.14      markus    812:        int on = 1;
1.1       deraadt   813:
1.14      markus    814:        /* Record that we are in interactive mode. */
                    815:        interactive_mode = interactive;
1.1       deraadt   816:
1.19      markus    817:        /* Only set socket options if using a socket.  */
                    818:        if (!packet_connection_is_on_socket())
1.14      markus    819:                return;
                    820:        if (keepalives) {
                    821:                /* Set keepalives if requested. */
                    822:                if (setsockopt(connection_in, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
1.19      markus    823:                    sizeof(on)) < 0)
1.14      markus    824:                        error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
                    825:        }
1.19      markus    826:        /*
                    827:         * IPTOS_LOWDELAY, TCP_NODELAY and IPTOS_THROUGHPUT are IPv4 only
                    828:         */
                    829:        if (!packet_connection_is_ipv4())
                    830:                return;
1.14      markus    831:        if (interactive) {
1.16      markus    832:                /*
                    833:                 * Set IP options for an interactive connection.  Use
                    834:                 * IPTOS_LOWDELAY and TCP_NODELAY.
                    835:                 */
1.14      markus    836:                int lowdelay = IPTOS_LOWDELAY;
                    837:                if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &lowdelay,
1.19      markus    838:                    sizeof(lowdelay)) < 0)
1.14      markus    839:                        error("setsockopt IPTOS_LOWDELAY: %.100s", strerror(errno));
                    840:                if (setsockopt(connection_in, IPPROTO_TCP, TCP_NODELAY, (void *) &on,
1.19      markus    841:                    sizeof(on)) < 0)
1.14      markus    842:                        error("setsockopt TCP_NODELAY: %.100s", strerror(errno));
                    843:        } else {
1.16      markus    844:                /*
                    845:                 * Set IP options for a non-interactive connection.  Use
                    846:                 * IPTOS_THROUGHPUT.
                    847:                 */
1.14      markus    848:                int throughput = IPTOS_THROUGHPUT;
                    849:                if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, (void *) &throughput,
1.19      markus    850:                    sizeof(throughput)) < 0)
1.14      markus    851:                        error("setsockopt IPTOS_THROUGHPUT: %.100s", strerror(errno));
                    852:        }
1.1       deraadt   853: }
                    854:
                    855: /* Returns true if the current connection is interactive. */
                    856:
1.2       provos    857: int
                    858: packet_is_interactive()
1.1       deraadt   859: {
1.14      markus    860:        return interactive_mode;
1.12      markus    861: }
                    862:
                    863: int
                    864: packet_set_maxsize(int s)
                    865: {
1.14      markus    866:        static int called = 0;
                    867:        if (called) {
                    868:                log("packet_set_maxsize: called twice: old %d new %d", max_packet_size, s);
                    869:                return -1;
                    870:        }
                    871:        if (s < 4 * 1024 || s > 1024 * 1024) {
                    872:                log("packet_set_maxsize: bad size %d", s);
                    873:                return -1;
                    874:        }
                    875:        log("packet_set_maxsize: setting to %d", s);
                    876:        max_packet_size = s;
                    877:        return s;
1.1       deraadt   878: }