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

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