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

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