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

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