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

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