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

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