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

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