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

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