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

1.161   ! andreas     1: /* $OpenBSD: packet.c,v 1.160 2009/02/13 11:50:21 markus 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.76      stevesk   590: packet_put_string(const void *buf, u_int len)
1.1       deraadt   591: {
1.161   ! andreas   592:        buffer_put_string(&active_state->outgoing_packet, buf, len);
1.1       deraadt   593: }
1.125     deraadt   594:
1.24      markus    595: void
                    596: packet_put_cstring(const char *str)
                    597: {
1.161   ! andreas   598:        buffer_put_cstring(&active_state->outgoing_packet, str);
1.24      markus    599: }
1.125     deraadt   600:
1.24      markus    601: void
1.76      stevesk   602: packet_put_raw(const void *buf, u_int len)
1.24      markus    603: {
1.161   ! andreas   604:        buffer_append(&active_state->outgoing_packet, buf, len);
1.24      markus    605: }
1.125     deraadt   606:
1.2       provos    607: void
1.14      markus    608: packet_put_bignum(BIGNUM * value)
1.1       deraadt   609: {
1.161   ! andreas   610:        buffer_put_bignum(&active_state->outgoing_packet, value);
1.1       deraadt   611: }
1.125     deraadt   612:
1.24      markus    613: void
                    614: packet_put_bignum2(BIGNUM * value)
                    615: {
1.161   ! andreas   616:        buffer_put_bignum2(&active_state->outgoing_packet, value);
1.24      markus    617: }
1.1       deraadt   618:
1.16      markus    619: /*
                    620:  * Finalizes and sends the packet.  If the encryption key has been set,
                    621:  * encrypts the packet before sending.
                    622:  */
1.14      markus    623:
1.68      itojun    624: static void
1.49      itojun    625: packet_send1(void)
1.1       deraadt   626: {
1.89      markus    627:        u_char buf[8], *cp;
1.14      markus    628:        int i, padding, len;
1.40      markus    629:        u_int checksum;
1.115     avsm      630:        u_int32_t rnd = 0;
1.14      markus    631:
1.16      markus    632:        /*
                    633:         * If using packet compression, compress the payload of the outgoing
                    634:         * packet.
                    635:         */
1.161   ! andreas   636:        if (active_state->packet_compression) {
        !           637:                buffer_clear(&active_state->compression_buffer);
1.14      markus    638:                /* Skip padding. */
1.161   ! andreas   639:                buffer_consume(&active_state->outgoing_packet, 8);
1.14      markus    640:                /* padding */
1.161   ! andreas   641:                buffer_append(&active_state->compression_buffer,
        !           642:                    "\0\0\0\0\0\0\0\0", 8);
        !           643:                buffer_compress(&active_state->outgoing_packet,
        !           644:                    &active_state->compression_buffer);
        !           645:                buffer_clear(&active_state->outgoing_packet);
        !           646:                buffer_append(&active_state->outgoing_packet,
        !           647:                    buffer_ptr(&active_state->compression_buffer),
        !           648:                    buffer_len(&active_state->compression_buffer));
1.14      markus    649:        }
                    650:        /* Compute packet length without padding (add checksum, remove padding). */
1.161   ! andreas   651:        len = buffer_len(&active_state->outgoing_packet) + 4 - 8;
1.14      markus    652:
1.32      markus    653:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    654:        padding = 8 - len % 8;
1.161   ! andreas   655:        if (!active_state->send_context.plaintext) {
        !           656:                cp = buffer_ptr(&active_state->outgoing_packet);
1.14      markus    657:                for (i = 0; i < padding; i++) {
                    658:                        if (i % 4 == 0)
1.115     avsm      659:                                rnd = arc4random();
                    660:                        cp[7 - i] = rnd & 0xff;
                    661:                        rnd >>= 8;
1.14      markus    662:                }
                    663:        }
1.161   ! andreas   664:        buffer_consume(&active_state->outgoing_packet, 8 - padding);
1.14      markus    665:
                    666:        /* Add check bytes. */
1.161   ! andreas   667:        checksum = ssh_crc32(buffer_ptr(&active_state->outgoing_packet),
        !           668:            buffer_len(&active_state->outgoing_packet));
1.131     djm       669:        put_u32(buf, checksum);
1.161   ! andreas   670:        buffer_append(&active_state->outgoing_packet, buf, 4);
1.1       deraadt   671:
                    672: #ifdef PACKET_DEBUG
1.14      markus    673:        fprintf(stderr, "packet_send plain: ");
1.161   ! andreas   674:        buffer_dump(&active_state->outgoing_packet);
1.1       deraadt   675: #endif
                    676:
1.14      markus    677:        /* Append to output. */
1.131     djm       678:        put_u32(buf, len);
1.161   ! andreas   679:        buffer_append(&active_state->output, buf, 4);
        !           680:        cp = buffer_append_space(&active_state->output,
        !           681:            buffer_len(&active_state->outgoing_packet));
        !           682:        cipher_crypt(&active_state->send_context, cp,
        !           683:            buffer_ptr(&active_state->outgoing_packet),
        !           684:            buffer_len(&active_state->outgoing_packet));
1.14      markus    685:
1.1       deraadt   686: #ifdef PACKET_DEBUG
1.14      markus    687:        fprintf(stderr, "encrypted: ");
1.161   ! andreas   688:        buffer_dump(&active_state->output);
1.1       deraadt   689: #endif
1.161   ! andreas   690:        active_state->p_send.packets++;
        !           691:        active_state->p_send.bytes += len +
        !           692:            buffer_len(&active_state->outgoing_packet);
        !           693:        buffer_clear(&active_state->outgoing_packet);
1.1       deraadt   694:
1.16      markus    695:        /*
1.120     djm       696:         * Note that the packet is now only buffered in output.  It won't be
1.16      markus    697:         * actually sent until packet_write_wait or packet_write_poll is
                    698:         * called.
                    699:         */
1.1       deraadt   700: }
                    701:
1.91      markus    702: void
1.57      markus    703: set_newkeys(int mode)
                    704: {
                    705:        Enc *enc;
                    706:        Mac *mac;
                    707:        Comp *comp;
                    708:        CipherContext *cc;
1.105     markus    709:        u_int64_t *max_blocks;
1.115     avsm      710:        int crypt_type;
1.57      markus    711:
1.100     markus    712:        debug2("set_newkeys: mode %d", mode);
1.57      markus    713:
1.88      markus    714:        if (mode == MODE_OUT) {
1.161   ! andreas   715:                cc = &active_state->send_context;
1.115     avsm      716:                crypt_type = CIPHER_ENCRYPT;
1.161   ! andreas   717:                active_state->p_send.packets = active_state->p_send.blocks = 0;
        !           718:                max_blocks = &active_state->max_blocks_out;
1.88      markus    719:        } else {
1.161   ! andreas   720:                cc = &active_state->receive_context;
1.115     avsm      721:                crypt_type = CIPHER_DECRYPT;
1.161   ! andreas   722:                active_state->p_read.packets = active_state->p_read.blocks = 0;
        !           723:                max_blocks = &active_state->max_blocks_in;
1.88      markus    724:        }
1.161   ! andreas   725:        if (active_state->newkeys[mode] != NULL) {
1.100     markus    726:                debug("set_newkeys: rekeying");
1.88      markus    727:                cipher_cleanup(cc);
1.161   ! andreas   728:                enc  = &active_state->newkeys[mode]->enc;
        !           729:                mac  = &active_state->newkeys[mode]->mac;
        !           730:                comp = &active_state->newkeys[mode]->comp;
1.148     pvalchev  731:                mac_clear(mac);
1.59      markus    732:                xfree(enc->name);
                    733:                xfree(enc->iv);
                    734:                xfree(enc->key);
                    735:                xfree(mac->name);
                    736:                xfree(mac->key);
                    737:                xfree(comp->name);
1.161   ! andreas   738:                xfree(active_state->newkeys[mode]);
1.57      markus    739:        }
1.161   ! andreas   740:        active_state->newkeys[mode] = kex_get_newkeys(mode);
        !           741:        if (active_state->newkeys[mode] == NULL)
1.57      markus    742:                fatal("newkeys: no keys for mode %d", mode);
1.161   ! andreas   743:        enc  = &active_state->newkeys[mode]->enc;
        !           744:        mac  = &active_state->newkeys[mode]->mac;
        !           745:        comp = &active_state->newkeys[mode]->comp;
1.148     pvalchev  746:        if (mac_init(mac) == 0)
1.57      markus    747:                mac->enabled = 1;
                    748:        DBG(debug("cipher_init_context: %d", mode));
1.88      markus    749:        cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1.115     avsm      750:            enc->iv, enc->block_size, crypt_type);
1.91      markus    751:        /* Deleting the keys does not gain extra security */
                    752:        /* memset(enc->iv,  0, enc->block_size);
1.147     djm       753:           memset(enc->key, 0, enc->key_len);
                    754:           memset(mac->key, 0, mac->key_len); */
1.118     markus    755:        if ((comp->type == COMP_ZLIB ||
1.161   ! andreas   756:            (comp->type == COMP_DELAYED &&
        !           757:             active_state->after_authentication)) && comp->enabled == 0) {
1.60      markus    758:                packet_init_compression();
                    759:                if (mode == MODE_OUT)
                    760:                        buffer_compress_init_send(6);
                    761:                else
                    762:                        buffer_compress_init_recv();
1.57      markus    763:                comp->enabled = 1;
                    764:        }
1.109     markus    765:        /*
                    766:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    767:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    768:         */
                    769:        if (enc->block_size >= 16)
                    770:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    771:        else
                    772:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.161   ! andreas   773:        if (active_state->rekey_limit)
        !           774:                *max_blocks = MIN(*max_blocks,
        !           775:                    active_state->rekey_limit / enc->block_size);
1.57      markus    776: }
                    777:
1.16      markus    778: /*
1.118     markus    779:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker   780:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus    781:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                    782:  */
                    783: static void
                    784: packet_enable_delayed_compress(void)
                    785: {
                    786:        Comp *comp = NULL;
                    787:        int mode;
                    788:
                    789:        /*
                    790:         * Remember that we are past the authentication step, so rekeying
                    791:         * with COMP_DELAYED will turn on compression immediately.
                    792:         */
1.161   ! andreas   793:        active_state->after_authentication = 1;
1.118     markus    794:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus    795:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1.161   ! andreas   796:                if (active_state->newkeys[mode] == NULL)
1.145     markus    797:                        continue;
1.161   ! andreas   798:                comp = &active_state->newkeys[mode]->comp;
1.118     markus    799:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.119     markus    800:                        packet_init_compression();
1.118     markus    801:                        if (mode == MODE_OUT)
                    802:                                buffer_compress_init_send(6);
                    803:                        else
                    804:                                buffer_compress_init_recv();
                    805:                        comp->enabled = 1;
                    806:                }
                    807:        }
                    808: }
                    809:
                    810: /*
1.25      markus    811:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                    812:  */
1.68      itojun    813: static void
1.105     markus    814: packet_send2_wrapped(void)
1.25      markus    815: {
1.89      markus    816:        u_char type, *cp, *macbuf = NULL;
1.71      markus    817:        u_char padlen, pad;
1.40      markus    818:        u_int packet_length = 0;
1.71      markus    819:        u_int i, len;
1.115     avsm      820:        u_int32_t rnd = 0;
1.25      markus    821:        Enc *enc   = NULL;
                    822:        Mac *mac   = NULL;
                    823:        Comp *comp = NULL;
                    824:        int block_size;
                    825:
1.161   ! andreas   826:        if (active_state->newkeys[MODE_OUT] != NULL) {
        !           827:                enc  = &active_state->newkeys[MODE_OUT]->enc;
        !           828:                mac  = &active_state->newkeys[MODE_OUT]->mac;
        !           829:                comp = &active_state->newkeys[MODE_OUT]->comp;
1.25      markus    830:        }
1.88      markus    831:        block_size = enc ? enc->block_size : 8;
1.25      markus    832:
1.161   ! andreas   833:        cp = buffer_ptr(&active_state->outgoing_packet);
1.89      markus    834:        type = cp[5];
1.25      markus    835:
                    836: #ifdef PACKET_DEBUG
                    837:        fprintf(stderr, "plain:     ");
1.161   ! andreas   838:        buffer_dump(&active_state->outgoing_packet);
1.25      markus    839: #endif
                    840:
                    841:        if (comp && comp->enabled) {
1.161   ! andreas   842:                len = buffer_len(&active_state->outgoing_packet);
1.25      markus    843:                /* skip header, compress only payload */
1.161   ! andreas   844:                buffer_consume(&active_state->outgoing_packet, 5);
        !           845:                buffer_clear(&active_state->compression_buffer);
        !           846:                buffer_compress(&active_state->outgoing_packet,
        !           847:                    &active_state->compression_buffer);
        !           848:                buffer_clear(&active_state->outgoing_packet);
        !           849:                buffer_append(&active_state->outgoing_packet, "\0\0\0\0\0", 5);
        !           850:                buffer_append(&active_state->outgoing_packet,
        !           851:                    buffer_ptr(&active_state->compression_buffer),
        !           852:                    buffer_len(&active_state->compression_buffer));
1.25      markus    853:                DBG(debug("compression: raw %d compressed %d", len,
1.161   ! andreas   854:                    buffer_len(&active_state->outgoing_packet)));
1.25      markus    855:        }
                    856:
                    857:        /* sizeof (packet_len + pad_len + payload) */
1.161   ! andreas   858:        len = buffer_len(&active_state->outgoing_packet);
1.25      markus    859:
                    860:        /*
                    861:         * calc size of padding, alloc space, get random data,
                    862:         * minimum padding is 4 bytes
                    863:         */
                    864:        padlen = block_size - (len % block_size);
                    865:        if (padlen < 4)
                    866:                padlen += block_size;
1.161   ! andreas   867:        if (active_state->extra_pad) {
1.71      markus    868:                /* will wrap if extra_pad+padlen > 255 */
1.161   ! andreas   869:                active_state->extra_pad =
        !           870:                    roundup(active_state->extra_pad, block_size);
        !           871:                pad = active_state->extra_pad -
        !           872:                    ((len + padlen) % active_state->extra_pad);
1.93      markus    873:                debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
1.161   ! andreas   874:                    pad, len, padlen, active_state->extra_pad);
1.71      markus    875:                padlen += pad;
1.161   ! andreas   876:                active_state->extra_pad = 0;
1.71      markus    877:        }
1.161   ! andreas   878:        cp = buffer_append_space(&active_state->outgoing_packet, padlen);
        !           879:        if (enc && !active_state->send_context.plaintext) {
1.32      markus    880:                /* random padding */
1.25      markus    881:                for (i = 0; i < padlen; i++) {
                    882:                        if (i % 4 == 0)
1.115     avsm      883:                                rnd = arc4random();
                    884:                        cp[i] = rnd & 0xff;
                    885:                        rnd >>= 8;
1.25      markus    886:                }
1.32      markus    887:        } else {
                    888:                /* clear padding */
                    889:                memset(cp, 0, padlen);
1.25      markus    890:        }
                    891:        /* packet_length includes payload, padding and padding length field */
1.161   ! andreas   892:        packet_length = buffer_len(&active_state->outgoing_packet) - 4;
        !           893:        cp = buffer_ptr(&active_state->outgoing_packet);
1.131     djm       894:        put_u32(cp, packet_length);
1.89      markus    895:        cp[4] = padlen;
1.25      markus    896:        DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
                    897:
                    898:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
                    899:        if (mac && mac->enabled) {
1.161   ! andreas   900:                macbuf = mac_compute(mac, active_state->p_send.seqnr,
        !           901:                    buffer_ptr(&active_state->outgoing_packet),
        !           902:                    buffer_len(&active_state->outgoing_packet));
        !           903:                DBG(debug("done calc MAC out #%d", active_state->p_send.seqnr));
1.25      markus    904:        }
                    905:        /* encrypt packet and append to output buffer. */
1.161   ! andreas   906:        cp = buffer_append_space(&active_state->output,
        !           907:            buffer_len(&active_state->outgoing_packet));
        !           908:        cipher_crypt(&active_state->send_context, cp,
        !           909:            buffer_ptr(&active_state->outgoing_packet),
        !           910:            buffer_len(&active_state->outgoing_packet));
1.25      markus    911:        /* append unencrypted MAC */
                    912:        if (mac && mac->enabled)
1.161   ! andreas   913:                buffer_append(&active_state->output, macbuf, mac->mac_len);
1.25      markus    914: #ifdef PACKET_DEBUG
                    915:        fprintf(stderr, "encrypted: ");
1.161   ! andreas   916:        buffer_dump(&active_state->output);
1.25      markus    917: #endif
1.29      markus    918:        /* increment sequence number for outgoing packets */
1.161   ! andreas   919:        if (++active_state->p_send.seqnr == 0)
1.106     itojun    920:                logit("outgoing seqnr wraps around");
1.161   ! andreas   921:        if (++active_state->p_send.packets == 0)
1.105     markus    922:                if (!(datafellows & SSH_BUG_NOREKEY))
                    923:                        fatal("XXX too many packets with same key");
1.161   ! andreas   924:        active_state->p_send.blocks += (packet_length + 4) / block_size;
        !           925:        active_state->p_send.bytes += packet_length + 4;
        !           926:        buffer_clear(&active_state->outgoing_packet);
1.25      markus    927:
1.57      markus    928:        if (type == SSH2_MSG_NEWKEYS)
                    929:                set_newkeys(MODE_OUT);
1.161   ! andreas   930:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && active_state->server_side)
1.118     markus    931:                packet_enable_delayed_compress();
1.25      markus    932: }
                    933:
1.105     markus    934: static void
                    935: packet_send2(void)
                    936: {
                    937:        static int rekeying = 0;
                    938:        struct packet *p;
                    939:        u_char type, *cp;
                    940:
1.161   ! andreas   941:        cp = buffer_ptr(&active_state->outgoing_packet);
1.105     markus    942:        type = cp[5];
                    943:
                    944:        /* during rekeying we can only send key exchange messages */
                    945:        if (rekeying) {
                    946:                if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
                    947:                    (type <= SSH2_MSG_TRANSPORT_MAX))) {
                    948:                        debug("enqueue packet: %u", type);
                    949:                        p = xmalloc(sizeof(*p));
                    950:                        p->type = type;
1.161   ! andreas   951:                        memcpy(&p->payload, &active_state->outgoing_packet,
        !           952:                            sizeof(Buffer));
        !           953:                        buffer_init(&active_state->outgoing_packet);
        !           954:                        TAILQ_INSERT_TAIL(&active_state->outgoing, p, next);
1.105     markus    955:                        return;
                    956:                }
                    957:        }
                    958:
                    959:        /* rekeying starts with sending KEXINIT */
                    960:        if (type == SSH2_MSG_KEXINIT)
                    961:                rekeying = 1;
                    962:
                    963:        packet_send2_wrapped();
                    964:
                    965:        /* after a NEWKEYS message we can send the complete queue */
                    966:        if (type == SSH2_MSG_NEWKEYS) {
                    967:                rekeying = 0;
1.161   ! andreas   968:                while ((p = TAILQ_FIRST(&active_state->outgoing))) {
1.105     markus    969:                        type = p->type;
                    970:                        debug("dequeue packet: %u", type);
1.161   ! andreas   971:                        buffer_free(&active_state->outgoing_packet);
        !           972:                        memcpy(&active_state->outgoing_packet, &p->payload,
1.105     markus    973:                            sizeof(Buffer));
1.161   ! andreas   974:                        TAILQ_REMOVE(&active_state->outgoing, p, next);
1.105     markus    975:                        xfree(p);
                    976:                        packet_send2_wrapped();
                    977:                }
                    978:        }
                    979: }
                    980:
1.25      markus    981: void
1.73      itojun    982: packet_send(void)
1.25      markus    983: {
1.62      markus    984:        if (compat20)
1.25      markus    985:                packet_send2();
                    986:        else
                    987:                packet_send1();
                    988:        DBG(debug("packet_send done"));
                    989: }
                    990:
                    991: /*
1.16      markus    992:  * Waits until a packet has been received, and returns its type.  Note that
                    993:  * no other data is processed until this returns, so this function should not
                    994:  * be used during the interactive session.
                    995:  */
1.1       deraadt   996:
1.2       provos    997: int
1.82      markus    998: packet_read_seqnr(u_int32_t *seqnr_p)
1.1       deraadt   999: {
1.154     dtucker  1000:        int type, len, ret, ms_remain;
1.56      millert  1001:        fd_set *setp;
1.14      markus   1002:        char buf[8192];
1.155     deraadt  1003:        struct timeval timeout, start, *timeoutp = NULL;
                   1004:
1.25      markus   1005:        DBG(debug("packet_read()"));
1.14      markus   1006:
1.161   ! andreas  1007:        setp = (fd_set *)xcalloc(howmany(active_state->connection_in + 1,
        !          1008:            NFDBITS), sizeof(fd_mask));
1.56      millert  1009:
1.14      markus   1010:        /* Since we are blocking, ensure that all written packets have been sent. */
                   1011:        packet_write_wait();
                   1012:
                   1013:        /* Stay in the loop until we have received a complete packet. */
                   1014:        for (;;) {
                   1015:                /* Try to read a packet from the buffer. */
1.82      markus   1016:                type = packet_read_poll_seqnr(seqnr_p);
1.62      markus   1017:                if (!compat20 && (
1.32      markus   1018:                    type == SSH_SMSG_SUCCESS
1.14      markus   1019:                    || type == SSH_SMSG_FAILURE
                   1020:                    || type == SSH_CMSG_EOF
1.32      markus   1021:                    || type == SSH_CMSG_EXIT_CONFIRMATION))
1.79      markus   1022:                        packet_check_eom();
1.14      markus   1023:                /* If we got a packet, return it. */
1.56      millert  1024:                if (type != SSH_MSG_NONE) {
                   1025:                        xfree(setp);
1.14      markus   1026:                        return type;
1.56      millert  1027:                }
1.16      markus   1028:                /*
                   1029:                 * Otherwise, wait for some data to arrive, add it to the
                   1030:                 * buffer, and try again.
                   1031:                 */
1.161   ! andreas  1032:                memset(setp, 0, howmany(active_state->connection_in + 1,
        !          1033:                    NFDBITS) * sizeof(fd_mask));
        !          1034:                FD_SET(active_state->connection_in, setp);
1.16      markus   1035:
1.161   ! andreas  1036:                if (active_state->packet_timeout_ms > 0) {
        !          1037:                        ms_remain = active_state->packet_timeout_ms;
1.154     dtucker  1038:                        timeoutp = &timeout;
                   1039:                }
1.14      markus   1040:                /* Wait for some data to arrive. */
1.154     dtucker  1041:                for (;;) {
1.161   ! andreas  1042:                        if (active_state->packet_timeout_ms != -1) {
1.154     dtucker  1043:                                ms_to_timeval(&timeout, ms_remain);
                   1044:                                gettimeofday(&start, NULL);
                   1045:                        }
1.161   ! andreas  1046:                        if ((ret = select(active_state->connection_in + 1, setp,
        !          1047:                            NULL, NULL, timeoutp)) >= 0)
1.154     dtucker  1048:                                break;
1.161   ! andreas  1049:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1050:                                break;
1.161   ! andreas  1051:                        if (active_state->packet_timeout_ms == -1)
1.154     dtucker  1052:                                continue;
                   1053:                        ms_subtract_diff(&start, &ms_remain);
                   1054:                        if (ms_remain <= 0) {
                   1055:                                ret = 0;
                   1056:                                break;
                   1057:                        }
                   1058:                }
                   1059:                if (ret == 0) {
                   1060:                        logit("Connection to %.200s timed out while "
                   1061:                            "waiting to read", get_remote_ipaddr());
                   1062:                        cleanup_exit(255);
                   1063:                }
1.14      markus   1064:                /* Read data from the socket. */
1.161   ! andreas  1065:                len = read(active_state->connection_in, buf, sizeof(buf));
1.18      markus   1066:                if (len == 0) {
1.106     itojun   1067:                        logit("Connection closed by %.200s", get_remote_ipaddr());
1.112     markus   1068:                        cleanup_exit(255);
1.18      markus   1069:                }
1.14      markus   1070:                if (len < 0)
                   1071:                        fatal("Read from socket failed: %.100s", strerror(errno));
                   1072:                /* Append it to the buffer. */
                   1073:                packet_process_incoming(buf, len);
                   1074:        }
                   1075:        /* NOTREACHED */
1.1       deraadt  1076: }
                   1077:
1.77      djm      1078: int
1.82      markus   1079: packet_read(void)
1.77      djm      1080: {
1.82      markus   1081:        return packet_read_seqnr(NULL);
1.77      djm      1082: }
                   1083:
1.16      markus   1084: /*
                   1085:  * Waits until a packet has been received, verifies that its type matches
                   1086:  * that given, and gives a fatal error and exits if there is a mismatch.
                   1087:  */
1.1       deraadt  1088:
1.2       provos   1089: void
1.82      markus   1090: packet_read_expect(int expected_type)
1.1       deraadt  1091: {
1.14      markus   1092:        int type;
1.1       deraadt  1093:
1.82      markus   1094:        type = packet_read();
1.14      markus   1095:        if (type != expected_type)
                   1096:                packet_disconnect("Protocol error: expected packet type %d, got %d",
1.25      markus   1097:                    expected_type, type);
1.1       deraadt  1098: }
                   1099:
                   1100: /* Checks if a full packet is available in the data received so far via
1.14      markus   1101:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                   1102:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                   1103:  *
1.150     dtucker  1104:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                   1105:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                   1106:  * to higher levels.
1.14      markus   1107:  */
1.1       deraadt  1108:
1.68      itojun   1109: static int
1.82      markus   1110: packet_read_poll1(void)
1.1       deraadt  1111: {
1.40      markus   1112:        u_int len, padded_len;
1.89      markus   1113:        u_char *cp, type;
1.40      markus   1114:        u_int checksum, stored_checksum;
1.14      markus   1115:
                   1116:        /* Check if input size is less than minimum packet size. */
1.161   ! andreas  1117:        if (buffer_len(&active_state->input) < 4 + 8)
1.14      markus   1118:                return SSH_MSG_NONE;
                   1119:        /* Get length of incoming packet. */
1.161   ! andreas  1120:        cp = buffer_ptr(&active_state->input);
1.131     djm      1121:        len = get_u32(cp);
1.14      markus   1122:        if (len < 1 + 2 + 2 || len > 256 * 1024)
1.98      markus   1123:                packet_disconnect("Bad packet length %u.", len);
1.14      markus   1124:        padded_len = (len + 8) & ~7;
                   1125:
                   1126:        /* Check if the packet has been entirely received. */
1.161   ! andreas  1127:        if (buffer_len(&active_state->input) < 4 + padded_len)
1.14      markus   1128:                return SSH_MSG_NONE;
                   1129:
                   1130:        /* The entire packet is in buffer. */
                   1131:
                   1132:        /* Consume packet length. */
1.161   ! andreas  1133:        buffer_consume(&active_state->input, 4);
1.14      markus   1134:
1.62      markus   1135:        /*
                   1136:         * Cryptographic attack detector for ssh
                   1137:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                   1138:         * Ariel Futoransky(futo@core-sdi.com)
                   1139:         */
1.161   ! andreas  1140:        if (!active_state->receive_context.plaintext) {
        !          1141:                switch (detect_attack(buffer_ptr(&active_state->input),
        !          1142:                    padded_len)) {
1.144     djm      1143:                case DEATTACK_DETECTED:
                   1144:                        packet_disconnect("crc32 compensation attack: "
                   1145:                            "network attack detected");
                   1146:                case DEATTACK_DOS_DETECTED:
                   1147:                        packet_disconnect("deattack denial of "
                   1148:                            "service detected");
                   1149:                }
                   1150:        }
1.62      markus   1151:
                   1152:        /* Decrypt data to incoming_packet. */
1.161   ! andreas  1153:        buffer_clear(&active_state->incoming_packet);
        !          1154:        cp = buffer_append_space(&active_state->incoming_packet, padded_len);
        !          1155:        cipher_crypt(&active_state->receive_context, cp,
        !          1156:            buffer_ptr(&active_state->input), padded_len);
1.62      markus   1157:
1.161   ! andreas  1158:        buffer_consume(&active_state->input, padded_len);
1.1       deraadt  1159:
                   1160: #ifdef PACKET_DEBUG
1.14      markus   1161:        fprintf(stderr, "read_poll plain: ");
1.161   ! andreas  1162:        buffer_dump(&active_state->incoming_packet);
1.1       deraadt  1163: #endif
                   1164:
1.14      markus   1165:        /* Compute packet checksum. */
1.161   ! andreas  1166:        checksum = ssh_crc32(buffer_ptr(&active_state->incoming_packet),
        !          1167:            buffer_len(&active_state->incoming_packet) - 4);
1.14      markus   1168:
                   1169:        /* Skip padding. */
1.161   ! andreas  1170:        buffer_consume(&active_state->incoming_packet, 8 - len % 8);
1.14      markus   1171:
                   1172:        /* Test check bytes. */
1.161   ! andreas  1173:        if (len != buffer_len(&active_state->incoming_packet))
1.77      djm      1174:                packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1.161   ! andreas  1175:                    len, buffer_len(&active_state->incoming_packet));
1.14      markus   1176:
1.161   ! andreas  1177:        cp = (u_char *)buffer_ptr(&active_state->incoming_packet) + len - 4;
1.131     djm      1178:        stored_checksum = get_u32(cp);
1.14      markus   1179:        if (checksum != stored_checksum)
                   1180:                packet_disconnect("Corrupted check bytes on input.");
1.161   ! andreas  1181:        buffer_consume_end(&active_state->incoming_packet, 4);
1.14      markus   1182:
1.161   ! andreas  1183:        if (active_state->packet_compression) {
        !          1184:                buffer_clear(&active_state->compression_buffer);
        !          1185:                buffer_uncompress(&active_state->incoming_packet,
        !          1186:                    &active_state->compression_buffer);
        !          1187:                buffer_clear(&active_state->incoming_packet);
        !          1188:                buffer_append(&active_state->incoming_packet,
        !          1189:                    buffer_ptr(&active_state->compression_buffer),
        !          1190:                    buffer_len(&active_state->compression_buffer));
        !          1191:        }
        !          1192:        active_state->p_read.packets++;
        !          1193:        active_state->p_read.bytes += padded_len + 4;
        !          1194:        type = buffer_get_char(&active_state->incoming_packet);
1.116     markus   1195:        if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
                   1196:                packet_disconnect("Invalid ssh1 packet type: %d", type);
1.62      markus   1197:        return type;
1.1       deraadt  1198: }
1.14      markus   1199:
1.68      itojun   1200: static int
1.82      markus   1201: packet_read_poll2(u_int32_t *seqnr_p)
1.25      markus   1202: {
1.40      markus   1203:        u_int padlen, need;
1.89      markus   1204:        u_char *macbuf, *cp, type;
1.117     djm      1205:        u_int maclen, block_size;
1.25      markus   1206:        Enc *enc   = NULL;
                   1207:        Mac *mac   = NULL;
                   1208:        Comp *comp = NULL;
                   1209:
1.161   ! andreas  1210:        if (active_state->packet_discard)
1.159     markus   1211:                return SSH_MSG_NONE;
                   1212:
1.161   ! andreas  1213:        if (active_state->newkeys[MODE_IN] != NULL) {
        !          1214:                enc  = &active_state->newkeys[MODE_IN]->enc;
        !          1215:                mac  = &active_state->newkeys[MODE_IN]->mac;
        !          1216:                comp = &active_state->newkeys[MODE_IN]->comp;
1.25      markus   1217:        }
                   1218:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1219:        block_size = enc ? enc->block_size : 8;
1.25      markus   1220:
1.161   ! andreas  1221:        if (active_state->packlen == 0) {
1.25      markus   1222:                /*
                   1223:                 * check if input size is less than the cipher block size,
                   1224:                 * decrypt first block and extract length of incoming packet
                   1225:                 */
1.161   ! andreas  1226:                if (buffer_len(&active_state->input) < block_size)
1.25      markus   1227:                        return SSH_MSG_NONE;
1.161   ! andreas  1228:                buffer_clear(&active_state->incoming_packet);
        !          1229:                cp = buffer_append_space(&active_state->incoming_packet,
1.25      markus   1230:                    block_size);
1.161   ! andreas  1231:                cipher_crypt(&active_state->receive_context, cp,
        !          1232:                    buffer_ptr(&active_state->input), block_size);
        !          1233:                cp = buffer_ptr(&active_state->incoming_packet);
        !          1234:                active_state->packlen = get_u32(cp);
        !          1235:                if (active_state->packlen < 1 + 4 ||
        !          1236:                    active_state->packlen > PACKET_MAX_SIZE) {
1.110     markus   1237: #ifdef PACKET_DEBUG
1.161   ! andreas  1238:                        buffer_dump(&active_state->incoming_packet);
1.110     markus   1239: #endif
1.161   ! andreas  1240:                        logit("Bad packet length %u.", active_state->packlen);
        !          1241:                        packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1242:                            PACKET_MAX_SIZE);
                   1243:                        return SSH_MSG_NONE;
1.25      markus   1244:                }
1.161   ! andreas  1245:                DBG(debug("input: packet len %u", active_state->packlen+4));
        !          1246:                buffer_consume(&active_state->input, block_size);
1.25      markus   1247:        }
                   1248:        /* we have a partial packet of block_size bytes */
1.161   ! andreas  1249:        need = 4 + active_state->packlen - block_size;
1.25      markus   1250:        DBG(debug("partial packet %d, need %d, maclen %d", block_size,
                   1251:            need, maclen));
1.158     markus   1252:        if (need % block_size != 0) {
                   1253:                logit("padding error: need %d block %d mod %d",
1.25      markus   1254:                    need, block_size, need % block_size);
1.161   ! andreas  1255:                packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1256:                    PACKET_MAX_SIZE - block_size);
                   1257:                return SSH_MSG_NONE;
1.158     markus   1258:        }
1.25      markus   1259:        /*
                   1260:         * check if the entire packet has been received and
                   1261:         * decrypt into incoming_packet
                   1262:         */
1.161   ! andreas  1263:        if (buffer_len(&active_state->input) < need + maclen)
1.25      markus   1264:                return SSH_MSG_NONE;
                   1265: #ifdef PACKET_DEBUG
                   1266:        fprintf(stderr, "read_poll enc/full: ");
1.161   ! andreas  1267:        buffer_dump(&active_state->input);
1.25      markus   1268: #endif
1.161   ! andreas  1269:        cp = buffer_append_space(&active_state->incoming_packet, need);
        !          1270:        cipher_crypt(&active_state->receive_context, cp,
        !          1271:            buffer_ptr(&active_state->input), need);
        !          1272:        buffer_consume(&active_state->input, need);
1.25      markus   1273:        /*
                   1274:         * compute MAC over seqnr and packet,
                   1275:         * increment sequence number for incoming packet
                   1276:         */
1.29      markus   1277:        if (mac && mac->enabled) {
1.161   ! andreas  1278:                macbuf = mac_compute(mac, active_state->p_read.seqnr,
        !          1279:                    buffer_ptr(&active_state->incoming_packet),
        !          1280:                    buffer_len(&active_state->incoming_packet));
        !          1281:                if (memcmp(macbuf, buffer_ptr(&active_state->input),
        !          1282:                    mac->mac_len) != 0) {
1.159     markus   1283:                        logit("Corrupted MAC on input.");
                   1284:                        if (need > PACKET_MAX_SIZE)
                   1285:                                fatal("internal error need %d", need);
1.161   ! andreas  1286:                        packet_start_discard(enc, mac, active_state->packlen,
1.159     markus   1287:                            PACKET_MAX_SIZE - need);
                   1288:                        return SSH_MSG_NONE;
                   1289:                }
                   1290:
1.161   ! andreas  1291:                DBG(debug("MAC #%d ok", active_state->p_read.seqnr));
        !          1292:                buffer_consume(&active_state->input, mac->mac_len);
1.25      markus   1293:        }
1.159     markus   1294:        /* XXX now it's safe to use fatal/packet_disconnect */
1.77      djm      1295:        if (seqnr_p != NULL)
1.161   ! andreas  1296:                *seqnr_p = active_state->p_read.seqnr;
        !          1297:        if (++active_state->p_read.seqnr == 0)
1.106     itojun   1298:                logit("incoming seqnr wraps around");
1.161   ! andreas  1299:        if (++active_state->p_read.packets == 0)
1.105     markus   1300:                if (!(datafellows & SSH_BUG_NOREKEY))
                   1301:                        fatal("XXX too many packets with same key");
1.161   ! andreas  1302:        active_state->p_read.blocks += (active_state->packlen + 4) / block_size;
        !          1303:        active_state->p_read.bytes += active_state->packlen + 4;
1.25      markus   1304:
                   1305:        /* get padlen */
1.161   ! andreas  1306:        cp = buffer_ptr(&active_state->incoming_packet);
1.89      markus   1307:        padlen = cp[4];
1.25      markus   1308:        DBG(debug("input: padlen %d", padlen));
                   1309:        if (padlen < 4)
                   1310:                packet_disconnect("Corrupted padlen %d on input.", padlen);
                   1311:
                   1312:        /* skip packet size + padlen, discard padding */
1.161   ! andreas  1313:        buffer_consume(&active_state->incoming_packet, 4 + 1);
        !          1314:        buffer_consume_end(&active_state->incoming_packet, padlen);
1.25      markus   1315:
1.161   ! andreas  1316:        DBG(debug("input: len before de-compress %d",
        !          1317:            buffer_len(&active_state->incoming_packet)));
1.25      markus   1318:        if (comp && comp->enabled) {
1.161   ! andreas  1319:                buffer_clear(&active_state->compression_buffer);
        !          1320:                buffer_uncompress(&active_state->incoming_packet,
        !          1321:                    &active_state->compression_buffer);
        !          1322:                buffer_clear(&active_state->incoming_packet);
        !          1323:                buffer_append(&active_state->incoming_packet,
        !          1324:                    buffer_ptr(&active_state->compression_buffer),
        !          1325:                    buffer_len(&active_state->compression_buffer));
1.97      deraadt  1326:                DBG(debug("input: len after de-compress %d",
1.161   ! andreas  1327:                    buffer_len(&active_state->incoming_packet)));
1.25      markus   1328:        }
                   1329:        /*
                   1330:         * get packet type, implies consume.
                   1331:         * return length of payload (without type field)
                   1332:         */
1.161   ! andreas  1333:        type = buffer_get_char(&active_state->incoming_packet);
1.116     markus   1334:        if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
                   1335:                packet_disconnect("Invalid ssh2 packet type: %d", type);
1.57      markus   1336:        if (type == SSH2_MSG_NEWKEYS)
                   1337:                set_newkeys(MODE_IN);
1.161   ! andreas  1338:        else if (type == SSH2_MSG_USERAUTH_SUCCESS &&
        !          1339:            !active_state->server_side)
1.118     markus   1340:                packet_enable_delayed_compress();
1.25      markus   1341: #ifdef PACKET_DEBUG
1.55      deraadt  1342:        fprintf(stderr, "read/plain[%d]:\r\n", type);
1.161   ! andreas  1343:        buffer_dump(&active_state->incoming_packet);
1.25      markus   1344: #endif
1.62      markus   1345:        /* reset for next packet */
1.161   ! andreas  1346:        active_state->packlen = 0;
1.62      markus   1347:        return type;
1.25      markus   1348: }
                   1349:
                   1350: int
1.82      markus   1351: packet_read_poll_seqnr(u_int32_t *seqnr_p)
1.25      markus   1352: {
1.96      deraadt  1353:        u_int reason, seqnr;
1.62      markus   1354:        u_char type;
1.25      markus   1355:        char *msg;
1.62      markus   1356:
1.25      markus   1357:        for (;;) {
1.62      markus   1358:                if (compat20) {
1.82      markus   1359:                        type = packet_read_poll2(seqnr_p);
1.153     djm      1360:                        if (type) {
1.161   ! andreas  1361:                                active_state->keep_alive_timeouts = 0;
1.25      markus   1362:                                DBG(debug("received packet type %d", type));
1.153     djm      1363:                        }
1.74      deraadt  1364:                        switch (type) {
1.150     dtucker  1365:                        case SSH2_MSG_IGNORE:
1.151     dtucker  1366:                                debug3("Received SSH2_MSG_IGNORE");
1.150     dtucker  1367:                                break;
1.25      markus   1368:                        case SSH2_MSG_DEBUG:
                   1369:                                packet_get_char();
                   1370:                                msg = packet_get_string(NULL);
                   1371:                                debug("Remote: %.900s", msg);
                   1372:                                xfree(msg);
                   1373:                                msg = packet_get_string(NULL);
                   1374:                                xfree(msg);
                   1375:                                break;
                   1376:                        case SSH2_MSG_DISCONNECT:
                   1377:                                reason = packet_get_int();
                   1378:                                msg = packet_get_string(NULL);
1.106     itojun   1379:                                logit("Received disconnect from %s: %u: %.400s",
1.96      deraadt  1380:                                    get_remote_ipaddr(), reason, msg);
1.25      markus   1381:                                xfree(msg);
1.112     markus   1382:                                cleanup_exit(255);
1.84      markus   1383:                                break;
                   1384:                        case SSH2_MSG_UNIMPLEMENTED:
                   1385:                                seqnr = packet_get_int();
1.96      deraadt  1386:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1387:                                    seqnr);
1.150     dtucker  1388:                                break;
1.25      markus   1389:                        default:
                   1390:                                return type;
1.48      stevesk  1391:                        }
1.25      markus   1392:                } else {
1.82      markus   1393:                        type = packet_read_poll1();
1.74      deraadt  1394:                        switch (type) {
1.25      markus   1395:                        case SSH_MSG_IGNORE:
                   1396:                                break;
                   1397:                        case SSH_MSG_DEBUG:
                   1398:                                msg = packet_get_string(NULL);
                   1399:                                debug("Remote: %.900s", msg);
                   1400:                                xfree(msg);
                   1401:                                break;
                   1402:                        case SSH_MSG_DISCONNECT:
                   1403:                                msg = packet_get_string(NULL);
1.106     itojun   1404:                                logit("Received disconnect from %s: %.400s",
1.96      deraadt  1405:                                    get_remote_ipaddr(), msg);
1.112     markus   1406:                                cleanup_exit(255);
1.25      markus   1407:                                break;
                   1408:                        default:
1.62      markus   1409:                                if (type)
1.25      markus   1410:                                        DBG(debug("received packet type %d", type));
                   1411:                                return type;
1.48      stevesk  1412:                        }
1.25      markus   1413:                }
                   1414:        }
1.77      djm      1415: }
                   1416:
                   1417: int
1.82      markus   1418: packet_read_poll(void)
1.77      djm      1419: {
1.82      markus   1420:        return packet_read_poll_seqnr(NULL);
1.25      markus   1421: }
                   1422:
1.16      markus   1423: /*
                   1424:  * Buffers the given amount of input characters.  This is intended to be used
                   1425:  * together with packet_read_poll.
                   1426:  */
1.1       deraadt  1427:
1.2       provos   1428: void
1.40      markus   1429: packet_process_incoming(const char *buf, u_int len)
1.1       deraadt  1430: {
1.161   ! andreas  1431:        if (active_state->packet_discard) {
        !          1432:                active_state->keep_alive_timeouts = 0; /* ?? */
        !          1433:                if (len >= active_state->packet_discard)
1.159     markus   1434:                        packet_stop_discard();
1.161   ! andreas  1435:                active_state->packet_discard -= len;
1.159     markus   1436:                return;
                   1437:        }
1.161   ! andreas  1438:        buffer_append(&active_state->input, buf, len);
1.1       deraadt  1439: }
                   1440:
                   1441: /* Returns a character from the packet. */
                   1442:
1.40      markus   1443: u_int
1.73      itojun   1444: packet_get_char(void)
1.1       deraadt  1445: {
1.14      markus   1446:        char ch;
1.97      deraadt  1447:
1.161   ! andreas  1448:        buffer_get(&active_state->incoming_packet, &ch, 1);
1.40      markus   1449:        return (u_char) ch;
1.1       deraadt  1450: }
                   1451:
                   1452: /* Returns an integer from the packet data. */
                   1453:
1.40      markus   1454: u_int
1.73      itojun   1455: packet_get_int(void)
1.1       deraadt  1456: {
1.161   ! andreas  1457:        return buffer_get_int(&active_state->incoming_packet);
1.1       deraadt  1458: }
                   1459:
1.16      markus   1460: /*
                   1461:  * Returns an arbitrary precision integer from the packet data.  The integer
                   1462:  * must have been initialized before this call.
                   1463:  */
1.1       deraadt  1464:
1.2       provos   1465: void
1.80      markus   1466: packet_get_bignum(BIGNUM * value)
1.1       deraadt  1467: {
1.161   ! andreas  1468:        buffer_get_bignum(&active_state->incoming_packet, value);
1.24      markus   1469: }
                   1470:
                   1471: void
1.80      markus   1472: packet_get_bignum2(BIGNUM * value)
1.24      markus   1473: {
1.161   ! andreas  1474:        buffer_get_bignum2(&active_state->incoming_packet, value);
1.24      markus   1475: }
                   1476:
1.76      stevesk  1477: void *
1.117     djm      1478: packet_get_raw(u_int *length_ptr)
1.24      markus   1479: {
1.161   ! andreas  1480:        u_int bytes = buffer_len(&active_state->incoming_packet);
1.97      deraadt  1481:
1.24      markus   1482:        if (length_ptr != NULL)
                   1483:                *length_ptr = bytes;
1.161   ! andreas  1484:        return buffer_ptr(&active_state->incoming_packet);
1.28      markus   1485: }
                   1486:
                   1487: int
                   1488: packet_remaining(void)
                   1489: {
1.161   ! andreas  1490:        return buffer_len(&active_state->incoming_packet);
1.1       deraadt  1491: }
                   1492:
1.16      markus   1493: /*
                   1494:  * Returns a string from the packet data.  The string is allocated using
                   1495:  * xmalloc; it is the responsibility of the calling program to free it when
                   1496:  * no longer needed.  The length_ptr argument may be NULL, or point to an
                   1497:  * integer into which the length of the string is stored.
                   1498:  */
1.1       deraadt  1499:
1.76      stevesk  1500: void *
1.40      markus   1501: packet_get_string(u_int *length_ptr)
1.1       deraadt  1502: {
1.161   ! andreas  1503:        return buffer_get_string(&active_state->incoming_packet, length_ptr);
1.152     markus   1504: }
                   1505:
                   1506: void *
                   1507: packet_get_string_ptr(u_int *length_ptr)
                   1508: {
1.161   ! andreas  1509:        return buffer_get_string_ptr(&active_state->incoming_packet, length_ptr);
1.1       deraadt  1510: }
                   1511:
1.16      markus   1512: /*
                   1513:  * Sends a diagnostic message from the server to the client.  This message
                   1514:  * can be sent at any time (but not while constructing another message). The
                   1515:  * message is printed immediately, but only if the client is being executed
                   1516:  * in verbose mode.  These messages are primarily intended to ease debugging
                   1517:  * authentication problems.   The length of the formatted message must not
                   1518:  * exceed 1024 bytes.  This will automatically call packet_write_wait.
                   1519:  */
1.1       deraadt  1520:
1.2       provos   1521: void
1.14      markus   1522: packet_send_debug(const char *fmt,...)
1.1       deraadt  1523: {
1.14      markus   1524:        char buf[1024];
                   1525:        va_list args;
1.39      markus   1526:
                   1527:        if (compat20 && (datafellows & SSH_BUG_DEBUG))
                   1528:                return;
1.14      markus   1529:
                   1530:        va_start(args, fmt);
                   1531:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1532:        va_end(args);
                   1533:
1.30      markus   1534:        if (compat20) {
                   1535:                packet_start(SSH2_MSG_DEBUG);
                   1536:                packet_put_char(0);     /* bool: always display */
                   1537:                packet_put_cstring(buf);
                   1538:                packet_put_cstring("");
                   1539:        } else {
                   1540:                packet_start(SSH_MSG_DEBUG);
                   1541:                packet_put_cstring(buf);
                   1542:        }
1.14      markus   1543:        packet_send();
                   1544:        packet_write_wait();
1.1       deraadt  1545: }
                   1546:
1.16      markus   1547: /*
                   1548:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1549:  * connection, and exits.  This function never returns. The error message
                   1550:  * should not contain a newline.  The length of the formatted message must
                   1551:  * not exceed 1024 bytes.
                   1552:  */
1.1       deraadt  1553:
1.2       provos   1554: void
1.14      markus   1555: packet_disconnect(const char *fmt,...)
1.1       deraadt  1556: {
1.14      markus   1557:        char buf[1024];
                   1558:        va_list args;
                   1559:        static int disconnecting = 0;
1.97      deraadt  1560:
1.14      markus   1561:        if (disconnecting)      /* Guard against recursive invocations. */
                   1562:                fatal("packet_disconnect called recursively.");
                   1563:        disconnecting = 1;
                   1564:
1.16      markus   1565:        /*
                   1566:         * Format the message.  Note that the caller must make sure the
                   1567:         * message is of limited size.
                   1568:         */
1.14      markus   1569:        va_start(args, fmt);
                   1570:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1571:        va_end(args);
                   1572:
1.99      markus   1573:        /* Display the error locally */
1.106     itojun   1574:        logit("Disconnecting: %.100s", buf);
1.99      markus   1575:
1.14      markus   1576:        /* Send the disconnect message to the other side, and wait for it to get sent. */
1.25      markus   1577:        if (compat20) {
                   1578:                packet_start(SSH2_MSG_DISCONNECT);
                   1579:                packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
                   1580:                packet_put_cstring(buf);
                   1581:                packet_put_cstring("");
                   1582:        } else {
                   1583:                packet_start(SSH_MSG_DISCONNECT);
1.65      markus   1584:                packet_put_cstring(buf);
1.25      markus   1585:        }
1.14      markus   1586:        packet_send();
                   1587:        packet_write_wait();
                   1588:
                   1589:        /* Stop listening for connections. */
1.67      markus   1590:        channel_close_all();
1.14      markus   1591:
                   1592:        /* Close the connection. */
                   1593:        packet_close();
1.112     markus   1594:        cleanup_exit(255);
1.1       deraadt  1595: }
                   1596:
1.16      markus   1597: /* Checks if there is any buffered output, and tries to write some of the output. */
1.1       deraadt  1598:
1.2       provos   1599: void
1.73      itojun   1600: packet_write_poll(void)
1.1       deraadt  1601: {
1.161   ! andreas  1602:        int len = buffer_len(&active_state->output);
1.97      deraadt  1603:
1.14      markus   1604:        if (len > 0) {
1.161   ! andreas  1605:                len = write(active_state->connection_out,
        !          1606:                    buffer_ptr(&active_state->output), len);
1.156     djm      1607:                if (len == -1) {
                   1608:                        if (errno == EINTR || errno == EAGAIN)
1.14      markus   1609:                                return;
1.156     djm      1610:                        fatal("Write failed: %.100s", strerror(errno));
1.14      markus   1611:                }
1.156     djm      1612:                if (len == 0)
                   1613:                        fatal("Write connection closed");
1.161   ! andreas  1614:                buffer_consume(&active_state->output, len);
1.14      markus   1615:        }
1.1       deraadt  1616: }
                   1617:
1.16      markus   1618: /*
                   1619:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1620:  * written.
                   1621:  */
1.1       deraadt  1622:
1.2       provos   1623: void
1.73      itojun   1624: packet_write_wait(void)
1.1       deraadt  1625: {
1.56      millert  1626:        fd_set *setp;
1.154     dtucker  1627:        int ret, ms_remain;
                   1628:        struct timeval start, timeout, *timeoutp = NULL;
1.56      millert  1629:
1.161   ! andreas  1630:        setp = (fd_set *)xcalloc(howmany(active_state->connection_out + 1,
        !          1631:            NFDBITS), sizeof(fd_mask));
1.14      markus   1632:        packet_write_poll();
                   1633:        while (packet_have_data_to_write()) {
1.161   ! andreas  1634:                memset(setp, 0, howmany(active_state->connection_out + 1,
        !          1635:                    NFDBITS) * sizeof(fd_mask));
        !          1636:                FD_SET(active_state->connection_out, setp);
1.154     dtucker  1637:
1.161   ! andreas  1638:                if (active_state->packet_timeout_ms > 0) {
        !          1639:                        ms_remain = active_state->packet_timeout_ms;
1.154     dtucker  1640:                        timeoutp = &timeout;
                   1641:                }
                   1642:                for (;;) {
1.161   ! andreas  1643:                        if (active_state->packet_timeout_ms != -1) {
1.154     dtucker  1644:                                ms_to_timeval(&timeout, ms_remain);
                   1645:                                gettimeofday(&start, NULL);
                   1646:                        }
1.161   ! andreas  1647:                        if ((ret = select(active_state->connection_out + 1,
        !          1648:                            NULL, setp, NULL, timeoutp)) >= 0)
1.154     dtucker  1649:                                break;
1.161   ! andreas  1650:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1651:                                break;
1.161   ! andreas  1652:                        if (active_state->packet_timeout_ms == -1)
1.154     dtucker  1653:                                continue;
                   1654:                        ms_subtract_diff(&start, &ms_remain);
                   1655:                        if (ms_remain <= 0) {
                   1656:                                ret = 0;
                   1657:                                break;
                   1658:                        }
                   1659:                }
                   1660:                if (ret == 0) {
                   1661:                        logit("Connection to %.200s timed out while "
                   1662:                            "waiting to write", get_remote_ipaddr());
                   1663:                        cleanup_exit(255);
                   1664:                }
1.14      markus   1665:                packet_write_poll();
                   1666:        }
1.56      millert  1667:        xfree(setp);
1.1       deraadt  1668: }
                   1669:
                   1670: /* Returns true if there is buffered data to write to the connection. */
                   1671:
1.2       provos   1672: int
1.73      itojun   1673: packet_have_data_to_write(void)
1.1       deraadt  1674: {
1.161   ! andreas  1675:        return buffer_len(&active_state->output) != 0;
1.1       deraadt  1676: }
                   1677:
                   1678: /* Returns true if there is not too much data to write to the connection. */
                   1679:
1.2       provos   1680: int
1.73      itojun   1681: packet_not_very_much_data_to_write(void)
1.1       deraadt  1682: {
1.161   ! andreas  1683:        if (active_state->interactive_mode)
        !          1684:                return buffer_len(&active_state->output) < 16384;
1.14      markus   1685:        else
1.161   ! andreas  1686:                return buffer_len(&active_state->output) < 128 * 1024;
1.1       deraadt  1687: }
                   1688:
1.102     markus   1689: static void
1.101     markus   1690: packet_set_tos(int interactive)
                   1691: {
                   1692:        int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
                   1693:
                   1694:        if (!packet_connection_is_on_socket() ||
                   1695:            !packet_connection_is_ipv4())
                   1696:                return;
1.161   ! andreas  1697:        if (setsockopt(active_state->connection_in, IPPROTO_IP, IP_TOS, &tos,
1.101     markus   1698:            sizeof(tos)) < 0)
                   1699:                error("setsockopt IP_TOS %d: %.100s:",
                   1700:                    tos, strerror(errno));
                   1701: }
                   1702:
1.1       deraadt  1703: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   1704:
1.2       provos   1705: void
1.43      markus   1706: packet_set_interactive(int interactive)
1.1       deraadt  1707: {
1.43      markus   1708:        static int called = 0;
1.44      markus   1709:
1.43      markus   1710:        if (called)
                   1711:                return;
                   1712:        called = 1;
1.1       deraadt  1713:
1.14      markus   1714:        /* Record that we are in interactive mode. */
1.161   ! andreas  1715:        active_state->interactive_mode = interactive;
1.1       deraadt  1716:
1.19      markus   1717:        /* Only set socket options if using a socket.  */
                   1718:        if (!packet_connection_is_on_socket())
1.14      markus   1719:                return;
1.161   ! andreas  1720:        set_nodelay(active_state->connection_in);
1.101     markus   1721:        packet_set_tos(interactive);
1.1       deraadt  1722: }
                   1723:
                   1724: /* Returns true if the current connection is interactive. */
                   1725:
1.2       provos   1726: int
1.73      itojun   1727: packet_is_interactive(void)
1.1       deraadt  1728: {
1.161   ! andreas  1729:        return active_state->interactive_mode;
1.12      markus   1730: }
                   1731:
1.113     deraadt  1732: int
1.108     markus   1733: packet_set_maxsize(u_int s)
1.12      markus   1734: {
1.14      markus   1735:        static int called = 0;
1.97      deraadt  1736:
1.14      markus   1737:        if (called) {
1.106     itojun   1738:                logit("packet_set_maxsize: called twice: old %d new %d",
1.161   ! andreas  1739:                    active_state->max_packet_size, s);
1.14      markus   1740:                return -1;
                   1741:        }
                   1742:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   1743:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   1744:                return -1;
                   1745:        }
1.70      markus   1746:        called = 1;
1.66      markus   1747:        debug("packet_set_maxsize: setting to %d", s);
1.161   ! andreas  1748:        active_state->max_packet_size = s;
1.14      markus   1749:        return s;
1.53      markus   1750: }
                   1751:
1.161   ! andreas  1752: int
        !          1753: packet_inc_alive_timeouts(void)
        !          1754: {
        !          1755:        return ++active_state->keep_alive_timeouts;
        !          1756: }
        !          1757:
        !          1758: void
        !          1759: packet_set_alive_timeouts(int ka)
        !          1760: {
        !          1761:        active_state->keep_alive_timeouts = ka;
        !          1762: }
        !          1763:
        !          1764: u_int
        !          1765: packet_get_maxsize(void)
        !          1766: {
        !          1767:        return active_state->max_packet_size;
        !          1768: }
        !          1769:
1.71      markus   1770: /* roundup current message to pad bytes */
                   1771: void
                   1772: packet_add_padding(u_char pad)
                   1773: {
1.161   ! andreas  1774:        active_state->extra_pad = pad;
1.71      markus   1775: }
                   1776:
1.53      markus   1777: /*
                   1778:  * 9.2.  Ignored Data Message
1.61      markus   1779:  *
1.53      markus   1780:  *   byte      SSH_MSG_IGNORE
                   1781:  *   string    data
1.61      markus   1782:  *
1.53      markus   1783:  * All implementations MUST understand (and ignore) this message at any
                   1784:  * time (after receiving the protocol version). No implementation is
                   1785:  * required to send them. This message can be used as an additional
                   1786:  * protection measure against advanced traffic analysis techniques.
                   1787:  */
1.54      markus   1788: void
                   1789: packet_send_ignore(int nbytes)
                   1790: {
1.115     avsm     1791:        u_int32_t rnd = 0;
1.54      markus   1792:        int i;
                   1793:
                   1794:        packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1.53      markus   1795:        packet_put_int(nbytes);
1.75      deraadt  1796:        for (i = 0; i < nbytes; i++) {
1.53      markus   1797:                if (i % 4 == 0)
1.115     avsm     1798:                        rnd = arc4random();
1.129     deraadt  1799:                packet_put_char((u_char)rnd & 0xff);
1.115     avsm     1800:                rnd >>= 8;
1.53      markus   1801:        }
1.105     markus   1802: }
                   1803:
1.113     deraadt  1804: #define MAX_PACKETS    (1U<<31)
1.105     markus   1805: int
                   1806: packet_need_rekeying(void)
                   1807: {
                   1808:        if (datafellows & SSH_BUG_NOREKEY)
                   1809:                return 0;
                   1810:        return
1.161   ! andreas  1811:            (active_state->p_send.packets > MAX_PACKETS) ||
        !          1812:            (active_state->p_read.packets > MAX_PACKETS) ||
        !          1813:            (active_state->max_blocks_out &&
        !          1814:                (active_state->p_send.blocks > active_state->max_blocks_out)) ||
        !          1815:            (active_state->max_blocks_in &&
        !          1816:                (active_state->p_read.blocks > active_state->max_blocks_in));
1.105     markus   1817: }
                   1818:
                   1819: void
                   1820: packet_set_rekey_limit(u_int32_t bytes)
                   1821: {
1.161   ! andreas  1822:        active_state->rekey_limit = bytes;
1.118     markus   1823: }
                   1824:
                   1825: void
                   1826: packet_set_server(void)
                   1827: {
1.161   ! andreas  1828:        active_state->server_side = 1;
1.118     markus   1829: }
                   1830:
                   1831: void
                   1832: packet_set_authenticated(void)
                   1833: {
1.161   ! andreas  1834:        active_state->after_authentication = 1;
        !          1835: }
        !          1836:
        !          1837: void *
        !          1838: packet_get_input(void)
        !          1839: {
        !          1840:        return (void *)&active_state->input;
        !          1841: }
        !          1842:
        !          1843: void *
        !          1844: packet_get_output(void)
        !          1845: {
        !          1846:        return (void *)&active_state->output;
        !          1847: }
        !          1848:
        !          1849: void *
        !          1850: packet_get_newkeys(int mode)
        !          1851: {
        !          1852:        return (void *)active_state->newkeys[mode];
1.1       deraadt  1853: }