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

1.206     jsg         1: /* $OpenBSD: packet.c,v 1.205 2015/01/30 01:13:33 djm Exp $ */
1.1       deraadt     2: /*
1.15      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.35      deraadt     6:  * This file contains code implementing the packet protocol and communication
                      7:  * with the other side.  This same code is used both on client and server side.
1.29      markus      8:  *
1.35      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
1.29      markus     14:  *
1.25      markus     15:  *
                     16:  * SSH2 packet format added by Markus Friedl.
1.69      markus     17:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.25      markus     18:  *
1.35      deraadt    19:  * Redistribution and use in source and binary forms, with or without
                     20:  * modification, are permitted provided that the following conditions
                     21:  * are met:
                     22:  * 1. Redistributions of source code must retain the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer.
                     24:  * 2. Redistributions in binary form must reproduce the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer in the
                     26:  *    documentation and/or other materials provided with the distribution.
                     27:  *
                     28:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     29:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     30:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     31:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     32:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     33:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     34:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     35:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     36:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     37:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.15      deraadt    38:  */
1.1       deraadt    39:
1.203     deraadt    40: #include <sys/param.h> /* MIN roundup */
1.142     deraadt    41: #include <sys/types.h>
1.105     markus     42: #include <sys/queue.h>
1.132     stevesk    43: #include <sys/socket.h>
1.138     stevesk    44: #include <sys/time.h>
1.132     stevesk    45: #include <netinet/in.h>
1.121     stevesk    46: #include <netinet/ip.h>
1.134     stevesk    47:
1.135     stevesk    48: #include <errno.h>
1.134     stevesk    49: #include <stdarg.h>
1.141     stevesk    50: #include <stdio.h>
1.140     stevesk    51: #include <stdlib.h>
1.137     stevesk    52: #include <string.h>
1.136     stevesk    53: #include <unistd.h>
1.203     deraadt    54: #include <limits.h>
1.142     deraadt    55: #include <signal.h>
1.184     dtucker    56: #include <time.h>
1.1       deraadt    57:
1.201     markus     58: #include <zlib.h>
                     59:
                     60: #include "buffer.h"    /* typedefs XXX */
                     61: #include "key.h"       /* typedefs XXX */
                     62:
1.1       deraadt    63: #include "xmalloc.h"
                     64: #include "crc32.h"
1.9       dugsong    65: #include "deattack.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.201     markus     70: #include "sshkey.h"
1.25      markus     71: #include "kex.h"
1.200     markus     72: #include "digest.h"
1.50      markus     73: #include "mac.h"
1.46      markus     74: #include "log.h"
                     75: #include "canohost.h"
1.87      stevesk    76: #include "misc.h"
1.198     millert    77: #include "channels.h"
1.95      markus     78: #include "ssh.h"
1.201     markus     79: #include "packet.h"
                     80: #include "roaming.h"
1.197     djm        81: #include "ssherr.h"
1.201     markus     82: #include "sshbuf.h"
1.25      markus     83:
                     84: #ifdef PACKET_DEBUG
                     85: #define DBG(x) x
                     86: #else
                     87: #define DBG(x)
                     88: #endif
                     89:
1.159     markus     90: #define PACKET_MAX_SIZE (256 * 1024)
                     91:
1.161     andreas    92: struct packet_state {
                     93:        u_int32_t seqnr;
                     94:        u_int32_t packets;
                     95:        u_int64_t blocks;
                     96:        u_int64_t bytes;
                     97: };
                     98:
                     99: struct packet {
                    100:        TAILQ_ENTRY(packet) next;
                    101:        u_char type;
1.201     markus    102:        struct sshbuf *payload;
1.161     andreas   103: };
                    104:
                    105: struct session_state {
                    106:        /*
                    107:         * This variable contains the file descriptors used for
                    108:         * communicating with the other side.  connection_in is used for
                    109:         * reading; connection_out for writing.  These can be the same
                    110:         * descriptor, in which case it is assumed to be a socket.
                    111:         */
                    112:        int connection_in;
                    113:        int connection_out;
                    114:
                    115:        /* Protocol flags for the remote side. */
                    116:        u_int remote_protocol_flags;
1.1       deraadt   117:
1.161     andreas   118:        /* Encryption context for receiving data.  Only used for decryption. */
1.201     markus    119:        struct sshcipher_ctx receive_context;
1.1       deraadt   120:
1.161     andreas   121:        /* Encryption context for sending data.  Only used for encryption. */
1.201     markus    122:        struct sshcipher_ctx send_context;
1.14      markus    123:
1.161     andreas   124:        /* Buffer for raw input data from the socket. */
1.201     markus    125:        struct sshbuf *input;
1.1       deraadt   126:
1.161     andreas   127:        /* Buffer for raw output data going to the socket. */
1.201     markus    128:        struct sshbuf *output;
1.1       deraadt   129:
1.161     andreas   130:        /* Buffer for the partial outgoing packet being constructed. */
1.201     markus    131:        struct sshbuf *outgoing_packet;
1.1       deraadt   132:
1.161     andreas   133:        /* Buffer for the incoming packet currently being processed. */
1.201     markus    134:        struct sshbuf *incoming_packet;
1.1       deraadt   135:
1.161     andreas   136:        /* Scratch buffer for packet compression/decompression. */
1.201     markus    137:        struct sshbuf *compression_buffer;
                    138:
                    139:        /* Incoming/outgoing compression dictionaries */
                    140:        z_stream compression_in_stream;
                    141:        z_stream compression_out_stream;
                    142:        int compression_in_started;
                    143:        int compression_out_started;
                    144:        int compression_in_failures;
                    145:        int compression_out_failures;
1.1       deraadt   146:
1.161     andreas   147:        /*
                    148:         * Flag indicating whether packet compression/decompression is
                    149:         * enabled.
                    150:         */
                    151:        int packet_compression;
1.1       deraadt   152:
1.161     andreas   153:        /* default maximum packet size */
                    154:        u_int max_packet_size;
1.1       deraadt   155:
1.161     andreas   156:        /* Flag indicating whether this module has been initialized. */
                    157:        int initialized;
1.12      markus    158:
1.161     andreas   159:        /* Set to true if the connection is interactive. */
                    160:        int interactive_mode;
1.1       deraadt   161:
1.161     andreas   162:        /* Set to true if we are the server side. */
                    163:        int server_side;
1.1       deraadt   164:
1.161     andreas   165:        /* Set to true if we are authenticated. */
                    166:        int after_authentication;
1.118     markus    167:
1.161     andreas   168:        int keep_alive_timeouts;
1.118     markus    169:
1.161     andreas   170:        /* The maximum time that we will wait to send or receive a packet */
                    171:        int packet_timeout_ms;
1.151     dtucker   172:
1.161     andreas   173:        /* Session key information for Encryption and MAC */
1.201     markus    174:        struct newkeys *newkeys[MODE_MAX];
1.161     andreas   175:        struct packet_state p_read, p_send;
1.154     dtucker   176:
1.184     dtucker   177:        /* Volume-based rekeying */
1.161     andreas   178:        u_int64_t max_blocks_in, max_blocks_out;
                    179:        u_int32_t rekey_limit;
1.105     markus    180:
1.184     dtucker   181:        /* Time-based rekeying */
                    182:        time_t rekey_interval;  /* how often in seconds */
                    183:        time_t rekey_time;      /* time of last rekeying */
                    184:
1.161     andreas   185:        /* Session key for protocol v1 */
                    186:        u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
                    187:        u_int ssh1_keylen;
1.25      markus    188:
1.161     andreas   189:        /* roundup current message to extra_pad bytes */
                    190:        u_char extra_pad;
1.95      markus    191:
1.161     andreas   192:        /* XXX discard incoming data after MAC error */
                    193:        u_int packet_discard;
1.201     markus    194:        struct sshmac *packet_discard_mac;
1.71      markus    195:
1.161     andreas   196:        /* Used in packet_read_poll2() */
                    197:        u_int packlen;
1.159     markus    198:
1.165     andreas   199:        /* Used in packet_send2 */
                    200:        int rekeying;
                    201:
                    202:        /* Used in packet_set_interactive */
                    203:        int set_interactive_called;
                    204:
                    205:        /* Used in packet_set_maxsize */
                    206:        int set_maxsize_called;
                    207:
1.201     markus    208:        /* One-off warning about weak ciphers */
                    209:        int cipher_warning_done;
                    210:
                    211:        /* SSH1 CRC compensation attack detector */
                    212:        struct deattack_ctx deattack;
                    213:
1.161     andreas   214:        TAILQ_HEAD(, packet) outgoing;
1.105     markus    215: };
1.161     andreas   216:
1.201     markus    217: struct ssh *
                    218: ssh_alloc_session_state(void)
1.161     andreas   219: {
1.201     markus    220:        struct ssh *ssh = NULL;
                    221:        struct session_state *state = NULL;
1.161     andreas   222:
1.201     markus    223:        if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
                    224:            (state = calloc(1, sizeof(*state))) == NULL ||
                    225:            (state->input = sshbuf_new()) == NULL ||
                    226:            (state->output = sshbuf_new()) == NULL ||
                    227:            (state->outgoing_packet = sshbuf_new()) == NULL ||
                    228:            (state->incoming_packet = sshbuf_new()) == NULL)
                    229:                goto fail;
                    230:        TAILQ_INIT(&state->outgoing);
1.202     markus    231:        TAILQ_INIT(&ssh->private_keys);
                    232:        TAILQ_INIT(&ssh->public_keys);
1.201     markus    233:        state->connection_in = -1;
                    234:        state->connection_out = -1;
                    235:        state->max_packet_size = 32768;
                    236:        state->packet_timeout_ms = -1;
                    237:        state->p_send.packets = state->p_read.packets = 0;
                    238:        state->initialized = 1;
                    239:        /*
                    240:         * ssh_packet_send2() needs to queue packets until
                    241:         * we've done the initial key exchange.
                    242:         */
                    243:        state->rekeying = 1;
                    244:        ssh->state = state;
                    245:        return ssh;
                    246:  fail:
                    247:        if (state) {
                    248:                sshbuf_free(state->input);
                    249:                sshbuf_free(state->output);
                    250:                sshbuf_free(state->incoming_packet);
                    251:                sshbuf_free(state->outgoing_packet);
                    252:                free(state);
                    253:        }
                    254:        free(ssh);
                    255:        return NULL;
1.161     andreas   256: }
1.105     markus    257:
1.16      markus    258: /*
                    259:  * Sets the descriptors used for communication.  Disables encryption until
                    260:  * packet_set_encryption_key is called.
                    261:  */
1.201     markus    262: struct ssh *
                    263: ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
1.1       deraadt   264: {
1.201     markus    265:        struct session_state *state;
                    266:        const struct sshcipher *none = cipher_by_name("none");
1.197     djm       267:        int r;
1.97      deraadt   268:
1.205     djm       269:        if (none == NULL) {
                    270:                error("%s: cannot load cipher 'none'", __func__);
                    271:                return NULL;
                    272:        }
1.201     markus    273:        if (ssh == NULL)
                    274:                ssh = ssh_alloc_session_state();
1.205     djm       275:        if (ssh == NULL) {
                    276:                error("%s: cound not allocate state", __func__);
                    277:                return NULL;
                    278:        }
1.201     markus    279:        state = ssh->state;
                    280:        state->connection_in = fd_in;
                    281:        state->connection_out = fd_out;
                    282:        if ((r = cipher_init(&state->send_context, none,
1.197     djm       283:            (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
1.201     markus    284:            (r = cipher_init(&state->receive_context, none,
1.205     djm       285:            (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
                    286:                error("%s: cipher_init failed: %s", __func__, ssh_err(r));
                    287:                return NULL;
                    288:        }
1.201     markus    289:        state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
                    290:        deattack_init(&state->deattack);
1.207   ! djm       291:        /*
        !           292:         * Cache the IP address of the remote connection for use in error
        !           293:         * messages that might be generated after the connection has closed.
        !           294:         */
        !           295:        (void)ssh_remote_ipaddr(ssh);
1.201     markus    296:        return ssh;
1.1       deraadt   297: }
                    298:
1.154     dtucker   299: void
1.201     markus    300: ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
1.154     dtucker   301: {
1.201     markus    302:        struct session_state *state = ssh->state;
                    303:
1.174     djm       304:        if (timeout <= 0 || count <= 0) {
1.201     markus    305:                state->packet_timeout_ms = -1;
1.154     dtucker   306:                return;
                    307:        }
                    308:        if ((INT_MAX / 1000) / count < timeout)
1.201     markus    309:                state->packet_timeout_ms = INT_MAX;
1.154     dtucker   310:        else
1.201     markus    311:                state->packet_timeout_ms = timeout * count * 1000;
1.154     dtucker   312: }
                    313:
1.201     markus    314: int
                    315: ssh_packet_stop_discard(struct ssh *ssh)
1.159     markus    316: {
1.201     markus    317:        struct session_state *state = ssh->state;
                    318:        int r;
                    319:
                    320:        if (state->packet_discard_mac) {
1.159     markus    321:                char buf[1024];
1.201     markus    322:
1.159     markus    323:                memset(buf, 'a', sizeof(buf));
1.201     markus    324:                while (sshbuf_len(state->incoming_packet) <
1.161     andreas   325:                    PACKET_MAX_SIZE)
1.201     markus    326:                        if ((r = sshbuf_put(state->incoming_packet, buf,
                    327:                            sizeof(buf))) != 0)
                    328:                                return r;
                    329:                (void) mac_compute(state->packet_discard_mac,
                    330:                    state->p_read.seqnr,
                    331:                    sshbuf_ptr(state->incoming_packet), PACKET_MAX_SIZE,
                    332:                    NULL, 0);
1.159     markus    333:        }
1.201     markus    334:        logit("Finished discarding for %.200s", ssh_remote_ipaddr(ssh));
                    335:        return SSH_ERR_MAC_INVALID;
1.159     markus    336: }
                    337:
1.201     markus    338: static int
                    339: ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
                    340:     struct sshmac *mac, u_int packet_length, u_int discard)
1.159     markus    341: {
1.201     markus    342:        struct session_state *state = ssh->state;
                    343:        int r;
                    344:
                    345:        if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
                    346:                if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
                    347:                        return r;
                    348:                return SSH_ERR_MAC_INVALID;
                    349:        }
1.159     markus    350:        if (packet_length != PACKET_MAX_SIZE && mac && mac->enabled)
1.201     markus    351:                state->packet_discard_mac = mac;
                    352:        if (sshbuf_len(state->input) >= discard &&
                    353:           (r = ssh_packet_stop_discard(ssh)) != 0)
                    354:                return r;
                    355:        state->packet_discard = discard - sshbuf_len(state->input);
                    356:        return 0;
1.159     markus    357: }
                    358:
1.19      markus    359: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    360:
                    361: int
1.201     markus    362: ssh_packet_connection_is_on_socket(struct ssh *ssh)
1.19      markus    363: {
1.201     markus    364:        struct session_state *state = ssh->state;
1.19      markus    365:        struct sockaddr_storage from, to;
                    366:        socklen_t fromlen, tolen;
                    367:
                    368:        /* filedescriptors in and out are the same, so it's a socket */
1.201     markus    369:        if (state->connection_in == state->connection_out)
1.19      markus    370:                return 1;
                    371:        fromlen = sizeof(from);
                    372:        memset(&from, 0, sizeof(from));
1.201     markus    373:        if (getpeername(state->connection_in, (struct sockaddr *)&from,
1.161     andreas   374:            &fromlen) < 0)
1.19      markus    375:                return 0;
                    376:        tolen = sizeof(to);
                    377:        memset(&to, 0, sizeof(to));
1.201     markus    378:        if (getpeername(state->connection_out, (struct sockaddr *)&to,
1.161     andreas   379:            &tolen) < 0)
1.19      markus    380:                return 0;
                    381:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    382:                return 0;
                    383:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    384:                return 0;
                    385:        return 1;
                    386: }
                    387:
1.91      markus    388: void
1.201     markus    389: ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
1.91      markus    390: {
1.201     markus    391:        if (ibytes)
                    392:                *ibytes = ssh->state->p_read.bytes;
                    393:        if (obytes)
                    394:                *obytes = ssh->state->p_send.bytes;
1.91      markus    395: }
1.125     deraadt   396:
1.91      markus    397: int
1.201     markus    398: ssh_packet_connection_af(struct ssh *ssh)
1.19      markus    399: {
                    400:        struct sockaddr_storage to;
1.21      deraadt   401:        socklen_t tolen = sizeof(to);
1.19      markus    402:
                    403:        memset(&to, 0, sizeof(to));
1.201     markus    404:        if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
1.161     andreas   405:            &tolen) < 0)
1.19      markus    406:                return 0;
1.173     djm       407:        return to.ss_family;
1.19      markus    408: }
                    409:
1.1       deraadt   410: /* Sets the connection into non-blocking mode. */
                    411:
1.2       provos    412: void
1.201     markus    413: ssh_packet_set_nonblocking(struct ssh *ssh)
1.1       deraadt   414: {
1.14      markus    415:        /* Set the socket into non-blocking mode. */
1.201     markus    416:        set_nonblock(ssh->state->connection_in);
1.14      markus    417:
1.201     markus    418:        if (ssh->state->connection_out != ssh->state->connection_in)
                    419:                set_nonblock(ssh->state->connection_out);
1.1       deraadt   420: }
                    421:
                    422: /* Returns the socket used for reading. */
                    423:
1.2       provos    424: int
1.201     markus    425: ssh_packet_get_connection_in(struct ssh *ssh)
1.1       deraadt   426: {
1.201     markus    427:        return ssh->state->connection_in;
1.1       deraadt   428: }
                    429:
                    430: /* Returns the descriptor used for writing. */
                    431:
1.2       provos    432: int
1.201     markus    433: ssh_packet_get_connection_out(struct ssh *ssh)
1.1       deraadt   434: {
1.201     markus    435:        return ssh->state->connection_out;
                    436: }
                    437:
                    438: /*
                    439:  * Returns the IP-address of the remote host as a string.  The returned
                    440:  * string must not be freed.
                    441:  */
                    442:
                    443: const char *
                    444: ssh_remote_ipaddr(struct ssh *ssh)
                    445: {
                    446:        /* Check whether we have cached the ipaddr. */
                    447:        if (ssh->remote_ipaddr == NULL)
                    448:                ssh->remote_ipaddr = ssh_packet_connection_is_on_socket(ssh) ?
                    449:                    get_peer_ipaddr(ssh->state->connection_in) :
                    450:                    strdup("UNKNOWN");
                    451:        if (ssh->remote_ipaddr == NULL)
                    452:                return "UNKNOWN";
                    453:        return ssh->remote_ipaddr;
1.1       deraadt   454: }
                    455:
                    456: /* Closes the connection and clears and frees internal data structures. */
                    457:
1.2       provos    458: void
1.201     markus    459: ssh_packet_close(struct ssh *ssh)
1.1       deraadt   460: {
1.201     markus    461:        struct session_state *state = ssh->state;
                    462:        int r;
                    463:        u_int mode;
                    464:
                    465:        if (!state->initialized)
1.14      markus    466:                return;
1.201     markus    467:        state->initialized = 0;
                    468:        if (state->connection_in == state->connection_out) {
                    469:                shutdown(state->connection_out, SHUT_RDWR);
                    470:                close(state->connection_out);
1.14      markus    471:        } else {
1.201     markus    472:                close(state->connection_in);
                    473:                close(state->connection_out);
1.14      markus    474:        }
1.201     markus    475:        sshbuf_free(state->input);
                    476:        sshbuf_free(state->output);
                    477:        sshbuf_free(state->outgoing_packet);
                    478:        sshbuf_free(state->incoming_packet);
                    479:        for (mode = 0; mode < MODE_MAX; mode++)
                    480:                kex_free_newkeys(state->newkeys[mode]);
                    481:        if (state->compression_buffer) {
                    482:                sshbuf_free(state->compression_buffer);
                    483:                if (state->compression_out_started) {
                    484:                        z_streamp stream = &state->compression_out_stream;
                    485:                        debug("compress outgoing: "
                    486:                            "raw data %llu, compressed %llu, factor %.2f",
                    487:                                (unsigned long long)stream->total_in,
                    488:                                (unsigned long long)stream->total_out,
                    489:                                stream->total_in == 0 ? 0.0 :
                    490:                                (double) stream->total_out / stream->total_in);
                    491:                        if (state->compression_out_failures == 0)
                    492:                                deflateEnd(stream);
                    493:                }
                    494:                if (state->compression_in_started) {
                    495:                        z_streamp stream = &state->compression_out_stream;
                    496:                        debug("compress incoming: "
                    497:                            "raw data %llu, compressed %llu, factor %.2f",
                    498:                            (unsigned long long)stream->total_out,
                    499:                            (unsigned long long)stream->total_in,
                    500:                            stream->total_out == 0 ? 0.0 :
                    501:                            (double) stream->total_in / stream->total_out);
                    502:                        if (state->compression_in_failures == 0)
                    503:                                inflateEnd(stream);
                    504:                }
1.14      markus    505:        }
1.201     markus    506:        if ((r = cipher_cleanup(&state->send_context)) != 0)
                    507:                error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
                    508:        if ((r = cipher_cleanup(&state->receive_context)) != 0)
                    509:                error("%s: cipher_cleanup failed: %s", __func__, ssh_err(r));
                    510:        if (ssh->remote_ipaddr) {
                    511:                free(ssh->remote_ipaddr);
                    512:                ssh->remote_ipaddr = NULL;
                    513:        }
                    514:        free(ssh->state);
                    515:        ssh->state = NULL;
1.1       deraadt   516: }
                    517:
                    518: /* Sets remote side protocol flags. */
                    519:
1.2       provos    520: void
1.201     markus    521: ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
1.1       deraadt   522: {
1.201     markus    523:        ssh->state->remote_protocol_flags = protocol_flags;
1.1       deraadt   524: }
                    525:
                    526: /* Returns the remote protocol flags set earlier by the above function. */
                    527:
1.40      markus    528: u_int
1.201     markus    529: ssh_packet_get_protocol_flags(struct ssh *ssh)
1.1       deraadt   530: {
1.201     markus    531:        return ssh->state->remote_protocol_flags;
1.1       deraadt   532: }
                    533:
1.16      markus    534: /*
                    535:  * Starts packet compression from the next packet on in both directions.
                    536:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    537:  */
1.1       deraadt   538:
1.201     markus    539: static int
                    540: ssh_packet_init_compression(struct ssh *ssh)
1.60      markus    541: {
1.201     markus    542:        if (!ssh->state->compression_buffer &&
                    543:           ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
                    544:                return SSH_ERR_ALLOC_FAIL;
                    545:        return 0;
1.60      markus    546: }
                    547:
1.201     markus    548: static int
                    549: start_compression_out(struct ssh *ssh, int level)
1.1       deraadt   550: {
1.201     markus    551:        if (level < 1 || level > 9)
                    552:                return SSH_ERR_INVALID_ARGUMENT;
                    553:        debug("Enabling compression at level %d.", level);
                    554:        if (ssh->state->compression_out_started == 1)
                    555:                deflateEnd(&ssh->state->compression_out_stream);
                    556:        switch (deflateInit(&ssh->state->compression_out_stream, level)) {
                    557:        case Z_OK:
                    558:                ssh->state->compression_out_started = 1;
                    559:                break;
                    560:        case Z_MEM_ERROR:
                    561:                return SSH_ERR_ALLOC_FAIL;
                    562:        default:
                    563:                return SSH_ERR_INTERNAL_ERROR;
                    564:        }
                    565:        return 0;
1.1       deraadt   566: }
                    567:
1.201     markus    568: static int
                    569: start_compression_in(struct ssh *ssh)
                    570: {
                    571:        if (ssh->state->compression_in_started == 1)
                    572:                inflateEnd(&ssh->state->compression_in_stream);
                    573:        switch (inflateInit(&ssh->state->compression_in_stream)) {
                    574:        case Z_OK:
                    575:                ssh->state->compression_in_started = 1;
                    576:                break;
                    577:        case Z_MEM_ERROR:
                    578:                return SSH_ERR_ALLOC_FAIL;
                    579:        default:
                    580:                return SSH_ERR_INTERNAL_ERROR;
                    581:        }
                    582:        return 0;
                    583: }
1.95      markus    584:
1.201     markus    585: int
                    586: ssh_packet_start_compression(struct ssh *ssh, int level)
1.1       deraadt   587: {
1.197     djm       588:        int r;
1.97      deraadt   589:
1.201     markus    590:        if (ssh->state->packet_compression && !compat20)
                    591:                return SSH_ERR_INTERNAL_ERROR;
                    592:        ssh->state->packet_compression = 1;
                    593:        if ((r = ssh_packet_init_compression(ssh)) != 0 ||
                    594:            (r = start_compression_in(ssh)) != 0 ||
                    595:            (r = start_compression_out(ssh, level)) != 0)
                    596:                return r;
                    597:        return 0;
1.95      markus    598: }
                    599:
1.201     markus    600: /* XXX remove need for separate compression buffer */
                    601: static int
                    602: compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
1.95      markus    603: {
1.201     markus    604:        u_char buf[4096];
                    605:        int r, status;
                    606:
                    607:        if (ssh->state->compression_out_started != 1)
                    608:                return SSH_ERR_INTERNAL_ERROR;
                    609:
                    610:        /* This case is not handled below. */
                    611:        if (sshbuf_len(in) == 0)
                    612:                return 0;
                    613:
                    614:        /* Input is the contents of the input buffer. */
                    615:        if ((ssh->state->compression_out_stream.next_in =
                    616:            sshbuf_mutable_ptr(in)) == NULL)
                    617:                return SSH_ERR_INTERNAL_ERROR;
                    618:        ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
                    619:
                    620:        /* Loop compressing until deflate() returns with avail_out != 0. */
                    621:        do {
                    622:                /* Set up fixed-size output buffer. */
                    623:                ssh->state->compression_out_stream.next_out = buf;
                    624:                ssh->state->compression_out_stream.avail_out = sizeof(buf);
                    625:
                    626:                /* Compress as much data into the buffer as possible. */
                    627:                status = deflate(&ssh->state->compression_out_stream,
                    628:                    Z_PARTIAL_FLUSH);
                    629:                switch (status) {
                    630:                case Z_MEM_ERROR:
                    631:                        return SSH_ERR_ALLOC_FAIL;
                    632:                case Z_OK:
                    633:                        /* Append compressed data to output_buffer. */
                    634:                        if ((r = sshbuf_put(out, buf, sizeof(buf) -
                    635:                            ssh->state->compression_out_stream.avail_out)) != 0)
                    636:                                return r;
                    637:                        break;
                    638:                case Z_STREAM_ERROR:
                    639:                default:
                    640:                        ssh->state->compression_out_failures++;
                    641:                        return SSH_ERR_INVALID_FORMAT;
                    642:                }
                    643:        } while (ssh->state->compression_out_stream.avail_out == 0);
                    644:        return 0;
1.1       deraadt   645: }
                    646:
1.201     markus    647: static int
                    648: uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
1.1       deraadt   649: {
1.201     markus    650:        u_char buf[4096];
                    651:        int r, status;
1.1       deraadt   652:
1.201     markus    653:        if (ssh->state->compression_in_started != 1)
                    654:                return SSH_ERR_INTERNAL_ERROR;
1.25      markus    655:
1.201     markus    656:        if ((ssh->state->compression_in_stream.next_in =
                    657:            sshbuf_mutable_ptr(in)) == NULL)
                    658:                return SSH_ERR_INTERNAL_ERROR;
                    659:        ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
1.97      deraadt   660:
1.201     markus    661:        for (;;) {
                    662:                /* Set up fixed-size output buffer. */
                    663:                ssh->state->compression_in_stream.next_out = buf;
                    664:                ssh->state->compression_in_stream.avail_out = sizeof(buf);
                    665:
                    666:                status = inflate(&ssh->state->compression_in_stream,
                    667:                    Z_PARTIAL_FLUSH);
                    668:                switch (status) {
                    669:                case Z_OK:
                    670:                        if ((r = sshbuf_put(out, buf, sizeof(buf) -
                    671:                            ssh->state->compression_in_stream.avail_out)) != 0)
                    672:                                return r;
                    673:                        break;
                    674:                case Z_BUF_ERROR:
                    675:                        /*
                    676:                         * Comments in zlib.h say that we should keep calling
                    677:                         * inflate() until we get an error.  This appears to
                    678:                         * be the error that we get.
                    679:                         */
                    680:                        return 0;
                    681:                case Z_DATA_ERROR:
                    682:                        return SSH_ERR_INVALID_FORMAT;
                    683:                case Z_MEM_ERROR:
                    684:                        return SSH_ERR_ALLOC_FAIL;
                    685:                case Z_STREAM_ERROR:
                    686:                default:
                    687:                        ssh->state->compression_in_failures++;
                    688:                        return SSH_ERR_INTERNAL_ERROR;
                    689:                }
                    690:        }
                    691:        /* NOTREACHED */
1.1       deraadt   692: }
1.125     deraadt   693:
1.201     markus    694: /* Serialise compression state into a blob for privsep */
                    695: static int
                    696: ssh_packet_get_compress_state(struct sshbuf *m, struct ssh *ssh)
1.1       deraadt   697: {
1.201     markus    698:        struct session_state *state = ssh->state;
                    699:        struct sshbuf *b;
                    700:        int r;
                    701:
                    702:        if ((b = sshbuf_new()) == NULL)
                    703:                return SSH_ERR_ALLOC_FAIL;
                    704:        if (state->compression_in_started) {
                    705:                if ((r = sshbuf_put_string(b, &state->compression_in_stream,
                    706:                    sizeof(state->compression_in_stream))) != 0)
                    707:                        goto out;
                    708:        } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
                    709:                goto out;
                    710:        if (state->compression_out_started) {
                    711:                if ((r = sshbuf_put_string(b, &state->compression_out_stream,
                    712:                    sizeof(state->compression_out_stream))) != 0)
                    713:                        goto out;
                    714:        } else if ((r = sshbuf_put_string(b, NULL, 0)) != 0)
                    715:                goto out;
                    716:        r = sshbuf_put_stringb(m, b);
                    717:  out:
                    718:        sshbuf_free(b);
                    719:        return r;
1.1       deraadt   720: }
1.125     deraadt   721:
1.201     markus    722: /* Deserialise compression state from a blob for privsep */
                    723: static int
                    724: ssh_packet_set_compress_state(struct ssh *ssh, struct sshbuf *m)
1.162     andreas   725: {
1.201     markus    726:        struct session_state *state = ssh->state;
                    727:        struct sshbuf *b = NULL;
                    728:        int r;
                    729:        const u_char *inblob, *outblob;
                    730:        size_t inl, outl;
1.162     andreas   731:
1.201     markus    732:        if ((r = sshbuf_froms(m, &b)) != 0)
                    733:                goto out;
                    734:        if ((r = sshbuf_get_string_direct(b, &inblob, &inl)) != 0 ||
                    735:            (r = sshbuf_get_string_direct(b, &outblob, &outl)) != 0)
                    736:                goto out;
                    737:        if (inl == 0)
                    738:                state->compression_in_started = 0;
                    739:        else if (inl != sizeof(state->compression_in_stream)) {
                    740:                r = SSH_ERR_INTERNAL_ERROR;
                    741:                goto out;
                    742:        } else {
                    743:                state->compression_in_started = 1;
                    744:                memcpy(&state->compression_in_stream, inblob, inl);
                    745:        }
                    746:        if (outl == 0)
                    747:                state->compression_out_started = 0;
                    748:        else if (outl != sizeof(state->compression_out_stream)) {
                    749:                r = SSH_ERR_INTERNAL_ERROR;
                    750:                goto out;
                    751:        } else {
                    752:                state->compression_out_started = 1;
                    753:                memcpy(&state->compression_out_stream, outblob, outl);
                    754:        }
                    755:        r = 0;
                    756:  out:
                    757:        sshbuf_free(b);
                    758:        return r;
1.1       deraadt   759: }
1.125     deraadt   760:
1.24      markus    761: void
1.201     markus    762: ssh_packet_set_compress_hooks(struct ssh *ssh, void *ctx,
                    763:     void *(*allocfunc)(void *, u_int, u_int),
                    764:     void (*freefunc)(void *, void *))
                    765: {
                    766:        ssh->state->compression_out_stream.zalloc = (alloc_func)allocfunc;
                    767:        ssh->state->compression_out_stream.zfree = (free_func)freefunc;
                    768:        ssh->state->compression_out_stream.opaque = ctx;
                    769:        ssh->state->compression_in_stream.zalloc = (alloc_func)allocfunc;
                    770:        ssh->state->compression_in_stream.zfree = (free_func)freefunc;
                    771:        ssh->state->compression_in_stream.opaque = ctx;
1.24      markus    772: }
1.125     deraadt   773:
1.201     markus    774: /*
                    775:  * Causes any further packets to be encrypted using the given key.  The same
                    776:  * key is used for both sending and reception.  However, both directions are
                    777:  * encrypted independently of each other.
                    778:  */
1.125     deraadt   779:
1.195     markus    780: #ifdef WITH_OPENSSL
1.2       provos    781: void
1.201     markus    782: ssh_packet_set_encryption_key(struct ssh *ssh, const u_char *key, u_int keylen, int number)
1.1       deraadt   783: {
1.201     markus    784:        struct session_state *state = ssh->state;
                    785:        const struct sshcipher *cipher = cipher_by_number(number);
                    786:        int r;
                    787:        const char *wmsg;
1.125     deraadt   788:
1.201     markus    789:        if (cipher == NULL)
                    790:                fatal("%s: unknown cipher number %d", __func__, number);
                    791:        if (keylen < 20)
                    792:                fatal("%s: keylen too small: %d", __func__, keylen);
                    793:        if (keylen > SSH_SESSION_KEY_LENGTH)
                    794:                fatal("%s: keylen too big: %d", __func__, keylen);
                    795:        memcpy(state->ssh1_key, key, keylen);
                    796:        state->ssh1_keylen = keylen;
                    797:        if ((r = cipher_init(&state->send_context, cipher, key, keylen,
                    798:            NULL, 0, CIPHER_ENCRYPT)) != 0 ||
                    799:            (r = cipher_init(&state->receive_context, cipher, key, keylen,
                    800:            NULL, 0, CIPHER_DECRYPT) != 0))
                    801:                fatal("%s: cipher_init failed: %s", __func__, ssh_err(r));
                    802:        if (!state->cipher_warning_done &&
                    803:            ((wmsg = cipher_warning_message(&state->send_context)) != NULL ||
                    804:            (wmsg = cipher_warning_message(&state->send_context)) != NULL)) {
                    805:                error("Warning: %s", wmsg);
                    806:                state->cipher_warning_done = 1;
                    807:        }
1.170     djm       808: }
1.195     markus    809: #endif
1.170     djm       810:
1.16      markus    811: /*
                    812:  * Finalizes and sends the packet.  If the encryption key has been set,
                    813:  * encrypts the packet before sending.
                    814:  */
1.14      markus    815:
1.201     markus    816: int
                    817: ssh_packet_send1(struct ssh *ssh)
1.1       deraadt   818: {
1.201     markus    819:        struct session_state *state = ssh->state;
1.89      markus    820:        u_char buf[8], *cp;
1.201     markus    821:        int r, padding, len;
1.40      markus    822:        u_int checksum;
1.14      markus    823:
1.16      markus    824:        /*
                    825:         * If using packet compression, compress the payload of the outgoing
                    826:         * packet.
                    827:         */
1.201     markus    828:        if (state->packet_compression) {
                    829:                sshbuf_reset(state->compression_buffer);
1.14      markus    830:                /* Skip padding. */
1.201     markus    831:                if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
                    832:                        goto out;
1.14      markus    833:                /* padding */
1.201     markus    834:                if ((r = sshbuf_put(state->compression_buffer,
                    835:                    "\0\0\0\0\0\0\0\0", 8)) != 0)
                    836:                        goto out;
                    837:                if ((r = compress_buffer(ssh, state->outgoing_packet,
                    838:                    state->compression_buffer)) != 0)
                    839:                        goto out;
                    840:                sshbuf_reset(state->outgoing_packet);
                    841:                 if ((r = sshbuf_putb(state->outgoing_packet,
                    842:                     state->compression_buffer)) != 0)
                    843:                        goto out;
1.14      markus    844:        }
                    845:        /* Compute packet length without padding (add checksum, remove padding). */
1.201     markus    846:        len = sshbuf_len(state->outgoing_packet) + 4 - 8;
1.14      markus    847:
1.32      markus    848:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    849:        padding = 8 - len % 8;
1.201     markus    850:        if (!state->send_context.plaintext) {
                    851:                cp = sshbuf_mutable_ptr(state->outgoing_packet);
                    852:                if (cp == NULL) {
                    853:                        r = SSH_ERR_INTERNAL_ERROR;
                    854:                        goto out;
1.14      markus    855:                }
1.201     markus    856:                arc4random_buf(cp + 8 - padding, padding);
1.14      markus    857:        }
1.201     markus    858:        if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
                    859:                goto out;
1.14      markus    860:
                    861:        /* Add check bytes. */
1.201     markus    862:        checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
                    863:            sshbuf_len(state->outgoing_packet));
                    864:        POKE_U32(buf, checksum);
                    865:        if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
                    866:                goto out;
1.1       deraadt   867:
                    868: #ifdef PACKET_DEBUG
1.14      markus    869:        fprintf(stderr, "packet_send plain: ");
1.201     markus    870:        sshbuf_dump(state->outgoing_packet, stderr);
1.1       deraadt   871: #endif
                    872:
1.14      markus    873:        /* Append to output. */
1.201     markus    874:        POKE_U32(buf, len);
                    875:        if ((r = sshbuf_put(state->output, buf, 4)) != 0)
                    876:                goto out;
                    877:        if ((r = sshbuf_reserve(state->output,
                    878:            sshbuf_len(state->outgoing_packet), &cp)) != 0)
                    879:                goto out;
                    880:        if ((r = cipher_crypt(&state->send_context, 0, cp,
                    881:            sshbuf_ptr(state->outgoing_packet),
                    882:            sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
                    883:                goto out;
1.14      markus    884:
1.1       deraadt   885: #ifdef PACKET_DEBUG
1.14      markus    886:        fprintf(stderr, "encrypted: ");
1.201     markus    887:        sshbuf_dump(state->output, stderr);
1.1       deraadt   888: #endif
1.201     markus    889:        state->p_send.packets++;
                    890:        state->p_send.bytes += len +
                    891:            sshbuf_len(state->outgoing_packet);
                    892:        sshbuf_reset(state->outgoing_packet);
1.1       deraadt   893:
1.16      markus    894:        /*
1.120     djm       895:         * Note that the packet is now only buffered in output.  It won't be
1.205     djm       896:         * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
                    897:         * is called.
1.16      markus    898:         */
1.201     markus    899:        r = 0;
                    900:  out:
                    901:        return r;
1.1       deraadt   902: }
                    903:
1.201     markus    904: int
                    905: ssh_set_newkeys(struct ssh *ssh, int mode)
1.57      markus    906: {
1.201     markus    907:        struct session_state *state = ssh->state;
                    908:        struct sshenc *enc;
                    909:        struct sshmac *mac;
                    910:        struct sshcomp *comp;
                    911:        struct sshcipher_ctx *cc;
1.105     markus    912:        u_int64_t *max_blocks;
1.201     markus    913:        const char *wmsg;
1.197     djm       914:        int r, crypt_type;
1.57      markus    915:
1.100     markus    916:        debug2("set_newkeys: mode %d", mode);
1.57      markus    917:
1.88      markus    918:        if (mode == MODE_OUT) {
1.201     markus    919:                cc = &state->send_context;
1.115     avsm      920:                crypt_type = CIPHER_ENCRYPT;
1.201     markus    921:                state->p_send.packets = state->p_send.blocks = 0;
                    922:                max_blocks = &state->max_blocks_out;
1.88      markus    923:        } else {
1.201     markus    924:                cc = &state->receive_context;
1.115     avsm      925:                crypt_type = CIPHER_DECRYPT;
1.201     markus    926:                state->p_read.packets = state->p_read.blocks = 0;
                    927:                max_blocks = &state->max_blocks_in;
1.88      markus    928:        }
1.201     markus    929:        if (state->newkeys[mode] != NULL) {
1.100     markus    930:                debug("set_newkeys: rekeying");
1.201     markus    931:                if ((r = cipher_cleanup(cc)) != 0)
                    932:                        return r;
                    933:                enc  = &state->newkeys[mode]->enc;
                    934:                mac  = &state->newkeys[mode]->mac;
                    935:                comp = &state->newkeys[mode]->comp;
1.148     pvalchev  936:                mac_clear(mac);
1.192     djm       937:                explicit_bzero(enc->iv,  enc->iv_len);
                    938:                explicit_bzero(enc->key, enc->key_len);
                    939:                explicit_bzero(mac->key, mac->key_len);
1.186     djm       940:                free(enc->name);
                    941:                free(enc->iv);
                    942:                free(enc->key);
                    943:                free(mac->name);
                    944:                free(mac->key);
                    945:                free(comp->name);
1.201     markus    946:                free(state->newkeys[mode]);
1.57      markus    947:        }
1.201     markus    948:        /* move newkeys from kex to state */
                    949:        if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
                    950:                return SSH_ERR_INTERNAL_ERROR;
                    951:        ssh->kex->newkeys[mode] = NULL;
                    952:        enc  = &state->newkeys[mode]->enc;
                    953:        mac  = &state->newkeys[mode]->mac;
                    954:        comp = &state->newkeys[mode]->comp;
                    955:        if (cipher_authlen(enc->cipher) == 0) {
                    956:                if ((r = mac_init(mac)) != 0)
                    957:                        return r;
                    958:        }
                    959:        mac->enabled = 1;
1.57      markus    960:        DBG(debug("cipher_init_context: %d", mode));
1.197     djm       961:        if ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,
                    962:            enc->iv, enc->iv_len, crypt_type)) != 0)
1.201     markus    963:                return r;
                    964:        if (!state->cipher_warning_done &&
                    965:            (wmsg = cipher_warning_message(cc)) != NULL) {
                    966:                error("Warning: %s", wmsg);
                    967:                state->cipher_warning_done = 1;
                    968:        }
1.91      markus    969:        /* Deleting the keys does not gain extra security */
1.192     djm       970:        /* explicit_bzero(enc->iv,  enc->block_size);
                    971:           explicit_bzero(enc->key, enc->key_len);
                    972:           explicit_bzero(mac->key, mac->key_len); */
1.118     markus    973:        if ((comp->type == COMP_ZLIB ||
1.161     andreas   974:            (comp->type == COMP_DELAYED &&
1.201     markus    975:             state->after_authentication)) && comp->enabled == 0) {
                    976:                if ((r = ssh_packet_init_compression(ssh)) < 0)
                    977:                        return r;
                    978:                if (mode == MODE_OUT) {
                    979:                        if ((r = start_compression_out(ssh, 6)) != 0)
                    980:                                return r;
                    981:                } else {
                    982:                        if ((r = start_compression_in(ssh)) != 0)
                    983:                                return r;
                    984:                }
1.57      markus    985:                comp->enabled = 1;
                    986:        }
1.109     markus    987:        /*
                    988:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    989:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    990:         */
                    991:        if (enc->block_size >= 16)
                    992:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    993:        else
                    994:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.201     markus    995:        if (state->rekey_limit)
1.161     andreas   996:                *max_blocks = MIN(*max_blocks,
1.201     markus    997:                    state->rekey_limit / enc->block_size);
                    998:        return 0;
1.57      markus    999: }
                   1000:
1.16      markus   1001: /*
1.118     markus   1002:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker  1003:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus   1004:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                   1005:  */
1.201     markus   1006: static int
                   1007: ssh_packet_enable_delayed_compress(struct ssh *ssh)
1.118     markus   1008: {
1.201     markus   1009:        struct session_state *state = ssh->state;
                   1010:        struct sshcomp *comp = NULL;
                   1011:        int r, mode;
1.118     markus   1012:
                   1013:        /*
                   1014:         * Remember that we are past the authentication step, so rekeying
                   1015:         * with COMP_DELAYED will turn on compression immediately.
                   1016:         */
1.201     markus   1017:        state->after_authentication = 1;
1.118     markus   1018:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus   1019:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1.201     markus   1020:                if (state->newkeys[mode] == NULL)
1.145     markus   1021:                        continue;
1.201     markus   1022:                comp = &state->newkeys[mode]->comp;
1.118     markus   1023:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.201     markus   1024:                        if ((r = ssh_packet_init_compression(ssh)) != 0)
                   1025:                                return r;
                   1026:                        if (mode == MODE_OUT) {
                   1027:                                if ((r = start_compression_out(ssh, 6)) != 0)
                   1028:                                        return r;
                   1029:                        } else {
                   1030:                                if ((r = start_compression_in(ssh)) != 0)
                   1031:                                        return r;
                   1032:                        }
1.118     markus   1033:                        comp->enabled = 1;
                   1034:                }
                   1035:        }
1.201     markus   1036:        return 0;
1.118     markus   1037: }
                   1038:
                   1039: /*
1.25      markus   1040:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                   1041:  */
1.201     markus   1042: int
                   1043: ssh_packet_send2_wrapped(struct ssh *ssh)
1.25      markus   1044: {
1.201     markus   1045:        struct session_state *state = ssh->state;
1.200     markus   1046:        u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1.178     markus   1047:        u_char padlen, pad = 0;
1.201     markus   1048:        u_int authlen = 0, aadlen = 0;
                   1049:        u_int len;
                   1050:        struct sshenc *enc   = NULL;
                   1051:        struct sshmac *mac   = NULL;
                   1052:        struct sshcomp *comp = NULL;
                   1053:        int r, block_size;
                   1054:
                   1055:        if (state->newkeys[MODE_OUT] != NULL) {
                   1056:                enc  = &state->newkeys[MODE_OUT]->enc;
                   1057:                mac  = &state->newkeys[MODE_OUT]->mac;
                   1058:                comp = &state->newkeys[MODE_OUT]->comp;
1.180     markus   1059:                /* disable mac for authenticated encryption */
                   1060:                if ((authlen = cipher_authlen(enc->cipher)) != 0)
                   1061:                        mac = NULL;
1.25      markus   1062:        }
1.88      markus   1063:        block_size = enc ? enc->block_size : 8;
1.180     markus   1064:        aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1.25      markus   1065:
1.201     markus   1066:        type = (sshbuf_ptr(state->outgoing_packet))[5];
1.25      markus   1067:
                   1068: #ifdef PACKET_DEBUG
                   1069:        fprintf(stderr, "plain:     ");
1.201     markus   1070:        sshbuf_dump(state->outgoing_packet, stderr);
1.25      markus   1071: #endif
                   1072:
                   1073:        if (comp && comp->enabled) {
1.201     markus   1074:                len = sshbuf_len(state->outgoing_packet);
1.25      markus   1075:                /* skip header, compress only payload */
1.201     markus   1076:                if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
                   1077:                        goto out;
                   1078:                sshbuf_reset(state->compression_buffer);
                   1079:                if ((r = compress_buffer(ssh, state->outgoing_packet,
                   1080:                    state->compression_buffer)) != 0)
                   1081:                        goto out;
                   1082:                sshbuf_reset(state->outgoing_packet);
                   1083:                if ((r = sshbuf_put(state->outgoing_packet,
                   1084:                    "\0\0\0\0\0", 5)) != 0 ||
                   1085:                    (r = sshbuf_putb(state->outgoing_packet,
                   1086:                    state->compression_buffer)) != 0)
                   1087:                        goto out;
                   1088:                DBG(debug("compression: raw %d compressed %zd", len,
                   1089:                    sshbuf_len(state->outgoing_packet)));
1.25      markus   1090:        }
                   1091:
                   1092:        /* sizeof (packet_len + pad_len + payload) */
1.201     markus   1093:        len = sshbuf_len(state->outgoing_packet);
1.25      markus   1094:
                   1095:        /*
                   1096:         * calc size of padding, alloc space, get random data,
                   1097:         * minimum padding is 4 bytes
                   1098:         */
1.178     markus   1099:        len -= aadlen; /* packet length is not encrypted for EtM modes */
1.25      markus   1100:        padlen = block_size - (len % block_size);
                   1101:        if (padlen < 4)
                   1102:                padlen += block_size;
1.201     markus   1103:        if (state->extra_pad) {
1.71      markus   1104:                /* will wrap if extra_pad+padlen > 255 */
1.201     markus   1105:                state->extra_pad =
                   1106:                    roundup(state->extra_pad, block_size);
                   1107:                pad = state->extra_pad -
                   1108:                    ((len + padlen) % state->extra_pad);
1.193     djm      1109:                DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1.201     markus   1110:                    __func__, pad, len, padlen, state->extra_pad));
1.71      markus   1111:                padlen += pad;
1.201     markus   1112:                state->extra_pad = 0;
1.71      markus   1113:        }
1.201     markus   1114:        if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
                   1115:                goto out;
                   1116:        if (enc && !state->send_context.plaintext) {
1.32      markus   1117:                /* random padding */
1.201     markus   1118:                arc4random_buf(cp, padlen);
1.32      markus   1119:        } else {
                   1120:                /* clear padding */
1.192     djm      1121:                explicit_bzero(cp, padlen);
1.25      markus   1122:        }
1.178     markus   1123:        /* sizeof (packet_len + pad_len + payload + padding) */
1.201     markus   1124:        len = sshbuf_len(state->outgoing_packet);
                   1125:        cp = sshbuf_mutable_ptr(state->outgoing_packet);
                   1126:        if (cp == NULL) {
                   1127:                r = SSH_ERR_INTERNAL_ERROR;
                   1128:                goto out;
                   1129:        }
1.25      markus   1130:        /* packet_length includes payload, padding and padding length field */
1.201     markus   1131:        POKE_U32(cp, len - 4);
1.89      markus   1132:        cp[4] = padlen;
1.178     markus   1133:        DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
                   1134:            len, padlen, aadlen));
1.25      markus   1135:
                   1136:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
1.178     markus   1137:        if (mac && mac->enabled && !mac->etm) {
1.201     markus   1138:                if ((r = mac_compute(mac, state->p_send.seqnr,
                   1139:                    sshbuf_ptr(state->outgoing_packet), len,
1.200     markus   1140:                    macbuf, sizeof(macbuf))) != 0)
1.201     markus   1141:                        goto out;
                   1142:                DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1.25      markus   1143:        }
                   1144:        /* encrypt packet and append to output buffer. */
1.201     markus   1145:        if ((r = sshbuf_reserve(state->output,
                   1146:            sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
                   1147:                goto out;
                   1148:        if ((r = cipher_crypt(&state->send_context, state->p_send.seqnr, cp,
                   1149:            sshbuf_ptr(state->outgoing_packet),
                   1150:            len - aadlen, aadlen, authlen)) != 0)
                   1151:                goto out;
1.25      markus   1152:        /* append unencrypted MAC */
1.178     markus   1153:        if (mac && mac->enabled) {
                   1154:                if (mac->etm) {
                   1155:                        /* EtM: compute mac over aadlen + cipher text */
1.201     markus   1156:                        if ((r = mac_compute(mac, state->p_send.seqnr,
                   1157:                            cp, len, macbuf, sizeof(macbuf))) != 0)
                   1158:                                goto out;
1.178     markus   1159:                        DBG(debug("done calc MAC(EtM) out #%d",
1.201     markus   1160:                            state->p_send.seqnr));
1.178     markus   1161:                }
1.201     markus   1162:                if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
                   1163:                        goto out;
1.178     markus   1164:        }
1.25      markus   1165: #ifdef PACKET_DEBUG
                   1166:        fprintf(stderr, "encrypted: ");
1.201     markus   1167:        sshbuf_dump(state->output, stderr);
1.25      markus   1168: #endif
1.29      markus   1169:        /* increment sequence number for outgoing packets */
1.201     markus   1170:        if (++state->p_send.seqnr == 0)
1.106     itojun   1171:                logit("outgoing seqnr wraps around");
1.201     markus   1172:        if (++state->p_send.packets == 0)
                   1173:                if (!(ssh->compat & SSH_BUG_NOREKEY))
                   1174:                        return SSH_ERR_NEED_REKEY;
                   1175:        state->p_send.blocks += len / block_size;
                   1176:        state->p_send.bytes += len;
                   1177:        sshbuf_reset(state->outgoing_packet);
1.25      markus   1178:
1.57      markus   1179:        if (type == SSH2_MSG_NEWKEYS)
1.201     markus   1180:                r = ssh_set_newkeys(ssh, MODE_OUT);
                   1181:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
                   1182:                r = ssh_packet_enable_delayed_compress(ssh);
                   1183:        else
                   1184:                r = 0;
                   1185:  out:
                   1186:        return r;
1.25      markus   1187: }
                   1188:
1.201     markus   1189: int
                   1190: ssh_packet_send2(struct ssh *ssh)
1.105     markus   1191: {
1.201     markus   1192:        struct session_state *state = ssh->state;
1.105     markus   1193:        struct packet *p;
1.201     markus   1194:        u_char type;
                   1195:        int r;
1.105     markus   1196:
1.201     markus   1197:        type = sshbuf_ptr(state->outgoing_packet)[5];
1.105     markus   1198:
                   1199:        /* during rekeying we can only send key exchange messages */
1.201     markus   1200:        if (state->rekeying) {
1.175     markus   1201:                if ((type < SSH2_MSG_TRANSPORT_MIN) ||
                   1202:                    (type > SSH2_MSG_TRANSPORT_MAX) ||
                   1203:                    (type == SSH2_MSG_SERVICE_REQUEST) ||
                   1204:                    (type == SSH2_MSG_SERVICE_ACCEPT)) {
1.105     markus   1205:                        debug("enqueue packet: %u", type);
1.201     markus   1206:                        p = calloc(1, sizeof(*p));
                   1207:                        if (p == NULL)
                   1208:                                return SSH_ERR_ALLOC_FAIL;
1.105     markus   1209:                        p->type = type;
1.201     markus   1210:                        p->payload = state->outgoing_packet;
                   1211:                        TAILQ_INSERT_TAIL(&state->outgoing, p, next);
                   1212:                        state->outgoing_packet = sshbuf_new();
                   1213:                        if (state->outgoing_packet == NULL)
                   1214:                                return SSH_ERR_ALLOC_FAIL;
                   1215:                        return 0;
1.105     markus   1216:                }
                   1217:        }
                   1218:
                   1219:        /* rekeying starts with sending KEXINIT */
                   1220:        if (type == SSH2_MSG_KEXINIT)
1.201     markus   1221:                state->rekeying = 1;
1.105     markus   1222:
1.201     markus   1223:        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1224:                return r;
1.105     markus   1225:
                   1226:        /* after a NEWKEYS message we can send the complete queue */
                   1227:        if (type == SSH2_MSG_NEWKEYS) {
1.201     markus   1228:                state->rekeying = 0;
                   1229:                state->rekey_time = monotime();
                   1230:                while ((p = TAILQ_FIRST(&state->outgoing))) {
1.105     markus   1231:                        type = p->type;
                   1232:                        debug("dequeue packet: %u", type);
1.201     markus   1233:                        sshbuf_free(state->outgoing_packet);
                   1234:                        state->outgoing_packet = p->payload;
                   1235:                        TAILQ_REMOVE(&state->outgoing, p, next);
1.186     djm      1236:                        free(p);
1.201     markus   1237:                        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1238:                                return r;
1.105     markus   1239:                }
                   1240:        }
1.201     markus   1241:        return 0;
1.25      markus   1242: }
                   1243:
                   1244: /*
1.16      markus   1245:  * Waits until a packet has been received, and returns its type.  Note that
                   1246:  * no other data is processed until this returns, so this function should not
                   1247:  * be used during the interactive session.
                   1248:  */
1.1       deraadt  1249:
1.2       provos   1250: int
1.201     markus   1251: ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.1       deraadt  1252: {
1.201     markus   1253:        struct session_state *state = ssh->state;
                   1254:        int len, r, ms_remain, cont;
1.56      millert  1255:        fd_set *setp;
1.14      markus   1256:        char buf[8192];
1.155     deraadt  1257:        struct timeval timeout, start, *timeoutp = NULL;
                   1258:
1.25      markus   1259:        DBG(debug("packet_read()"));
1.14      markus   1260:
1.201     markus   1261:        setp = (fd_set *)calloc(howmany(state->connection_in + 1,
1.161     andreas  1262:            NFDBITS), sizeof(fd_mask));
1.201     markus   1263:        if (setp == NULL)
                   1264:                return SSH_ERR_ALLOC_FAIL;
1.56      millert  1265:
1.205     djm      1266:        /*
                   1267:         * Since we are blocking, ensure that all written packets have
                   1268:         * been sent.
                   1269:         */
1.207   ! djm      1270:        if ((r = ssh_packet_write_wait(ssh)) != 0)
1.205     djm      1271:                return r;
1.14      markus   1272:
                   1273:        /* Stay in the loop until we have received a complete packet. */
                   1274:        for (;;) {
                   1275:                /* Try to read a packet from the buffer. */
1.201     markus   1276:                r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
                   1277:                if (r != 0)
                   1278:                        break;
1.62      markus   1279:                if (!compat20 && (
1.201     markus   1280:                    *typep == SSH_SMSG_SUCCESS
                   1281:                    || *typep == SSH_SMSG_FAILURE
                   1282:                    || *typep == SSH_CMSG_EOF
                   1283:                    || *typep == SSH_CMSG_EXIT_CONFIRMATION))
                   1284:                        if ((r = sshpkt_get_end(ssh)) != 0)
                   1285:                                break;
1.14      markus   1286:                /* If we got a packet, return it. */
1.201     markus   1287:                if (*typep != SSH_MSG_NONE)
                   1288:                        break;
1.16      markus   1289:                /*
                   1290:                 * Otherwise, wait for some data to arrive, add it to the
                   1291:                 * buffer, and try again.
                   1292:                 */
1.201     markus   1293:                memset(setp, 0, howmany(state->connection_in + 1,
1.161     andreas  1294:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   1295:                FD_SET(state->connection_in, setp);
1.16      markus   1296:
1.201     markus   1297:                if (state->packet_timeout_ms > 0) {
                   1298:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  1299:                        timeoutp = &timeout;
                   1300:                }
1.14      markus   1301:                /* Wait for some data to arrive. */
1.154     dtucker  1302:                for (;;) {
1.201     markus   1303:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  1304:                                ms_to_timeval(&timeout, ms_remain);
                   1305:                                gettimeofday(&start, NULL);
                   1306:                        }
1.201     markus   1307:                        if ((r = select(state->connection_in + 1, setp,
1.161     andreas  1308:                            NULL, NULL, timeoutp)) >= 0)
1.154     dtucker  1309:                                break;
1.161     andreas  1310:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1311:                                break;
1.201     markus   1312:                        if (state->packet_timeout_ms == -1)
1.154     dtucker  1313:                                continue;
                   1314:                        ms_subtract_diff(&start, &ms_remain);
                   1315:                        if (ms_remain <= 0) {
1.201     markus   1316:                                r = 0;
1.154     dtucker  1317:                                break;
                   1318:                        }
                   1319:                }
1.204     djm      1320:                if (r == 0)
                   1321:                        return SSH_ERR_CONN_TIMEOUT;
1.14      markus   1322:                /* Read data from the socket. */
1.163     andreas  1323:                do {
                   1324:                        cont = 0;
1.201     markus   1325:                        len = roaming_read(state->connection_in, buf,
1.163     andreas  1326:                            sizeof(buf), &cont);
                   1327:                } while (len == 0 && cont);
1.204     djm      1328:                if (len == 0)
                   1329:                        return SSH_ERR_CONN_CLOSED;
1.14      markus   1330:                if (len < 0)
1.204     djm      1331:                        return SSH_ERR_SYSTEM_ERROR;
                   1332:
1.14      markus   1333:                /* Append it to the buffer. */
1.204     djm      1334:                if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
                   1335:                        return r;
1.14      markus   1336:        }
1.201     markus   1337:        free(setp);
                   1338:        return r;
1.1       deraadt  1339: }
                   1340:
1.77      djm      1341: int
1.201     markus   1342: ssh_packet_read(struct ssh *ssh)
1.77      djm      1343: {
1.201     markus   1344:        u_char type;
                   1345:        int r;
                   1346:
                   1347:        if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
                   1348:                fatal("%s: %s", __func__, ssh_err(r));
                   1349:        return type;
1.77      djm      1350: }
                   1351:
1.16      markus   1352: /*
                   1353:  * Waits until a packet has been received, verifies that its type matches
                   1354:  * that given, and gives a fatal error and exits if there is a mismatch.
                   1355:  */
1.1       deraadt  1356:
1.205     djm      1357: int
                   1358: ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1.1       deraadt  1359: {
1.205     djm      1360:        int r;
                   1361:        u_char type;
1.1       deraadt  1362:
1.205     djm      1363:        if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
                   1364:                return r;
                   1365:        if (type != expected_type) {
                   1366:                if ((r = sshpkt_disconnect(ssh,
1.201     markus   1367:                    "Protocol error: expected packet type %d, got %d",
1.205     djm      1368:                    expected_type, type)) != 0)
                   1369:                        return r;
                   1370:                return SSH_ERR_PROTOCOL_ERROR;
                   1371:        }
                   1372:        return 0;
1.1       deraadt  1373: }
                   1374:
                   1375: /* Checks if a full packet is available in the data received so far via
1.14      markus   1376:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                   1377:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                   1378:  *
1.150     dtucker  1379:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                   1380:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                   1381:  * to higher levels.
1.14      markus   1382:  */
1.1       deraadt  1383:
1.201     markus   1384: int
                   1385: ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1.1       deraadt  1386: {
1.201     markus   1387:        struct session_state *state = ssh->state;
1.40      markus   1388:        u_int len, padded_len;
1.205     djm      1389:        const char *emsg;
1.201     markus   1390:        const u_char *cp;
                   1391:        u_char *p;
1.40      markus   1392:        u_int checksum, stored_checksum;
1.201     markus   1393:        int r;
                   1394:
                   1395:        *typep = SSH_MSG_NONE;
1.14      markus   1396:
                   1397:        /* Check if input size is less than minimum packet size. */
1.201     markus   1398:        if (sshbuf_len(state->input) < 4 + 8)
                   1399:                return 0;
1.14      markus   1400:        /* Get length of incoming packet. */
1.201     markus   1401:        len = PEEK_U32(sshbuf_ptr(state->input));
1.205     djm      1402:        if (len < 1 + 2 + 2 || len > 256 * 1024) {
                   1403:                if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
                   1404:                    len)) != 0)
                   1405:                        return r;
                   1406:                return SSH_ERR_CONN_CORRUPT;
                   1407:        }
1.14      markus   1408:        padded_len = (len + 8) & ~7;
                   1409:
                   1410:        /* Check if the packet has been entirely received. */
1.201     markus   1411:        if (sshbuf_len(state->input) < 4 + padded_len)
                   1412:                return 0;
1.14      markus   1413:
                   1414:        /* The entire packet is in buffer. */
                   1415:
                   1416:        /* Consume packet length. */
1.201     markus   1417:        if ((r = sshbuf_consume(state->input, 4)) != 0)
                   1418:                goto out;
1.14      markus   1419:
1.62      markus   1420:        /*
                   1421:         * Cryptographic attack detector for ssh
                   1422:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                   1423:         * Ariel Futoransky(futo@core-sdi.com)
                   1424:         */
1.201     markus   1425:        if (!state->receive_context.plaintext) {
1.205     djm      1426:                emsg = NULL;
1.201     markus   1427:                switch (detect_attack(&state->deattack,
                   1428:                    sshbuf_ptr(state->input), padded_len)) {
                   1429:                case DEATTACK_OK:
                   1430:                        break;
1.144     djm      1431:                case DEATTACK_DETECTED:
1.205     djm      1432:                        emsg = "crc32 compensation attack detected";
                   1433:                        break;
1.144     djm      1434:                case DEATTACK_DOS_DETECTED:
1.205     djm      1435:                        emsg = "deattack denial of service detected";
                   1436:                        break;
1.201     markus   1437:                default:
1.205     djm      1438:                        emsg = "deattack error";
                   1439:                        break;
                   1440:                }
                   1441:                if (emsg != NULL) {
                   1442:                        error("%s", emsg);
                   1443:                        if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
                   1444:                            (r = ssh_packet_write_wait(ssh)) != 0)
                   1445:                                        return r;
                   1446:                        return SSH_ERR_CONN_CORRUPT;
1.144     djm      1447:                }
                   1448:        }
1.62      markus   1449:
                   1450:        /* Decrypt data to incoming_packet. */
1.201     markus   1451:        sshbuf_reset(state->incoming_packet);
                   1452:        if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
                   1453:                goto out;
                   1454:        if ((r = cipher_crypt(&state->receive_context, 0, p,
                   1455:            sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
                   1456:                goto out;
1.62      markus   1457:
1.201     markus   1458:        if ((r = sshbuf_consume(state->input, padded_len)) != 0)
                   1459:                goto out;
1.1       deraadt  1460:
                   1461: #ifdef PACKET_DEBUG
1.14      markus   1462:        fprintf(stderr, "read_poll plain: ");
1.201     markus   1463:        sshbuf_dump(state->incoming_packet, stderr);
1.1       deraadt  1464: #endif
                   1465:
1.14      markus   1466:        /* Compute packet checksum. */
1.201     markus   1467:        checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
                   1468:            sshbuf_len(state->incoming_packet) - 4);
1.14      markus   1469:
                   1470:        /* Skip padding. */
1.201     markus   1471:        if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
                   1472:                goto out;
1.14      markus   1473:
                   1474:        /* Test check bytes. */
1.205     djm      1475:        if (len != sshbuf_len(state->incoming_packet)) {
                   1476:                error("%s: len %d != sshbuf_len %zd", __func__,
1.201     markus   1477:                    len, sshbuf_len(state->incoming_packet));
1.205     djm      1478:                if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
                   1479:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1480:                        return r;
                   1481:                return SSH_ERR_CONN_CORRUPT;
                   1482:        }
1.14      markus   1483:
1.201     markus   1484:        cp = sshbuf_ptr(state->incoming_packet) + len - 4;
                   1485:        stored_checksum = PEEK_U32(cp);
1.205     djm      1486:        if (checksum != stored_checksum) {
                   1487:                error("Corrupted check bytes on input");
                   1488:                if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
                   1489:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1490:                        return r;
                   1491:                return SSH_ERR_CONN_CORRUPT;
                   1492:        }
1.201     markus   1493:        if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
                   1494:                goto out;
                   1495:
                   1496:        if (state->packet_compression) {
                   1497:                sshbuf_reset(state->compression_buffer);
                   1498:                if ((r = uncompress_buffer(ssh, state->incoming_packet,
                   1499:                    state->compression_buffer)) != 0)
                   1500:                        goto out;
                   1501:                sshbuf_reset(state->incoming_packet);
                   1502:                if ((r = sshbuf_putb(state->incoming_packet,
                   1503:                    state->compression_buffer)) != 0)
                   1504:                        goto out;
                   1505:        }
                   1506:        state->p_read.packets++;
                   1507:        state->p_read.bytes += padded_len + 4;
                   1508:        if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
                   1509:                goto out;
1.205     djm      1510:        if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
                   1511:                error("Invalid ssh1 packet type: %d", *typep);
                   1512:                if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
                   1513:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1514:                        return r;
                   1515:                return SSH_ERR_PROTOCOL_ERROR;
                   1516:        }
1.201     markus   1517:        r = 0;
                   1518:  out:
                   1519:        return r;
1.1       deraadt  1520: }
1.14      markus   1521:
1.201     markus   1522: int
                   1523: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.25      markus   1524: {
1.201     markus   1525:        struct session_state *state = ssh->state;
1.40      markus   1526:        u_int padlen, need;
1.201     markus   1527:        u_char *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
                   1528:        u_int maclen, aadlen = 0, authlen = 0, block_size;
                   1529:        struct sshenc *enc   = NULL;
                   1530:        struct sshmac *mac   = NULL;
                   1531:        struct sshcomp *comp = NULL;
1.200     markus   1532:        int r;
1.201     markus   1533:
                   1534:        *typep = SSH_MSG_NONE;
                   1535:
                   1536:        if (state->packet_discard)
                   1537:                return 0;
                   1538:
                   1539:        if (state->newkeys[MODE_IN] != NULL) {
                   1540:                enc  = &state->newkeys[MODE_IN]->enc;
                   1541:                mac  = &state->newkeys[MODE_IN]->mac;
                   1542:                comp = &state->newkeys[MODE_IN]->comp;
1.180     markus   1543:                /* disable mac for authenticated encryption */
                   1544:                if ((authlen = cipher_authlen(enc->cipher)) != 0)
                   1545:                        mac = NULL;
1.25      markus   1546:        }
                   1547:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1548:        block_size = enc ? enc->block_size : 8;
1.180     markus   1549:        aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1.25      markus   1550:
1.201     markus   1551:        if (aadlen && state->packlen == 0) {
                   1552:                if (cipher_get_length(&state->receive_context,
                   1553:                    &state->packlen, state->p_read.seqnr,
                   1554:                    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
                   1555:                        return 0;
                   1556:                if (state->packlen < 1 + 4 ||
                   1557:                    state->packlen > PACKET_MAX_SIZE) {
1.178     markus   1558: #ifdef PACKET_DEBUG
1.201     markus   1559:                        sshbuf_dump(state->input, stderr);
1.178     markus   1560: #endif
1.201     markus   1561:                        logit("Bad packet length %u.", state->packlen);
                   1562:                        if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
                   1563:                                return r;
1.178     markus   1564:                }
1.201     markus   1565:                sshbuf_reset(state->incoming_packet);
                   1566:        } else if (state->packlen == 0) {
1.25      markus   1567:                /*
                   1568:                 * check if input size is less than the cipher block size,
                   1569:                 * decrypt first block and extract length of incoming packet
                   1570:                 */
1.201     markus   1571:                if (sshbuf_len(state->input) < block_size)
                   1572:                        return 0;
                   1573:                sshbuf_reset(state->incoming_packet);
                   1574:                if ((r = sshbuf_reserve(state->incoming_packet, block_size,
                   1575:                    &cp)) != 0)
                   1576:                        goto out;
                   1577:                if ((r = cipher_crypt(&state->receive_context,
                   1578:                    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
                   1579:                    block_size, 0, 0)) != 0)
                   1580:                        goto out;
                   1581:                state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
                   1582:                if (state->packlen < 1 + 4 ||
                   1583:                    state->packlen > PACKET_MAX_SIZE) {
1.110     markus   1584: #ifdef PACKET_DEBUG
1.201     markus   1585:                        fprintf(stderr, "input: \n");
                   1586:                        sshbuf_dump(state->input, stderr);
                   1587:                        fprintf(stderr, "incoming_packet: \n");
                   1588:                        sshbuf_dump(state->incoming_packet, stderr);
1.110     markus   1589: #endif
1.201     markus   1590:                        logit("Bad packet length %u.", state->packlen);
                   1591:                        return ssh_packet_start_discard(ssh, enc, mac,
                   1592:                            state->packlen, PACKET_MAX_SIZE);
1.25      markus   1593:                }
1.201     markus   1594:                if ((r = sshbuf_consume(state->input, block_size)) != 0)
                   1595:                        goto out;
1.25      markus   1596:        }
1.201     markus   1597:        DBG(debug("input: packet len %u", state->packlen+4));
                   1598:
1.178     markus   1599:        if (aadlen) {
                   1600:                /* only the payload is encrypted */
1.201     markus   1601:                need = state->packlen;
1.178     markus   1602:        } else {
                   1603:                /*
                   1604:                 * the payload size and the payload are encrypted, but we
                   1605:                 * have a partial packet of block_size bytes
                   1606:                 */
1.201     markus   1607:                need = 4 + state->packlen - block_size;
1.178     markus   1608:        }
1.180     markus   1609:        DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
                   1610:            " aadlen %d", block_size, need, maclen, authlen, aadlen));
1.158     markus   1611:        if (need % block_size != 0) {
                   1612:                logit("padding error: need %d block %d mod %d",
1.25      markus   1613:                    need, block_size, need % block_size);
1.201     markus   1614:                return ssh_packet_start_discard(ssh, enc, mac,
                   1615:                    state->packlen, PACKET_MAX_SIZE - block_size);
1.158     markus   1616:        }
1.25      markus   1617:        /*
                   1618:         * check if the entire packet has been received and
1.178     markus   1619:         * decrypt into incoming_packet:
                   1620:         * 'aadlen' bytes are unencrypted, but authenticated.
1.180     markus   1621:         * 'need' bytes are encrypted, followed by either
                   1622:         * 'authlen' bytes of authentication tag or
1.178     markus   1623:         * 'maclen' bytes of message authentication code.
1.25      markus   1624:         */
1.201     markus   1625:        if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
                   1626:                return 0;
1.25      markus   1627: #ifdef PACKET_DEBUG
                   1628:        fprintf(stderr, "read_poll enc/full: ");
1.201     markus   1629:        sshbuf_dump(state->input, stderr);
1.25      markus   1630: #endif
1.178     markus   1631:        /* EtM: compute mac over encrypted input */
1.201     markus   1632:        if (mac && mac->enabled && mac->etm) {
                   1633:                if ((r = mac_compute(mac, state->p_read.seqnr,
                   1634:                    sshbuf_ptr(state->input), aadlen + need,
1.200     markus   1635:                    macbuf, sizeof(macbuf))) != 0)
1.201     markus   1636:                        goto out;
                   1637:        }
                   1638:        if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
                   1639:            &cp)) != 0)
                   1640:                goto out;
                   1641:        if ((r = cipher_crypt(&state->receive_context, state->p_read.seqnr, cp,
                   1642:            sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
                   1643:                goto out;
                   1644:        if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
                   1645:                goto out;
1.25      markus   1646:        /*
                   1647:         * compute MAC over seqnr and packet,
                   1648:         * increment sequence number for incoming packet
                   1649:         */
1.29      markus   1650:        if (mac && mac->enabled) {
1.178     markus   1651:                if (!mac->etm)
1.201     markus   1652:                        if ((r = mac_compute(mac, state->p_read.seqnr,
                   1653:                            sshbuf_ptr(state->incoming_packet),
                   1654:                            sshbuf_len(state->incoming_packet),
1.200     markus   1655:                            macbuf, sizeof(macbuf))) != 0)
1.201     markus   1656:                                goto out;
                   1657:                if (timingsafe_bcmp(macbuf, sshbuf_ptr(state->input),
1.161     andreas  1658:                    mac->mac_len) != 0) {
1.159     markus   1659:                        logit("Corrupted MAC on input.");
                   1660:                        if (need > PACKET_MAX_SIZE)
1.201     markus   1661:                                return SSH_ERR_INTERNAL_ERROR;
                   1662:                        return ssh_packet_start_discard(ssh, enc, mac,
                   1663:                            state->packlen, PACKET_MAX_SIZE - need);
                   1664:                }
                   1665:
                   1666:                DBG(debug("MAC #%d ok", state->p_read.seqnr));
                   1667:                if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
                   1668:                        goto out;
1.25      markus   1669:        }
1.77      djm      1670:        if (seqnr_p != NULL)
1.201     markus   1671:                *seqnr_p = state->p_read.seqnr;
                   1672:        if (++state->p_read.seqnr == 0)
1.106     itojun   1673:                logit("incoming seqnr wraps around");
1.201     markus   1674:        if (++state->p_read.packets == 0)
                   1675:                if (!(ssh->compat & SSH_BUG_NOREKEY))
                   1676:                        return SSH_ERR_NEED_REKEY;
                   1677:        state->p_read.blocks += (state->packlen + 4) / block_size;
                   1678:        state->p_read.bytes += state->packlen + 4;
1.25      markus   1679:
                   1680:        /* get padlen */
1.201     markus   1681:        padlen = sshbuf_ptr(state->incoming_packet)[4];
1.25      markus   1682:        DBG(debug("input: padlen %d", padlen));
1.205     djm      1683:        if (padlen < 4) {
                   1684:                if ((r = sshpkt_disconnect(ssh,
                   1685:                    "Corrupted padlen %d on input.", padlen)) != 0 ||
                   1686:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1687:                        return r;
                   1688:                return SSH_ERR_CONN_CORRUPT;
                   1689:        }
1.25      markus   1690:
                   1691:        /* skip packet size + padlen, discard padding */
1.201     markus   1692:        if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
                   1693:            ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
                   1694:                goto out;
1.25      markus   1695:
1.201     markus   1696:        DBG(debug("input: len before de-compress %zd",
                   1697:            sshbuf_len(state->incoming_packet)));
1.25      markus   1698:        if (comp && comp->enabled) {
1.201     markus   1699:                sshbuf_reset(state->compression_buffer);
                   1700:                if ((r = uncompress_buffer(ssh, state->incoming_packet,
                   1701:                    state->compression_buffer)) != 0)
                   1702:                        goto out;
                   1703:                sshbuf_reset(state->incoming_packet);
                   1704:                if ((r = sshbuf_putb(state->incoming_packet,
                   1705:                    state->compression_buffer)) != 0)
                   1706:                        goto out;
                   1707:                DBG(debug("input: len after de-compress %zd",
                   1708:                    sshbuf_len(state->incoming_packet)));
1.25      markus   1709:        }
                   1710:        /*
                   1711:         * get packet type, implies consume.
                   1712:         * return length of payload (without type field)
                   1713:         */
1.201     markus   1714:        if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
                   1715:                goto out;
1.205     djm      1716:        if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
                   1717:                if ((r = sshpkt_disconnect(ssh,
                   1718:                    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
                   1719:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1720:                        return r;
                   1721:                return SSH_ERR_PROTOCOL_ERROR;
                   1722:        }
1.201     markus   1723:        if (*typep == SSH2_MSG_NEWKEYS)
                   1724:                r = ssh_set_newkeys(ssh, MODE_IN);
                   1725:        else if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
                   1726:                r = ssh_packet_enable_delayed_compress(ssh);
                   1727:        else
                   1728:                r = 0;
1.25      markus   1729: #ifdef PACKET_DEBUG
1.201     markus   1730:        fprintf(stderr, "read/plain[%d]:\r\n", *typep);
                   1731:        sshbuf_dump(state->incoming_packet, stderr);
1.25      markus   1732: #endif
1.62      markus   1733:        /* reset for next packet */
1.201     markus   1734:        state->packlen = 0;
                   1735:  out:
                   1736:        return r;
1.25      markus   1737: }
                   1738:
                   1739: int
1.201     markus   1740: ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.25      markus   1741: {
1.201     markus   1742:        struct session_state *state = ssh->state;
1.96      deraadt  1743:        u_int reason, seqnr;
1.201     markus   1744:        int r;
                   1745:        u_char *msg;
1.62      markus   1746:
1.25      markus   1747:        for (;;) {
1.201     markus   1748:                msg = NULL;
1.62      markus   1749:                if (compat20) {
1.201     markus   1750:                        r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
                   1751:                        if (r != 0)
                   1752:                                return r;
                   1753:                        if (*typep) {
                   1754:                                state->keep_alive_timeouts = 0;
                   1755:                                DBG(debug("received packet type %d", *typep));
1.153     djm      1756:                        }
1.201     markus   1757:                        switch (*typep) {
1.150     dtucker  1758:                        case SSH2_MSG_IGNORE:
1.151     dtucker  1759:                                debug3("Received SSH2_MSG_IGNORE");
1.150     dtucker  1760:                                break;
1.25      markus   1761:                        case SSH2_MSG_DEBUG:
1.201     markus   1762:                                if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
                   1763:                                    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
                   1764:                                    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
                   1765:                                        if (msg)
                   1766:                                                free(msg);
                   1767:                                        return r;
                   1768:                                }
1.25      markus   1769:                                debug("Remote: %.900s", msg);
1.186     djm      1770:                                free(msg);
1.25      markus   1771:                                break;
                   1772:                        case SSH2_MSG_DISCONNECT:
1.201     markus   1773:                                if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
                   1774:                                    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1775:                                        return r;
1.182     djm      1776:                                /* Ignore normal client exit notifications */
1.201     markus   1777:                                do_log2(ssh->state->server_side &&
1.182     djm      1778:                                    reason == SSH2_DISCONNECT_BY_APPLICATION ?
                   1779:                                    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
                   1780:                                    "Received disconnect from %s: %u: %.400s",
1.201     markus   1781:                                    ssh_remote_ipaddr(ssh), reason, msg);
1.186     djm      1782:                                free(msg);
1.201     markus   1783:                                return SSH_ERR_DISCONNECTED;
1.84      markus   1784:                        case SSH2_MSG_UNIMPLEMENTED:
1.201     markus   1785:                                if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
                   1786:                                        return r;
1.96      deraadt  1787:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1788:                                    seqnr);
1.150     dtucker  1789:                                break;
1.25      markus   1790:                        default:
1.201     markus   1791:                                return 0;
1.48      stevesk  1792:                        }
1.25      markus   1793:                } else {
1.201     markus   1794:                        r = ssh_packet_read_poll1(ssh, typep);
                   1795:                        switch (*typep) {
1.188     djm      1796:                        case SSH_MSG_NONE:
                   1797:                                return SSH_MSG_NONE;
1.25      markus   1798:                        case SSH_MSG_IGNORE:
                   1799:                                break;
                   1800:                        case SSH_MSG_DEBUG:
1.201     markus   1801:                                if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1802:                                        return r;
1.25      markus   1803:                                debug("Remote: %.900s", msg);
1.186     djm      1804:                                free(msg);
1.25      markus   1805:                                break;
                   1806:                        case SSH_MSG_DISCONNECT:
1.201     markus   1807:                                if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1808:                                        return r;
1.181     djm      1809:                                error("Received disconnect from %s: %.400s",
1.201     markus   1810:                                    ssh_remote_ipaddr(ssh), msg);
                   1811:                                free(msg);
                   1812:                                return SSH_ERR_DISCONNECTED;
1.25      markus   1813:                        default:
1.201     markus   1814:                                DBG(debug("received packet type %d", *typep));
                   1815:                                return 0;
1.48      stevesk  1816:                        }
1.25      markus   1817:                }
                   1818:        }
                   1819: }
                   1820:
1.16      markus   1821: /*
                   1822:  * Buffers the given amount of input characters.  This is intended to be used
                   1823:  * together with packet_read_poll.
                   1824:  */
1.1       deraadt  1825:
1.204     djm      1826: int
1.201     markus   1827: ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1.1       deraadt  1828: {
1.201     markus   1829:        struct session_state *state = ssh->state;
                   1830:        int r;
                   1831:
                   1832:        if (state->packet_discard) {
                   1833:                state->keep_alive_timeouts = 0; /* ?? */
                   1834:                if (len >= state->packet_discard) {
                   1835:                        if ((r = ssh_packet_stop_discard(ssh)) != 0)
1.204     djm      1836:                                return r;
1.201     markus   1837:                }
                   1838:                state->packet_discard -= len;
1.204     djm      1839:                return 0;
1.159     markus   1840:        }
1.201     markus   1841:        if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1.204     djm      1842:                return r;
                   1843:
                   1844:        return 0;
1.28      markus   1845: }
                   1846:
                   1847: int
1.201     markus   1848: ssh_packet_remaining(struct ssh *ssh)
1.28      markus   1849: {
1.201     markus   1850:        return sshbuf_len(ssh->state->incoming_packet);
1.1       deraadt  1851: }
                   1852:
1.16      markus   1853: /*
                   1854:  * Sends a diagnostic message from the server to the client.  This message
                   1855:  * can be sent at any time (but not while constructing another message). The
                   1856:  * message is printed immediately, but only if the client is being executed
                   1857:  * in verbose mode.  These messages are primarily intended to ease debugging
                   1858:  * authentication problems.   The length of the formatted message must not
1.205     djm      1859:  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1.16      markus   1860:  */
1.2       provos   1861: void
1.201     markus   1862: ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1.1       deraadt  1863: {
1.14      markus   1864:        char buf[1024];
                   1865:        va_list args;
1.201     markus   1866:        int r;
1.39      markus   1867:
1.201     markus   1868:        if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
1.39      markus   1869:                return;
1.14      markus   1870:
                   1871:        va_start(args, fmt);
                   1872:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1873:        va_end(args);
                   1874:
1.30      markus   1875:        if (compat20) {
1.201     markus   1876:                if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
                   1877:                    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
                   1878:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   1879:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   1880:                    (r = sshpkt_send(ssh)) != 0)
                   1881:                        fatal("%s: %s", __func__, ssh_err(r));
1.30      markus   1882:        } else {
1.201     markus   1883:                if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
                   1884:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   1885:                    (r = sshpkt_send(ssh)) != 0)
                   1886:                        fatal("%s: %s", __func__, ssh_err(r));
1.30      markus   1887:        }
1.205     djm      1888:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   1889:                fatal("%s: %s", __func__, ssh_err(r));
                   1890: }
                   1891:
                   1892: /*
                   1893:  * Pretty-print connection-terminating errors and exit.
                   1894:  */
                   1895: void
                   1896: sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
                   1897: {
                   1898:        switch (r) {
                   1899:        case SSH_ERR_CONN_CLOSED:
                   1900:                logit("Connection closed by %.200s", ssh_remote_ipaddr(ssh));
                   1901:                cleanup_exit(255);
                   1902:        case SSH_ERR_CONN_TIMEOUT:
                   1903:                logit("Connection to %.200s timed out while "
                   1904:                    "waiting to write", ssh_remote_ipaddr(ssh));
                   1905:                cleanup_exit(255);
                   1906:        default:
                   1907:                fatal("%s%sConnection to %.200s: %s",
                   1908:                    tag != NULL ? tag : "", tag != NULL ? ": " : "",
                   1909:                    ssh_remote_ipaddr(ssh), ssh_err(r));
                   1910:        }
1.1       deraadt  1911: }
                   1912:
1.16      markus   1913: /*
                   1914:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1915:  * connection, and exits.  This function never returns. The error message
                   1916:  * should not contain a newline.  The length of the formatted message must
                   1917:  * not exceed 1024 bytes.
                   1918:  */
1.2       provos   1919: void
1.201     markus   1920: ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1.1       deraadt  1921: {
1.14      markus   1922:        char buf[1024];
                   1923:        va_list args;
                   1924:        static int disconnecting = 0;
1.201     markus   1925:        int r;
1.97      deraadt  1926:
1.14      markus   1927:        if (disconnecting)      /* Guard against recursive invocations. */
                   1928:                fatal("packet_disconnect called recursively.");
                   1929:        disconnecting = 1;
                   1930:
1.16      markus   1931:        /*
                   1932:         * Format the message.  Note that the caller must make sure the
                   1933:         * message is of limited size.
                   1934:         */
1.14      markus   1935:        va_start(args, fmt);
                   1936:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1937:        va_end(args);
                   1938:
1.99      markus   1939:        /* Display the error locally */
1.106     itojun   1940:        logit("Disconnecting: %.100s", buf);
1.99      markus   1941:
1.205     djm      1942:        /*
                   1943:         * Send the disconnect message to the other side, and wait
                   1944:         * for it to get sent.
                   1945:         */
                   1946:        if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
                   1947:                sshpkt_fatal(ssh, __func__, r);
                   1948:
                   1949:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   1950:                sshpkt_fatal(ssh, __func__, r);
1.14      markus   1951:
                   1952:        /* Close the connection. */
1.201     markus   1953:        ssh_packet_close(ssh);
1.112     markus   1954:        cleanup_exit(255);
1.1       deraadt  1955: }
                   1956:
1.205     djm      1957: /*
                   1958:  * Checks if there is any buffered output, and tries to write some of
                   1959:  * the output.
                   1960:  */
                   1961: int
1.201     markus   1962: ssh_packet_write_poll(struct ssh *ssh)
1.1       deraadt  1963: {
1.201     markus   1964:        struct session_state *state = ssh->state;
                   1965:        int len = sshbuf_len(state->output);
                   1966:        int cont, r;
1.97      deraadt  1967:
1.14      markus   1968:        if (len > 0) {
1.163     andreas  1969:                cont = 0;
1.201     markus   1970:                len = roaming_write(state->connection_out,
                   1971:                    sshbuf_ptr(state->output), len, &cont);
1.156     djm      1972:                if (len == -1) {
                   1973:                        if (errno == EINTR || errno == EAGAIN)
1.205     djm      1974:                                return 0;
                   1975:                        return SSH_ERR_SYSTEM_ERROR;
1.14      markus   1976:                }
1.163     andreas  1977:                if (len == 0 && !cont)
1.205     djm      1978:                        return SSH_ERR_CONN_CLOSED;
1.201     markus   1979:                if ((r = sshbuf_consume(state->output, len)) != 0)
1.205     djm      1980:                        return r;
1.14      markus   1981:        }
1.205     djm      1982:        return 0;
1.1       deraadt  1983: }
                   1984:
1.16      markus   1985: /*
                   1986:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1987:  * written.
                   1988:  */
1.205     djm      1989: int
1.201     markus   1990: ssh_packet_write_wait(struct ssh *ssh)
1.1       deraadt  1991: {
1.56      millert  1992:        fd_set *setp;
1.205     djm      1993:        int ret, r, ms_remain = 0;
1.154     dtucker  1994:        struct timeval start, timeout, *timeoutp = NULL;
1.201     markus   1995:        struct session_state *state = ssh->state;
1.56      millert  1996:
1.201     markus   1997:        setp = (fd_set *)calloc(howmany(state->connection_out + 1,
1.161     andreas  1998:            NFDBITS), sizeof(fd_mask));
1.201     markus   1999:        if (setp == NULL)
1.205     djm      2000:                return SSH_ERR_ALLOC_FAIL;
1.201     markus   2001:        ssh_packet_write_poll(ssh);
                   2002:        while (ssh_packet_have_data_to_write(ssh)) {
                   2003:                memset(setp, 0, howmany(state->connection_out + 1,
1.161     andreas  2004:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   2005:                FD_SET(state->connection_out, setp);
1.154     dtucker  2006:
1.201     markus   2007:                if (state->packet_timeout_ms > 0) {
                   2008:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  2009:                        timeoutp = &timeout;
                   2010:                }
                   2011:                for (;;) {
1.201     markus   2012:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  2013:                                ms_to_timeval(&timeout, ms_remain);
                   2014:                                gettimeofday(&start, NULL);
                   2015:                        }
1.201     markus   2016:                        if ((ret = select(state->connection_out + 1,
1.161     andreas  2017:                            NULL, setp, NULL, timeoutp)) >= 0)
1.154     dtucker  2018:                                break;
1.161     andreas  2019:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  2020:                                break;
1.201     markus   2021:                        if (state->packet_timeout_ms == -1)
1.154     dtucker  2022:                                continue;
                   2023:                        ms_subtract_diff(&start, &ms_remain);
                   2024:                        if (ms_remain <= 0) {
                   2025:                                ret = 0;
                   2026:                                break;
                   2027:                        }
                   2028:                }
                   2029:                if (ret == 0) {
1.205     djm      2030:                        free(setp);
                   2031:                        return SSH_ERR_CONN_TIMEOUT;
                   2032:                }
                   2033:                if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   2034:                        free(setp);
                   2035:                        return r;
1.154     dtucker  2036:                }
1.14      markus   2037:        }
1.186     djm      2038:        free(setp);
1.205     djm      2039:        return 0;
1.1       deraadt  2040: }
                   2041:
                   2042: /* Returns true if there is buffered data to write to the connection. */
                   2043:
1.2       provos   2044: int
1.201     markus   2045: ssh_packet_have_data_to_write(struct ssh *ssh)
1.1       deraadt  2046: {
1.201     markus   2047:        return sshbuf_len(ssh->state->output) != 0;
1.1       deraadt  2048: }
                   2049:
                   2050: /* Returns true if there is not too much data to write to the connection. */
                   2051:
1.2       provos   2052: int
1.201     markus   2053: ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
1.1       deraadt  2054: {
1.201     markus   2055:        if (ssh->state->interactive_mode)
                   2056:                return sshbuf_len(ssh->state->output) < 16384;
1.14      markus   2057:        else
1.201     markus   2058:                return sshbuf_len(ssh->state->output) < 128 * 1024;
1.1       deraadt  2059: }
                   2060:
1.201     markus   2061: void
                   2062: ssh_packet_set_tos(struct ssh *ssh, int tos)
1.101     markus   2063: {
1.201     markus   2064:        if (!ssh_packet_connection_is_on_socket(ssh))
1.101     markus   2065:                return;
1.201     markus   2066:        switch (ssh_packet_connection_af(ssh)) {
1.173     djm      2067:        case AF_INET:
                   2068:                debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1.201     markus   2069:                if (setsockopt(ssh->state->connection_in,
1.173     djm      2070:                    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
                   2071:                        error("setsockopt IP_TOS %d: %.100s:",
                   2072:                            tos, strerror(errno));
                   2073:                break;
                   2074:        case AF_INET6:
                   2075:                debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1.201     markus   2076:                if (setsockopt(ssh->state->connection_in,
1.173     djm      2077:                    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
                   2078:                        error("setsockopt IPV6_TCLASS %d: %.100s:",
                   2079:                            tos, strerror(errno));
                   2080:                break;
                   2081:        }
1.101     markus   2082: }
                   2083:
1.1       deraadt  2084: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   2085:
1.2       provos   2086: void
1.201     markus   2087: ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
1.1       deraadt  2088: {
1.201     markus   2089:        struct session_state *state = ssh->state;
                   2090:
                   2091:        if (state->set_interactive_called)
1.43      markus   2092:                return;
1.201     markus   2093:        state->set_interactive_called = 1;
1.1       deraadt  2094:
1.14      markus   2095:        /* Record that we are in interactive mode. */
1.201     markus   2096:        state->interactive_mode = interactive;
1.1       deraadt  2097:
1.19      markus   2098:        /* Only set socket options if using a socket.  */
1.201     markus   2099:        if (!ssh_packet_connection_is_on_socket(ssh))
1.14      markus   2100:                return;
1.201     markus   2101:        set_nodelay(state->connection_in);
                   2102:        ssh_packet_set_tos(ssh, interactive ? qos_interactive :
                   2103:            qos_bulk);
1.1       deraadt  2104: }
                   2105:
                   2106: /* Returns true if the current connection is interactive. */
                   2107:
1.2       provos   2108: int
1.201     markus   2109: ssh_packet_is_interactive(struct ssh *ssh)
1.1       deraadt  2110: {
1.201     markus   2111:        return ssh->state->interactive_mode;
1.12      markus   2112: }
                   2113:
1.113     deraadt  2114: int
1.201     markus   2115: ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
1.12      markus   2116: {
1.201     markus   2117:        struct session_state *state = ssh->state;
                   2118:
                   2119:        if (state->set_maxsize_called) {
1.106     itojun   2120:                logit("packet_set_maxsize: called twice: old %d new %d",
1.201     markus   2121:                    state->max_packet_size, s);
1.14      markus   2122:                return -1;
                   2123:        }
                   2124:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   2125:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   2126:                return -1;
                   2127:        }
1.201     markus   2128:        state->set_maxsize_called = 1;
1.66      markus   2129:        debug("packet_set_maxsize: setting to %d", s);
1.201     markus   2130:        state->max_packet_size = s;
1.14      markus   2131:        return s;
1.53      markus   2132: }
                   2133:
1.161     andreas  2134: int
1.201     markus   2135: ssh_packet_inc_alive_timeouts(struct ssh *ssh)
1.161     andreas  2136: {
1.201     markus   2137:        return ++ssh->state->keep_alive_timeouts;
1.161     andreas  2138: }
                   2139:
                   2140: void
1.201     markus   2141: ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
1.161     andreas  2142: {
1.201     markus   2143:        ssh->state->keep_alive_timeouts = ka;
1.161     andreas  2144: }
                   2145:
                   2146: u_int
1.201     markus   2147: ssh_packet_get_maxsize(struct ssh *ssh)
1.71      markus   2148: {
1.201     markus   2149:        return ssh->state->max_packet_size;
1.71      markus   2150: }
                   2151:
1.53      markus   2152: /*
                   2153:  * 9.2.  Ignored Data Message
1.61      markus   2154:  *
1.53      markus   2155:  *   byte      SSH_MSG_IGNORE
                   2156:  *   string    data
1.61      markus   2157:  *
1.53      markus   2158:  * All implementations MUST understand (and ignore) this message at any
                   2159:  * time (after receiving the protocol version). No implementation is
                   2160:  * required to send them. This message can be used as an additional
                   2161:  * protection measure against advanced traffic analysis techniques.
                   2162:  */
1.54      markus   2163: void
1.201     markus   2164: ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
1.54      markus   2165: {
1.115     avsm     2166:        u_int32_t rnd = 0;
1.201     markus   2167:        int r, i;
1.54      markus   2168:
1.201     markus   2169:        if ((r = sshpkt_start(ssh, compat20 ?
                   2170:            SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
                   2171:            (r = sshpkt_put_u32(ssh, nbytes)) != 0)
                   2172:                fatal("%s: %s", __func__, ssh_err(r));
1.75      deraadt  2173:        for (i = 0; i < nbytes; i++) {
1.53      markus   2174:                if (i % 4 == 0)
1.115     avsm     2175:                        rnd = arc4random();
1.201     markus   2176:                if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
                   2177:                        fatal("%s: %s", __func__, ssh_err(r));
1.115     avsm     2178:                rnd >>= 8;
1.53      markus   2179:        }
1.105     markus   2180: }
                   2181:
1.113     deraadt  2182: #define MAX_PACKETS    (1U<<31)
1.105     markus   2183: int
1.201     markus   2184: ssh_packet_need_rekeying(struct ssh *ssh)
1.105     markus   2185: {
1.201     markus   2186:        struct session_state *state = ssh->state;
                   2187:
                   2188:        if (ssh->compat & SSH_BUG_NOREKEY)
1.105     markus   2189:                return 0;
                   2190:        return
1.201     markus   2191:            (state->p_send.packets > MAX_PACKETS) ||
                   2192:            (state->p_read.packets > MAX_PACKETS) ||
                   2193:            (state->max_blocks_out &&
                   2194:                (state->p_send.blocks > state->max_blocks_out)) ||
                   2195:            (state->max_blocks_in &&
                   2196:                (state->p_read.blocks > state->max_blocks_in)) ||
                   2197:            (state->rekey_interval != 0 && state->rekey_time +
                   2198:                 state->rekey_interval <= monotime());
1.105     markus   2199: }
                   2200:
                   2201: void
1.201     markus   2202: ssh_packet_set_rekey_limits(struct ssh *ssh, u_int32_t bytes, time_t seconds)
1.105     markus   2203: {
1.184     dtucker  2204:        debug3("rekey after %lld bytes, %d seconds", (long long)bytes,
                   2205:            (int)seconds);
1.201     markus   2206:        ssh->state->rekey_limit = bytes;
                   2207:        ssh->state->rekey_interval = seconds;
1.184     dtucker  2208:        /*
                   2209:         * We set the time here so that in post-auth privsep slave we count
                   2210:         * from the completion of the authentication.
                   2211:         */
1.201     markus   2212:        ssh->state->rekey_time = monotime();
1.184     dtucker  2213: }
                   2214:
                   2215: time_t
1.201     markus   2216: ssh_packet_get_rekey_timeout(struct ssh *ssh)
1.184     dtucker  2217: {
                   2218:        time_t seconds;
                   2219:
1.201     markus   2220:        seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
1.187     dtucker  2221:            monotime();
1.185     dtucker  2222:        return (seconds <= 0 ? 1 : seconds);
1.118     markus   2223: }
                   2224:
                   2225: void
1.201     markus   2226: ssh_packet_set_server(struct ssh *ssh)
1.118     markus   2227: {
1.201     markus   2228:        ssh->state->server_side = 1;
1.118     markus   2229: }
                   2230:
                   2231: void
1.201     markus   2232: ssh_packet_set_authenticated(struct ssh *ssh)
1.118     markus   2233: {
1.201     markus   2234:        ssh->state->after_authentication = 1;
1.161     andreas  2235: }
                   2236:
                   2237: void *
1.201     markus   2238: ssh_packet_get_input(struct ssh *ssh)
1.161     andreas  2239: {
1.201     markus   2240:        return (void *)ssh->state->input;
1.161     andreas  2241: }
                   2242:
                   2243: void *
1.201     markus   2244: ssh_packet_get_output(struct ssh *ssh)
1.161     andreas  2245: {
1.201     markus   2246:        return (void *)ssh->state->output;
1.166     andreas  2247: }
                   2248:
1.201     markus   2249: /* XXX TODO update roaming to new API (does not work anyway) */
1.166     andreas  2250: /*
                   2251:  * Save the state for the real connection, and use a separate state when
                   2252:  * resuming a suspended connection.
                   2253:  */
                   2254: void
1.201     markus   2255: ssh_packet_backup_state(struct ssh *ssh,
                   2256:     struct ssh *backup_state)
1.166     andreas  2257: {
1.201     markus   2258:        struct ssh *tmp;
1.166     andreas  2259:
1.201     markus   2260:        close(ssh->state->connection_in);
                   2261:        ssh->state->connection_in = -1;
                   2262:        close(ssh->state->connection_out);
                   2263:        ssh->state->connection_out = -1;
1.166     andreas  2264:        if (backup_state)
                   2265:                tmp = backup_state;
                   2266:        else
1.201     markus   2267:                tmp = ssh_alloc_session_state();
                   2268:        backup_state = ssh;
                   2269:        ssh = tmp;
1.166     andreas  2270: }
                   2271:
1.201     markus   2272: /* XXX FIXME FIXME FIXME */
1.166     andreas  2273: /*
                   2274:  * Swap in the old state when resuming a connecion.
                   2275:  */
                   2276: void
1.201     markus   2277: ssh_packet_restore_state(struct ssh *ssh,
                   2278:     struct ssh *backup_state)
1.166     andreas  2279: {
1.201     markus   2280:        struct ssh *tmp;
1.166     andreas  2281:        u_int len;
1.201     markus   2282:        int r;
1.166     andreas  2283:
                   2284:        tmp = backup_state;
1.201     markus   2285:        backup_state = ssh;
                   2286:        ssh = tmp;
                   2287:        ssh->state->connection_in = backup_state->state->connection_in;
                   2288:        backup_state->state->connection_in = -1;
                   2289:        ssh->state->connection_out = backup_state->state->connection_out;
                   2290:        backup_state->state->connection_out = -1;
                   2291:        len = sshbuf_len(backup_state->state->input);
1.166     andreas  2292:        if (len > 0) {
1.201     markus   2293:                if ((r = sshbuf_putb(ssh->state->input,
                   2294:                    backup_state->state->input)) != 0)
                   2295:                        fatal("%s: %s", __func__, ssh_err(r));
                   2296:                sshbuf_reset(backup_state->state->input);
1.166     andreas  2297:                add_recv_bytes(len);
1.196     markus   2298:        }
                   2299: }
                   2300:
                   2301: /* Reset after_authentication and reset compression in post-auth privsep */
1.201     markus   2302: static int
                   2303: ssh_packet_set_postauth(struct ssh *ssh)
1.196     markus   2304: {
1.201     markus   2305:        struct sshcomp *comp;
                   2306:        int r, mode;
1.196     markus   2307:
                   2308:        debug("%s: called", __func__);
                   2309:        /* This was set in net child, but is not visible in user child */
1.201     markus   2310:        ssh->state->after_authentication = 1;
                   2311:        ssh->state->rekeying = 0;
1.196     markus   2312:        for (mode = 0; mode < MODE_MAX; mode++) {
1.201     markus   2313:                if (ssh->state->newkeys[mode] == NULL)
1.196     markus   2314:                        continue;
1.201     markus   2315:                comp = &ssh->state->newkeys[mode]->comp;
                   2316:                if (comp && comp->enabled &&
                   2317:                    (r = ssh_packet_init_compression(ssh)) != 0)
                   2318:                        return r;
                   2319:        }
                   2320:        return 0;
                   2321: }
                   2322:
                   2323: /* Packet state (de-)serialization for privsep */
                   2324:
                   2325: /* turn kex into a blob for packet state serialization */
                   2326: static int
                   2327: kex_to_blob(struct sshbuf *m, struct kex *kex)
                   2328: {
                   2329:        int r;
                   2330:
                   2331:        if ((r = sshbuf_put_string(m, kex->session_id,
                   2332:            kex->session_id_len)) != 0 ||
                   2333:            (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
                   2334:            (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
                   2335:            (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
                   2336:            (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
                   2337:            (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
                   2338:            (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
                   2339:            (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
                   2340:            (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
                   2341:                return r;
                   2342:        return 0;
                   2343: }
                   2344:
                   2345: /* turn key exchange results into a blob for packet state serialization */
                   2346: static int
                   2347: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2348: {
                   2349:        struct sshbuf *b;
                   2350:        struct sshcipher_ctx *cc;
                   2351:        struct sshcomp *comp;
                   2352:        struct sshenc *enc;
                   2353:        struct sshmac *mac;
                   2354:        struct newkeys *newkey;
                   2355:        int r;
                   2356:
                   2357:        if ((newkey = ssh->state->newkeys[mode]) == NULL)
                   2358:                return SSH_ERR_INTERNAL_ERROR;
                   2359:        enc = &newkey->enc;
                   2360:        mac = &newkey->mac;
                   2361:        comp = &newkey->comp;
                   2362:        cc = (mode == MODE_OUT) ? &ssh->state->send_context :
                   2363:            &ssh->state->receive_context;
                   2364:        if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
                   2365:                return r;
                   2366:        if ((b = sshbuf_new()) == NULL)
                   2367:                return SSH_ERR_ALLOC_FAIL;
                   2368:        /* The cipher struct is constant and shared, you export pointer */
                   2369:        if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
                   2370:            (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
                   2371:            (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
                   2372:            (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
                   2373:            (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
                   2374:            (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
                   2375:                goto out;
                   2376:        if (cipher_authlen(enc->cipher) == 0) {
                   2377:                if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
                   2378:                    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
                   2379:                    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
                   2380:                        goto out;
                   2381:        }
                   2382:        if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
                   2383:            (r = sshbuf_put_u32(b, comp->enabled)) != 0 ||
                   2384:            (r = sshbuf_put_cstring(b, comp->name)) != 0)
                   2385:                goto out;
                   2386:        r = sshbuf_put_stringb(m, b);
                   2387:  out:
                   2388:        if (b != NULL)
                   2389:                sshbuf_free(b);
                   2390:        return r;
                   2391: }
                   2392:
                   2393: /* serialize packet state into a blob */
                   2394: int
                   2395: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
                   2396: {
                   2397:        struct session_state *state = ssh->state;
                   2398:        u_char *p;
                   2399:        size_t slen, rlen;
                   2400:        int r, ssh1cipher;
                   2401:
                   2402:        if (!compat20) {
                   2403:                ssh1cipher = cipher_get_number(state->receive_context.cipher);
                   2404:                slen = cipher_get_keyiv_len(&state->send_context);
                   2405:                rlen = cipher_get_keyiv_len(&state->receive_context);
                   2406:                if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
                   2407:                    (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
                   2408:                    (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
                   2409:                    (r = sshbuf_put_u32(m, slen)) != 0 ||
                   2410:                    (r = sshbuf_reserve(m, slen, &p)) != 0 ||
                   2411:                    (r = cipher_get_keyiv(&state->send_context, p, slen)) != 0 ||
                   2412:                    (r = sshbuf_put_u32(m, rlen)) != 0 ||
                   2413:                    (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
                   2414:                    (r = cipher_get_keyiv(&state->receive_context, p, rlen)) != 0)
                   2415:                        return r;
                   2416:        } else {
                   2417:                if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
                   2418:                    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
                   2419:                    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
                   2420:                    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
                   2421:                    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
                   2422:                    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
                   2423:                    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
                   2424:                    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
                   2425:                    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
                   2426:                    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
                   2427:                    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
                   2428:                        return r;
                   2429:        }
                   2430:
                   2431:        slen = cipher_get_keycontext(&state->send_context, NULL);
                   2432:        rlen = cipher_get_keycontext(&state->receive_context, NULL);
                   2433:        if ((r = sshbuf_put_u32(m, slen)) != 0 ||
                   2434:            (r = sshbuf_reserve(m, slen, &p)) != 0)
                   2435:                return r;
                   2436:        if (cipher_get_keycontext(&state->send_context, p) != (int)slen)
                   2437:                return SSH_ERR_INTERNAL_ERROR;
                   2438:        if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
                   2439:            (r = sshbuf_reserve(m, rlen, &p)) != 0)
                   2440:                return r;
                   2441:        if (cipher_get_keycontext(&state->receive_context, p) != (int)rlen)
                   2442:                return SSH_ERR_INTERNAL_ERROR;
                   2443:
                   2444:        if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
                   2445:            (r = sshbuf_put_stringb(m, state->input)) != 0 ||
                   2446:            (r = sshbuf_put_stringb(m, state->output)) != 0)
                   2447:                return r;
                   2448:
                   2449:        if (compat20) {
                   2450:                if ((r = sshbuf_put_u64(m, get_sent_bytes())) != 0 ||
                   2451:                    (r = sshbuf_put_u64(m, get_recv_bytes())) != 0)
                   2452:                        return r;
                   2453:        }
                   2454:        return 0;
                   2455: }
                   2456:
                   2457: /* restore key exchange results from blob for packet state de-serialization */
                   2458: static int
                   2459: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2460: {
                   2461:        struct sshbuf *b = NULL;
                   2462:        struct sshcomp *comp;
                   2463:        struct sshenc *enc;
                   2464:        struct sshmac *mac;
                   2465:        struct newkeys *newkey = NULL;
                   2466:        size_t keylen, ivlen, maclen;
                   2467:        int r;
                   2468:
                   2469:        if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
                   2470:                r = SSH_ERR_ALLOC_FAIL;
                   2471:                goto out;
                   2472:        }
                   2473:        if ((r = sshbuf_froms(m, &b)) != 0)
                   2474:                goto out;
                   2475: #ifdef DEBUG_PK
                   2476:        sshbuf_dump(b, stderr);
                   2477: #endif
                   2478:        enc = &newkey->enc;
                   2479:        mac = &newkey->mac;
                   2480:        comp = &newkey->comp;
                   2481:
                   2482:        if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
                   2483:            (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
                   2484:            (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
                   2485:            (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
                   2486:            (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
                   2487:            (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
                   2488:                goto out;
                   2489:        if (cipher_authlen(enc->cipher) == 0) {
                   2490:                if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
                   2491:                        goto out;
                   2492:                if ((r = mac_setup(mac, mac->name)) != 0)
                   2493:                        goto out;
                   2494:                if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
                   2495:                    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
                   2496:                        goto out;
                   2497:                if (maclen > mac->key_len) {
                   2498:                        r = SSH_ERR_INVALID_FORMAT;
                   2499:                        goto out;
                   2500:                }
                   2501:                mac->key_len = maclen;
                   2502:        }
                   2503:        if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
                   2504:            (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
                   2505:            (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
                   2506:                goto out;
                   2507:        if (enc->name == NULL ||
                   2508:            cipher_by_name(enc->name) != enc->cipher) {
                   2509:                r = SSH_ERR_INVALID_FORMAT;
                   2510:                goto out;
                   2511:        }
                   2512:        if (sshbuf_len(b) != 0) {
                   2513:                r = SSH_ERR_INVALID_FORMAT;
                   2514:                goto out;
                   2515:        }
                   2516:        enc->key_len = keylen;
                   2517:        enc->iv_len = ivlen;
                   2518:        ssh->kex->newkeys[mode] = newkey;
                   2519:        newkey = NULL;
                   2520:        r = 0;
                   2521:  out:
                   2522:        if (newkey != NULL)
                   2523:                free(newkey);
                   2524:        if (b != NULL)
                   2525:                sshbuf_free(b);
                   2526:        return r;
                   2527: }
                   2528:
                   2529: /* restore kex from blob for packet state de-serialization */
                   2530: static int
                   2531: kex_from_blob(struct sshbuf *m, struct kex **kexp)
                   2532: {
                   2533:        struct kex *kex;
                   2534:        int r;
                   2535:
                   2536:        if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
                   2537:            (kex->my = sshbuf_new()) == NULL ||
                   2538:            (kex->peer = sshbuf_new()) == NULL) {
                   2539:                r = SSH_ERR_ALLOC_FAIL;
                   2540:                goto out;
                   2541:        }
                   2542:        if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
                   2543:            (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
                   2544:            (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
                   2545:            (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
                   2546:            (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
                   2547:            (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
                   2548:            (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
                   2549:            (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
                   2550:            (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
                   2551:                goto out;
                   2552:        kex->server = 1;
                   2553:        kex->done = 1;
                   2554:        r = 0;
                   2555:  out:
                   2556:        if (r != 0 || kexp == NULL) {
                   2557:                if (kex != NULL) {
                   2558:                        if (kex->my != NULL)
                   2559:                                sshbuf_free(kex->my);
                   2560:                        if (kex->peer != NULL)
                   2561:                                sshbuf_free(kex->peer);
                   2562:                        free(kex);
                   2563:                }
                   2564:                if (kexp != NULL)
                   2565:                        *kexp = NULL;
                   2566:        } else {
                   2567:                *kexp = kex;
                   2568:        }
                   2569:        return r;
                   2570: }
                   2571:
                   2572: /*
                   2573:  * Restore packet state from content of blob 'm' (de-serialization).
                   2574:  * Note that 'm' will be partially consumed on parsing or any other errors.
                   2575:  */
                   2576: int
                   2577: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
                   2578: {
                   2579:        struct session_state *state = ssh->state;
                   2580:        const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
                   2581:        size_t ssh1keylen, rlen, slen, ilen, olen;
                   2582:        int r;
                   2583:        u_int ssh1cipher = 0;
                   2584:        u_int64_t sent_bytes = 0, recv_bytes = 0;
                   2585:
                   2586:        if (!compat20) {
                   2587:                if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
                   2588:                    (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
                   2589:                    (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
                   2590:                    (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
                   2591:                    (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
                   2592:                        return r;
                   2593:                if (ssh1cipher > INT_MAX)
                   2594:                        return SSH_ERR_KEY_UNKNOWN_CIPHER;
                   2595:                ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
                   2596:                    (int)ssh1cipher);
                   2597:                if (cipher_get_keyiv_len(&state->send_context) != (int)slen ||
                   2598:                    cipher_get_keyiv_len(&state->receive_context) != (int)rlen)
                   2599:                        return SSH_ERR_INVALID_FORMAT;
                   2600:                if ((r = cipher_set_keyiv(&state->send_context, ivout)) != 0 ||
                   2601:                    (r = cipher_set_keyiv(&state->receive_context, ivin)) != 0)
                   2602:                        return r;
                   2603:        } else {
                   2604:                if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
                   2605:                    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
                   2606:                    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
                   2607:                    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
                   2608:                    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
                   2609:                    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
                   2610:                    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
                   2611:                    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
                   2612:                    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
                   2613:                    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
                   2614:                    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
                   2615:                        return r;
                   2616:                /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
                   2617:                if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
                   2618:                    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
                   2619:                        return r;
                   2620:        }
                   2621:        if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
                   2622:            (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
                   2623:                return r;
                   2624:        if (cipher_get_keycontext(&state->send_context, NULL) != (int)slen ||
                   2625:            cipher_get_keycontext(&state->receive_context, NULL) != (int)rlen)
                   2626:                return SSH_ERR_INVALID_FORMAT;
                   2627:        cipher_set_keycontext(&state->send_context, keyout);
                   2628:        cipher_set_keycontext(&state->receive_context, keyin);
                   2629:
                   2630:        if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 ||
                   2631:            (r = ssh_packet_set_postauth(ssh)) != 0)
                   2632:                return r;
                   2633:
                   2634:        sshbuf_reset(state->input);
                   2635:        sshbuf_reset(state->output);
                   2636:        if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
                   2637:            (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
                   2638:            (r = sshbuf_put(state->input, input, ilen)) != 0 ||
                   2639:            (r = sshbuf_put(state->output, output, olen)) != 0)
                   2640:                return r;
                   2641:
                   2642:        if (compat20) {
                   2643:                if ((r = sshbuf_get_u64(m, &sent_bytes)) != 0 ||
                   2644:                    (r = sshbuf_get_u64(m, &recv_bytes)) != 0)
                   2645:                        return r;
                   2646:                roam_set_bytes(sent_bytes, recv_bytes);
                   2647:        }
                   2648:        if (sshbuf_len(m))
                   2649:                return SSH_ERR_INVALID_FORMAT;
                   2650:        debug3("%s: done", __func__);
                   2651:        return 0;
                   2652: }
                   2653:
                   2654: /* NEW API */
                   2655:
                   2656: /* put data to the outgoing packet */
                   2657:
                   2658: int
                   2659: sshpkt_put(struct ssh *ssh, const void *v, size_t len)
                   2660: {
                   2661:        return sshbuf_put(ssh->state->outgoing_packet, v, len);
                   2662: }
                   2663:
                   2664: int
                   2665: sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
                   2666: {
                   2667:        return sshbuf_putb(ssh->state->outgoing_packet, b);
                   2668: }
                   2669:
                   2670: int
                   2671: sshpkt_put_u8(struct ssh *ssh, u_char val)
                   2672: {
                   2673:        return sshbuf_put_u8(ssh->state->outgoing_packet, val);
                   2674: }
                   2675:
                   2676: int
                   2677: sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
                   2678: {
                   2679:        return sshbuf_put_u32(ssh->state->outgoing_packet, val);
                   2680: }
                   2681:
                   2682: int
                   2683: sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
                   2684: {
                   2685:        return sshbuf_put_u64(ssh->state->outgoing_packet, val);
                   2686: }
                   2687:
                   2688: int
                   2689: sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
                   2690: {
                   2691:        return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
                   2692: }
                   2693:
                   2694: int
                   2695: sshpkt_put_cstring(struct ssh *ssh, const void *v)
                   2696: {
                   2697:        return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
                   2698: }
                   2699:
                   2700: int
                   2701: sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
                   2702: {
                   2703:        return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
                   2704: }
                   2705:
                   2706: int
                   2707: sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
                   2708: {
                   2709:        return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
                   2710: }
                   2711:
                   2712: int
                   2713: sshpkt_put_bignum1(struct ssh *ssh, const BIGNUM *v)
                   2714: {
                   2715:        return sshbuf_put_bignum1(ssh->state->outgoing_packet, v);
                   2716: }
                   2717:
                   2718: int
                   2719: sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
                   2720: {
                   2721:        return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
                   2722: }
                   2723:
                   2724: /* fetch data from the incoming packet */
                   2725:
                   2726: int
                   2727: sshpkt_get(struct ssh *ssh, void *valp, size_t len)
                   2728: {
                   2729:        return sshbuf_get(ssh->state->incoming_packet, valp, len);
                   2730: }
                   2731:
                   2732: int
                   2733: sshpkt_get_u8(struct ssh *ssh, u_char *valp)
                   2734: {
                   2735:        return sshbuf_get_u8(ssh->state->incoming_packet, valp);
                   2736: }
                   2737:
                   2738: int
                   2739: sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
                   2740: {
                   2741:        return sshbuf_get_u32(ssh->state->incoming_packet, valp);
                   2742: }
                   2743:
                   2744: int
                   2745: sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
                   2746: {
                   2747:        return sshbuf_get_u64(ssh->state->incoming_packet, valp);
                   2748: }
                   2749:
                   2750: int
                   2751: sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
                   2752: {
                   2753:        return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
                   2754: }
                   2755:
                   2756: int
                   2757: sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
                   2758: {
                   2759:        return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
                   2760: }
                   2761:
                   2762: int
                   2763: sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
                   2764: {
                   2765:        return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
                   2766: }
                   2767:
                   2768: int
                   2769: sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
                   2770: {
                   2771:        return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
                   2772: }
                   2773:
                   2774: int
                   2775: sshpkt_get_bignum1(struct ssh *ssh, BIGNUM *v)
                   2776: {
                   2777:        return sshbuf_get_bignum1(ssh->state->incoming_packet, v);
                   2778: }
                   2779:
                   2780: int
                   2781: sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
                   2782: {
                   2783:        return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
                   2784: }
                   2785:
                   2786: int
                   2787: sshpkt_get_end(struct ssh *ssh)
                   2788: {
                   2789:        if (sshbuf_len(ssh->state->incoming_packet) > 0)
                   2790:                return SSH_ERR_UNEXPECTED_TRAILING_DATA;
                   2791:        return 0;
                   2792: }
                   2793:
                   2794: const u_char *
                   2795: sshpkt_ptr(struct ssh *ssh, size_t *lenp)
                   2796: {
                   2797:        if (lenp != NULL)
                   2798:                *lenp = sshbuf_len(ssh->state->incoming_packet);
                   2799:        return sshbuf_ptr(ssh->state->incoming_packet);
                   2800: }
                   2801:
                   2802: /* start a new packet */
                   2803:
                   2804: int
                   2805: sshpkt_start(struct ssh *ssh, u_char type)
                   2806: {
                   2807:        u_char buf[9];
                   2808:        int len;
                   2809:
                   2810:        DBG(debug("packet_start[%d]", type));
                   2811:        len = compat20 ? 6 : 9;
                   2812:        memset(buf, 0, len - 1);
                   2813:        buf[len - 1] = type;
                   2814:        sshbuf_reset(ssh->state->outgoing_packet);
                   2815:        return sshbuf_put(ssh->state->outgoing_packet, buf, len);
                   2816: }
                   2817:
                   2818: /* send it */
                   2819:
                   2820: int
                   2821: sshpkt_send(struct ssh *ssh)
                   2822: {
                   2823:        if (compat20)
                   2824:                return ssh_packet_send2(ssh);
                   2825:        else
                   2826:                return ssh_packet_send1(ssh);
                   2827: }
                   2828:
                   2829: int
                   2830: sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
                   2831: {
                   2832:        char buf[1024];
                   2833:        va_list args;
                   2834:        int r;
                   2835:
                   2836:        va_start(args, fmt);
                   2837:        vsnprintf(buf, sizeof(buf), fmt, args);
                   2838:        va_end(args);
                   2839:
                   2840:        if (compat20) {
                   2841:                if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   2842:                    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
                   2843:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2844:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   2845:                    (r = sshpkt_send(ssh)) != 0)
                   2846:                        return r;
                   2847:        } else {
                   2848:                if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
                   2849:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2850:                    (r = sshpkt_send(ssh)) != 0)
                   2851:                        return r;
1.166     andreas  2852:        }
1.201     markus   2853:        return 0;
                   2854: }
                   2855:
                   2856: /* roundup current message to pad bytes */
                   2857: int
                   2858: sshpkt_add_padding(struct ssh *ssh, u_char pad)
                   2859: {
                   2860:        ssh->state->extra_pad = pad;
                   2861:        return 0;
1.1       deraadt  2862: }