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

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