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

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