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

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