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

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