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

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