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

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