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

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