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

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