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

1.162   ! andreas     1: /* $OpenBSD: packet.c,v 1.161 2009/05/25 06:48:01 andreas Exp $ */
1.1       deraadt     2: /*
1.15      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.35      deraadt     6:  * This file contains code implementing the packet protocol and communication
                      7:  * with the other side.  This same code is used both on client and server side.
1.29      markus      8:  *
1.35      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
1.29      markus     14:  *
1.25      markus     15:  *
                     16:  * SSH2 packet format added by Markus Friedl.
1.69      markus     17:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.25      markus     18:  *
1.35      deraadt    19:  * Redistribution and use in source and binary forms, with or without
                     20:  * modification, are permitted provided that the following conditions
                     21:  * are met:
                     22:  * 1. Redistributions of source code must retain the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer.
                     24:  * 2. Redistributions in binary form must reproduce the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer in the
                     26:  *    documentation and/or other materials provided with the distribution.
                     27:  *
                     28:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     29:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     30:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     31:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     32:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     33:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     34:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     35:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     36:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     37:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.15      deraadt    38:  */
1.1       deraadt    39:
1.142     deraadt    40: #include <sys/types.h>
1.105     markus     41: #include <sys/queue.h>
1.132     stevesk    42: #include <sys/socket.h>
1.138     stevesk    43: #include <sys/time.h>
1.139     stevesk    44: #include <sys/param.h>
1.121     stevesk    45:
                     46: #include <netinet/in_systm.h>
1.132     stevesk    47: #include <netinet/in.h>
1.121     stevesk    48: #include <netinet/ip.h>
1.134     stevesk    49:
1.135     stevesk    50: #include <errno.h>
1.134     stevesk    51: #include <stdarg.h>
1.141     stevesk    52: #include <stdio.h>
1.140     stevesk    53: #include <stdlib.h>
1.137     stevesk    54: #include <string.h>
1.136     stevesk    55: #include <unistd.h>
1.142     deraadt    56: #include <signal.h>
1.1       deraadt    57:
                     58: #include "xmalloc.h"
                     59: #include "buffer.h"
                     60: #include "packet.h"
                     61: #include "crc32.h"
                     62: #include "compress.h"
1.9       dugsong    63: #include "deattack.h"
1.64      markus     64: #include "channels.h"
1.25      markus     65: #include "compat.h"
1.45      markus     66: #include "ssh1.h"
1.25      markus     67: #include "ssh2.h"
1.37      markus     68: #include "cipher.h"
1.142     deraadt    69: #include "key.h"
1.25      markus     70: #include "kex.h"
1.50      markus     71: #include "mac.h"
1.46      markus     72: #include "log.h"
                     73: #include "canohost.h"
1.87      stevesk    74: #include "misc.h"
1.95      markus     75: #include "ssh.h"
1.25      markus     76:
                     77: #ifdef PACKET_DEBUG
                     78: #define DBG(x) x
                     79: #else
                     80: #define DBG(x)
                     81: #endif
                     82:
1.159     markus     83: #define PACKET_MAX_SIZE (256 * 1024)
                     84:
1.161     andreas    85: struct packet_state {
                     86:        u_int32_t seqnr;
                     87:        u_int32_t packets;
                     88:        u_int64_t blocks;
                     89:        u_int64_t bytes;
                     90: };
                     91:
                     92: struct packet {
                     93:        TAILQ_ENTRY(packet) next;
                     94:        u_char type;
                     95:        Buffer payload;
                     96: };
                     97:
                     98: struct session_state {
                     99:        /*
                    100:         * This variable contains the file descriptors used for
                    101:         * communicating with the other side.  connection_in is used for
                    102:         * reading; connection_out for writing.  These can be the same
                    103:         * descriptor, in which case it is assumed to be a socket.
                    104:         */
                    105:        int connection_in;
                    106:        int connection_out;
                    107:
                    108:        /* Protocol flags for the remote side. */
                    109:        u_int remote_protocol_flags;
1.1       deraadt   110:
1.161     andreas   111:        /* Encryption context for receiving data.  Only used for decryption. */
                    112:        CipherContext receive_context;
1.1       deraadt   113:
1.161     andreas   114:        /* Encryption context for sending data.  Only used for encryption. */
                    115:        CipherContext send_context;
1.14      markus    116:
1.161     andreas   117:        /* Buffer for raw input data from the socket. */
                    118:        Buffer input;
1.1       deraadt   119:
1.161     andreas   120:        /* Buffer for raw output data going to the socket. */
                    121:        Buffer output;
1.1       deraadt   122:
1.161     andreas   123:        /* Buffer for the partial outgoing packet being constructed. */
                    124:        Buffer outgoing_packet;
1.1       deraadt   125:
1.161     andreas   126:        /* Buffer for the incoming packet currently being processed. */
                    127:        Buffer incoming_packet;
1.1       deraadt   128:
1.161     andreas   129:        /* Scratch buffer for packet compression/decompression. */
                    130:        Buffer compression_buffer;
                    131:        int compression_buffer_ready;
1.1       deraadt   132:
1.161     andreas   133:        /*
                    134:         * Flag indicating whether packet compression/decompression is
                    135:         * enabled.
                    136:         */
                    137:        int packet_compression;
1.1       deraadt   138:
1.161     andreas   139:        /* default maximum packet size */
                    140:        u_int max_packet_size;
1.1       deraadt   141:
1.161     andreas   142:        /* Flag indicating whether this module has been initialized. */
                    143:        int initialized;
1.12      markus    144:
1.161     andreas   145:        /* Set to true if the connection is interactive. */
                    146:        int interactive_mode;
1.1       deraadt   147:
1.161     andreas   148:        /* Set to true if we are the server side. */
                    149:        int server_side;
1.1       deraadt   150:
1.161     andreas   151:        /* Set to true if we are authenticated. */
                    152:        int after_authentication;
1.118     markus    153:
1.161     andreas   154:        int keep_alive_timeouts;
1.118     markus    155:
1.161     andreas   156:        /* The maximum time that we will wait to send or receive a packet */
                    157:        int packet_timeout_ms;
1.151     dtucker   158:
1.161     andreas   159:        /* Session key information for Encryption and MAC */
                    160:        Newkeys *newkeys[MODE_MAX];
                    161:        struct packet_state p_read, p_send;
1.154     dtucker   162:
1.161     andreas   163:        u_int64_t max_blocks_in, max_blocks_out;
                    164:        u_int32_t rekey_limit;
1.105     markus    165:
1.161     andreas   166:        /* Session key for protocol v1 */
                    167:        u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
                    168:        u_int ssh1_keylen;
1.25      markus    169:
1.161     andreas   170:        /* roundup current message to extra_pad bytes */
                    171:        u_char extra_pad;
1.95      markus    172:
1.161     andreas   173:        /* XXX discard incoming data after MAC error */
                    174:        u_int packet_discard;
                    175:        Mac *packet_discard_mac;
1.71      markus    176:
1.161     andreas   177:        /* Used in packet_read_poll2() */
                    178:        u_int packlen;
1.159     markus    179:
1.161     andreas   180:        TAILQ_HEAD(, packet) outgoing;
1.105     markus    181: };
1.161     andreas   182:
                    183: static struct session_state *active_state;
                    184:
                    185: static struct session_state *
                    186: alloc_session_state()
                    187: {
                    188:     struct session_state *s = xcalloc(1, sizeof(*s));
                    189:
                    190:     s->connection_in = -1;
                    191:     s->connection_out = -1;
                    192:     s->max_packet_size = 32768;
                    193:     s->packet_timeout_ms = -1;
                    194:     return s;
                    195: }
1.105     markus    196:
1.16      markus    197: /*
                    198:  * Sets the descriptors used for communication.  Disables encryption until
                    199:  * packet_set_encryption_key is called.
                    200:  */
1.2       provos    201: void
                    202: packet_set_connection(int fd_in, int fd_out)
1.1       deraadt   203: {
1.37      markus    204:        Cipher *none = cipher_by_name("none");
1.97      deraadt   205:
1.37      markus    206:        if (none == NULL)
                    207:                fatal("packet_set_connection: cannot load cipher 'none'");
1.161     andreas   208:        if (active_state == NULL)
                    209:                active_state = alloc_session_state();
                    210:        active_state->connection_in = fd_in;
                    211:        active_state->connection_out = fd_out;
                    212:        cipher_init(&active_state->send_context, none, (const u_char *)"",
1.113     deraadt   213:            0, NULL, 0, CIPHER_ENCRYPT);
1.161     andreas   214:        cipher_init(&active_state->receive_context, none, (const u_char *)"",
1.113     deraadt   215:            0, NULL, 0, CIPHER_DECRYPT);
1.161     andreas   216:        active_state->newkeys[MODE_IN] = active_state->newkeys[MODE_OUT] = NULL;
                    217:        if (!active_state->initialized) {
                    218:                active_state->initialized = 1;
                    219:                buffer_init(&active_state->input);
                    220:                buffer_init(&active_state->output);
                    221:                buffer_init(&active_state->outgoing_packet);
                    222:                buffer_init(&active_state->incoming_packet);
                    223:                TAILQ_INIT(&active_state->outgoing);
                    224:                active_state->p_send.packets = active_state->p_read.packets = 0;
1.14      markus    225:        }
1.1       deraadt   226: }
                    227:
1.154     dtucker   228: void
                    229: packet_set_timeout(int timeout, int count)
                    230: {
                    231:        if (timeout == 0 || count == 0) {
1.161     andreas   232:                active_state->packet_timeout_ms = -1;
1.154     dtucker   233:                return;
                    234:        }
                    235:        if ((INT_MAX / 1000) / count < timeout)
1.161     andreas   236:                active_state->packet_timeout_ms = INT_MAX;
1.154     dtucker   237:        else
1.161     andreas   238:                active_state->packet_timeout_ms = timeout * count * 1000;
1.154     dtucker   239: }
                    240:
1.159     markus    241: static void
                    242: packet_stop_discard(void)
                    243: {
1.161     andreas   244:        if (active_state->packet_discard_mac) {
1.159     markus    245:                char buf[1024];
                    246:
                    247:                memset(buf, 'a', sizeof(buf));
1.161     andreas   248:                while (buffer_len(&active_state->incoming_packet) <
                    249:                    PACKET_MAX_SIZE)
                    250:                        buffer_append(&active_state->incoming_packet, buf,
                    251:                            sizeof(buf));
                    252:                (void) mac_compute(active_state->packet_discard_mac,
                    253:                    active_state->p_read.seqnr,
                    254:                    buffer_ptr(&active_state->incoming_packet),
1.159     markus    255:                    PACKET_MAX_SIZE);
                    256:        }
                    257:        logit("Finished discarding for %.200s", get_remote_ipaddr());
                    258:        cleanup_exit(255);
                    259: }
                    260:
                    261: static void
                    262: packet_start_discard(Enc *enc, Mac *mac, u_int packet_length, u_int discard)
                    263: {
1.160     markus    264:        if (enc == NULL || !cipher_is_cbc(enc->cipher))
1.159     markus    265:                packet_disconnect("Packet corrupt");
                    266:        if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
1.161     andreas   267:                active_state->packet_discard_mac = mac;
                    268:        if (buffer_len(&active_state->input) >= discard)
1.159     markus    269:                packet_stop_discard();
1.161     andreas   270:        active_state->packet_discard = discard -
                    271:            buffer_len(&active_state->input);
1.159     markus    272: }
                    273:
1.19      markus    274: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    275:
                    276: int
1.73      itojun    277: packet_connection_is_on_socket(void)
1.19      markus    278: {
                    279:        struct sockaddr_storage from, to;
                    280:        socklen_t fromlen, tolen;
                    281:
                    282:        /* filedescriptors in and out are the same, so it's a socket */
1.161     andreas   283:        if (active_state->connection_in == active_state->connection_out)
1.19      markus    284:                return 1;
                    285:        fromlen = sizeof(from);
                    286:        memset(&from, 0, sizeof(from));
1.161     andreas   287:        if (getpeername(active_state->connection_in, (struct sockaddr *)&from,
                    288:            &fromlen) < 0)
1.19      markus    289:                return 0;
                    290:        tolen = sizeof(to);
                    291:        memset(&to, 0, sizeof(to));
1.161     andreas   292:        if (getpeername(active_state->connection_out, (struct sockaddr *)&to,
                    293:            &tolen) < 0)
1.19      markus    294:                return 0;
                    295:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    296:                return 0;
                    297:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    298:                return 0;
                    299:        return 1;
                    300: }
                    301:
1.92      markus    302: /*
1.91      markus    303:  * Exports an IV from the CipherContext required to export the key
                    304:  * state back from the unprivileged child to the privileged parent
                    305:  * process.
                    306:  */
                    307:
                    308: void
                    309: packet_get_keyiv(int mode, u_char *iv, u_int len)
                    310: {
                    311:        CipherContext *cc;
                    312:
                    313:        if (mode == MODE_OUT)
1.161     andreas   314:                cc = &active_state->send_context;
1.91      markus    315:        else
1.161     andreas   316:                cc = &active_state->receive_context;
1.91      markus    317:
                    318:        cipher_get_keyiv(cc, iv, len);
                    319: }
                    320:
                    321: int
                    322: packet_get_keycontext(int mode, u_char *dat)
                    323: {
                    324:        CipherContext *cc;
1.92      markus    325:
1.91      markus    326:        if (mode == MODE_OUT)
1.161     andreas   327:                cc = &active_state->send_context;
1.91      markus    328:        else
1.161     andreas   329:                cc = &active_state->receive_context;
1.91      markus    330:
                    331:        return (cipher_get_keycontext(cc, dat));
                    332: }
                    333:
                    334: void
                    335: packet_set_keycontext(int mode, u_char *dat)
                    336: {
                    337:        CipherContext *cc;
1.92      markus    338:
1.91      markus    339:        if (mode == MODE_OUT)
1.161     andreas   340:                cc = &active_state->send_context;
1.91      markus    341:        else
1.161     andreas   342:                cc = &active_state->receive_context;
1.91      markus    343:
                    344:        cipher_set_keycontext(cc, dat);
                    345: }
                    346:
                    347: int
                    348: packet_get_keyiv_len(int mode)
                    349: {
                    350:        CipherContext *cc;
                    351:
                    352:        if (mode == MODE_OUT)
1.161     andreas   353:                cc = &active_state->send_context;
1.91      markus    354:        else
1.161     andreas   355:                cc = &active_state->receive_context;
1.91      markus    356:
                    357:        return (cipher_get_keyiv_len(cc));
                    358: }
1.125     deraadt   359:
1.91      markus    360: void
                    361: packet_set_iv(int mode, u_char *dat)
                    362: {
                    363:        CipherContext *cc;
                    364:
                    365:        if (mode == MODE_OUT)
1.161     andreas   366:                cc = &active_state->send_context;
1.91      markus    367:        else
1.161     andreas   368:                cc = &active_state->receive_context;
1.91      markus    369:
                    370:        cipher_set_keyiv(cc, dat);
                    371: }
1.125     deraadt   372:
1.91      markus    373: int
1.107     deraadt   374: packet_get_ssh1_cipher(void)
1.91      markus    375: {
1.161     andreas   376:        return (cipher_get_number(active_state->receive_context.cipher));
1.91      markus    377: }
                    378:
1.105     markus    379: void
1.157     markus    380: packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets,
                    381:     u_int64_t *bytes)
1.105     markus    382: {
                    383:        struct packet_state *state;
1.104     markus    384:
1.161     andreas   385:        state = (mode == MODE_IN) ?
                    386:            &active_state->p_read : &active_state->p_send;
1.157     markus    387:        if (seqnr)
                    388:                *seqnr = state->seqnr;
                    389:        if (blocks)
                    390:                *blocks = state->blocks;
                    391:        if (packets)
                    392:                *packets = state->packets;
                    393:        if (bytes)
                    394:                *bytes = state->bytes;
1.91      markus    395: }
                    396:
                    397: void
1.157     markus    398: packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets,
                    399:     u_int64_t bytes)
1.91      markus    400: {
1.105     markus    401:        struct packet_state *state;
                    402:
1.161     andreas   403:        state = (mode == MODE_IN) ?
                    404:            &active_state->p_read : &active_state->p_send;
1.105     markus    405:        state->seqnr = seqnr;
                    406:        state->blocks = blocks;
                    407:        state->packets = packets;
1.157     markus    408:        state->bytes = bytes;
1.91      markus    409: }
                    410:
1.19      markus    411: /* returns 1 if connection is via ipv4 */
                    412:
                    413: int
1.73      itojun    414: packet_connection_is_ipv4(void)
1.19      markus    415: {
                    416:        struct sockaddr_storage to;
1.21      deraadt   417:        socklen_t tolen = sizeof(to);
1.19      markus    418:
                    419:        memset(&to, 0, sizeof(to));
1.161     andreas   420:        if (getsockname(active_state->connection_out, (struct sockaddr *)&to,
                    421:            &tolen) < 0)
1.19      markus    422:                return 0;
                    423:        if (to.ss_family != AF_INET)
                    424:                return 0;
                    425:        return 1;
                    426: }
                    427:
1.1       deraadt   428: /* Sets the connection into non-blocking mode. */
                    429:
1.2       provos    430: void
1.73      itojun    431: packet_set_nonblocking(void)
1.1       deraadt   432: {
1.14      markus    433:        /* Set the socket into non-blocking mode. */
1.161     andreas   434:        set_nonblock(active_state->connection_in);
1.14      markus    435:
1.161     andreas   436:        if (active_state->connection_out != active_state->connection_in)
                    437:                set_nonblock(active_state->connection_out);
1.1       deraadt   438: }
                    439:
                    440: /* Returns the socket used for reading. */
                    441:
1.2       provos    442: int
1.73      itojun    443: packet_get_connection_in(void)
1.1       deraadt   444: {
1.161     andreas   445:        return active_state->connection_in;
1.1       deraadt   446: }
                    447:
                    448: /* Returns the descriptor used for writing. */
                    449:
1.2       provos    450: int
1.73      itojun    451: packet_get_connection_out(void)
1.1       deraadt   452: {
1.161     andreas   453:        return active_state->connection_out;
1.1       deraadt   454: }
                    455:
                    456: /* Closes the connection and clears and frees internal data structures. */
                    457:
1.2       provos    458: void
1.73      itojun    459: packet_close(void)
1.1       deraadt   460: {
1.161     andreas   461:        if (!active_state->initialized)
1.14      markus    462:                return;
1.161     andreas   463:        active_state->initialized = 0;
                    464:        if (active_state->connection_in == active_state->connection_out) {
                    465:                shutdown(active_state->connection_out, SHUT_RDWR);
                    466:                close(active_state->connection_out);
1.14      markus    467:        } else {
1.161     andreas   468:                close(active_state->connection_in);
                    469:                close(active_state->connection_out);
1.14      markus    470:        }
1.161     andreas   471:        buffer_free(&active_state->input);
                    472:        buffer_free(&active_state->output);
                    473:        buffer_free(&active_state->outgoing_packet);
                    474:        buffer_free(&active_state->incoming_packet);
                    475:        if (active_state->compression_buffer_ready) {
                    476:                buffer_free(&active_state->compression_buffer);
1.14      markus    477:                buffer_compress_uninit();
                    478:        }
1.161     andreas   479:        cipher_cleanup(&active_state->send_context);
                    480:        cipher_cleanup(&active_state->receive_context);
1.1       deraadt   481: }
                    482:
                    483: /* Sets remote side protocol flags. */
                    484:
1.2       provos    485: void
1.40      markus    486: packet_set_protocol_flags(u_int protocol_flags)
1.1       deraadt   487: {
1.161     andreas   488:        active_state->remote_protocol_flags = protocol_flags;
1.1       deraadt   489: }
                    490:
                    491: /* Returns the remote protocol flags set earlier by the above function. */
                    492:
1.40      markus    493: u_int
1.73      itojun    494: packet_get_protocol_flags(void)
1.1       deraadt   495: {
1.161     andreas   496:        return active_state->remote_protocol_flags;
1.1       deraadt   497: }
                    498:
1.16      markus    499: /*
                    500:  * Starts packet compression from the next packet on in both directions.
                    501:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    502:  */
1.1       deraadt   503:
1.68      itojun    504: static void
                    505: packet_init_compression(void)
1.60      markus    506: {
1.161     andreas   507:        if (active_state->compression_buffer_ready == 1)
1.60      markus    508:                return;
1.161     andreas   509:        active_state->compression_buffer_ready = 1;
                    510:        buffer_init(&active_state->compression_buffer);
1.60      markus    511: }
                    512:
1.2       provos    513: void
                    514: packet_start_compression(int level)
1.1       deraadt   515: {
1.161     andreas   516:        if (active_state->packet_compression && !compat20)
1.14      markus    517:                fatal("Compression already enabled.");
1.161     andreas   518:        active_state->packet_compression = 1;
1.60      markus    519:        packet_init_compression();
                    520:        buffer_compress_init_send(level);
                    521:        buffer_compress_init_recv();
1.1       deraadt   522: }
                    523:
1.16      markus    524: /*
                    525:  * Causes any further packets to be encrypted using the given key.  The same
                    526:  * key is used for both sending and reception.  However, both directions are
                    527:  * encrypted independently of each other.
                    528:  */
1.95      markus    529:
1.2       provos    530: void
1.40      markus    531: packet_set_encryption_key(const u_char *key, u_int keylen,
1.37      markus    532:     int number)
1.1       deraadt   533: {
1.37      markus    534:        Cipher *cipher = cipher_by_number(number);
1.97      deraadt   535:
1.37      markus    536:        if (cipher == NULL)
                    537:                fatal("packet_set_encryption_key: unknown cipher number %d", number);
1.25      markus    538:        if (keylen < 20)
1.37      markus    539:                fatal("packet_set_encryption_key: keylen too small: %d", keylen);
1.95      markus    540:        if (keylen > SSH_SESSION_KEY_LENGTH)
                    541:                fatal("packet_set_encryption_key: keylen too big: %d", keylen);
1.161     andreas   542:        memcpy(active_state->ssh1_key, key, keylen);
                    543:        active_state->ssh1_keylen = keylen;
                    544:        cipher_init(&active_state->send_context, cipher, key, keylen, NULL,
                    545:            0, CIPHER_ENCRYPT);
                    546:        cipher_init(&active_state->receive_context, cipher, key, keylen, NULL,
                    547:            0, CIPHER_DECRYPT);
1.95      markus    548: }
                    549:
                    550: u_int
                    551: packet_get_encryption_key(u_char *key)
                    552: {
                    553:        if (key == NULL)
1.161     andreas   554:                return (active_state->ssh1_keylen);
                    555:        memcpy(key, active_state->ssh1_key, active_state->ssh1_keylen);
                    556:        return (active_state->ssh1_keylen);
1.1       deraadt   557: }
                    558:
1.62      markus    559: /* Start constructing a packet to send. */
1.2       provos    560: void
1.62      markus    561: packet_start(u_char type)
1.1       deraadt   562: {
1.62      markus    563:        u_char buf[9];
                    564:        int len;
1.1       deraadt   565:
1.62      markus    566:        DBG(debug("packet_start[%d]", type));
                    567:        len = compat20 ? 6 : 9;
                    568:        memset(buf, 0, len - 1);
                    569:        buf[len - 1] = type;
1.161     andreas   570:        buffer_clear(&active_state->outgoing_packet);
                    571:        buffer_append(&active_state->outgoing_packet, buf, len);
1.25      markus    572: }
                    573:
1.62      markus    574: /* Append payload. */
1.2       provos    575: void
                    576: packet_put_char(int value)
1.1       deraadt   577: {
1.14      markus    578:        char ch = value;
1.97      deraadt   579:
1.161     andreas   580:        buffer_append(&active_state->outgoing_packet, &ch, 1);
1.1       deraadt   581: }
1.125     deraadt   582:
1.2       provos    583: void
1.40      markus    584: packet_put_int(u_int value)
1.1       deraadt   585: {
1.161     andreas   586:        buffer_put_int(&active_state->outgoing_packet, value);
1.1       deraadt   587: }
1.125     deraadt   588:
1.2       provos    589: void
1.162   ! andreas   590: packet_put_int64(u_int64_t value)
        !           591: {
        !           592:        buffer_put_int64(&active_state->outgoing_packet, value);
        !           593: }
        !           594:
        !           595: void
1.76      stevesk   596: packet_put_string(const void *buf, u_int len)
1.1       deraadt   597: {
1.161     andreas   598:        buffer_put_string(&active_state->outgoing_packet, buf, len);
1.1       deraadt   599: }
1.125     deraadt   600:
1.24      markus    601: void
                    602: packet_put_cstring(const char *str)
                    603: {
1.161     andreas   604:        buffer_put_cstring(&active_state->outgoing_packet, str);
1.24      markus    605: }
1.125     deraadt   606:
1.24      markus    607: void
1.76      stevesk   608: packet_put_raw(const void *buf, u_int len)
1.24      markus    609: {
1.161     andreas   610:        buffer_append(&active_state->outgoing_packet, buf, len);
1.24      markus    611: }
1.125     deraadt   612:
1.2       provos    613: void
1.14      markus    614: packet_put_bignum(BIGNUM * value)
1.1       deraadt   615: {
1.161     andreas   616:        buffer_put_bignum(&active_state->outgoing_packet, value);
1.1       deraadt   617: }
1.125     deraadt   618:
1.24      markus    619: void
                    620: packet_put_bignum2(BIGNUM * value)
                    621: {
1.161     andreas   622:        buffer_put_bignum2(&active_state->outgoing_packet, value);
1.24      markus    623: }
1.1       deraadt   624:
1.16      markus    625: /*
                    626:  * Finalizes and sends the packet.  If the encryption key has been set,
                    627:  * encrypts the packet before sending.
                    628:  */
1.14      markus    629:
1.68      itojun    630: static void
1.49      itojun    631: packet_send1(void)
1.1       deraadt   632: {
1.89      markus    633:        u_char buf[8], *cp;
1.14      markus    634:        int i, padding, len;
1.40      markus    635:        u_int checksum;
1.115     avsm      636:        u_int32_t rnd = 0;
1.14      markus    637:
1.16      markus    638:        /*
                    639:         * If using packet compression, compress the payload of the outgoing
                    640:         * packet.
                    641:         */
1.161     andreas   642:        if (active_state->packet_compression) {
                    643:                buffer_clear(&active_state->compression_buffer);
1.14      markus    644:                /* Skip padding. */
1.161     andreas   645:                buffer_consume(&active_state->outgoing_packet, 8);
1.14      markus    646:                /* padding */
1.161     andreas   647:                buffer_append(&active_state->compression_buffer,
                    648:                    "\0\0\0\0\0\0\0\0", 8);
                    649:                buffer_compress(&active_state->outgoing_packet,
                    650:                    &active_state->compression_buffer);
                    651:                buffer_clear(&active_state->outgoing_packet);
                    652:                buffer_append(&active_state->outgoing_packet,
                    653:                    buffer_ptr(&active_state->compression_buffer),
                    654:                    buffer_len(&active_state->compression_buffer));
1.14      markus    655:        }
                    656:        /* Compute packet length without padding (add checksum, remove padding). */
1.161     andreas   657:        len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
1.14      markus    658:
1.32      markus    659:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    660:        padding = 8 - len % 8;
1.161     andreas   661:        if (!active_state->send_context.plaintext) {
                    662:                cp = buffer_ptr(&active_state->outgoing_packet);
1.14      markus    663:                for (i = 0; i < padding; i++) {
                    664:                        if (i % 4 == 0)
1.115     avsm      665:                                rnd = arc4random();
                    666:                        cp[7 - i] = rnd & 0xff;
                    667:                        rnd >>= 8;
1.14      markus    668:                }
                    669:        }
1.161     andreas   670:        buffer_consume(&active_state->outgoing_packet, 8 - padding);
1.14      markus    671:
                    672:        /* Add check bytes. */
1.161     andreas   673:        checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
                    674:            buffer_len(&active_state->outgoing_packet));
1.131     djm       675:        put_u32(buf, checksum);
1.161     andreas   676:        buffer_append(&active_state->outgoing_packet, buf, 4);
1.1       deraadt   677:
                    678: #ifdef PACKET_DEBUG
1.14      markus    679:        fprintf(stderr, "packet_send plain: ");
1.161     andreas   680:        buffer_dump(&active_state->outgoing_packet);
1.1       deraadt   681: #endif
                    682:
1.14      markus    683:        /* Append to output. */
1.131     djm       684:        put_u32(buf, len);
1.161     andreas   685:        buffer_append(&active_state->output, buf, 4);
                    686:        cp = buffer_append_space(&active_state->output,
                    687:            buffer_len(&active_state->outgoing_packet));
                    688:        cipher_crypt(&active_state->send_context, cp,
                    689:            buffer_ptr(&active_state->outgoing_packet),
                    690:            buffer_len(&active_state->outgoing_packet));
1.14      markus    691:
1.1       deraadt   692: #ifdef PACKET_DEBUG
1.14      markus    693:        fprintf(stderr, "encrypted: ");
1.161     andreas   694:        buffer_dump(&active_state->output);
1.1       deraadt   695: #endif
1.161     andreas   696:        active_state->p_send.packets++;
                    697:        active_state->p_send.bytes += len +
                    698:            buffer_len(&active_state->outgoing_packet);
                    699:        buffer_clear(&active_state->outgoing_packet);
1.1       deraadt   700:
1.16      markus    701:        /*
1.120     djm       702:         * Note that the packet is now only buffered in output.  It won't be
1.16      markus    703:         * actually sent until packet_write_wait or packet_write_poll is
                    704:         * called.
                    705:         */
1.1       deraadt   706: }
                    707:
1.91      markus    708: void
1.57      markus    709: set_newkeys(int mode)
                    710: {
                    711:        Enc *enc;
                    712:        Mac *mac;
                    713:        Comp *comp;
                    714:        CipherContext *cc;
1.105     markus    715:        u_int64_t *max_blocks;
1.115     avsm      716:        int crypt_type;
1.57      markus    717:
1.100     markus    718:        debug2("set_newkeys: mode %d", mode);
1.57      markus    719:
1.88      markus    720:        if (mode == MODE_OUT) {
1.161     andreas   721:                cc = &active_state->send_context;
1.115     avsm      722:                crypt_type = CIPHER_ENCRYPT;
1.161     andreas   723:                active_state->p_send.packets = active_state->p_send.blocks = 0;
                    724:                max_blocks = &active_state->max_blocks_out;
1.88      markus    725:        } else {
1.161     andreas   726:                cc = &active_state->receive_context;
1.115     avsm      727:                crypt_type = CIPHER_DECRYPT;
1.161     andreas   728:                active_state->p_read.packets = active_state->p_read.blocks = 0;
                    729:                max_blocks = &active_state->max_blocks_in;
1.88      markus    730:        }
1.161     andreas   731:        if (active_state->newkeys[mode] != NULL) {
1.100     markus    732:                debug("set_newkeys: rekeying");
1.88      markus    733:                cipher_cleanup(cc);
1.161     andreas   734:                enc  = &active_state->newkeys[mode]->enc;
                    735:                mac  = &active_state->newkeys[mode]->mac;
                    736:                comp = &active_state->newkeys[mode]->comp;
1.148     pvalchev  737:                mac_clear(mac);
1.59      markus    738:                xfree(enc->name);
                    739:                xfree(enc->iv);
                    740:                xfree(enc->key);
                    741:                xfree(mac->name);
                    742:                xfree(mac->key);
                    743:                xfree(comp->name);
1.161     andreas   744:                xfree(active_state->newkeys[mode]);
1.57      markus    745:        }
1.161     andreas   746:        active_state->newkeys[mode] = kex_get_newkeys(mode);
                    747:        if (active_state->newkeys[mode] == NULL)
1.57      markus    748:                fatal("newkeys: no keys for mode %d", mode);
1.161     andreas   749:        enc  = &active_state->newkeys[mode]->enc;
                    750:        mac  = &active_state->newkeys[mode]->mac;
                    751:        comp = &active_state->newkeys[mode]->comp;
1.148     pvalchev  752:        if (mac_init(mac) == 0)
1.57      markus    753:                mac->enabled = 1;
                    754:        DBG(debug("cipher_init_context: %d", mode));
1.88      markus    755:        cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1.115     avsm      756:            enc->iv, enc->block_size, crypt_type);
1.91      markus    757:        /* Deleting the keys does not gain extra security */
                    758:        /* memset(enc->iv,  0, enc->block_size);
1.147     djm       759:           memset(enc->key, 0, enc->key_len);
                    760:           memset(mac->key, 0, mac->key_len); */
1.118     markus    761:        if ((comp->type == COMP_ZLIB ||
1.161     andreas   762:            (comp->type == COMP_DELAYED &&
                    763:             active_state->after_authentication)) && comp->enabled == 0) {
1.60      markus    764:                packet_init_compression();
                    765:                if (mode == MODE_OUT)
                    766:                        buffer_compress_init_send(6);
                    767:                else
                    768:                        buffer_compress_init_recv();
1.57      markus    769:                comp->enabled = 1;
                    770:        }
1.109     markus    771:        /*
                    772:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    773:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    774:         */
                    775:        if (enc->block_size >= 16)
                    776:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    777:        else
                    778:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.161     andreas   779:        if (active_state->rekey_limit)
                    780:                *max_blocks = MIN(*max_blocks,
                    781:                    active_state->rekey_limit / enc->block_size);
1.57      markus    782: }
                    783:
1.16      markus    784: /*
1.118     markus    785:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker   786:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus    787:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                    788:  */
                    789: static void
                    790: packet_enable_delayed_compress(void)
                    791: {
                    792:        Comp *comp = NULL;
                    793:        int mode;
                    794:
                    795:        /*
                    796:         * Remember that we are past the authentication step, so rekeying
                    797:         * with COMP_DELAYED will turn on compression immediately.
                    798:         */
1.161     andreas   799:        active_state->after_authentication = 1;
1.118     markus    800:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus    801:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1.161     andreas   802:                if (active_state->newkeys[mode] == NULL)
1.145     markus    803:                        continue;
1.161     andreas   804:                comp = &active_state->newkeys[mode]->comp;
1.118     markus    805:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.119     markus    806:                        packet_init_compression();
1.118     markus    807:                        if (mode == MODE_OUT)
                    808:                                buffer_compress_init_send(6);
                    809:                        else
                    810:                                buffer_compress_init_recv();
                    811:                        comp->enabled = 1;
                    812:                }
                    813:        }
                    814: }
                    815:
                    816: /*
1.25      markus    817:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                    818:  */
1.68      itojun    819: static void
1.105     markus    820: packet_send2_wrapped(void)
1.25      markus    821: {
1.89      markus    822:        u_char type, *cp, *macbuf = NULL;
1.71      markus    823:        u_char padlen, pad;
1.40      markus    824:        u_int packet_length = 0;
1.71      markus    825:        u_int i, len;
1.115     avsm      826:        u_int32_t rnd = 0;
1.25      markus    827:        Enc *enc   = NULL;
                    828:        Mac *mac   = NULL;
                    829:        Comp *comp = NULL;
                    830:        int block_size;
                    831:
1.161     andreas   832:        if (active_state->newkeys[MODE_OUT] != NULL) {
                    833:                enc  = &active_state->newkeys[MODE_OUT]->enc;
                    834:                mac  = &active_state->newkeys[MODE_OUT]->mac;
                    835:                comp = &active_state->newkeys[MODE_OUT]->comp;
1.25      markus    836:        }
1.88      markus    837:        block_size = enc ? enc->block_size : 8;
1.25      markus    838:
1.161     andreas   839:        cp = buffer_ptr(&active_state->outgoing_packet);
1.89      markus    840:        type = cp[5];
1.25      markus    841:
                    842: #ifdef PACKET_DEBUG
                    843:        fprintf(stderr, "plain:     ");
1.161     andreas   844:        buffer_dump(&active_state->outgoing_packet);
1.25      markus    845: #endif
                    846:
                    847:        if (comp && comp->enabled) {
1.161     andreas   848:                len = buffer_len(&active_state->outgoing_packet);
1.25      markus    849:                /* skip header, compress only payload */
1.161     andreas   850:                buffer_consume(&active_state->outgoing_packet, 5);
                    851:                buffer_clear(&active_state->compression_buffer);
                    852:                buffer_compress(&active_state->outgoing_packet,
                    853:                    &active_state->compression_buffer);
                    854:                buffer_clear(&active_state->outgoing_packet);
                    855:                buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
                    856:                buffer_append(&active_state->outgoing_packet,
                    857:                    buffer_ptr(&active_state->compression_buffer),
                    858:                    buffer_len(&active_state->compression_buffer));
1.25      markus    859:                DBG(debug("compression: raw %d compressed %d", len,
1.161     andreas   860:                    buffer_len(&active_state->outgoing_packet)));
1.25      markus    861:        }
                    862:
                    863:        /* sizeof (packet_len + pad_len + payload) */
1.161     andreas   864:        len = buffer_len(&active_state->outgoing_packet);
1.25      markus    865:
                    866:        /*
                    867:         * calc size of padding, alloc space, get random data,
                    868:         * minimum padding is 4 bytes
                    869:         */
                    870:        padlen = block_size - (len % block_size);
                    871:        if (padlen < 4)
                    872:                padlen += block_size;
1.161     andreas   873:        if (active_state->extra_pad) {
1.71      markus    874:                /* will wrap if extra_pad+padlen > 255 */
1.161     andreas   875:                active_state->extra_pad =
                    876:                    roundup(active_state->extra_pad, block_size);
                    877:                pad = active_state->extra_pad -
                    878:                    ((len + padlen) % active_state->extra_pad);
1.93      markus    879:                debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
1.161     andreas   880:                    pad, len, padlen, active_state->extra_pad);
1.71      markus    881:                padlen += pad;
1.161     andreas   882:                active_state->extra_pad = 0;
1.71      markus    883:        }
1.161     andreas   884:        cp = buffer_append_space(&active_state->outgoing_packet, padlen);
                    885:        if (enc && !active_state->send_context.plaintext) {
1.32      markus    886:                /* random padding */
1.25      markus    887:                for (i = 0; i < padlen; i++) {
                    888:                        if (i % 4 == 0)
1.115     avsm      889:                                rnd = arc4random();
                    890:                        cp[i] = rnd & 0xff;
                    891:                        rnd >>= 8;
1.25      markus    892:                }
1.32      markus    893:        } else {
                    894:                /* clear padding */
                    895:                memset(cp, 0, padlen);
1.25      markus    896:        }
                    897:        /* packet_length includes payload, padding and padding length field */
1.161     andreas   898:        packet_length = buffer_len(&active_state->outgoing_packet) - 4;
                    899:        cp = buffer_ptr(&active_state->outgoing_packet);
1.131     djm       900:        put_u32(cp, packet_length);
1.89      markus    901:        cp[4] = padlen;
1.25      markus    902:        DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
                    903:
                    904:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
                    905:        if (mac && mac->enabled) {
1.161     andreas   906:                macbuf = mac_compute(mac, active_state->p_send.seqnr,
                    907:                    buffer_ptr(&active_state->outgoing_packet),
                    908:                    buffer_len(&active_state->outgoing_packet));
                    909:                DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
1.25      markus    910:        }
                    911:        /* encrypt packet and append to output buffer. */
1.161     andreas   912:        cp = buffer_append_space(&active_state->output,
                    913:            buffer_len(&active_state->outgoing_packet));
                    914:        cipher_crypt(&active_state->send_context, cp,
                    915:            buffer_ptr(&active_state->outgoing_packet),
                    916:            buffer_len(&active_state->outgoing_packet));
1.25      markus    917:        /* append unencrypted MAC */
                    918:        if (mac && mac->enabled)
1.161     andreas   919:                buffer_append(&active_state->output, macbuf, mac->mac_len);
1.25      markus    920: #ifdef PACKET_DEBUG
                    921:        fprintf(stderr, "encrypted: ");
1.161     andreas   922:        buffer_dump(&active_state->output);
1.25      markus    923: #endif
1.29      markus    924:        /* increment sequence number for outgoing packets */
1.161     andreas   925:        if (++active_state->p_send.seqnr == 0)
1.106     itojun    926:                logit("outgoing seqnr wraps around");
1.161     andreas   927:        if (++active_state->p_send.packets == 0)
1.105     markus    928:                if (!(datafellows & SSH_BUG_NOREKEY))
                    929:                        fatal("XXX too many packets with same key");
1.161     andreas   930:        active_state->p_send.blocks += (packet_length + 4) / block_size;
                    931:        active_state->p_send.bytes += packet_length + 4;
                    932:        buffer_clear(&active_state->outgoing_packet);
1.25      markus    933:
1.57      markus    934:        if (type == SSH2_MSG_NEWKEYS)
                    935:                set_newkeys(MODE_OUT);
1.161     andreas   936:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
1.118     markus    937:                packet_enable_delayed_compress();
1.25      markus    938: }
                    939:
1.105     markus    940: static void
                    941: packet_send2(void)
                    942: {
                    943:        static int rekeying = 0;
                    944:        struct packet *p;
                    945:        u_char type, *cp;
                    946:
1.161     andreas   947:        cp = buffer_ptr(&active_state->outgoing_packet);
1.105     markus    948:        type = cp[5];
                    949:
                    950:        /* during rekeying we can only send key exchange messages */
                    951:        if (rekeying) {
                    952:                if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
                    953:                    (type <= SSH2_MSG_TRANSPORT_MAX))) {
                    954:                        debug("enqueue packet: %u", type);
                    955:                        p = xmalloc(sizeof(*p));
                    956:                        p->type = type;
1.161     andreas   957:                        memcpy(&p->payload, &active_state->outgoing_packet,
                    958:                            sizeof(Buffer));
                    959:                        buffer_init(&active_state->outgoing_packet);
                    960:                        TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1.105     markus    961:                        return;
                    962:                }
                    963:        }
                    964:
                    965:        /* rekeying starts with sending KEXINIT */
                    966:        if (type == SSH2_MSG_KEXINIT)
                    967:                rekeying = 1;
                    968:
                    969:        packet_send2_wrapped();
                    970:
                    971:        /* after a NEWKEYS message we can send the complete queue */
                    972:        if (type == SSH2_MSG_NEWKEYS) {
                    973:                rekeying = 0;
1.161     andreas   974:                while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1.105     markus    975:                        type = p->type;
                    976:                        debug("dequeue packet: %u", type);
1.161     andreas   977:                        buffer_free(&active_state->outgoing_packet);
                    978:                        memcpy(&active_state->outgoing_packet, &p->payload,
1.105     markus    979:                            sizeof(Buffer));
1.161     andreas   980:                        TAILQ_REMOVE(&active_state->outgoing, p, next);
1.105     markus    981:                        xfree(p);
                    982:                        packet_send2_wrapped();
                    983:                }
                    984:        }
                    985: }
                    986:
1.25      markus    987: void
1.73      itojun    988: packet_send(void)
1.25      markus    989: {
1.62      markus    990:        if (compat20)
1.25      markus    991:                packet_send2();
                    992:        else
                    993:                packet_send1();
                    994:        DBG(debug("packet_send done"));
                    995: }
                    996:
                    997: /*
1.16      markus    998:  * Waits until a packet has been received, and returns its type.  Note that
                    999:  * no other data is processed until this returns, so this function should not
                   1000:  * be used during the interactive session.
                   1001:  */
1.1       deraadt  1002:
1.2       provos   1003: int
1.82      markus   1004: packet_read_seqnr(u_int32_t *seqnr_p)
1.1       deraadt  1005: {
1.154     dtucker  1006:        int type, len, ret, ms_remain;
1.56      millert  1007:        fd_set *setp;
1.14      markus   1008:        char buf[8192];
1.155     deraadt  1009:        struct timeval timeout, start, *timeoutp = NULL;
                   1010:
1.25      markus   1011:        DBG(debug("packet_read()"));
1.14      markus   1012:
1.161     andreas  1013:        setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
                   1014:            NFDBITS), sizeof(fd_mask));
1.56      millert  1015:
1.14      markus   1016:        /* Since we are blocking, ensure that all written packets have been sent. */
                   1017:        packet_write_wait();
                   1018:
                   1019:        /* Stay in the loop until we have received a complete packet. */
                   1020:        for (;;) {
                   1021:                /* Try to read a packet from the buffer. */
1.82      markus   1022:                type = packet_read_poll_seqnr(seqnr_p);
1.62      markus   1023:                if (!compat20 && (
1.32      markus   1024:                    type == SSH_SMSG_SUCCESS
1.14      markus   1025:                    || type == SSH_SMSG_FAILURE
                   1026:                    || type == SSH_CMSG_EOF
1.32      markus   1027:                    || type == SSH_CMSG_EXIT_CONFIRMATION))
1.79      markus   1028:                        packet_check_eom();
1.14      markus   1029:                /* If we got a packet, return it. */
1.56      millert  1030:                if (type != SSH_MSG_NONE) {
                   1031:                        xfree(setp);
1.14      markus   1032:                        return type;
1.56      millert  1033:                }
1.16      markus   1034:                /*
                   1035:                 * Otherwise, wait for some data to arrive, add it to the
                   1036:                 * buffer, and try again.
                   1037:                 */
1.161     andreas  1038:                memset(setp, 0, howmany(active_state->connection_in + 1,
                   1039:                    NFDBITS) * sizeof(fd_mask));
                   1040:                FD_SET(active_state->connection_in, setp);
1.16      markus   1041:
1.161     andreas  1042:                if (active_state->packet_timeout_ms > 0) {
                   1043:                        ms_remain = active_state->packet_timeout_ms;
1.154     dtucker  1044:                        timeoutp = &timeout;
                   1045:                }
1.14      markus   1046:                /* Wait for some data to arrive. */
1.154     dtucker  1047:                for (;;) {
1.161     andreas  1048:                        if (active_state->packet_timeout_ms != -1) {
1.154     dtucker  1049:                                ms_to_timeval(&timeout, ms_remain);
                   1050:                                gettimeofday(&start, NULL);
                   1051:                        }
1.161     andreas  1052:                        if ((ret = select(active_state->connection_in + 1, setp,
                   1053:                            NULL, NULL, timeoutp)) >= 0)
1.154     dtucker  1054:                                break;
1.161     andreas  1055:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1056:                                break;
1.161     andreas  1057:                        if (active_state->packet_timeout_ms == -1)
1.154     dtucker  1058:                                continue;
                   1059:                        ms_subtract_diff(&start, &ms_remain);
                   1060:                        if (ms_remain <= 0) {
                   1061:                                ret = 0;
                   1062:                                break;
                   1063:                        }
                   1064:                }
                   1065:                if (ret == 0) {
                   1066:                        logit("Connection to %.200s timed out while "
                   1067:                            "waiting to read", get_remote_ipaddr());
                   1068:                        cleanup_exit(255);
                   1069:                }
1.14      markus   1070:                /* Read data from the socket. */
1.161     andreas  1071:                len = read(active_state->connection_in, buf, sizeof(buf));
1.18      markus   1072:                if (len == 0) {
1.106     itojun   1073:                        logit("Connection closed by %.200s", get_remote_ipaddr());
1.112     markus   1074:                        cleanup_exit(255);
1.18      markus   1075:                }
1.14      markus   1076:                if (len < 0)
                   1077:                        fatal("Read from socket failed: %.100s", strerror(errno));
                   1078:                /* Append it to the buffer. */
                   1079:                packet_process_incoming(buf, len);
                   1080:        }
                   1081:        /* NOTREACHED */
1.1       deraadt  1082: }
                   1083:
1.77      djm      1084: int
1.82      markus   1085: packet_read(void)
1.77      djm      1086: {
1.82      markus   1087:        return packet_read_seqnr(NULL);
1.77      djm      1088: }
                   1089:
1.16      markus   1090: /*
                   1091:  * Waits until a packet has been received, verifies that its type matches
                   1092:  * that given, and gives a fatal error and exits if there is a mismatch.
                   1093:  */
1.1       deraadt  1094:
1.2       provos   1095: void
1.82      markus   1096: packet_read_expect(int expected_type)
1.1       deraadt  1097: {
1.14      markus   1098:        int type;
1.1       deraadt  1099:
1.82      markus   1100:        type = packet_read();
1.14      markus   1101:        if (type != expected_type)
                   1102:                packet_disconnect("Protocol error: expected packet type %d, got %d",
1.25      markus   1103:                    expected_type, type);
1.1       deraadt  1104: }
                   1105:
                   1106: /* Checks if a full packet is available in the data received so far via
1.14      markus   1107:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                   1108:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                   1109:  *
1.150     dtucker  1110:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                   1111:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                   1112:  * to higher levels.
1.14      markus   1113:  */
1.1       deraadt  1114:
1.68      itojun   1115: static int
1.82      markus   1116: packet_read_poll1(void)
1.1       deraadt  1117: {
1.40      markus   1118:        u_int len, padded_len;
1.89      markus   1119:        u_char *cp, type;
1.40      markus   1120:        u_int checksum, stored_checksum;
1.14      markus   1121:
                   1122:        /* Check if input size is less than minimum packet size. */
1.161     andreas  1123:        if (buffer_len(&active_state->input) < 4 + 8)
1.14      markus   1124:                return SSH_MSG_NONE;
                   1125:        /* Get length of incoming packet. */
1.161     andreas  1126:        cp = buffer_ptr(&active_state->input);
1.131     djm      1127:        len = get_u32(cp);
1.14      markus   1128:        if (len < 1 + 2 + 2 || len > 256 * 1024)
1.98      markus   1129:                packet_disconnect("Bad packet length %u.", len);
1.14      markus   1130:        padded_len = (len + 8) & ~7;
                   1131:
                   1132:        /* Check if the packet has been entirely received. */
1.161     andreas  1133:        if (buffer_len(&active_state->input) < 4 + padded_len)
1.14      markus   1134:                return SSH_MSG_NONE;
                   1135:
                   1136:        /* The entire packet is in buffer. */
                   1137:
                   1138:        /* Consume packet length. */
1.161     andreas  1139:        buffer_consume(&active_state->input, 4);
1.14      markus   1140:
1.62      markus   1141:        /*
                   1142:         * Cryptographic attack detector for ssh
                   1143:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                   1144:         * Ariel Futoransky(futo@core-sdi.com)
                   1145:         */
1.161     andreas  1146:        if (!active_state->receive_context.plaintext) {
                   1147:                switch (detect_attack(buffer_ptr(&active_state->input),
                   1148:                    padded_len)) {
1.144     djm      1149:                case DEATTACK_DETECTED:
                   1150:                        packet_disconnect("crc32 compensation attack: "
                   1151:                            "network attack detected");
                   1152:                case DEATTACK_DOS_DETECTED:
                   1153:                        packet_disconnect("deattack denial of "
                   1154:                            "service detected");
                   1155:                }
                   1156:        }
1.62      markus   1157:
                   1158:        /* Decrypt data to incoming_packet. */
1.161     andreas  1159:        buffer_clear(&active_state->incoming_packet);
                   1160:        cp = buffer_append_space(&active_state->incoming_packet, padded_len);
                   1161:        cipher_crypt(&active_state->receive_context, cp,
                   1162:            buffer_ptr(&active_state->input), padded_len);
1.62      markus   1163:
1.161     andreas  1164:        buffer_consume(&active_state->input, padded_len);
1.1       deraadt  1165:
                   1166: #ifdef PACKET_DEBUG
1.14      markus   1167:        fprintf(stderr, "read_poll plain: ");
1.161     andreas  1168:        buffer_dump(&active_state->incoming_packet);
1.1       deraadt  1169: #endif
                   1170:
1.14      markus   1171:        /* Compute packet checksum. */
1.161     andreas  1172:        checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
                   1173:            buffer_len(&active_state->incoming_packet) - 4);
1.14      markus   1174:
                   1175:        /* Skip padding. */
1.161     andreas  1176:        buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1.14      markus   1177:
                   1178:        /* Test check bytes. */
1.161     andreas  1179:        if (len != buffer_len(&active_state->incoming_packet))
1.77      djm      1180:                packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1.161     andreas  1181:                    len, buffer_len(&active_state->incoming_packet));
1.14      markus   1182:
1.161     andreas  1183:        cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1.131     djm      1184:        stored_checksum = get_u32(cp);
1.14      markus   1185:        if (checksum != stored_checksum)
                   1186:                packet_disconnect("Corrupted check bytes on input.");
1.161     andreas  1187:        buffer_consume_end(&active_state->incoming_packet, 4);
1.14      markus   1188:
1.161     andreas  1189:        if (active_state->packet_compression) {
                   1190:                buffer_clear(&active_state->compression_buffer);
                   1191:                buffer_uncompress(&active_state->incoming_packet,
                   1192:                    &active_state->compression_buffer);
                   1193:                buffer_clear(&active_state->incoming_packet);
                   1194:                buffer_append(&active_state->incoming_packet,
                   1195:                    buffer_ptr(&active_state->compression_buffer),
                   1196:                    buffer_len(&active_state->compression_buffer));
                   1197:        }
                   1198:        active_state->p_read.packets++;
                   1199:        active_state->p_read.bytes += padded_len + 4;
                   1200:        type = buffer_get_char(&active_state->incoming_packet);
1.116     markus   1201:        if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
                   1202:                packet_disconnect("Invalid ssh1 packet type: %d", type);
1.62      markus   1203:        return type;
1.1       deraadt  1204: }
1.14      markus   1205:
1.68      itojun   1206: static int
1.82      markus   1207: packet_read_poll2(u_int32_t *seqnr_p)
1.25      markus   1208: {
1.40      markus   1209:        u_int padlen, need;
1.89      markus   1210:        u_char *macbuf, *cp, type;
1.117     djm      1211:        u_int maclen, block_size;
1.25      markus   1212:        Enc *enc   = NULL;
                   1213:        Mac *mac   = NULL;
                   1214:        Comp *comp = NULL;
                   1215:
1.161     andreas  1216:        if (active_state->packet_discard)
1.159     markus   1217:                return SSH_MSG_NONE;
                   1218:
1.161     andreas  1219:        if (active_state->newkeys[MODE_IN] != NULL) {
                   1220:                enc  = &active_state->newkeys[MODE_IN]->enc;
                   1221:                mac  = &active_state->newkeys[MODE_IN]->mac;
                   1222:                comp = &active_state->newkeys[MODE_IN]->comp;
1.25      markus   1223:        }
                   1224:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1225:        block_size = enc ? enc->block_size : 8;
1.25      markus   1226:
1.161     andreas  1227:        if (active_state->packlen == 0) {
1.25      markus   1228:                /*
                   1229:                 * check if input size is less than the cipher block size,
                   1230:                 * decrypt first block and extract length of incoming packet
                   1231:                 */
1.161     andreas  1232:                if (buffer_len(&active_state->input) < block_size)
1.25      markus   1233:                        return SSH_MSG_NONE;
1.161     andreas  1234:                buffer_clear(&active_state->incoming_packet);
                   1235:                cp = buffer_append_space(&active_state->incoming_packet,
1.25      markus   1236:                    block_size);
1.161     andreas  1237:                cipher_crypt(&active_state->receive_context, cp,
                   1238:                    buffer_ptr(&active_state->input), block_size);
                   1239:                cp = buffer_ptr(&active_state->incoming_packet);
                   1240:                active_state->packlen = get_u32(cp);
                   1241:                if (active_state->packlen < 1 + 4 ||
                   1242:                    active_state->packlen > PACKET_MAX_SIZE) {
1.110     markus   1243: #ifdef PACKET_DEBUG
1.161     andreas  1244:                        buffer_dump(&active_state->incoming_packet);
1.110     markus   1245: #endif
1.161     andreas  1246:                        logit("Bad packet length %u.", active_state->packlen);
                   1247:                        packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1248:                            PACKET_MAX_SIZE);
                   1249:                        return SSH_MSG_NONE;
1.25      markus   1250:                }
1.161     andreas  1251:                DBG(debug("input: packet len %u", active_state->packlen+4));
                   1252:                buffer_consume(&active_state->input, block_size);
1.25      markus   1253:        }
                   1254:        /* we have a partial packet of block_size bytes */
1.161     andreas  1255:        need = 4 + active_state->packlen - block_size;
1.25      markus   1256:        DBG(debug("partial packet %d, need %d, maclen %d", block_size,
                   1257:            need, maclen));
1.158     markus   1258:        if (need % block_size != 0) {
                   1259:                logit("padding error: need %d block %d mod %d",
1.25      markus   1260:                    need, block_size, need % block_size);
1.161     andreas  1261:                packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1262:                    PACKET_MAX_SIZE - block_size);
                   1263:                return SSH_MSG_NONE;
1.158     markus   1264:        }
1.25      markus   1265:        /*
                   1266:         * check if the entire packet has been received and
                   1267:         * decrypt into incoming_packet
                   1268:         */
1.161     andreas  1269:        if (buffer_len(&active_state->input) < need + maclen)
1.25      markus   1270:                return SSH_MSG_NONE;
                   1271: #ifdef PACKET_DEBUG
                   1272:        fprintf(stderr, "read_poll enc/full: ");
1.161     andreas  1273:        buffer_dump(&active_state->input);
1.25      markus   1274: #endif
1.161     andreas  1275:        cp = buffer_append_space(&active_state->incoming_packet, need);
                   1276:        cipher_crypt(&active_state->receive_context, cp,
                   1277:            buffer_ptr(&active_state->input), need);
                   1278:        buffer_consume(&active_state->input, need);
1.25      markus   1279:        /*
                   1280:         * compute MAC over seqnr and packet,
                   1281:         * increment sequence number for incoming packet
                   1282:         */
1.29      markus   1283:        if (mac && mac->enabled) {
1.161     andreas  1284:                macbuf = mac_compute(mac, active_state->p_read.seqnr,
                   1285:                    buffer_ptr(&active_state->incoming_packet),
                   1286:                    buffer_len(&active_state->incoming_packet));
                   1287:                if (memcmp(macbuf, buffer_ptr(&active_state->input),
                   1288:                    mac->mac_len) != 0) {
1.159     markus   1289:                        logit("Corrupted MAC on input.");
                   1290:                        if (need > PACKET_MAX_SIZE)
                   1291:                                fatal("internal error need %d", need);
1.161     andreas  1292:                        packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1293:                            PACKET_MAX_SIZE - need);
                   1294:                        return SSH_MSG_NONE;
                   1295:                }
                   1296:
1.161     andreas  1297:                DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
                   1298:                buffer_consume(&active_state->input, mac->mac_len);
1.25      markus   1299:        }
1.159     markus   1300:        /* XXX now it's safe to use fatal/packet_disconnect */
1.77      djm      1301:        if (seqnr_p != NULL)
1.161     andreas  1302:                *seqnr_p = active_state->p_read.seqnr;
                   1303:        if (++active_state->p_read.seqnr == 0)
1.106     itojun   1304:                logit("incoming seqnr wraps around");
1.161     andreas  1305:        if (++active_state->p_read.packets == 0)
1.105     markus   1306:                if (!(datafellows & SSH_BUG_NOREKEY))
                   1307:                        fatal("XXX too many packets with same key");
1.161     andreas  1308:        active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
                   1309:        active_state->p_read.bytes += active_state->packlen + 4;
1.25      markus   1310:
                   1311:        /* get padlen */
1.161     andreas  1312:        cp = buffer_ptr(&active_state->incoming_packet);
1.89      markus   1313:        padlen = cp[4];
1.25      markus   1314:        DBG(debug("input: padlen %d", padlen));
                   1315:        if (padlen < 4)
                   1316:                packet_disconnect("Corrupted padlen %d on input.", padlen);
                   1317:
                   1318:        /* skip packet size + padlen, discard padding */
1.161     andreas  1319:        buffer_consume(&active_state->incoming_packet, 4 + 1);
                   1320:        buffer_consume_end(&active_state->incoming_packet, padlen);
1.25      markus   1321:
1.161     andreas  1322:        DBG(debug("input: len before de-compress %d",
                   1323:            buffer_len(&active_state->incoming_packet)));
1.25      markus   1324:        if (comp && comp->enabled) {
1.161     andreas  1325:                buffer_clear(&active_state->compression_buffer);
                   1326:                buffer_uncompress(&active_state->incoming_packet,
                   1327:                    &active_state->compression_buffer);
                   1328:                buffer_clear(&active_state->incoming_packet);
                   1329:                buffer_append(&active_state->incoming_packet,
                   1330:                    buffer_ptr(&active_state->compression_buffer),
                   1331:                    buffer_len(&active_state->compression_buffer));
1.97      deraadt  1332:                DBG(debug("input: len after de-compress %d",
1.161     andreas  1333:                    buffer_len(&active_state->incoming_packet)));
1.25      markus   1334:        }
                   1335:        /*
                   1336:         * get packet type, implies consume.
                   1337:         * return length of payload (without type field)
                   1338:         */
1.161     andreas  1339:        type = buffer_get_char(&active_state->incoming_packet);
1.116     markus   1340:        if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
                   1341:                packet_disconnect("Invalid ssh2 packet type: %d", type);
1.57      markus   1342:        if (type == SSH2_MSG_NEWKEYS)
                   1343:                set_newkeys(MODE_IN);
1.161     andreas  1344:        else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
                   1345:            !active_state->server_side)
1.118     markus   1346:                packet_enable_delayed_compress();
1.25      markus   1347: #ifdef PACKET_DEBUG
1.55      deraadt  1348:        fprintf(stderr, "read/plain[%d]:\r\n", type);
1.161     andreas  1349:        buffer_dump(&active_state->incoming_packet);
1.25      markus   1350: #endif
1.62      markus   1351:        /* reset for next packet */
1.161     andreas  1352:        active_state->packlen = 0;
1.62      markus   1353:        return type;
1.25      markus   1354: }
                   1355:
                   1356: int
1.82      markus   1357: packet_read_poll_seqnr(u_int32_t *seqnr_p)
1.25      markus   1358: {
1.96      deraadt  1359:        u_int reason, seqnr;
1.62      markus   1360:        u_char type;
1.25      markus   1361:        char *msg;
1.62      markus   1362:
1.25      markus   1363:        for (;;) {
1.62      markus   1364:                if (compat20) {
1.82      markus   1365:                        type = packet_read_poll2(seqnr_p);
1.153     djm      1366:                        if (type) {
1.161     andreas  1367:                                active_state->keep_alive_timeouts = 0;
1.25      markus   1368:                                DBG(debug("received packet type %d", type));
1.153     djm      1369:                        }
1.74      deraadt  1370:                        switch (type) {
1.150     dtucker  1371:                        case SSH2_MSG_IGNORE:
1.151     dtucker  1372:                                debug3("Received SSH2_MSG_IGNORE");
1.150     dtucker  1373:                                break;
1.25      markus   1374:                        case SSH2_MSG_DEBUG:
                   1375:                                packet_get_char();
                   1376:                                msg = packet_get_string(NULL);
                   1377:                                debug("Remote: %.900s", msg);
                   1378:                                xfree(msg);
                   1379:                                msg = packet_get_string(NULL);
                   1380:                                xfree(msg);
                   1381:                                break;
                   1382:                        case SSH2_MSG_DISCONNECT:
                   1383:                                reason = packet_get_int();
                   1384:                                msg = packet_get_string(NULL);
1.106     itojun   1385:                                logit("Received disconnect from %s: %u: %.400s",
1.96      deraadt  1386:                                    get_remote_ipaddr(), reason, msg);
1.25      markus   1387:                                xfree(msg);
1.112     markus   1388:                                cleanup_exit(255);
1.84      markus   1389:                                break;
                   1390:                        case SSH2_MSG_UNIMPLEMENTED:
                   1391:                                seqnr = packet_get_int();
1.96      deraadt  1392:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1393:                                    seqnr);
1.150     dtucker  1394:                                break;
1.25      markus   1395:                        default:
                   1396:                                return type;
1.48      stevesk  1397:                        }
1.25      markus   1398:                } else {
1.82      markus   1399:                        type = packet_read_poll1();
1.74      deraadt  1400:                        switch (type) {
1.25      markus   1401:                        case SSH_MSG_IGNORE:
                   1402:                                break;
                   1403:                        case SSH_MSG_DEBUG:
                   1404:                                msg = packet_get_string(NULL);
                   1405:                                debug("Remote: %.900s", msg);
                   1406:                                xfree(msg);
                   1407:                                break;
                   1408:                        case SSH_MSG_DISCONNECT:
                   1409:                                msg = packet_get_string(NULL);
1.106     itojun   1410:                                logit("Received disconnect from %s: %.400s",
1.96      deraadt  1411:                                    get_remote_ipaddr(), msg);
1.112     markus   1412:                                cleanup_exit(255);
1.25      markus   1413:                                break;
                   1414:                        default:
1.62      markus   1415:                                if (type)
1.25      markus   1416:                                        DBG(debug("received packet type %d", type));
                   1417:                                return type;
1.48      stevesk  1418:                        }
1.25      markus   1419:                }
                   1420:        }
1.77      djm      1421: }
                   1422:
                   1423: int
1.82      markus   1424: packet_read_poll(void)
1.77      djm      1425: {
1.82      markus   1426:        return packet_read_poll_seqnr(NULL);
1.25      markus   1427: }
                   1428:
1.16      markus   1429: /*
                   1430:  * Buffers the given amount of input characters.  This is intended to be used
                   1431:  * together with packet_read_poll.
                   1432:  */
1.1       deraadt  1433:
1.2       provos   1434: void
1.40      markus   1435: packet_process_incoming(const char *buf, u_int len)
1.1       deraadt  1436: {
1.161     andreas  1437:        if (active_state->packet_discard) {
                   1438:                active_state->keep_alive_timeouts = 0; /* ?? */
                   1439:                if (len >= active_state->packet_discard)
1.159     markus   1440:                        packet_stop_discard();
1.161     andreas  1441:                active_state->packet_discard -= len;
1.159     markus   1442:                return;
                   1443:        }
1.161     andreas  1444:        buffer_append(&active_state->input, buf, len);
1.1       deraadt  1445: }
                   1446:
                   1447: /* Returns a character from the packet. */
                   1448:
1.40      markus   1449: u_int
1.73      itojun   1450: packet_get_char(void)
1.1       deraadt  1451: {
1.14      markus   1452:        char ch;
1.97      deraadt  1453:
1.161     andreas  1454:        buffer_get(&active_state->incoming_packet, &ch, 1);
1.40      markus   1455:        return (u_char) ch;
1.1       deraadt  1456: }
                   1457:
                   1458: /* Returns an integer from the packet data. */
                   1459:
1.40      markus   1460: u_int
1.73      itojun   1461: packet_get_int(void)
1.1       deraadt  1462: {
1.161     andreas  1463:        return buffer_get_int(&active_state->incoming_packet);
1.162   ! andreas  1464: }
        !          1465:
        !          1466: /* Returns an 64 bit integer from the packet data. */
        !          1467:
        !          1468: u_int64_t
        !          1469: packet_get_int64(void)
        !          1470: {
        !          1471:        return buffer_get_int64(&active_state->incoming_packet);
1.1       deraadt  1472: }
                   1473:
1.16      markus   1474: /*
                   1475:  * Returns an arbitrary precision integer from the packet data.  The integer
                   1476:  * must have been initialized before this call.
                   1477:  */
1.1       deraadt  1478:
1.2       provos   1479: void
1.80      markus   1480: packet_get_bignum(BIGNUM * value)
1.1       deraadt  1481: {
1.161     andreas  1482:        buffer_get_bignum(&active_state->incoming_packet, value);
1.24      markus   1483: }
                   1484:
                   1485: void
1.80      markus   1486: packet_get_bignum2(BIGNUM * value)
1.24      markus   1487: {
1.161     andreas  1488:        buffer_get_bignum2(&active_state->incoming_packet, value);
1.24      markus   1489: }
                   1490:
1.76      stevesk  1491: void *
1.117     djm      1492: packet_get_raw(u_int *length_ptr)
1.24      markus   1493: {
1.161     andreas  1494:        u_int bytes = buffer_len(&active_state->incoming_packet);
1.97      deraadt  1495:
1.24      markus   1496:        if (length_ptr != NULL)
                   1497:                *length_ptr = bytes;
1.161     andreas  1498:        return buffer_ptr(&active_state->incoming_packet);
1.28      markus   1499: }
                   1500:
                   1501: int
                   1502: packet_remaining(void)
                   1503: {
1.161     andreas  1504:        return buffer_len(&active_state->incoming_packet);
1.1       deraadt  1505: }
                   1506:
1.16      markus   1507: /*
                   1508:  * Returns a string from the packet data.  The string is allocated using
                   1509:  * xmalloc; it is the responsibility of the calling program to free it when
                   1510:  * no longer needed.  The length_ptr argument may be NULL, or point to an
                   1511:  * integer into which the length of the string is stored.
                   1512:  */
1.1       deraadt  1513:
1.76      stevesk  1514: void *
1.40      markus   1515: packet_get_string(u_int *length_ptr)
1.1       deraadt  1516: {
1.161     andreas  1517:        return buffer_get_string(&active_state->incoming_packet, length_ptr);
1.152     markus   1518: }
                   1519:
                   1520: void *
                   1521: packet_get_string_ptr(u_int *length_ptr)
                   1522: {
1.161     andreas  1523:        return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1.1       deraadt  1524: }
                   1525:
1.16      markus   1526: /*
                   1527:  * Sends a diagnostic message from the server to the client.  This message
                   1528:  * can be sent at any time (but not while constructing another message). The
                   1529:  * message is printed immediately, but only if the client is being executed
                   1530:  * in verbose mode.  These messages are primarily intended to ease debugging
                   1531:  * authentication problems.   The length of the formatted message must not
                   1532:  * exceed 1024 bytes.  This will automatically call packet_write_wait.
                   1533:  */
1.1       deraadt  1534:
1.2       provos   1535: void
1.14      markus   1536: packet_send_debug(const char *fmt,...)
1.1       deraadt  1537: {
1.14      markus   1538:        char buf[1024];
                   1539:        va_list args;
1.39      markus   1540:
                   1541:        if (compat20 && (datafellows & SSH_BUG_DEBUG))
                   1542:                return;
1.14      markus   1543:
                   1544:        va_start(args, fmt);
                   1545:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1546:        va_end(args);
                   1547:
1.30      markus   1548:        if (compat20) {
                   1549:                packet_start(SSH2_MSG_DEBUG);
                   1550:                packet_put_char(0);     /* bool: always display */
                   1551:                packet_put_cstring(buf);
                   1552:                packet_put_cstring("");
                   1553:        } else {
                   1554:                packet_start(SSH_MSG_DEBUG);
                   1555:                packet_put_cstring(buf);
                   1556:        }
1.14      markus   1557:        packet_send();
                   1558:        packet_write_wait();
1.1       deraadt  1559: }
                   1560:
1.16      markus   1561: /*
                   1562:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1563:  * connection, and exits.  This function never returns. The error message
                   1564:  * should not contain a newline.  The length of the formatted message must
                   1565:  * not exceed 1024 bytes.
                   1566:  */
1.1       deraadt  1567:
1.2       provos   1568: void
1.14      markus   1569: packet_disconnect(const char *fmt,...)
1.1       deraadt  1570: {
1.14      markus   1571:        char buf[1024];
                   1572:        va_list args;
                   1573:        static int disconnecting = 0;
1.97      deraadt  1574:
1.14      markus   1575:        if (disconnecting)      /* Guard against recursive invocations. */
                   1576:                fatal("packet_disconnect called recursively.");
                   1577:        disconnecting = 1;
                   1578:
1.16      markus   1579:        /*
                   1580:         * Format the message.  Note that the caller must make sure the
                   1581:         * message is of limited size.
                   1582:         */
1.14      markus   1583:        va_start(args, fmt);
                   1584:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1585:        va_end(args);
                   1586:
1.99      markus   1587:        /* Display the error locally */
1.106     itojun   1588:        logit("Disconnecting: %.100s", buf);
1.99      markus   1589:
1.14      markus   1590:        /* Send the disconnect message to the other side, and wait for it to get sent. */
1.25      markus   1591:        if (compat20) {
                   1592:                packet_start(SSH2_MSG_DISCONNECT);
                   1593:                packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
                   1594:                packet_put_cstring(buf);
                   1595:                packet_put_cstring("");
                   1596:        } else {
                   1597:                packet_start(SSH_MSG_DISCONNECT);
1.65      markus   1598:                packet_put_cstring(buf);
1.25      markus   1599:        }
1.14      markus   1600:        packet_send();
                   1601:        packet_write_wait();
                   1602:
                   1603:        /* Stop listening for connections. */
1.67      markus   1604:        channel_close_all();
1.14      markus   1605:
                   1606:        /* Close the connection. */
                   1607:        packet_close();
1.112     markus   1608:        cleanup_exit(255);
1.1       deraadt  1609: }
                   1610:
1.16      markus   1611: /* Checks if there is any buffered output, and tries to write some of the output. */
1.1       deraadt  1612:
1.2       provos   1613: void
1.73      itojun   1614: packet_write_poll(void)
1.1       deraadt  1615: {
1.161     andreas  1616:        int len = buffer_len(&active_state->output);
1.97      deraadt  1617:
1.14      markus   1618:        if (len > 0) {
1.161     andreas  1619:                len = write(active_state->connection_out,
                   1620:                    buffer_ptr(&active_state->output), len);
1.156     djm      1621:                if (len == -1) {
                   1622:                        if (errno == EINTR || errno == EAGAIN)
1.14      markus   1623:                                return;
1.156     djm      1624:                        fatal("Write failed: %.100s", strerror(errno));
1.14      markus   1625:                }
1.156     djm      1626:                if (len == 0)
                   1627:                        fatal("Write connection closed");
1.161     andreas  1628:                buffer_consume(&active_state->output, len);
1.14      markus   1629:        }
1.1       deraadt  1630: }
                   1631:
1.16      markus   1632: /*
                   1633:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1634:  * written.
                   1635:  */
1.1       deraadt  1636:
1.2       provos   1637: void
1.73      itojun   1638: packet_write_wait(void)
1.1       deraadt  1639: {
1.56      millert  1640:        fd_set *setp;
1.154     dtucker  1641:        int ret, ms_remain;
                   1642:        struct timeval start, timeout, *timeoutp = NULL;
1.56      millert  1643:
1.161     andreas  1644:        setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
                   1645:            NFDBITS), sizeof(fd_mask));
1.14      markus   1646:        packet_write_poll();
                   1647:        while (packet_have_data_to_write()) {
1.161     andreas  1648:                memset(setp, 0, howmany(active_state->connection_out + 1,
                   1649:                    NFDBITS) * sizeof(fd_mask));
                   1650:                FD_SET(active_state->connection_out, setp);
1.154     dtucker  1651:
1.161     andreas  1652:                if (active_state->packet_timeout_ms > 0) {
                   1653:                        ms_remain = active_state->packet_timeout_ms;
1.154     dtucker  1654:                        timeoutp = &timeout;
                   1655:                }
                   1656:                for (;;) {
1.161     andreas  1657:                        if (active_state->packet_timeout_ms != -1) {
1.154     dtucker  1658:                                ms_to_timeval(&timeout, ms_remain);
                   1659:                                gettimeofday(&start, NULL);
                   1660:                        }
1.161     andreas  1661:                        if ((ret = select(active_state->connection_out + 1,
                   1662:                            NULL, setp, NULL, timeoutp)) >= 0)
1.154     dtucker  1663:                                break;
1.161     andreas  1664:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1665:                                break;
1.161     andreas  1666:                        if (active_state->packet_timeout_ms == -1)
1.154     dtucker  1667:                                continue;
                   1668:                        ms_subtract_diff(&start, &ms_remain);
                   1669:                        if (ms_remain <= 0) {
                   1670:                                ret = 0;
                   1671:                                break;
                   1672:                        }
                   1673:                }
                   1674:                if (ret == 0) {
                   1675:                        logit("Connection to %.200s timed out while "
                   1676:                            "waiting to write", get_remote_ipaddr());
                   1677:                        cleanup_exit(255);
                   1678:                }
1.14      markus   1679:                packet_write_poll();
                   1680:        }
1.56      millert  1681:        xfree(setp);
1.1       deraadt  1682: }
                   1683:
                   1684: /* Returns true if there is buffered data to write to the connection. */
                   1685:
1.2       provos   1686: int
1.73      itojun   1687: packet_have_data_to_write(void)
1.1       deraadt  1688: {
1.161     andreas  1689:        return buffer_len(&active_state->output) != 0;
1.1       deraadt  1690: }
                   1691:
                   1692: /* Returns true if there is not too much data to write to the connection. */
                   1693:
1.2       provos   1694: int
1.73      itojun   1695: packet_not_very_much_data_to_write(void)
1.1       deraadt  1696: {
1.161     andreas  1697:        if (active_state->interactive_mode)
                   1698:                return buffer_len(&active_state->output) < 16384;
1.14      markus   1699:        else
1.161     andreas  1700:                return buffer_len(&active_state->output) < 128 * 1024;
1.1       deraadt  1701: }
                   1702:
1.102     markus   1703: static void
1.101     markus   1704: packet_set_tos(int interactive)
                   1705: {
                   1706:        int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
                   1707:
                   1708:        if (!packet_connection_is_on_socket() ||
                   1709:            !packet_connection_is_ipv4())
                   1710:                return;
1.161     andreas  1711:        if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1.101     markus   1712:            sizeof(tos)) < 0)
                   1713:                error("setsockopt IP_TOS %d: %.100s:",
                   1714:                    tos, strerror(errno));
                   1715: }
                   1716:
1.1       deraadt  1717: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   1718:
1.2       provos   1719: void
1.43      markus   1720: packet_set_interactive(int interactive)
1.1       deraadt  1721: {
1.43      markus   1722:        static int called = 0;
1.44      markus   1723:
1.43      markus   1724:        if (called)
                   1725:                return;
                   1726:        called = 1;
1.1       deraadt  1727:
1.14      markus   1728:        /* Record that we are in interactive mode. */
1.161     andreas  1729:        active_state->interactive_mode = interactive;
1.1       deraadt  1730:
1.19      markus   1731:        /* Only set socket options if using a socket.  */
                   1732:        if (!packet_connection_is_on_socket())
1.14      markus   1733:                return;
1.161     andreas  1734:        set_nodelay(active_state->connection_in);
1.101     markus   1735:        packet_set_tos(interactive);
1.1       deraadt  1736: }
                   1737:
                   1738: /* Returns true if the current connection is interactive. */
                   1739:
1.2       provos   1740: int
1.73      itojun   1741: packet_is_interactive(void)
1.1       deraadt  1742: {
1.161     andreas  1743:        return active_state->interactive_mode;
1.12      markus   1744: }
                   1745:
1.113     deraadt  1746: int
1.108     markus   1747: packet_set_maxsize(u_int s)
1.12      markus   1748: {
1.14      markus   1749:        static int called = 0;
1.97      deraadt  1750:
1.14      markus   1751:        if (called) {
1.106     itojun   1752:                logit("packet_set_maxsize: called twice: old %d new %d",
1.161     andreas  1753:                    active_state->max_packet_size, s);
1.14      markus   1754:                return -1;
                   1755:        }
                   1756:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   1757:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   1758:                return -1;
                   1759:        }
1.70      markus   1760:        called = 1;
1.66      markus   1761:        debug("packet_set_maxsize: setting to %d", s);
1.161     andreas  1762:        active_state->max_packet_size = s;
1.14      markus   1763:        return s;
1.53      markus   1764: }
                   1765:
1.161     andreas  1766: int
                   1767: packet_inc_alive_timeouts(void)
                   1768: {
                   1769:        return ++active_state->keep_alive_timeouts;
                   1770: }
                   1771:
                   1772: void
                   1773: packet_set_alive_timeouts(int ka)
                   1774: {
                   1775:        active_state->keep_alive_timeouts = ka;
                   1776: }
                   1777:
                   1778: u_int
                   1779: packet_get_maxsize(void)
                   1780: {
                   1781:        return active_state->max_packet_size;
                   1782: }
                   1783:
1.71      markus   1784: /* roundup current message to pad bytes */
                   1785: void
                   1786: packet_add_padding(u_char pad)
                   1787: {
1.161     andreas  1788:        active_state->extra_pad = pad;
1.71      markus   1789: }
                   1790:
1.53      markus   1791: /*
                   1792:  * 9.2.  Ignored Data Message
1.61      markus   1793:  *
1.53      markus   1794:  *   byte      SSH_MSG_IGNORE
                   1795:  *   string    data
1.61      markus   1796:  *
1.53      markus   1797:  * All implementations MUST understand (and ignore) this message at any
                   1798:  * time (after receiving the protocol version). No implementation is
                   1799:  * required to send them. This message can be used as an additional
                   1800:  * protection measure against advanced traffic analysis techniques.
                   1801:  */
1.54      markus   1802: void
                   1803: packet_send_ignore(int nbytes)
                   1804: {
1.115     avsm     1805:        u_int32_t rnd = 0;
1.54      markus   1806:        int i;
                   1807:
                   1808:        packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1.53      markus   1809:        packet_put_int(nbytes);
1.75      deraadt  1810:        for (i = 0; i < nbytes; i++) {
1.53      markus   1811:                if (i % 4 == 0)
1.115     avsm     1812:                        rnd = arc4random();
1.129     deraadt  1813:                packet_put_char((u_char)rnd & 0xff);
1.115     avsm     1814:                rnd >>= 8;
1.53      markus   1815:        }
1.105     markus   1816: }
                   1817:
1.113     deraadt  1818: #define MAX_PACKETS    (1U<<31)
1.105     markus   1819: int
                   1820: packet_need_rekeying(void)
                   1821: {
                   1822:        if (datafellows & SSH_BUG_NOREKEY)
                   1823:                return 0;
                   1824:        return
1.161     andreas  1825:            (active_state->p_send.packets > MAX_PACKETS) ||
                   1826:            (active_state->p_read.packets > MAX_PACKETS) ||
                   1827:            (active_state->max_blocks_out &&
                   1828:                (active_state->p_send.blocks > active_state->max_blocks_out)) ||
                   1829:            (active_state->max_blocks_in &&
                   1830:                (active_state->p_read.blocks > active_state->max_blocks_in));
1.105     markus   1831: }
                   1832:
                   1833: void
                   1834: packet_set_rekey_limit(u_int32_t bytes)
                   1835: {
1.161     andreas  1836:        active_state->rekey_limit = bytes;
1.118     markus   1837: }
                   1838:
                   1839: void
                   1840: packet_set_server(void)
                   1841: {
1.161     andreas  1842:        active_state->server_side = 1;
1.118     markus   1843: }
                   1844:
                   1845: void
                   1846: packet_set_authenticated(void)
                   1847: {
1.161     andreas  1848:        active_state->after_authentication = 1;
                   1849: }
                   1850:
                   1851: void *
                   1852: packet_get_input(void)
                   1853: {
                   1854:        return (void *)&active_state->input;
                   1855: }
                   1856:
                   1857: void *
                   1858: packet_get_output(void)
                   1859: {
                   1860:        return (void *)&active_state->output;
                   1861: }
                   1862:
                   1863: void *
                   1864: packet_get_newkeys(int mode)
                   1865: {
                   1866:        return (void *)active_state->newkeys[mode];
1.1       deraadt  1867: }