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

1.248   ! djm         1: /* $OpenBSD: packet.c,v 1.247 2017/03/11 13:07:35 markus Exp $ */
1.1       deraadt     2: /*
1.15      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.35      deraadt     6:  * This file contains code implementing the packet protocol and communication
                      7:  * with the other side.  This same code is used both on client and server side.
1.29      markus      8:  *
1.35      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
1.29      markus     14:  *
1.25      markus     15:  *
                     16:  * SSH2 packet format added by Markus Friedl.
1.69      markus     17:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.25      markus     18:  *
1.35      deraadt    19:  * Redistribution and use in source and binary forms, with or without
                     20:  * modification, are permitted provided that the following conditions
                     21:  * are met:
                     22:  * 1. Redistributions of source code must retain the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer.
                     24:  * 2. Redistributions in binary form must reproduce the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer in the
                     26:  *    documentation and/or other materials provided with the distribution.
                     27:  *
                     28:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     29:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     30:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     31:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     32:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     33:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     34:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     35:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     36:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     37:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.15      deraadt    38:  */
1.1       deraadt    39:
1.142     deraadt    40: #include <sys/types.h>
1.105     markus     41: #include <sys/queue.h>
1.132     stevesk    42: #include <sys/socket.h>
1.138     stevesk    43: #include <sys/time.h>
1.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.229     djm       275:        return compat20 &&
                    276:            (ssh->state->rekeying || (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.201     markus    690:        if (ssh->state->packet_compression && !compat20)
                    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.16      markus    806: /*
                    807:  * Finalizes and sends the packet.  If the encryption key has been set,
                    808:  * encrypts the packet before sending.
                    809:  */
1.14      markus    810:
1.201     markus    811: int
                    812: ssh_packet_send1(struct ssh *ssh)
1.1       deraadt   813: {
1.201     markus    814:        struct session_state *state = ssh->state;
1.89      markus    815:        u_char buf[8], *cp;
1.201     markus    816:        int r, padding, len;
1.40      markus    817:        u_int checksum;
1.14      markus    818:
1.16      markus    819:        /*
                    820:         * If using packet compression, compress the payload of the outgoing
                    821:         * packet.
                    822:         */
1.201     markus    823:        if (state->packet_compression) {
                    824:                sshbuf_reset(state->compression_buffer);
1.14      markus    825:                /* Skip padding. */
1.201     markus    826:                if ((r = sshbuf_consume(state->outgoing_packet, 8)) != 0)
                    827:                        goto out;
1.14      markus    828:                /* padding */
1.201     markus    829:                if ((r = sshbuf_put(state->compression_buffer,
                    830:                    "\0\0\0\0\0\0\0\0", 8)) != 0)
                    831:                        goto out;
                    832:                if ((r = compress_buffer(ssh, state->outgoing_packet,
                    833:                    state->compression_buffer)) != 0)
                    834:                        goto out;
                    835:                sshbuf_reset(state->outgoing_packet);
                    836:                 if ((r = sshbuf_putb(state->outgoing_packet,
                    837:                     state->compression_buffer)) != 0)
                    838:                        goto out;
1.14      markus    839:        }
                    840:        /* Compute packet length without padding (add checksum, remove padding). */
1.201     markus    841:        len = sshbuf_len(state->outgoing_packet) + 4 - 8;
1.14      markus    842:
1.32      markus    843:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    844:        padding = 8 - len % 8;
1.235     djm       845:        if (!cipher_ctx_is_plaintext(state->send_context)) {
1.201     markus    846:                cp = sshbuf_mutable_ptr(state->outgoing_packet);
                    847:                if (cp == NULL) {
                    848:                        r = SSH_ERR_INTERNAL_ERROR;
                    849:                        goto out;
1.14      markus    850:                }
1.201     markus    851:                arc4random_buf(cp + 8 - padding, padding);
1.14      markus    852:        }
1.201     markus    853:        if ((r = sshbuf_consume(state->outgoing_packet, 8 - padding)) != 0)
                    854:                goto out;
1.14      markus    855:
                    856:        /* Add check bytes. */
1.201     markus    857:        checksum = ssh_crc32(sshbuf_ptr(state->outgoing_packet),
                    858:            sshbuf_len(state->outgoing_packet));
                    859:        POKE_U32(buf, checksum);
                    860:        if ((r = sshbuf_put(state->outgoing_packet, buf, 4)) != 0)
                    861:                goto out;
1.1       deraadt   862:
                    863: #ifdef PACKET_DEBUG
1.14      markus    864:        fprintf(stderr, "packet_send plain: ");
1.201     markus    865:        sshbuf_dump(state->outgoing_packet, stderr);
1.1       deraadt   866: #endif
                    867:
1.14      markus    868:        /* Append to output. */
1.201     markus    869:        POKE_U32(buf, len);
                    870:        if ((r = sshbuf_put(state->output, buf, 4)) != 0)
                    871:                goto out;
                    872:        if ((r = sshbuf_reserve(state->output,
                    873:            sshbuf_len(state->outgoing_packet), &cp)) != 0)
                    874:                goto out;
1.235     djm       875:        if ((r = cipher_crypt(state->send_context, 0, cp,
1.201     markus    876:            sshbuf_ptr(state->outgoing_packet),
                    877:            sshbuf_len(state->outgoing_packet), 0, 0)) != 0)
                    878:                goto out;
1.14      markus    879:
1.1       deraadt   880: #ifdef PACKET_DEBUG
1.14      markus    881:        fprintf(stderr, "encrypted: ");
1.201     markus    882:        sshbuf_dump(state->output, stderr);
1.1       deraadt   883: #endif
1.201     markus    884:        state->p_send.packets++;
                    885:        state->p_send.bytes += len +
                    886:            sshbuf_len(state->outgoing_packet);
                    887:        sshbuf_reset(state->outgoing_packet);
1.1       deraadt   888:
1.16      markus    889:        /*
1.120     djm       890:         * Note that the packet is now only buffered in output.  It won't be
1.205     djm       891:         * actually sent until ssh_packet_write_wait or ssh_packet_write_poll
                    892:         * is called.
1.16      markus    893:         */
1.201     markus    894:        r = 0;
                    895:  out:
                    896:        return r;
1.1       deraadt   897: }
                    898:
1.201     markus    899: int
                    900: ssh_set_newkeys(struct ssh *ssh, int mode)
1.57      markus    901: {
1.201     markus    902:        struct session_state *state = ssh->state;
                    903:        struct sshenc *enc;
                    904:        struct sshmac *mac;
                    905:        struct sshcomp *comp;
1.235     djm       906:        struct sshcipher_ctx **ccp;
1.236     markus    907:        struct packet_state *ps;
1.105     markus    908:        u_int64_t *max_blocks;
1.236     markus    909:        const char *wmsg, *dir;
1.197     djm       910:        int r, crypt_type;
1.57      markus    911:
1.100     markus    912:        debug2("set_newkeys: mode %d", mode);
1.57      markus    913:
1.88      markus    914:        if (mode == MODE_OUT) {
1.236     markus    915:                dir = "output";
1.235     djm       916:                ccp = &state->send_context;
1.115     avsm      917:                crypt_type = CIPHER_ENCRYPT;
1.236     markus    918:                ps = &state->p_send;
1.201     markus    919:                max_blocks = &state->max_blocks_out;
1.88      markus    920:        } else {
1.236     markus    921:                dir = "input";
1.235     djm       922:                ccp = &state->receive_context;
1.115     avsm      923:                crypt_type = CIPHER_DECRYPT;
1.236     markus    924:                ps = &state->p_read;
1.201     markus    925:                max_blocks = &state->max_blocks_in;
1.88      markus    926:        }
1.201     markus    927:        if (state->newkeys[mode] != NULL) {
1.236     markus    928:                debug("%s: rekeying after %llu %s blocks"
                    929:                    " (%llu bytes total)", __func__,
                    930:                    (unsigned long long)ps->blocks, dir,
                    931:                    (unsigned long long)ps->bytes);
1.235     djm       932:                cipher_free(*ccp);
                    933:                *ccp = NULL;
1.201     markus    934:                enc  = &state->newkeys[mode]->enc;
                    935:                mac  = &state->newkeys[mode]->mac;
                    936:                comp = &state->newkeys[mode]->comp;
1.148     pvalchev  937:                mac_clear(mac);
1.192     djm       938:                explicit_bzero(enc->iv,  enc->iv_len);
                    939:                explicit_bzero(enc->key, enc->key_len);
                    940:                explicit_bzero(mac->key, mac->key_len);
1.186     djm       941:                free(enc->name);
                    942:                free(enc->iv);
                    943:                free(enc->key);
                    944:                free(mac->name);
                    945:                free(mac->key);
                    946:                free(comp->name);
1.201     markus    947:                free(state->newkeys[mode]);
1.57      markus    948:        }
1.236     markus    949:        /* note that both bytes and the seqnr are not reset */
                    950:        ps->packets = ps->blocks = 0;
1.201     markus    951:        /* move newkeys from kex to state */
                    952:        if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
                    953:                return SSH_ERR_INTERNAL_ERROR;
                    954:        ssh->kex->newkeys[mode] = NULL;
                    955:        enc  = &state->newkeys[mode]->enc;
                    956:        mac  = &state->newkeys[mode]->mac;
                    957:        comp = &state->newkeys[mode]->comp;
                    958:        if (cipher_authlen(enc->cipher) == 0) {
                    959:                if ((r = mac_init(mac)) != 0)
                    960:                        return r;
                    961:        }
                    962:        mac->enabled = 1;
1.57      markus    963:        DBG(debug("cipher_init_context: %d", mode));
1.235     djm       964:        if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
1.197     djm       965:            enc->iv, enc->iv_len, crypt_type)) != 0)
1.201     markus    966:                return r;
                    967:        if (!state->cipher_warning_done &&
1.235     djm       968:            (wmsg = cipher_warning_message(*ccp)) != NULL) {
1.201     markus    969:                error("Warning: %s", wmsg);
                    970:                state->cipher_warning_done = 1;
                    971:        }
1.91      markus    972:        /* Deleting the keys does not gain extra security */
1.192     djm       973:        /* explicit_bzero(enc->iv,  enc->block_size);
                    974:           explicit_bzero(enc->key, enc->key_len);
                    975:           explicit_bzero(mac->key, mac->key_len); */
1.241     djm       976:        if ((comp->type == COMP_ZLIB ||
                    977:            (comp->type == COMP_DELAYED &&
                    978:             state->after_authentication)) && comp->enabled == 0) {
1.201     markus    979:                if ((r = ssh_packet_init_compression(ssh)) < 0)
                    980:                        return r;
                    981:                if (mode == MODE_OUT) {
                    982:                        if ((r = start_compression_out(ssh, 6)) != 0)
                    983:                                return r;
                    984:                } else {
                    985:                        if ((r = start_compression_in(ssh)) != 0)
                    986:                                return r;
                    987:                }
1.57      markus    988:                comp->enabled = 1;
                    989:        }
1.109     markus    990:        /*
                    991:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    992:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    993:         */
                    994:        if (enc->block_size >= 16)
                    995:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    996:        else
                    997:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.201     markus    998:        if (state->rekey_limit)
1.237     deraadt   999:                *max_blocks = MINIMUM(*max_blocks,
1.201     markus   1000:                    state->rekey_limit / enc->block_size);
1.227     djm      1001:        debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1.201     markus   1002:        return 0;
1.57      markus   1003: }
                   1004:
1.228     djm      1005: #define MAX_PACKETS    (1U<<31)
                   1006: static int
                   1007: ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
                   1008: {
                   1009:        struct session_state *state = ssh->state;
                   1010:        u_int32_t out_blocks;
                   1011:
                   1012:        /* XXX client can't cope with rekeying pre-auth */
                   1013:        if (!state->after_authentication)
                   1014:                return 0;
                   1015:
                   1016:        /* Haven't keyed yet or KEX in progress. */
                   1017:        if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
                   1018:                return 0;
                   1019:
                   1020:        /* Peer can't rekey */
                   1021:        if (ssh->compat & SSH_BUG_NOREKEY)
                   1022:                return 0;
                   1023:
                   1024:        /*
                   1025:         * Permit one packet in or out per rekey - this allows us to
                   1026:         * make progress when rekey limits are very small.
                   1027:         */
                   1028:        if (state->p_send.packets == 0 && state->p_read.packets == 0)
                   1029:                return 0;
                   1030:
                   1031:        /* Time-based rekeying */
                   1032:        if (state->rekey_interval != 0 &&
1.244     dtucker  1033:            (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1.228     djm      1034:                return 1;
                   1035:
                   1036:        /* Always rekey when MAX_PACKETS sent in either direction */
                   1037:        if (state->p_send.packets > MAX_PACKETS ||
                   1038:            state->p_read.packets > MAX_PACKETS)
                   1039:                return 1;
                   1040:
                   1041:        /* Rekey after (cipher-specific) maxiumum blocks */
1.237     deraadt  1042:        out_blocks = ROUNDUP(outbound_packet_len,
1.228     djm      1043:            state->newkeys[MODE_OUT]->enc.block_size);
                   1044:        return (state->max_blocks_out &&
                   1045:            (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
                   1046:            (state->max_blocks_in &&
                   1047:            (state->p_read.blocks > state->max_blocks_in));
                   1048: }
                   1049:
1.16      markus   1050: /*
1.118     markus   1051:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker  1052:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus   1053:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                   1054:  */
1.201     markus   1055: static int
                   1056: ssh_packet_enable_delayed_compress(struct ssh *ssh)
1.118     markus   1057: {
1.201     markus   1058:        struct session_state *state = ssh->state;
                   1059:        struct sshcomp *comp = NULL;
                   1060:        int r, mode;
1.118     markus   1061:
                   1062:        /*
                   1063:         * Remember that we are past the authentication step, so rekeying
                   1064:         * with COMP_DELAYED will turn on compression immediately.
                   1065:         */
1.201     markus   1066:        state->after_authentication = 1;
1.118     markus   1067:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus   1068:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1.201     markus   1069:                if (state->newkeys[mode] == NULL)
1.145     markus   1070:                        continue;
1.201     markus   1071:                comp = &state->newkeys[mode]->comp;
1.118     markus   1072:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.201     markus   1073:                        if ((r = ssh_packet_init_compression(ssh)) != 0)
                   1074:                                return r;
                   1075:                        if (mode == MODE_OUT) {
                   1076:                                if ((r = start_compression_out(ssh, 6)) != 0)
                   1077:                                        return r;
                   1078:                        } else {
                   1079:                                if ((r = start_compression_in(ssh)) != 0)
                   1080:                                        return r;
                   1081:                        }
1.118     markus   1082:                        comp->enabled = 1;
                   1083:                }
                   1084:        }
1.201     markus   1085:        return 0;
1.118     markus   1086: }
                   1087:
1.226     djm      1088: /* Used to mute debug logging for noisy packet types */
1.242     markus   1089: int
1.226     djm      1090: ssh_packet_log_type(u_char type)
                   1091: {
                   1092:        switch (type) {
                   1093:        case SSH2_MSG_CHANNEL_DATA:
                   1094:        case SSH2_MSG_CHANNEL_EXTENDED_DATA:
                   1095:        case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
                   1096:                return 0;
                   1097:        default:
                   1098:                return 1;
                   1099:        }
                   1100: }
                   1101:
1.118     markus   1102: /*
1.25      markus   1103:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                   1104:  */
1.201     markus   1105: int
                   1106: ssh_packet_send2_wrapped(struct ssh *ssh)
1.25      markus   1107: {
1.201     markus   1108:        struct session_state *state = ssh->state;
1.200     markus   1109:        u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1.233     djm      1110:        u_char tmp, padlen, pad = 0;
1.201     markus   1111:        u_int authlen = 0, aadlen = 0;
                   1112:        u_int len;
                   1113:        struct sshenc *enc   = NULL;
                   1114:        struct sshmac *mac   = NULL;
                   1115:        struct sshcomp *comp = NULL;
                   1116:        int r, block_size;
                   1117:
                   1118:        if (state->newkeys[MODE_OUT] != NULL) {
                   1119:                enc  = &state->newkeys[MODE_OUT]->enc;
                   1120:                mac  = &state->newkeys[MODE_OUT]->mac;
                   1121:                comp = &state->newkeys[MODE_OUT]->comp;
1.180     markus   1122:                /* disable mac for authenticated encryption */
                   1123:                if ((authlen = cipher_authlen(enc->cipher)) != 0)
                   1124:                        mac = NULL;
1.25      markus   1125:        }
1.88      markus   1126:        block_size = enc ? enc->block_size : 8;
1.180     markus   1127:        aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1.25      markus   1128:
1.201     markus   1129:        type = (sshbuf_ptr(state->outgoing_packet))[5];
1.226     djm      1130:        if (ssh_packet_log_type(type))
                   1131:                debug3("send packet: type %u", type);
1.25      markus   1132: #ifdef PACKET_DEBUG
                   1133:        fprintf(stderr, "plain:     ");
1.201     markus   1134:        sshbuf_dump(state->outgoing_packet, stderr);
1.25      markus   1135: #endif
                   1136:
                   1137:        if (comp && comp->enabled) {
1.201     markus   1138:                len = sshbuf_len(state->outgoing_packet);
1.25      markus   1139:                /* skip header, compress only payload */
1.201     markus   1140:                if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
                   1141:                        goto out;
                   1142:                sshbuf_reset(state->compression_buffer);
                   1143:                if ((r = compress_buffer(ssh, state->outgoing_packet,
                   1144:                    state->compression_buffer)) != 0)
                   1145:                        goto out;
                   1146:                sshbuf_reset(state->outgoing_packet);
                   1147:                if ((r = sshbuf_put(state->outgoing_packet,
                   1148:                    "\0\0\0\0\0", 5)) != 0 ||
                   1149:                    (r = sshbuf_putb(state->outgoing_packet,
                   1150:                    state->compression_buffer)) != 0)
                   1151:                        goto out;
                   1152:                DBG(debug("compression: raw %d compressed %zd", len,
                   1153:                    sshbuf_len(state->outgoing_packet)));
1.25      markus   1154:        }
                   1155:
                   1156:        /* sizeof (packet_len + pad_len + payload) */
1.201     markus   1157:        len = sshbuf_len(state->outgoing_packet);
1.25      markus   1158:
                   1159:        /*
                   1160:         * calc size of padding, alloc space, get random data,
                   1161:         * minimum padding is 4 bytes
                   1162:         */
1.178     markus   1163:        len -= aadlen; /* packet length is not encrypted for EtM modes */
1.25      markus   1164:        padlen = block_size - (len % block_size);
                   1165:        if (padlen < 4)
                   1166:                padlen += block_size;
1.201     markus   1167:        if (state->extra_pad) {
1.233     djm      1168:                tmp = state->extra_pad;
1.201     markus   1169:                state->extra_pad =
1.237     deraadt  1170:                    ROUNDUP(state->extra_pad, block_size);
1.233     djm      1171:                /* check if roundup overflowed */
                   1172:                if (state->extra_pad < tmp)
                   1173:                        return SSH_ERR_INVALID_ARGUMENT;
                   1174:                tmp = (len + padlen) % state->extra_pad;
                   1175:                /* Check whether pad calculation below will underflow */
                   1176:                if (tmp > state->extra_pad)
                   1177:                        return SSH_ERR_INVALID_ARGUMENT;
                   1178:                pad = state->extra_pad - tmp;
1.193     djm      1179:                DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1.201     markus   1180:                    __func__, pad, len, padlen, state->extra_pad));
1.233     djm      1181:                tmp = padlen;
1.71      markus   1182:                padlen += pad;
1.233     djm      1183:                /* Check whether padlen calculation overflowed */
                   1184:                if (padlen < tmp)
                   1185:                        return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1.201     markus   1186:                state->extra_pad = 0;
1.71      markus   1187:        }
1.201     markus   1188:        if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
                   1189:                goto out;
1.235     djm      1190:        if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1.32      markus   1191:                /* random padding */
1.201     markus   1192:                arc4random_buf(cp, padlen);
1.32      markus   1193:        } else {
                   1194:                /* clear padding */
1.192     djm      1195:                explicit_bzero(cp, padlen);
1.25      markus   1196:        }
1.178     markus   1197:        /* sizeof (packet_len + pad_len + payload + padding) */
1.201     markus   1198:        len = sshbuf_len(state->outgoing_packet);
                   1199:        cp = sshbuf_mutable_ptr(state->outgoing_packet);
                   1200:        if (cp == NULL) {
                   1201:                r = SSH_ERR_INTERNAL_ERROR;
                   1202:                goto out;
                   1203:        }
1.25      markus   1204:        /* packet_length includes payload, padding and padding length field */
1.201     markus   1205:        POKE_U32(cp, len - 4);
1.89      markus   1206:        cp[4] = padlen;
1.178     markus   1207:        DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
                   1208:            len, padlen, aadlen));
1.25      markus   1209:
                   1210:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
1.178     markus   1211:        if (mac && mac->enabled && !mac->etm) {
1.201     markus   1212:                if ((r = mac_compute(mac, state->p_send.seqnr,
                   1213:                    sshbuf_ptr(state->outgoing_packet), len,
1.200     markus   1214:                    macbuf, sizeof(macbuf))) != 0)
1.201     markus   1215:                        goto out;
                   1216:                DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1.25      markus   1217:        }
                   1218:        /* encrypt packet and append to output buffer. */
1.201     markus   1219:        if ((r = sshbuf_reserve(state->output,
                   1220:            sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
                   1221:                goto out;
1.235     djm      1222:        if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1.201     markus   1223:            sshbuf_ptr(state->outgoing_packet),
                   1224:            len - aadlen, aadlen, authlen)) != 0)
                   1225:                goto out;
1.25      markus   1226:        /* append unencrypted MAC */
1.178     markus   1227:        if (mac && mac->enabled) {
                   1228:                if (mac->etm) {
                   1229:                        /* EtM: compute mac over aadlen + cipher text */
1.201     markus   1230:                        if ((r = mac_compute(mac, state->p_send.seqnr,
                   1231:                            cp, len, macbuf, sizeof(macbuf))) != 0)
                   1232:                                goto out;
1.178     markus   1233:                        DBG(debug("done calc MAC(EtM) out #%d",
1.201     markus   1234:                            state->p_send.seqnr));
1.178     markus   1235:                }
1.201     markus   1236:                if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
                   1237:                        goto out;
1.178     markus   1238:        }
1.25      markus   1239: #ifdef PACKET_DEBUG
                   1240:        fprintf(stderr, "encrypted: ");
1.201     markus   1241:        sshbuf_dump(state->output, stderr);
1.25      markus   1242: #endif
1.29      markus   1243:        /* increment sequence number for outgoing packets */
1.201     markus   1244:        if (++state->p_send.seqnr == 0)
1.106     itojun   1245:                logit("outgoing seqnr wraps around");
1.201     markus   1246:        if (++state->p_send.packets == 0)
                   1247:                if (!(ssh->compat & SSH_BUG_NOREKEY))
                   1248:                        return SSH_ERR_NEED_REKEY;
                   1249:        state->p_send.blocks += len / block_size;
                   1250:        state->p_send.bytes += len;
                   1251:        sshbuf_reset(state->outgoing_packet);
1.25      markus   1252:
1.57      markus   1253:        if (type == SSH2_MSG_NEWKEYS)
1.201     markus   1254:                r = ssh_set_newkeys(ssh, MODE_OUT);
                   1255:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
                   1256:                r = ssh_packet_enable_delayed_compress(ssh);
                   1257:        else
                   1258:                r = 0;
                   1259:  out:
                   1260:        return r;
1.25      markus   1261: }
                   1262:
1.228     djm      1263: /* returns non-zero if the specified packet type is usec by KEX */
                   1264: static int
                   1265: ssh_packet_type_is_kex(u_char type)
                   1266: {
                   1267:        return
                   1268:            type >= SSH2_MSG_TRANSPORT_MIN &&
                   1269:            type <= SSH2_MSG_TRANSPORT_MAX &&
                   1270:            type != SSH2_MSG_SERVICE_REQUEST &&
                   1271:            type != SSH2_MSG_SERVICE_ACCEPT &&
                   1272:            type != SSH2_MSG_EXT_INFO;
                   1273: }
                   1274:
1.201     markus   1275: int
                   1276: ssh_packet_send2(struct ssh *ssh)
1.105     markus   1277: {
1.201     markus   1278:        struct session_state *state = ssh->state;
1.105     markus   1279:        struct packet *p;
1.201     markus   1280:        u_char type;
1.228     djm      1281:        int r, need_rekey;
1.105     markus   1282:
1.228     djm      1283:        if (sshbuf_len(state->outgoing_packet) < 6)
                   1284:                return SSH_ERR_INTERNAL_ERROR;
1.201     markus   1285:        type = sshbuf_ptr(state->outgoing_packet)[5];
1.228     djm      1286:        need_rekey = !ssh_packet_type_is_kex(type) &&
                   1287:            ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1.105     markus   1288:
1.228     djm      1289:        /*
                   1290:         * During rekeying we can only send key exchange messages.
                   1291:         * Queue everything else.
                   1292:         */
                   1293:        if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
                   1294:                if (need_rekey)
                   1295:                        debug3("%s: rekex triggered", __func__);
                   1296:                debug("enqueue packet: %u", type);
                   1297:                p = calloc(1, sizeof(*p));
                   1298:                if (p == NULL)
                   1299:                        return SSH_ERR_ALLOC_FAIL;
                   1300:                p->type = type;
                   1301:                p->payload = state->outgoing_packet;
                   1302:                TAILQ_INSERT_TAIL(&state->outgoing, p, next);
                   1303:                state->outgoing_packet = sshbuf_new();
                   1304:                if (state->outgoing_packet == NULL)
                   1305:                        return SSH_ERR_ALLOC_FAIL;
                   1306:                if (need_rekey) {
                   1307:                        /*
                   1308:                         * This packet triggered a rekey, so send the
                   1309:                         * KEXINIT now.
                   1310:                         * NB. reenters this function via kex_start_rekex().
                   1311:                         */
                   1312:                        return kex_start_rekex(ssh);
1.105     markus   1313:                }
1.228     djm      1314:                return 0;
1.105     markus   1315:        }
                   1316:
                   1317:        /* rekeying starts with sending KEXINIT */
                   1318:        if (type == SSH2_MSG_KEXINIT)
1.201     markus   1319:                state->rekeying = 1;
1.105     markus   1320:
1.201     markus   1321:        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1322:                return r;
1.105     markus   1323:
                   1324:        /* after a NEWKEYS message we can send the complete queue */
                   1325:        if (type == SSH2_MSG_NEWKEYS) {
1.201     markus   1326:                state->rekeying = 0;
                   1327:                state->rekey_time = monotime();
                   1328:                while ((p = TAILQ_FIRST(&state->outgoing))) {
1.105     markus   1329:                        type = p->type;
1.228     djm      1330:                        /*
                   1331:                         * If this packet triggers a rekex, then skip the
                   1332:                         * remaining packets in the queue for now.
                   1333:                         * NB. re-enters this function via kex_start_rekex.
                   1334:                         */
                   1335:                        if (ssh_packet_need_rekeying(ssh,
                   1336:                            sshbuf_len(p->payload))) {
                   1337:                                debug3("%s: queued packet triggered rekex",
                   1338:                                    __func__);
                   1339:                                return kex_start_rekex(ssh);
                   1340:                        }
1.105     markus   1341:                        debug("dequeue packet: %u", type);
1.201     markus   1342:                        sshbuf_free(state->outgoing_packet);
                   1343:                        state->outgoing_packet = p->payload;
                   1344:                        TAILQ_REMOVE(&state->outgoing, p, next);
1.228     djm      1345:                        memset(p, 0, sizeof(*p));
1.186     djm      1346:                        free(p);
1.201     markus   1347:                        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1348:                                return r;
1.105     markus   1349:                }
                   1350:        }
1.201     markus   1351:        return 0;
1.25      markus   1352: }
                   1353:
                   1354: /*
1.16      markus   1355:  * Waits until a packet has been received, and returns its type.  Note that
                   1356:  * no other data is processed until this returns, so this function should not
                   1357:  * be used during the interactive session.
                   1358:  */
1.1       deraadt  1359:
1.2       provos   1360: int
1.201     markus   1361: ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.1       deraadt  1362: {
1.201     markus   1363:        struct session_state *state = ssh->state;
1.222     markus   1364:        int len, r, ms_remain;
1.56      millert  1365:        fd_set *setp;
1.14      markus   1366:        char buf[8192];
1.155     deraadt  1367:        struct timeval timeout, start, *timeoutp = NULL;
                   1368:
1.25      markus   1369:        DBG(debug("packet_read()"));
1.14      markus   1370:
1.214     deraadt  1371:        setp = calloc(howmany(state->connection_in + 1,
1.161     andreas  1372:            NFDBITS), sizeof(fd_mask));
1.201     markus   1373:        if (setp == NULL)
                   1374:                return SSH_ERR_ALLOC_FAIL;
1.56      millert  1375:
1.205     djm      1376:        /*
                   1377:         * Since we are blocking, ensure that all written packets have
                   1378:         * been sent.
                   1379:         */
1.210     markus   1380:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   1381:                goto out;
1.14      markus   1382:
                   1383:        /* Stay in the loop until we have received a complete packet. */
                   1384:        for (;;) {
                   1385:                /* Try to read a packet from the buffer. */
1.201     markus   1386:                r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
                   1387:                if (r != 0)
                   1388:                        break;
1.62      markus   1389:                if (!compat20 && (
1.201     markus   1390:                    *typep == SSH_SMSG_SUCCESS
                   1391:                    || *typep == SSH_SMSG_FAILURE
                   1392:                    || *typep == SSH_CMSG_EOF
                   1393:                    || *typep == SSH_CMSG_EXIT_CONFIRMATION))
                   1394:                        if ((r = sshpkt_get_end(ssh)) != 0)
                   1395:                                break;
1.14      markus   1396:                /* If we got a packet, return it. */
1.201     markus   1397:                if (*typep != SSH_MSG_NONE)
                   1398:                        break;
1.16      markus   1399:                /*
                   1400:                 * Otherwise, wait for some data to arrive, add it to the
                   1401:                 * buffer, and try again.
                   1402:                 */
1.201     markus   1403:                memset(setp, 0, howmany(state->connection_in + 1,
1.161     andreas  1404:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   1405:                FD_SET(state->connection_in, setp);
1.16      markus   1406:
1.201     markus   1407:                if (state->packet_timeout_ms > 0) {
                   1408:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  1409:                        timeoutp = &timeout;
                   1410:                }
1.14      markus   1411:                /* Wait for some data to arrive. */
1.154     dtucker  1412:                for (;;) {
1.201     markus   1413:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  1414:                                ms_to_timeval(&timeout, ms_remain);
                   1415:                                gettimeofday(&start, NULL);
                   1416:                        }
1.201     markus   1417:                        if ((r = select(state->connection_in + 1, setp,
1.161     andreas  1418:                            NULL, NULL, timeoutp)) >= 0)
1.154     dtucker  1419:                                break;
1.161     andreas  1420:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1421:                                break;
1.201     markus   1422:                        if (state->packet_timeout_ms == -1)
1.154     dtucker  1423:                                continue;
                   1424:                        ms_subtract_diff(&start, &ms_remain);
                   1425:                        if (ms_remain <= 0) {
1.201     markus   1426:                                r = 0;
1.154     dtucker  1427:                                break;
                   1428:                        }
                   1429:                }
1.246     djm      1430:                if (r == 0) {
                   1431:                        r = SSH_ERR_CONN_TIMEOUT;
                   1432:                        goto out;
                   1433:                }
1.14      markus   1434:                /* Read data from the socket. */
1.222     markus   1435:                len = read(state->connection_in, buf, sizeof(buf));
1.210     markus   1436:                if (len == 0) {
                   1437:                        r = SSH_ERR_CONN_CLOSED;
                   1438:                        goto out;
                   1439:                }
                   1440:                if (len < 0) {
                   1441:                        r = SSH_ERR_SYSTEM_ERROR;
                   1442:                        goto out;
                   1443:                }
1.204     djm      1444:
1.14      markus   1445:                /* Append it to the buffer. */
1.204     djm      1446:                if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0)
1.210     markus   1447:                        goto out;
1.14      markus   1448:        }
1.210     markus   1449:  out:
1.201     markus   1450:        free(setp);
                   1451:        return r;
1.1       deraadt  1452: }
                   1453:
1.77      djm      1454: int
1.201     markus   1455: ssh_packet_read(struct ssh *ssh)
1.77      djm      1456: {
1.201     markus   1457:        u_char type;
                   1458:        int r;
                   1459:
                   1460:        if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
                   1461:                fatal("%s: %s", __func__, ssh_err(r));
                   1462:        return type;
1.77      djm      1463: }
                   1464:
1.16      markus   1465: /*
                   1466:  * Waits until a packet has been received, verifies that its type matches
                   1467:  * that given, and gives a fatal error and exits if there is a mismatch.
                   1468:  */
1.1       deraadt  1469:
1.205     djm      1470: int
                   1471: ssh_packet_read_expect(struct ssh *ssh, u_int expected_type)
1.1       deraadt  1472: {
1.205     djm      1473:        int r;
                   1474:        u_char type;
1.1       deraadt  1475:
1.205     djm      1476:        if ((r = ssh_packet_read_seqnr(ssh, &type, NULL)) != 0)
                   1477:                return r;
                   1478:        if (type != expected_type) {
                   1479:                if ((r = sshpkt_disconnect(ssh,
1.201     markus   1480:                    "Protocol error: expected packet type %d, got %d",
1.205     djm      1481:                    expected_type, type)) != 0)
                   1482:                        return r;
                   1483:                return SSH_ERR_PROTOCOL_ERROR;
                   1484:        }
                   1485:        return 0;
1.1       deraadt  1486: }
                   1487:
                   1488: /* Checks if a full packet is available in the data received so far via
1.14      markus   1489:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                   1490:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                   1491:  *
1.150     dtucker  1492:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                   1493:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                   1494:  * to higher levels.
1.14      markus   1495:  */
1.1       deraadt  1496:
1.201     markus   1497: int
                   1498: ssh_packet_read_poll1(struct ssh *ssh, u_char *typep)
1.1       deraadt  1499: {
1.201     markus   1500:        struct session_state *state = ssh->state;
1.40      markus   1501:        u_int len, padded_len;
1.205     djm      1502:        const char *emsg;
1.201     markus   1503:        const u_char *cp;
                   1504:        u_char *p;
1.40      markus   1505:        u_int checksum, stored_checksum;
1.201     markus   1506:        int r;
                   1507:
                   1508:        *typep = SSH_MSG_NONE;
1.14      markus   1509:
                   1510:        /* Check if input size is less than minimum packet size. */
1.201     markus   1511:        if (sshbuf_len(state->input) < 4 + 8)
                   1512:                return 0;
1.14      markus   1513:        /* Get length of incoming packet. */
1.201     markus   1514:        len = PEEK_U32(sshbuf_ptr(state->input));
1.205     djm      1515:        if (len < 1 + 2 + 2 || len > 256 * 1024) {
                   1516:                if ((r = sshpkt_disconnect(ssh, "Bad packet length %u",
                   1517:                    len)) != 0)
                   1518:                        return r;
                   1519:                return SSH_ERR_CONN_CORRUPT;
                   1520:        }
1.14      markus   1521:        padded_len = (len + 8) & ~7;
                   1522:
                   1523:        /* Check if the packet has been entirely received. */
1.201     markus   1524:        if (sshbuf_len(state->input) < 4 + padded_len)
                   1525:                return 0;
1.14      markus   1526:
                   1527:        /* The entire packet is in buffer. */
                   1528:
                   1529:        /* Consume packet length. */
1.201     markus   1530:        if ((r = sshbuf_consume(state->input, 4)) != 0)
                   1531:                goto out;
1.14      markus   1532:
1.62      markus   1533:        /*
                   1534:         * Cryptographic attack detector for ssh
                   1535:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                   1536:         * Ariel Futoransky(futo@core-sdi.com)
                   1537:         */
1.235     djm      1538:        if (!cipher_ctx_is_plaintext(state->receive_context)) {
1.205     djm      1539:                emsg = NULL;
1.201     markus   1540:                switch (detect_attack(&state->deattack,
                   1541:                    sshbuf_ptr(state->input), padded_len)) {
                   1542:                case DEATTACK_OK:
                   1543:                        break;
1.144     djm      1544:                case DEATTACK_DETECTED:
1.205     djm      1545:                        emsg = "crc32 compensation attack detected";
                   1546:                        break;
1.144     djm      1547:                case DEATTACK_DOS_DETECTED:
1.205     djm      1548:                        emsg = "deattack denial of service detected";
                   1549:                        break;
1.201     markus   1550:                default:
1.205     djm      1551:                        emsg = "deattack error";
                   1552:                        break;
                   1553:                }
                   1554:                if (emsg != NULL) {
                   1555:                        error("%s", emsg);
                   1556:                        if ((r = sshpkt_disconnect(ssh, "%s", emsg)) != 0 ||
                   1557:                            (r = ssh_packet_write_wait(ssh)) != 0)
                   1558:                                        return r;
                   1559:                        return SSH_ERR_CONN_CORRUPT;
1.144     djm      1560:                }
                   1561:        }
1.62      markus   1562:
                   1563:        /* Decrypt data to incoming_packet. */
1.201     markus   1564:        sshbuf_reset(state->incoming_packet);
                   1565:        if ((r = sshbuf_reserve(state->incoming_packet, padded_len, &p)) != 0)
                   1566:                goto out;
1.235     djm      1567:        if ((r = cipher_crypt(state->receive_context, 0, p,
1.201     markus   1568:            sshbuf_ptr(state->input), padded_len, 0, 0)) != 0)
                   1569:                goto out;
1.62      markus   1570:
1.201     markus   1571:        if ((r = sshbuf_consume(state->input, padded_len)) != 0)
                   1572:                goto out;
1.1       deraadt  1573:
                   1574: #ifdef PACKET_DEBUG
1.14      markus   1575:        fprintf(stderr, "read_poll plain: ");
1.201     markus   1576:        sshbuf_dump(state->incoming_packet, stderr);
1.1       deraadt  1577: #endif
                   1578:
1.14      markus   1579:        /* Compute packet checksum. */
1.201     markus   1580:        checksum = ssh_crc32(sshbuf_ptr(state->incoming_packet),
                   1581:            sshbuf_len(state->incoming_packet) - 4);
1.14      markus   1582:
                   1583:        /* Skip padding. */
1.201     markus   1584:        if ((r = sshbuf_consume(state->incoming_packet, 8 - len % 8)) != 0)
                   1585:                goto out;
1.14      markus   1586:
                   1587:        /* Test check bytes. */
1.205     djm      1588:        if (len != sshbuf_len(state->incoming_packet)) {
                   1589:                error("%s: len %d != sshbuf_len %zd", __func__,
1.201     markus   1590:                    len, sshbuf_len(state->incoming_packet));
1.205     djm      1591:                if ((r = sshpkt_disconnect(ssh, "invalid packet length")) != 0 ||
                   1592:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1593:                        return r;
                   1594:                return SSH_ERR_CONN_CORRUPT;
                   1595:        }
1.14      markus   1596:
1.201     markus   1597:        cp = sshbuf_ptr(state->incoming_packet) + len - 4;
                   1598:        stored_checksum = PEEK_U32(cp);
1.205     djm      1599:        if (checksum != stored_checksum) {
                   1600:                error("Corrupted check bytes on input");
                   1601:                if ((r = sshpkt_disconnect(ssh, "connection corrupted")) != 0 ||
                   1602:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1603:                        return r;
                   1604:                return SSH_ERR_CONN_CORRUPT;
                   1605:        }
1.201     markus   1606:        if ((r = sshbuf_consume_end(state->incoming_packet, 4)) < 0)
                   1607:                goto out;
                   1608:
                   1609:        if (state->packet_compression) {
                   1610:                sshbuf_reset(state->compression_buffer);
                   1611:                if ((r = uncompress_buffer(ssh, state->incoming_packet,
                   1612:                    state->compression_buffer)) != 0)
                   1613:                        goto out;
                   1614:                sshbuf_reset(state->incoming_packet);
                   1615:                if ((r = sshbuf_putb(state->incoming_packet,
                   1616:                    state->compression_buffer)) != 0)
                   1617:                        goto out;
                   1618:        }
                   1619:        state->p_read.packets++;
                   1620:        state->p_read.bytes += padded_len + 4;
                   1621:        if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
                   1622:                goto out;
1.205     djm      1623:        if (*typep < SSH_MSG_MIN || *typep > SSH_MSG_MAX) {
                   1624:                error("Invalid ssh1 packet type: %d", *typep);
                   1625:                if ((r = sshpkt_disconnect(ssh, "invalid packet type")) != 0 ||
                   1626:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1627:                        return r;
                   1628:                return SSH_ERR_PROTOCOL_ERROR;
                   1629:        }
1.201     markus   1630:        r = 0;
                   1631:  out:
                   1632:        return r;
1.1       deraadt  1633: }
1.14      markus   1634:
1.242     markus   1635: static int
                   1636: ssh_packet_read_poll2_mux(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
                   1637: {
                   1638:        struct session_state *state = ssh->state;
                   1639:        const u_char *cp;
                   1640:        size_t need;
                   1641:        int r;
                   1642:
                   1643:        if (ssh->kex)
                   1644:                return SSH_ERR_INTERNAL_ERROR;
                   1645:        *typep = SSH_MSG_NONE;
                   1646:        cp = sshbuf_ptr(state->input);
                   1647:        if (state->packlen == 0) {
                   1648:                if (sshbuf_len(state->input) < 4 + 1)
                   1649:                        return 0; /* packet is incomplete */
                   1650:                state->packlen = PEEK_U32(cp);
                   1651:                if (state->packlen < 4 + 1 ||
                   1652:                    state->packlen > PACKET_MAX_SIZE)
                   1653:                        return SSH_ERR_MESSAGE_INCOMPLETE;
                   1654:        }
                   1655:        need = state->packlen + 4;
                   1656:        if (sshbuf_len(state->input) < need)
                   1657:                return 0; /* packet is incomplete */
                   1658:        sshbuf_reset(state->incoming_packet);
                   1659:        if ((r = sshbuf_put(state->incoming_packet, cp + 4,
                   1660:            state->packlen)) != 0 ||
                   1661:            (r = sshbuf_consume(state->input, need)) != 0 ||
                   1662:            (r = sshbuf_get_u8(state->incoming_packet, NULL)) != 0 ||
                   1663:            (r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
                   1664:                return r;
                   1665:        if (ssh_packet_log_type(*typep))
                   1666:                debug3("%s: type %u", __func__, *typep);
                   1667:        /* sshbuf_dump(state->incoming_packet, stderr); */
                   1668:        /* reset for next packet */
                   1669:        state->packlen = 0;
                   1670:        return r;
                   1671: }
                   1672:
1.201     markus   1673: int
                   1674: ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.25      markus   1675: {
1.201     markus   1676:        struct session_state *state = ssh->state;
1.40      markus   1677:        u_int padlen, need;
1.231     djm      1678:        u_char *cp;
1.201     markus   1679:        u_int maclen, aadlen = 0, authlen = 0, block_size;
                   1680:        struct sshenc *enc   = NULL;
                   1681:        struct sshmac *mac   = NULL;
                   1682:        struct sshcomp *comp = NULL;
1.200     markus   1683:        int r;
1.201     markus   1684:
1.242     markus   1685:        if (state->mux)
                   1686:                return ssh_packet_read_poll2_mux(ssh, typep, seqnr_p);
                   1687:
1.201     markus   1688:        *typep = SSH_MSG_NONE;
                   1689:
                   1690:        if (state->packet_discard)
                   1691:                return 0;
                   1692:
                   1693:        if (state->newkeys[MODE_IN] != NULL) {
                   1694:                enc  = &state->newkeys[MODE_IN]->enc;
                   1695:                mac  = &state->newkeys[MODE_IN]->mac;
                   1696:                comp = &state->newkeys[MODE_IN]->comp;
1.180     markus   1697:                /* disable mac for authenticated encryption */
                   1698:                if ((authlen = cipher_authlen(enc->cipher)) != 0)
                   1699:                        mac = NULL;
1.25      markus   1700:        }
                   1701:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1702:        block_size = enc ? enc->block_size : 8;
1.180     markus   1703:        aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1.25      markus   1704:
1.201     markus   1705:        if (aadlen && state->packlen == 0) {
1.235     djm      1706:                if (cipher_get_length(state->receive_context,
1.201     markus   1707:                    &state->packlen, state->p_read.seqnr,
                   1708:                    sshbuf_ptr(state->input), sshbuf_len(state->input)) != 0)
                   1709:                        return 0;
                   1710:                if (state->packlen < 1 + 4 ||
                   1711:                    state->packlen > PACKET_MAX_SIZE) {
1.178     markus   1712: #ifdef PACKET_DEBUG
1.201     markus   1713:                        sshbuf_dump(state->input, stderr);
1.178     markus   1714: #endif
1.201     markus   1715:                        logit("Bad packet length %u.", state->packlen);
                   1716:                        if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
                   1717:                                return r;
1.217     djm      1718:                        return SSH_ERR_CONN_CORRUPT;
1.178     markus   1719:                }
1.201     markus   1720:                sshbuf_reset(state->incoming_packet);
                   1721:        } else if (state->packlen == 0) {
1.25      markus   1722:                /*
                   1723:                 * check if input size is less than the cipher block size,
                   1724:                 * decrypt first block and extract length of incoming packet
                   1725:                 */
1.201     markus   1726:                if (sshbuf_len(state->input) < block_size)
                   1727:                        return 0;
                   1728:                sshbuf_reset(state->incoming_packet);
                   1729:                if ((r = sshbuf_reserve(state->incoming_packet, block_size,
                   1730:                    &cp)) != 0)
                   1731:                        goto out;
1.235     djm      1732:                if ((r = cipher_crypt(state->receive_context,
1.201     markus   1733:                    state->p_send.seqnr, cp, sshbuf_ptr(state->input),
                   1734:                    block_size, 0, 0)) != 0)
                   1735:                        goto out;
                   1736:                state->packlen = PEEK_U32(sshbuf_ptr(state->incoming_packet));
                   1737:                if (state->packlen < 1 + 4 ||
                   1738:                    state->packlen > PACKET_MAX_SIZE) {
1.110     markus   1739: #ifdef PACKET_DEBUG
1.201     markus   1740:                        fprintf(stderr, "input: \n");
                   1741:                        sshbuf_dump(state->input, stderr);
                   1742:                        fprintf(stderr, "incoming_packet: \n");
                   1743:                        sshbuf_dump(state->incoming_packet, stderr);
1.110     markus   1744: #endif
1.201     markus   1745:                        logit("Bad packet length %u.", state->packlen);
1.234     markus   1746:                        return ssh_packet_start_discard(ssh, enc, mac, 0,
                   1747:                            PACKET_MAX_SIZE);
1.25      markus   1748:                }
1.201     markus   1749:                if ((r = sshbuf_consume(state->input, block_size)) != 0)
                   1750:                        goto out;
1.25      markus   1751:        }
1.201     markus   1752:        DBG(debug("input: packet len %u", state->packlen+4));
                   1753:
1.178     markus   1754:        if (aadlen) {
                   1755:                /* only the payload is encrypted */
1.201     markus   1756:                need = state->packlen;
1.178     markus   1757:        } else {
                   1758:                /*
                   1759:                 * the payload size and the payload are encrypted, but we
                   1760:                 * have a partial packet of block_size bytes
                   1761:                 */
1.201     markus   1762:                need = 4 + state->packlen - block_size;
1.178     markus   1763:        }
1.180     markus   1764:        DBG(debug("partial packet: block %d, need %d, maclen %d, authlen %d,"
                   1765:            " aadlen %d", block_size, need, maclen, authlen, aadlen));
1.158     markus   1766:        if (need % block_size != 0) {
                   1767:                logit("padding error: need %d block %d mod %d",
1.25      markus   1768:                    need, block_size, need % block_size);
1.234     markus   1769:                return ssh_packet_start_discard(ssh, enc, mac, 0,
                   1770:                    PACKET_MAX_SIZE - block_size);
1.158     markus   1771:        }
1.25      markus   1772:        /*
                   1773:         * check if the entire packet has been received and
1.178     markus   1774:         * decrypt into incoming_packet:
                   1775:         * 'aadlen' bytes are unencrypted, but authenticated.
1.180     markus   1776:         * 'need' bytes are encrypted, followed by either
                   1777:         * 'authlen' bytes of authentication tag or
1.178     markus   1778:         * 'maclen' bytes of message authentication code.
1.25      markus   1779:         */
1.201     markus   1780:        if (sshbuf_len(state->input) < aadlen + need + authlen + maclen)
1.231     djm      1781:                return 0; /* packet is incomplete */
1.25      markus   1782: #ifdef PACKET_DEBUG
                   1783:        fprintf(stderr, "read_poll enc/full: ");
1.201     markus   1784:        sshbuf_dump(state->input, stderr);
1.25      markus   1785: #endif
1.231     djm      1786:        /* EtM: check mac over encrypted input */
1.201     markus   1787:        if (mac && mac->enabled && mac->etm) {
1.231     djm      1788:                if ((r = mac_check(mac, state->p_read.seqnr,
1.201     markus   1789:                    sshbuf_ptr(state->input), aadlen + need,
1.231     djm      1790:                    sshbuf_ptr(state->input) + aadlen + need + authlen,
                   1791:                    maclen)) != 0) {
                   1792:                        if (r == SSH_ERR_MAC_INVALID)
                   1793:                                logit("Corrupted MAC on input.");
1.201     markus   1794:                        goto out;
1.231     djm      1795:                }
1.201     markus   1796:        }
                   1797:        if ((r = sshbuf_reserve(state->incoming_packet, aadlen + need,
                   1798:            &cp)) != 0)
                   1799:                goto out;
1.235     djm      1800:        if ((r = cipher_crypt(state->receive_context, state->p_read.seqnr, cp,
1.201     markus   1801:            sshbuf_ptr(state->input), need, aadlen, authlen)) != 0)
                   1802:                goto out;
                   1803:        if ((r = sshbuf_consume(state->input, aadlen + need + authlen)) != 0)
                   1804:                goto out;
1.29      markus   1805:        if (mac && mac->enabled) {
1.231     djm      1806:                /* Not EtM: check MAC over cleartext */
                   1807:                if (!mac->etm && (r = mac_check(mac, state->p_read.seqnr,
                   1808:                    sshbuf_ptr(state->incoming_packet),
                   1809:                    sshbuf_len(state->incoming_packet),
                   1810:                    sshbuf_ptr(state->input), maclen)) != 0) {
                   1811:                        if (r != SSH_ERR_MAC_INVALID)
1.201     markus   1812:                                goto out;
1.159     markus   1813:                        logit("Corrupted MAC on input.");
1.247     markus   1814:                        if (need + block_size > PACKET_MAX_SIZE)
1.201     markus   1815:                                return SSH_ERR_INTERNAL_ERROR;
                   1816:                        return ssh_packet_start_discard(ssh, enc, mac,
1.234     markus   1817:                            sshbuf_len(state->incoming_packet),
1.247     markus   1818:                            PACKET_MAX_SIZE - need - block_size);
1.201     markus   1819:                }
1.231     djm      1820:                /* Remove MAC from input buffer */
1.201     markus   1821:                DBG(debug("MAC #%d ok", state->p_read.seqnr));
                   1822:                if ((r = sshbuf_consume(state->input, mac->mac_len)) != 0)
                   1823:                        goto out;
1.25      markus   1824:        }
1.77      djm      1825:        if (seqnr_p != NULL)
1.201     markus   1826:                *seqnr_p = state->p_read.seqnr;
                   1827:        if (++state->p_read.seqnr == 0)
1.106     itojun   1828:                logit("incoming seqnr wraps around");
1.201     markus   1829:        if (++state->p_read.packets == 0)
                   1830:                if (!(ssh->compat & SSH_BUG_NOREKEY))
                   1831:                        return SSH_ERR_NEED_REKEY;
                   1832:        state->p_read.blocks += (state->packlen + 4) / block_size;
                   1833:        state->p_read.bytes += state->packlen + 4;
1.25      markus   1834:
                   1835:        /* get padlen */
1.201     markus   1836:        padlen = sshbuf_ptr(state->incoming_packet)[4];
1.25      markus   1837:        DBG(debug("input: padlen %d", padlen));
1.205     djm      1838:        if (padlen < 4) {
                   1839:                if ((r = sshpkt_disconnect(ssh,
                   1840:                    "Corrupted padlen %d on input.", padlen)) != 0 ||
                   1841:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1842:                        return r;
                   1843:                return SSH_ERR_CONN_CORRUPT;
                   1844:        }
1.25      markus   1845:
                   1846:        /* skip packet size + padlen, discard padding */
1.201     markus   1847:        if ((r = sshbuf_consume(state->incoming_packet, 4 + 1)) != 0 ||
                   1848:            ((r = sshbuf_consume_end(state->incoming_packet, padlen)) != 0))
                   1849:                goto out;
1.25      markus   1850:
1.201     markus   1851:        DBG(debug("input: len before de-compress %zd",
                   1852:            sshbuf_len(state->incoming_packet)));
1.25      markus   1853:        if (comp && comp->enabled) {
1.201     markus   1854:                sshbuf_reset(state->compression_buffer);
                   1855:                if ((r = uncompress_buffer(ssh, state->incoming_packet,
                   1856:                    state->compression_buffer)) != 0)
                   1857:                        goto out;
                   1858:                sshbuf_reset(state->incoming_packet);
                   1859:                if ((r = sshbuf_putb(state->incoming_packet,
                   1860:                    state->compression_buffer)) != 0)
                   1861:                        goto out;
                   1862:                DBG(debug("input: len after de-compress %zd",
                   1863:                    sshbuf_len(state->incoming_packet)));
1.25      markus   1864:        }
                   1865:        /*
                   1866:         * get packet type, implies consume.
                   1867:         * return length of payload (without type field)
                   1868:         */
1.201     markus   1869:        if ((r = sshbuf_get_u8(state->incoming_packet, typep)) != 0)
                   1870:                goto out;
1.226     djm      1871:        if (ssh_packet_log_type(*typep))
                   1872:                debug3("receive packet: type %u", *typep);
1.205     djm      1873:        if (*typep < SSH2_MSG_MIN || *typep >= SSH2_MSG_LOCAL_MIN) {
                   1874:                if ((r = sshpkt_disconnect(ssh,
                   1875:                    "Invalid ssh2 packet type: %d", *typep)) != 0 ||
                   1876:                    (r = ssh_packet_write_wait(ssh)) != 0)
                   1877:                        return r;
                   1878:                return SSH_ERR_PROTOCOL_ERROR;
                   1879:        }
1.243     djm      1880:        if (state->hook_in != NULL &&
                   1881:            (r = state->hook_in(ssh, state->incoming_packet, typep,
                   1882:            state->hook_in_ctx)) != 0)
                   1883:                return r;
1.238     markus   1884:        if (*typep == SSH2_MSG_USERAUTH_SUCCESS && !state->server_side)
1.201     markus   1885:                r = ssh_packet_enable_delayed_compress(ssh);
                   1886:        else
                   1887:                r = 0;
1.25      markus   1888: #ifdef PACKET_DEBUG
1.201     markus   1889:        fprintf(stderr, "read/plain[%d]:\r\n", *typep);
                   1890:        sshbuf_dump(state->incoming_packet, stderr);
1.25      markus   1891: #endif
1.62      markus   1892:        /* reset for next packet */
1.201     markus   1893:        state->packlen = 0;
1.228     djm      1894:
                   1895:        /* do we need to rekey? */
                   1896:        if (ssh_packet_need_rekeying(ssh, 0)) {
                   1897:                debug3("%s: rekex triggered", __func__);
                   1898:                if ((r = kex_start_rekex(ssh)) != 0)
                   1899:                        return r;
                   1900:        }
1.201     markus   1901:  out:
                   1902:        return r;
1.25      markus   1903: }
                   1904:
                   1905: int
1.201     markus   1906: ssh_packet_read_poll_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.25      markus   1907: {
1.201     markus   1908:        struct session_state *state = ssh->state;
1.96      deraadt  1909:        u_int reason, seqnr;
1.201     markus   1910:        int r;
                   1911:        u_char *msg;
1.62      markus   1912:
1.25      markus   1913:        for (;;) {
1.201     markus   1914:                msg = NULL;
1.62      markus   1915:                if (compat20) {
1.201     markus   1916:                        r = ssh_packet_read_poll2(ssh, typep, seqnr_p);
                   1917:                        if (r != 0)
                   1918:                                return r;
                   1919:                        if (*typep) {
                   1920:                                state->keep_alive_timeouts = 0;
                   1921:                                DBG(debug("received packet type %d", *typep));
1.153     djm      1922:                        }
1.201     markus   1923:                        switch (*typep) {
1.150     dtucker  1924:                        case SSH2_MSG_IGNORE:
1.151     dtucker  1925:                                debug3("Received SSH2_MSG_IGNORE");
1.150     dtucker  1926:                                break;
1.25      markus   1927:                        case SSH2_MSG_DEBUG:
1.201     markus   1928:                                if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||
                   1929:                                    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0 ||
                   1930:                                    (r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
1.219     mmcc     1931:                                        free(msg);
1.201     markus   1932:                                        return r;
                   1933:                                }
1.25      markus   1934:                                debug("Remote: %.900s", msg);
1.186     djm      1935:                                free(msg);
1.25      markus   1936:                                break;
                   1937:                        case SSH2_MSG_DISCONNECT:
1.201     markus   1938:                                if ((r = sshpkt_get_u32(ssh, &reason)) != 0 ||
                   1939:                                    (r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1940:                                        return r;
1.182     djm      1941:                                /* Ignore normal client exit notifications */
1.201     markus   1942:                                do_log2(ssh->state->server_side &&
1.182     djm      1943:                                    reason == SSH2_DISCONNECT_BY_APPLICATION ?
                   1944:                                    SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_ERROR,
1.220     djm      1945:                                    "Received disconnect from %s port %d:"
                   1946:                                    "%u: %.400s", ssh_remote_ipaddr(ssh),
                   1947:                                    ssh_remote_port(ssh), reason, msg);
1.186     djm      1948:                                free(msg);
1.201     markus   1949:                                return SSH_ERR_DISCONNECTED;
1.84      markus   1950:                        case SSH2_MSG_UNIMPLEMENTED:
1.201     markus   1951:                                if ((r = sshpkt_get_u32(ssh, &seqnr)) != 0)
                   1952:                                        return r;
1.96      deraadt  1953:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1954:                                    seqnr);
1.150     dtucker  1955:                                break;
1.25      markus   1956:                        default:
1.201     markus   1957:                                return 0;
1.48      stevesk  1958:                        }
1.25      markus   1959:                } else {
1.201     markus   1960:                        r = ssh_packet_read_poll1(ssh, typep);
                   1961:                        switch (*typep) {
1.188     djm      1962:                        case SSH_MSG_NONE:
                   1963:                                return SSH_MSG_NONE;
1.25      markus   1964:                        case SSH_MSG_IGNORE:
                   1965:                                break;
                   1966:                        case SSH_MSG_DEBUG:
1.201     markus   1967:                                if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1968:                                        return r;
1.25      markus   1969:                                debug("Remote: %.900s", msg);
1.186     djm      1970:                                free(msg);
1.25      markus   1971:                                break;
                   1972:                        case SSH_MSG_DISCONNECT:
1.201     markus   1973:                                if ((r = sshpkt_get_string(ssh, &msg, NULL)) != 0)
                   1974:                                        return r;
1.220     djm      1975:                                error("Received disconnect from %s port %d: "
                   1976:                                    "%.400s", ssh_remote_ipaddr(ssh),
                   1977:                                    ssh_remote_port(ssh), msg);
1.201     markus   1978:                                free(msg);
                   1979:                                return SSH_ERR_DISCONNECTED;
1.25      markus   1980:                        default:
1.201     markus   1981:                                DBG(debug("received packet type %d", *typep));
                   1982:                                return 0;
1.48      stevesk  1983:                        }
1.25      markus   1984:                }
                   1985:        }
                   1986: }
                   1987:
1.16      markus   1988: /*
                   1989:  * Buffers the given amount of input characters.  This is intended to be used
                   1990:  * together with packet_read_poll.
                   1991:  */
1.1       deraadt  1992:
1.204     djm      1993: int
1.201     markus   1994: ssh_packet_process_incoming(struct ssh *ssh, const char *buf, u_int len)
1.1       deraadt  1995: {
1.201     markus   1996:        struct session_state *state = ssh->state;
                   1997:        int r;
                   1998:
                   1999:        if (state->packet_discard) {
                   2000:                state->keep_alive_timeouts = 0; /* ?? */
                   2001:                if (len >= state->packet_discard) {
                   2002:                        if ((r = ssh_packet_stop_discard(ssh)) != 0)
1.204     djm      2003:                                return r;
1.201     markus   2004:                }
                   2005:                state->packet_discard -= len;
1.204     djm      2006:                return 0;
1.159     markus   2007:        }
1.201     markus   2008:        if ((r = sshbuf_put(ssh->state->input, buf, len)) != 0)
1.204     djm      2009:                return r;
                   2010:
                   2011:        return 0;
1.28      markus   2012: }
                   2013:
                   2014: int
1.201     markus   2015: ssh_packet_remaining(struct ssh *ssh)
1.28      markus   2016: {
1.201     markus   2017:        return sshbuf_len(ssh->state->incoming_packet);
1.1       deraadt  2018: }
                   2019:
1.16      markus   2020: /*
                   2021:  * Sends a diagnostic message from the server to the client.  This message
                   2022:  * can be sent at any time (but not while constructing another message). The
                   2023:  * message is printed immediately, but only if the client is being executed
                   2024:  * in verbose mode.  These messages are primarily intended to ease debugging
                   2025:  * authentication problems.   The length of the formatted message must not
1.205     djm      2026:  * exceed 1024 bytes.  This will automatically call ssh_packet_write_wait.
1.16      markus   2027:  */
1.2       provos   2028: void
1.201     markus   2029: ssh_packet_send_debug(struct ssh *ssh, const char *fmt,...)
1.1       deraadt  2030: {
1.14      markus   2031:        char buf[1024];
                   2032:        va_list args;
1.201     markus   2033:        int r;
1.39      markus   2034:
1.201     markus   2035:        if (compat20 && (ssh->compat & SSH_BUG_DEBUG))
1.39      markus   2036:                return;
1.14      markus   2037:
                   2038:        va_start(args, fmt);
                   2039:        vsnprintf(buf, sizeof(buf), fmt, args);
                   2040:        va_end(args);
                   2041:
1.30      markus   2042:        if (compat20) {
1.201     markus   2043:                if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
                   2044:                    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
                   2045:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2046:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   2047:                    (r = sshpkt_send(ssh)) != 0)
                   2048:                        fatal("%s: %s", __func__, ssh_err(r));
1.30      markus   2049:        } else {
1.201     markus   2050:                if ((r = sshpkt_start(ssh, SSH_MSG_DEBUG)) != 0 ||
                   2051:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2052:                    (r = sshpkt_send(ssh)) != 0)
                   2053:                        fatal("%s: %s", __func__, ssh_err(r));
1.30      markus   2054:        }
1.205     djm      2055:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   2056:                fatal("%s: %s", __func__, ssh_err(r));
                   2057: }
                   2058:
1.245     djm      2059: static void
                   2060: fmt_connection_id(struct ssh *ssh, char *s, size_t l)
                   2061: {
                   2062:        snprintf(s, l, "%.200s%s%s port %d",
                   2063:            ssh->log_preamble ? ssh->log_preamble : "",
                   2064:            ssh->log_preamble ? " " : "",
                   2065:            ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
                   2066: }
                   2067:
1.205     djm      2068: /*
                   2069:  * Pretty-print connection-terminating errors and exit.
                   2070:  */
                   2071: void
                   2072: sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
                   2073: {
1.245     djm      2074:        char remote_id[512];
                   2075:
                   2076:        fmt_connection_id(ssh, remote_id, sizeof(remote_id));
                   2077:
1.205     djm      2078:        switch (r) {
                   2079:        case SSH_ERR_CONN_CLOSED:
1.245     djm      2080:                logdie("Connection closed by %s", remote_id);
1.205     djm      2081:        case SSH_ERR_CONN_TIMEOUT:
1.245     djm      2082:                logdie("Connection %s %s timed out",
                   2083:                    ssh->state->server_side ? "from" : "to", remote_id);
1.212     djm      2084:        case SSH_ERR_DISCONNECTED:
1.245     djm      2085:                logdie("Disconnected from %s", remote_id);
1.212     djm      2086:        case SSH_ERR_SYSTEM_ERROR:
1.232     dtucker  2087:                if (errno == ECONNRESET)
1.245     djm      2088:                        logdie("Connection reset by %s", remote_id);
1.213     djm      2089:                /* FALLTHROUGH */
                   2090:        case SSH_ERR_NO_CIPHER_ALG_MATCH:
                   2091:        case SSH_ERR_NO_MAC_ALG_MATCH:
                   2092:        case SSH_ERR_NO_COMPRESS_ALG_MATCH:
                   2093:        case SSH_ERR_NO_KEX_ALG_MATCH:
                   2094:        case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
                   2095:                if (ssh && ssh->kex && ssh->kex->failed_choice) {
1.245     djm      2096:                        logdie("Unable to negotiate with %s: %s. "
                   2097:                            "Their offer: %s", remote_id, ssh_err(r),
1.220     djm      2098:                            ssh->kex->failed_choice);
1.212     djm      2099:                }
                   2100:                /* FALLTHROUGH */
1.205     djm      2101:        default:
1.245     djm      2102:                logdie("%s%sConnection %s %s: %s",
1.205     djm      2103:                    tag != NULL ? tag : "", tag != NULL ? ": " : "",
1.220     djm      2104:                    ssh->state->server_side ? "from" : "to",
1.245     djm      2105:                    remote_id, ssh_err(r));
1.205     djm      2106:        }
1.1       deraadt  2107: }
                   2108:
1.16      markus   2109: /*
                   2110:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   2111:  * connection, and exits.  This function never returns. The error message
                   2112:  * should not contain a newline.  The length of the formatted message must
                   2113:  * not exceed 1024 bytes.
                   2114:  */
1.2       provos   2115: void
1.201     markus   2116: ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1.1       deraadt  2117: {
1.245     djm      2118:        char buf[1024], remote_id[512];
1.14      markus   2119:        va_list args;
                   2120:        static int disconnecting = 0;
1.201     markus   2121:        int r;
1.97      deraadt  2122:
1.14      markus   2123:        if (disconnecting)      /* Guard against recursive invocations. */
                   2124:                fatal("packet_disconnect called recursively.");
                   2125:        disconnecting = 1;
                   2126:
1.16      markus   2127:        /*
                   2128:         * Format the message.  Note that the caller must make sure the
                   2129:         * message is of limited size.
                   2130:         */
1.245     djm      2131:        fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1.14      markus   2132:        va_start(args, fmt);
                   2133:        vsnprintf(buf, sizeof(buf), fmt, args);
                   2134:        va_end(args);
                   2135:
1.99      markus   2136:        /* Display the error locally */
1.245     djm      2137:        logit("Disconnecting %s: %.100s", remote_id, buf);
1.99      markus   2138:
1.205     djm      2139:        /*
                   2140:         * Send the disconnect message to the other side, and wait
                   2141:         * for it to get sent.
                   2142:         */
                   2143:        if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
                   2144:                sshpkt_fatal(ssh, __func__, r);
                   2145:
                   2146:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   2147:                sshpkt_fatal(ssh, __func__, r);
1.14      markus   2148:
                   2149:        /* Close the connection. */
1.201     markus   2150:        ssh_packet_close(ssh);
1.112     markus   2151:        cleanup_exit(255);
1.1       deraadt  2152: }
                   2153:
1.205     djm      2154: /*
                   2155:  * Checks if there is any buffered output, and tries to write some of
                   2156:  * the output.
                   2157:  */
                   2158: int
1.201     markus   2159: ssh_packet_write_poll(struct ssh *ssh)
1.1       deraadt  2160: {
1.201     markus   2161:        struct session_state *state = ssh->state;
                   2162:        int len = sshbuf_len(state->output);
1.222     markus   2163:        int r;
1.97      deraadt  2164:
1.14      markus   2165:        if (len > 0) {
1.222     markus   2166:                len = write(state->connection_out,
                   2167:                    sshbuf_ptr(state->output), len);
1.156     djm      2168:                if (len == -1) {
                   2169:                        if (errno == EINTR || errno == EAGAIN)
1.205     djm      2170:                                return 0;
                   2171:                        return SSH_ERR_SYSTEM_ERROR;
1.14      markus   2172:                }
1.222     markus   2173:                if (len == 0)
1.205     djm      2174:                        return SSH_ERR_CONN_CLOSED;
1.201     markus   2175:                if ((r = sshbuf_consume(state->output, len)) != 0)
1.205     djm      2176:                        return r;
1.14      markus   2177:        }
1.205     djm      2178:        return 0;
1.1       deraadt  2179: }
                   2180:
1.16      markus   2181: /*
                   2182:  * Calls packet_write_poll repeatedly until all pending output data has been
                   2183:  * written.
                   2184:  */
1.205     djm      2185: int
1.201     markus   2186: ssh_packet_write_wait(struct ssh *ssh)
1.1       deraadt  2187: {
1.56      millert  2188:        fd_set *setp;
1.205     djm      2189:        int ret, r, ms_remain = 0;
1.154     dtucker  2190:        struct timeval start, timeout, *timeoutp = NULL;
1.201     markus   2191:        struct session_state *state = ssh->state;
1.56      millert  2192:
1.214     deraadt  2193:        setp = calloc(howmany(state->connection_out + 1,
1.161     andreas  2194:            NFDBITS), sizeof(fd_mask));
1.201     markus   2195:        if (setp == NULL)
1.205     djm      2196:                return SSH_ERR_ALLOC_FAIL;
1.216     gsoares  2197:        if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   2198:                free(setp);
1.215     djm      2199:                return r;
1.216     gsoares  2200:        }
1.201     markus   2201:        while (ssh_packet_have_data_to_write(ssh)) {
                   2202:                memset(setp, 0, howmany(state->connection_out + 1,
1.161     andreas  2203:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   2204:                FD_SET(state->connection_out, setp);
1.154     dtucker  2205:
1.201     markus   2206:                if (state->packet_timeout_ms > 0) {
                   2207:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  2208:                        timeoutp = &timeout;
                   2209:                }
                   2210:                for (;;) {
1.201     markus   2211:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  2212:                                ms_to_timeval(&timeout, ms_remain);
                   2213:                                gettimeofday(&start, NULL);
                   2214:                        }
1.201     markus   2215:                        if ((ret = select(state->connection_out + 1,
1.161     andreas  2216:                            NULL, setp, NULL, timeoutp)) >= 0)
1.154     dtucker  2217:                                break;
1.161     andreas  2218:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  2219:                                break;
1.201     markus   2220:                        if (state->packet_timeout_ms == -1)
1.154     dtucker  2221:                                continue;
                   2222:                        ms_subtract_diff(&start, &ms_remain);
                   2223:                        if (ms_remain <= 0) {
                   2224:                                ret = 0;
                   2225:                                break;
                   2226:                        }
                   2227:                }
                   2228:                if (ret == 0) {
1.205     djm      2229:                        free(setp);
                   2230:                        return SSH_ERR_CONN_TIMEOUT;
                   2231:                }
                   2232:                if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   2233:                        free(setp);
                   2234:                        return r;
1.154     dtucker  2235:                }
1.14      markus   2236:        }
1.186     djm      2237:        free(setp);
1.205     djm      2238:        return 0;
1.1       deraadt  2239: }
                   2240:
                   2241: /* Returns true if there is buffered data to write to the connection. */
                   2242:
1.2       provos   2243: int
1.201     markus   2244: ssh_packet_have_data_to_write(struct ssh *ssh)
1.1       deraadt  2245: {
1.201     markus   2246:        return sshbuf_len(ssh->state->output) != 0;
1.1       deraadt  2247: }
                   2248:
                   2249: /* Returns true if there is not too much data to write to the connection. */
                   2250:
1.2       provos   2251: int
1.201     markus   2252: ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
1.1       deraadt  2253: {
1.201     markus   2254:        if (ssh->state->interactive_mode)
                   2255:                return sshbuf_len(ssh->state->output) < 16384;
1.14      markus   2256:        else
1.201     markus   2257:                return sshbuf_len(ssh->state->output) < 128 * 1024;
1.1       deraadt  2258: }
                   2259:
1.201     markus   2260: void
                   2261: ssh_packet_set_tos(struct ssh *ssh, int tos)
1.101     markus   2262: {
1.201     markus   2263:        if (!ssh_packet_connection_is_on_socket(ssh))
1.101     markus   2264:                return;
1.201     markus   2265:        switch (ssh_packet_connection_af(ssh)) {
1.173     djm      2266:        case AF_INET:
                   2267:                debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1.201     markus   2268:                if (setsockopt(ssh->state->connection_in,
1.173     djm      2269:                    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
                   2270:                        error("setsockopt IP_TOS %d: %.100s:",
                   2271:                            tos, strerror(errno));
                   2272:                break;
                   2273:        case AF_INET6:
                   2274:                debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1.201     markus   2275:                if (setsockopt(ssh->state->connection_in,
1.173     djm      2276:                    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
                   2277:                        error("setsockopt IPV6_TCLASS %d: %.100s:",
                   2278:                            tos, strerror(errno));
                   2279:                break;
                   2280:        }
1.101     markus   2281: }
                   2282:
1.1       deraadt  2283: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   2284:
1.2       provos   2285: void
1.201     markus   2286: ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
1.1       deraadt  2287: {
1.201     markus   2288:        struct session_state *state = ssh->state;
                   2289:
                   2290:        if (state->set_interactive_called)
1.43      markus   2291:                return;
1.201     markus   2292:        state->set_interactive_called = 1;
1.1       deraadt  2293:
1.14      markus   2294:        /* Record that we are in interactive mode. */
1.201     markus   2295:        state->interactive_mode = interactive;
1.1       deraadt  2296:
1.19      markus   2297:        /* Only set socket options if using a socket.  */
1.201     markus   2298:        if (!ssh_packet_connection_is_on_socket(ssh))
1.14      markus   2299:                return;
1.201     markus   2300:        set_nodelay(state->connection_in);
                   2301:        ssh_packet_set_tos(ssh, interactive ? qos_interactive :
                   2302:            qos_bulk);
1.1       deraadt  2303: }
                   2304:
                   2305: /* Returns true if the current connection is interactive. */
                   2306:
1.2       provos   2307: int
1.201     markus   2308: ssh_packet_is_interactive(struct ssh *ssh)
1.1       deraadt  2309: {
1.201     markus   2310:        return ssh->state->interactive_mode;
1.12      markus   2311: }
                   2312:
1.113     deraadt  2313: int
1.201     markus   2314: ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
1.12      markus   2315: {
1.201     markus   2316:        struct session_state *state = ssh->state;
                   2317:
                   2318:        if (state->set_maxsize_called) {
1.106     itojun   2319:                logit("packet_set_maxsize: called twice: old %d new %d",
1.201     markus   2320:                    state->max_packet_size, s);
1.14      markus   2321:                return -1;
                   2322:        }
                   2323:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   2324:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   2325:                return -1;
                   2326:        }
1.201     markus   2327:        state->set_maxsize_called = 1;
1.66      markus   2328:        debug("packet_set_maxsize: setting to %d", s);
1.201     markus   2329:        state->max_packet_size = s;
1.14      markus   2330:        return s;
1.53      markus   2331: }
                   2332:
1.161     andreas  2333: int
1.201     markus   2334: ssh_packet_inc_alive_timeouts(struct ssh *ssh)
1.161     andreas  2335: {
1.201     markus   2336:        return ++ssh->state->keep_alive_timeouts;
1.161     andreas  2337: }
                   2338:
                   2339: void
1.201     markus   2340: ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
1.161     andreas  2341: {
1.201     markus   2342:        ssh->state->keep_alive_timeouts = ka;
1.161     andreas  2343: }
                   2344:
                   2345: u_int
1.201     markus   2346: ssh_packet_get_maxsize(struct ssh *ssh)
1.71      markus   2347: {
1.201     markus   2348:        return ssh->state->max_packet_size;
1.71      markus   2349: }
                   2350:
1.53      markus   2351: /*
                   2352:  * 9.2.  Ignored Data Message
1.61      markus   2353:  *
1.53      markus   2354:  *   byte      SSH_MSG_IGNORE
                   2355:  *   string    data
1.61      markus   2356:  *
1.53      markus   2357:  * All implementations MUST understand (and ignore) this message at any
                   2358:  * time (after receiving the protocol version). No implementation is
                   2359:  * required to send them. This message can be used as an additional
                   2360:  * protection measure against advanced traffic analysis techniques.
                   2361:  */
1.54      markus   2362: void
1.201     markus   2363: ssh_packet_send_ignore(struct ssh *ssh, int nbytes)
1.54      markus   2364: {
1.115     avsm     2365:        u_int32_t rnd = 0;
1.201     markus   2366:        int r, i;
1.54      markus   2367:
1.201     markus   2368:        if ((r = sshpkt_start(ssh, compat20 ?
                   2369:            SSH2_MSG_IGNORE : SSH_MSG_IGNORE)) != 0 ||
                   2370:            (r = sshpkt_put_u32(ssh, nbytes)) != 0)
                   2371:                fatal("%s: %s", __func__, ssh_err(r));
1.75      deraadt  2372:        for (i = 0; i < nbytes; i++) {
1.53      markus   2373:                if (i % 4 == 0)
1.115     avsm     2374:                        rnd = arc4random();
1.201     markus   2375:                if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
                   2376:                        fatal("%s: %s", __func__, ssh_err(r));
1.115     avsm     2377:                rnd >>= 8;
1.53      markus   2378:        }
1.105     markus   2379: }
                   2380:
                   2381: void
1.244     dtucker  2382: ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
1.105     markus   2383: {
1.244     dtucker  2384:        debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
                   2385:            (unsigned int)seconds);
1.201     markus   2386:        ssh->state->rekey_limit = bytes;
                   2387:        ssh->state->rekey_interval = seconds;
1.184     dtucker  2388: }
                   2389:
                   2390: time_t
1.201     markus   2391: ssh_packet_get_rekey_timeout(struct ssh *ssh)
1.184     dtucker  2392: {
                   2393:        time_t seconds;
                   2394:
1.201     markus   2395:        seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
1.187     dtucker  2396:            monotime();
1.185     dtucker  2397:        return (seconds <= 0 ? 1 : seconds);
1.118     markus   2398: }
                   2399:
                   2400: void
1.201     markus   2401: ssh_packet_set_server(struct ssh *ssh)
1.118     markus   2402: {
1.201     markus   2403:        ssh->state->server_side = 1;
1.118     markus   2404: }
                   2405:
                   2406: void
1.201     markus   2407: ssh_packet_set_authenticated(struct ssh *ssh)
1.118     markus   2408: {
1.201     markus   2409:        ssh->state->after_authentication = 1;
1.161     andreas  2410: }
                   2411:
                   2412: void *
1.201     markus   2413: ssh_packet_get_input(struct ssh *ssh)
1.161     andreas  2414: {
1.201     markus   2415:        return (void *)ssh->state->input;
1.161     andreas  2416: }
                   2417:
                   2418: void *
1.201     markus   2419: ssh_packet_get_output(struct ssh *ssh)
1.161     andreas  2420: {
1.201     markus   2421:        return (void *)ssh->state->output;
1.166     andreas  2422: }
                   2423:
1.196     markus   2424: /* Reset after_authentication and reset compression in post-auth privsep */
1.201     markus   2425: static int
                   2426: ssh_packet_set_postauth(struct ssh *ssh)
1.196     markus   2427: {
1.239     djm      2428:        int r;
1.196     markus   2429:
                   2430:        debug("%s: called", __func__);
                   2431:        /* This was set in net child, but is not visible in user child */
1.201     markus   2432:        ssh->state->after_authentication = 1;
                   2433:        ssh->state->rekeying = 0;
1.239     djm      2434:        if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
                   2435:                return r;
1.201     markus   2436:        return 0;
                   2437: }
                   2438:
                   2439: /* Packet state (de-)serialization for privsep */
                   2440:
                   2441: /* turn kex into a blob for packet state serialization */
                   2442: static int
                   2443: kex_to_blob(struct sshbuf *m, struct kex *kex)
                   2444: {
                   2445:        int r;
                   2446:
                   2447:        if ((r = sshbuf_put_string(m, kex->session_id,
                   2448:            kex->session_id_len)) != 0 ||
                   2449:            (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
                   2450:            (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
                   2451:            (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
                   2452:            (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
                   2453:            (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
                   2454:            (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
                   2455:            (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
                   2456:            (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
                   2457:                return r;
                   2458:        return 0;
                   2459: }
                   2460:
                   2461: /* turn key exchange results into a blob for packet state serialization */
                   2462: static int
                   2463: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2464: {
                   2465:        struct sshbuf *b;
                   2466:        struct sshcipher_ctx *cc;
                   2467:        struct sshcomp *comp;
                   2468:        struct sshenc *enc;
                   2469:        struct sshmac *mac;
                   2470:        struct newkeys *newkey;
                   2471:        int r;
                   2472:
                   2473:        if ((newkey = ssh->state->newkeys[mode]) == NULL)
                   2474:                return SSH_ERR_INTERNAL_ERROR;
                   2475:        enc = &newkey->enc;
                   2476:        mac = &newkey->mac;
                   2477:        comp = &newkey->comp;
1.235     djm      2478:        cc = (mode == MODE_OUT) ? ssh->state->send_context :
                   2479:            ssh->state->receive_context;
1.201     markus   2480:        if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
                   2481:                return r;
                   2482:        if ((b = sshbuf_new()) == NULL)
                   2483:                return SSH_ERR_ALLOC_FAIL;
                   2484:        /* The cipher struct is constant and shared, you export pointer */
                   2485:        if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
                   2486:            (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
                   2487:            (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
                   2488:            (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
                   2489:            (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
                   2490:            (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
                   2491:                goto out;
                   2492:        if (cipher_authlen(enc->cipher) == 0) {
                   2493:                if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
                   2494:                    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
                   2495:                    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
                   2496:                        goto out;
                   2497:        }
                   2498:        if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
                   2499:            (r = sshbuf_put_cstring(b, comp->name)) != 0)
                   2500:                goto out;
                   2501:        r = sshbuf_put_stringb(m, b);
                   2502:  out:
1.221     mmcc     2503:        sshbuf_free(b);
1.201     markus   2504:        return r;
                   2505: }
                   2506:
                   2507: /* serialize packet state into a blob */
                   2508: int
                   2509: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
                   2510: {
                   2511:        struct session_state *state = ssh->state;
                   2512:        u_char *p;
                   2513:        size_t slen, rlen;
                   2514:        int r, ssh1cipher;
                   2515:
                   2516:        if (!compat20) {
1.235     djm      2517:                ssh1cipher = cipher_ctx_get_number(state->receive_context);
                   2518:                slen = cipher_get_keyiv_len(state->send_context);
                   2519:                rlen = cipher_get_keyiv_len(state->receive_context);
1.201     markus   2520:                if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
                   2521:                    (r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
                   2522:                    (r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
                   2523:                    (r = sshbuf_put_u32(m, slen)) != 0 ||
                   2524:                    (r = sshbuf_reserve(m, slen, &p)) != 0 ||
1.235     djm      2525:                    (r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
1.201     markus   2526:                    (r = sshbuf_put_u32(m, rlen)) != 0 ||
                   2527:                    (r = sshbuf_reserve(m, rlen, &p)) != 0 ||
1.235     djm      2528:                    (r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
1.201     markus   2529:                        return r;
                   2530:        } else {
                   2531:                if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
                   2532:                    (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
                   2533:                    (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
1.224     dtucker  2534:                    (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
1.208     markus   2535:                    (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
1.201     markus   2536:                    (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
                   2537:                    (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
                   2538:                    (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
                   2539:                    (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
                   2540:                    (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
                   2541:                    (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
                   2542:                    (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
                   2543:                    (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
                   2544:                        return r;
                   2545:        }
                   2546:
1.235     djm      2547:        slen = cipher_get_keycontext(state->send_context, NULL);
                   2548:        rlen = cipher_get_keycontext(state->receive_context, NULL);
1.201     markus   2549:        if ((r = sshbuf_put_u32(m, slen)) != 0 ||
                   2550:            (r = sshbuf_reserve(m, slen, &p)) != 0)
                   2551:                return r;
1.235     djm      2552:        if (cipher_get_keycontext(state->send_context, p) != (int)slen)
1.201     markus   2553:                return SSH_ERR_INTERNAL_ERROR;
                   2554:        if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
                   2555:            (r = sshbuf_reserve(m, rlen, &p)) != 0)
                   2556:                return r;
1.235     djm      2557:        if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
1.201     markus   2558:                return SSH_ERR_INTERNAL_ERROR;
1.239     djm      2559:        if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
1.201     markus   2560:            (r = sshbuf_put_stringb(m, state->output)) != 0)
                   2561:                return r;
                   2562:
                   2563:        return 0;
                   2564: }
                   2565:
                   2566: /* restore key exchange results from blob for packet state de-serialization */
                   2567: static int
                   2568: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2569: {
                   2570:        struct sshbuf *b = NULL;
                   2571:        struct sshcomp *comp;
                   2572:        struct sshenc *enc;
                   2573:        struct sshmac *mac;
                   2574:        struct newkeys *newkey = NULL;
                   2575:        size_t keylen, ivlen, maclen;
                   2576:        int r;
                   2577:
                   2578:        if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
                   2579:                r = SSH_ERR_ALLOC_FAIL;
                   2580:                goto out;
                   2581:        }
                   2582:        if ((r = sshbuf_froms(m, &b)) != 0)
                   2583:                goto out;
                   2584: #ifdef DEBUG_PK
                   2585:        sshbuf_dump(b, stderr);
                   2586: #endif
                   2587:        enc = &newkey->enc;
                   2588:        mac = &newkey->mac;
                   2589:        comp = &newkey->comp;
                   2590:
                   2591:        if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
                   2592:            (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
                   2593:            (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
                   2594:            (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
                   2595:            (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
                   2596:            (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
                   2597:                goto out;
                   2598:        if (cipher_authlen(enc->cipher) == 0) {
                   2599:                if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
                   2600:                        goto out;
                   2601:                if ((r = mac_setup(mac, mac->name)) != 0)
                   2602:                        goto out;
                   2603:                if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
                   2604:                    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
                   2605:                        goto out;
                   2606:                if (maclen > mac->key_len) {
                   2607:                        r = SSH_ERR_INVALID_FORMAT;
                   2608:                        goto out;
                   2609:                }
                   2610:                mac->key_len = maclen;
                   2611:        }
                   2612:        if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
                   2613:            (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
                   2614:                goto out;
                   2615:        if (enc->name == NULL ||
                   2616:            cipher_by_name(enc->name) != enc->cipher) {
                   2617:                r = SSH_ERR_INVALID_FORMAT;
                   2618:                goto out;
                   2619:        }
                   2620:        if (sshbuf_len(b) != 0) {
                   2621:                r = SSH_ERR_INVALID_FORMAT;
                   2622:                goto out;
                   2623:        }
                   2624:        enc->key_len = keylen;
                   2625:        enc->iv_len = ivlen;
                   2626:        ssh->kex->newkeys[mode] = newkey;
                   2627:        newkey = NULL;
                   2628:        r = 0;
                   2629:  out:
1.219     mmcc     2630:        free(newkey);
1.221     mmcc     2631:        sshbuf_free(b);
1.201     markus   2632:        return r;
                   2633: }
                   2634:
                   2635: /* restore kex from blob for packet state de-serialization */
                   2636: static int
                   2637: kex_from_blob(struct sshbuf *m, struct kex **kexp)
                   2638: {
                   2639:        struct kex *kex;
                   2640:        int r;
                   2641:
                   2642:        if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
                   2643:            (kex->my = sshbuf_new()) == NULL ||
                   2644:            (kex->peer = sshbuf_new()) == NULL) {
                   2645:                r = SSH_ERR_ALLOC_FAIL;
                   2646:                goto out;
                   2647:        }
                   2648:        if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
                   2649:            (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
                   2650:            (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
                   2651:            (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
                   2652:            (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
                   2653:            (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
                   2654:            (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
                   2655:            (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
                   2656:            (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
                   2657:                goto out;
                   2658:        kex->server = 1;
                   2659:        kex->done = 1;
                   2660:        r = 0;
                   2661:  out:
                   2662:        if (r != 0 || kexp == NULL) {
                   2663:                if (kex != NULL) {
1.221     mmcc     2664:                        sshbuf_free(kex->my);
                   2665:                        sshbuf_free(kex->peer);
1.201     markus   2666:                        free(kex);
                   2667:                }
                   2668:                if (kexp != NULL)
                   2669:                        *kexp = NULL;
                   2670:        } else {
                   2671:                *kexp = kex;
                   2672:        }
                   2673:        return r;
                   2674: }
                   2675:
                   2676: /*
                   2677:  * Restore packet state from content of blob 'm' (de-serialization).
                   2678:  * Note that 'm' will be partially consumed on parsing or any other errors.
                   2679:  */
                   2680: int
                   2681: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
                   2682: {
                   2683:        struct session_state *state = ssh->state;
                   2684:        const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output;
                   2685:        size_t ssh1keylen, rlen, slen, ilen, olen;
                   2686:        int r;
                   2687:        u_int ssh1cipher = 0;
                   2688:
                   2689:        if (!compat20) {
                   2690:                if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 ||
                   2691:                    (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 ||
                   2692:                    (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 ||
                   2693:                    (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 ||
                   2694:                    (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0)
                   2695:                        return r;
                   2696:                if (ssh1cipher > INT_MAX)
                   2697:                        return SSH_ERR_KEY_UNKNOWN_CIPHER;
                   2698:                ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen,
                   2699:                    (int)ssh1cipher);
1.235     djm      2700:                if (cipher_get_keyiv_len(state->send_context) != (int)slen ||
                   2701:                    cipher_get_keyiv_len(state->receive_context) != (int)rlen)
1.201     markus   2702:                        return SSH_ERR_INVALID_FORMAT;
1.235     djm      2703:                if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 ||
                   2704:                    (r = cipher_set_keyiv(state->receive_context, ivin)) != 0)
1.201     markus   2705:                        return r;
                   2706:        } else {
                   2707:                if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
                   2708:                    (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
                   2709:                    (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
1.224     dtucker  2710:                    (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
1.208     markus   2711:                    (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
1.201     markus   2712:                    (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
                   2713:                    (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
                   2714:                    (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
                   2715:                    (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
                   2716:                    (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
                   2717:                    (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
                   2718:                    (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
                   2719:                    (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
                   2720:                        return r;
1.208     markus   2721:                /*
                   2722:                 * We set the time here so that in post-auth privsep slave we
                   2723:                 * count from the completion of the authentication.
                   2724:                 */
                   2725:                state->rekey_time = monotime();
1.201     markus   2726:                /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
                   2727:                if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
                   2728:                    (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
                   2729:                        return r;
                   2730:        }
                   2731:        if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 ||
                   2732:            (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0)
                   2733:                return r;
1.235     djm      2734:        if (cipher_get_keycontext(state->send_context, NULL) != (int)slen ||
                   2735:            cipher_get_keycontext(state->receive_context, NULL) != (int)rlen)
1.201     markus   2736:                return SSH_ERR_INVALID_FORMAT;
1.235     djm      2737:        cipher_set_keycontext(state->send_context, keyout);
                   2738:        cipher_set_keycontext(state->receive_context, keyin);
1.201     markus   2739:
1.239     djm      2740:        if ((r = ssh_packet_set_postauth(ssh)) != 0)
1.201     markus   2741:                return r;
                   2742:
                   2743:        sshbuf_reset(state->input);
                   2744:        sshbuf_reset(state->output);
                   2745:        if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
                   2746:            (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
                   2747:            (r = sshbuf_put(state->input, input, ilen)) != 0 ||
                   2748:            (r = sshbuf_put(state->output, output, olen)) != 0)
                   2749:                return r;
                   2750:
                   2751:        if (sshbuf_len(m))
                   2752:                return SSH_ERR_INVALID_FORMAT;
                   2753:        debug3("%s: done", __func__);
                   2754:        return 0;
                   2755: }
                   2756:
                   2757: /* NEW API */
                   2758:
                   2759: /* put data to the outgoing packet */
                   2760:
                   2761: int
                   2762: sshpkt_put(struct ssh *ssh, const void *v, size_t len)
                   2763: {
                   2764:        return sshbuf_put(ssh->state->outgoing_packet, v, len);
                   2765: }
                   2766:
                   2767: int
                   2768: sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
                   2769: {
                   2770:        return sshbuf_putb(ssh->state->outgoing_packet, b);
                   2771: }
                   2772:
                   2773: int
                   2774: sshpkt_put_u8(struct ssh *ssh, u_char val)
                   2775: {
                   2776:        return sshbuf_put_u8(ssh->state->outgoing_packet, val);
                   2777: }
                   2778:
                   2779: int
                   2780: sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
                   2781: {
                   2782:        return sshbuf_put_u32(ssh->state->outgoing_packet, val);
                   2783: }
                   2784:
                   2785: int
                   2786: sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
                   2787: {
                   2788:        return sshbuf_put_u64(ssh->state->outgoing_packet, val);
                   2789: }
                   2790:
                   2791: int
                   2792: sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
                   2793: {
                   2794:        return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
                   2795: }
                   2796:
                   2797: int
                   2798: sshpkt_put_cstring(struct ssh *ssh, const void *v)
                   2799: {
                   2800:        return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
                   2801: }
                   2802:
                   2803: int
                   2804: sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
                   2805: {
                   2806:        return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
                   2807: }
                   2808:
1.211     djm      2809: #ifdef WITH_OPENSSL
1.201     markus   2810: int
                   2811: sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
                   2812: {
                   2813:        return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
                   2814: }
                   2815:
                   2816:
                   2817: int
                   2818: sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
                   2819: {
                   2820:        return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
                   2821: }
1.211     djm      2822: #endif /* WITH_OPENSSL */
1.201     markus   2823:
                   2824: /* fetch data from the incoming packet */
                   2825:
                   2826: int
                   2827: sshpkt_get(struct ssh *ssh, void *valp, size_t len)
                   2828: {
                   2829:        return sshbuf_get(ssh->state->incoming_packet, valp, len);
                   2830: }
                   2831:
                   2832: int
                   2833: sshpkt_get_u8(struct ssh *ssh, u_char *valp)
                   2834: {
                   2835:        return sshbuf_get_u8(ssh->state->incoming_packet, valp);
                   2836: }
                   2837:
                   2838: int
                   2839: sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
                   2840: {
                   2841:        return sshbuf_get_u32(ssh->state->incoming_packet, valp);
                   2842: }
                   2843:
                   2844: int
                   2845: sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
                   2846: {
                   2847:        return sshbuf_get_u64(ssh->state->incoming_packet, valp);
                   2848: }
                   2849:
                   2850: int
                   2851: sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
                   2852: {
                   2853:        return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
                   2854: }
                   2855:
                   2856: int
                   2857: sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
                   2858: {
                   2859:        return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
                   2860: }
                   2861:
                   2862: int
                   2863: sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
                   2864: {
                   2865:        return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
                   2866: }
                   2867:
1.211     djm      2868: #ifdef WITH_OPENSSL
1.201     markus   2869: int
                   2870: sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
                   2871: {
                   2872:        return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
                   2873: }
                   2874:
                   2875:
                   2876: int
                   2877: sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
                   2878: {
                   2879:        return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
                   2880: }
1.211     djm      2881: #endif /* WITH_OPENSSL */
1.201     markus   2882:
                   2883: int
                   2884: sshpkt_get_end(struct ssh *ssh)
                   2885: {
                   2886:        if (sshbuf_len(ssh->state->incoming_packet) > 0)
                   2887:                return SSH_ERR_UNEXPECTED_TRAILING_DATA;
                   2888:        return 0;
                   2889: }
                   2890:
                   2891: const u_char *
                   2892: sshpkt_ptr(struct ssh *ssh, size_t *lenp)
                   2893: {
                   2894:        if (lenp != NULL)
                   2895:                *lenp = sshbuf_len(ssh->state->incoming_packet);
                   2896:        return sshbuf_ptr(ssh->state->incoming_packet);
                   2897: }
                   2898:
                   2899: /* start a new packet */
                   2900:
                   2901: int
                   2902: sshpkt_start(struct ssh *ssh, u_char type)
                   2903: {
                   2904:        u_char buf[9];
                   2905:        int len;
                   2906:
                   2907:        DBG(debug("packet_start[%d]", type));
                   2908:        len = compat20 ? 6 : 9;
                   2909:        memset(buf, 0, len - 1);
                   2910:        buf[len - 1] = type;
                   2911:        sshbuf_reset(ssh->state->outgoing_packet);
                   2912:        return sshbuf_put(ssh->state->outgoing_packet, buf, len);
                   2913: }
                   2914:
1.242     markus   2915: static int
                   2916: ssh_packet_send_mux(struct ssh *ssh)
                   2917: {
                   2918:        struct session_state *state = ssh->state;
                   2919:        u_char type, *cp;
                   2920:        size_t len;
                   2921:        int r;
                   2922:
                   2923:        if (ssh->kex)
                   2924:                return SSH_ERR_INTERNAL_ERROR;
                   2925:        len = sshbuf_len(state->outgoing_packet);
                   2926:        if (len < 6)
                   2927:                return SSH_ERR_INTERNAL_ERROR;
                   2928:        cp = sshbuf_mutable_ptr(state->outgoing_packet);
                   2929:        type = cp[5];
                   2930:        if (ssh_packet_log_type(type))
                   2931:                debug3("%s: type %u", __func__, type);
                   2932:        /* drop everything, but the connection protocol */
                   2933:        if (type >= SSH2_MSG_CONNECTION_MIN &&
                   2934:            type <= SSH2_MSG_CONNECTION_MAX) {
                   2935:                POKE_U32(cp, len - 4);
                   2936:                if ((r = sshbuf_putb(state->output,
                   2937:                    state->outgoing_packet)) != 0)
                   2938:                        return r;
                   2939:                /* sshbuf_dump(state->output, stderr); */
                   2940:        }
                   2941:        sshbuf_reset(state->outgoing_packet);
                   2942:        return 0;
                   2943: }
                   2944:
1.201     markus   2945: /* send it */
                   2946:
                   2947: int
                   2948: sshpkt_send(struct ssh *ssh)
                   2949: {
1.242     markus   2950:        if (ssh->state && ssh->state->mux)
                   2951:                return ssh_packet_send_mux(ssh);
1.201     markus   2952:        if (compat20)
                   2953:                return ssh_packet_send2(ssh);
                   2954:        else
                   2955:                return ssh_packet_send1(ssh);
                   2956: }
                   2957:
                   2958: int
                   2959: sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
                   2960: {
                   2961:        char buf[1024];
                   2962:        va_list args;
                   2963:        int r;
                   2964:
                   2965:        va_start(args, fmt);
                   2966:        vsnprintf(buf, sizeof(buf), fmt, args);
                   2967:        va_end(args);
                   2968:
                   2969:        if (compat20) {
                   2970:                if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   2971:                    (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
                   2972:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2973:                    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   2974:                    (r = sshpkt_send(ssh)) != 0)
                   2975:                        return r;
                   2976:        } else {
                   2977:                if ((r = sshpkt_start(ssh, SSH_MSG_DISCONNECT)) != 0 ||
                   2978:                    (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2979:                    (r = sshpkt_send(ssh)) != 0)
                   2980:                        return r;
1.166     andreas  2981:        }
1.201     markus   2982:        return 0;
                   2983: }
                   2984:
                   2985: /* roundup current message to pad bytes */
                   2986: int
                   2987: sshpkt_add_padding(struct ssh *ssh, u_char pad)
                   2988: {
                   2989:        ssh->state->extra_pad = pad;
                   2990:        return 0;
1.1       deraadt  2991: }