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

1.275   ! sf          1: /* $OpenBSD: packet.c,v 1.274 2018/07/06 09:06:14 sf 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:        /* default maximum packet size */
                    145:        u_int max_packet_size;
1.1       deraadt   146:
1.161     andreas   147:        /* Flag indicating whether this module has been initialized. */
                    148:        int initialized;
1.12      markus    149:
1.161     andreas   150:        /* Set to true if the connection is interactive. */
                    151:        int interactive_mode;
1.1       deraadt   152:
1.161     andreas   153:        /* Set to true if we are the server side. */
                    154:        int server_side;
1.1       deraadt   155:
1.161     andreas   156:        /* Set to true if we are authenticated. */
                    157:        int after_authentication;
1.118     markus    158:
1.161     andreas   159:        int keep_alive_timeouts;
1.118     markus    160:
1.161     andreas   161:        /* The maximum time that we will wait to send or receive a packet */
                    162:        int packet_timeout_ms;
1.151     dtucker   163:
1.161     andreas   164:        /* Session key information for Encryption and MAC */
1.201     markus    165:        struct newkeys *newkeys[MODE_MAX];
1.161     andreas   166:        struct packet_state p_read, p_send;
1.154     dtucker   167:
1.184     dtucker   168:        /* Volume-based rekeying */
1.224     dtucker   169:        u_int64_t max_blocks_in, max_blocks_out, rekey_limit;
1.105     markus    170:
1.184     dtucker   171:        /* Time-based rekeying */
1.208     markus    172:        u_int32_t rekey_interval;       /* how often in seconds */
1.184     dtucker   173:        time_t rekey_time;      /* time of last rekeying */
                    174:
1.161     andreas   175:        /* roundup current message to extra_pad bytes */
                    176:        u_char extra_pad;
1.95      markus    177:
1.161     andreas   178:        /* XXX discard incoming data after MAC error */
                    179:        u_int packet_discard;
1.234     markus    180:        size_t packet_discard_mac_already;
1.201     markus    181:        struct sshmac *packet_discard_mac;
1.71      markus    182:
1.161     andreas   183:        /* Used in packet_read_poll2() */
                    184:        u_int packlen;
1.159     markus    185:
1.165     andreas   186:        /* Used in packet_send2 */
                    187:        int rekeying;
                    188:
1.242     markus    189:        /* Used in ssh_packet_send_mux() */
                    190:        int mux;
                    191:
1.165     andreas   192:        /* Used in packet_set_interactive */
                    193:        int set_interactive_called;
                    194:
                    195:        /* Used in packet_set_maxsize */
                    196:        int set_maxsize_called;
                    197:
1.201     markus    198:        /* One-off warning about weak ciphers */
                    199:        int cipher_warning_done;
                    200:
1.243     djm       201:        /* Hook for fuzzing inbound packets */
                    202:        ssh_packet_hook_fn *hook_in;
                    203:        void *hook_in_ctx;
                    204:
1.161     andreas   205:        TAILQ_HEAD(, packet) outgoing;
1.105     markus    206: };
1.161     andreas   207:
1.201     markus    208: struct ssh *
                    209: ssh_alloc_session_state(void)
1.161     andreas   210: {
1.201     markus    211:        struct ssh *ssh = NULL;
                    212:        struct session_state *state = NULL;
1.161     andreas   213:
1.201     markus    214:        if ((ssh = calloc(1, sizeof(*ssh))) == NULL ||
                    215:            (state = calloc(1, sizeof(*state))) == NULL ||
                    216:            (state->input = sshbuf_new()) == NULL ||
                    217:            (state->output = sshbuf_new()) == NULL ||
                    218:            (state->outgoing_packet = sshbuf_new()) == NULL ||
                    219:            (state->incoming_packet = sshbuf_new()) == NULL)
                    220:                goto fail;
                    221:        TAILQ_INIT(&state->outgoing);
1.202     markus    222:        TAILQ_INIT(&ssh->private_keys);
                    223:        TAILQ_INIT(&ssh->public_keys);
1.201     markus    224:        state->connection_in = -1;
                    225:        state->connection_out = -1;
                    226:        state->max_packet_size = 32768;
                    227:        state->packet_timeout_ms = -1;
                    228:        state->p_send.packets = state->p_read.packets = 0;
                    229:        state->initialized = 1;
                    230:        /*
                    231:         * ssh_packet_send2() needs to queue packets until
                    232:         * we've done the initial key exchange.
                    233:         */
                    234:        state->rekeying = 1;
                    235:        ssh->state = state;
                    236:        return ssh;
                    237:  fail:
                    238:        if (state) {
                    239:                sshbuf_free(state->input);
                    240:                sshbuf_free(state->output);
                    241:                sshbuf_free(state->incoming_packet);
                    242:                sshbuf_free(state->outgoing_packet);
                    243:                free(state);
                    244:        }
                    245:        free(ssh);
                    246:        return NULL;
1.161     andreas   247: }
1.105     markus    248:
1.243     djm       249: void
                    250: ssh_packet_set_input_hook(struct ssh *ssh, ssh_packet_hook_fn *hook, void *ctx)
                    251: {
                    252:        ssh->state->hook_in = hook;
                    253:        ssh->state->hook_in_ctx = ctx;
                    254: }
                    255:
1.228     djm       256: /* Returns nonzero if rekeying is in progress */
                    257: int
                    258: ssh_packet_is_rekeying(struct ssh *ssh)
                    259: {
1.249     djm       260:        return ssh->state->rekeying ||
                    261:            (ssh->kex != NULL && ssh->kex->done == 0);
1.228     djm       262: }
                    263:
1.16      markus    264: /*
1.253     naddy     265:  * Sets the descriptors used for communication.
1.16      markus    266:  */
1.201     markus    267: struct ssh *
                    268: ssh_packet_set_connection(struct ssh *ssh, int fd_in, int fd_out)
1.1       deraadt   269: {
1.201     markus    270:        struct session_state *state;
                    271:        const struct sshcipher *none = cipher_by_name("none");
1.197     djm       272:        int r;
1.97      deraadt   273:
1.205     djm       274:        if (none == NULL) {
                    275:                error("%s: cannot load cipher 'none'", __func__);
                    276:                return NULL;
                    277:        }
1.201     markus    278:        if (ssh == NULL)
                    279:                ssh = ssh_alloc_session_state();
1.205     djm       280:        if (ssh == NULL) {
                    281:                error("%s: cound not allocate state", __func__);
                    282:                return NULL;
                    283:        }
1.201     markus    284:        state = ssh->state;
                    285:        state->connection_in = fd_in;
                    286:        state->connection_out = fd_out;
                    287:        if ((r = cipher_init(&state->send_context, none,
1.197     djm       288:            (const u_char *)"", 0, NULL, 0, CIPHER_ENCRYPT)) != 0 ||
1.201     markus    289:            (r = cipher_init(&state->receive_context, none,
1.205     djm       290:            (const u_char *)"", 0, NULL, 0, CIPHER_DECRYPT)) != 0) {
                    291:                error("%s: cipher_init failed: %s", __func__, ssh_err(r));
1.230     djm       292:                free(ssh); /* XXX need ssh_free_session_state? */
1.205     djm       293:                return NULL;
                    294:        }
1.201     markus    295:        state->newkeys[MODE_IN] = state->newkeys[MODE_OUT] = NULL;
1.207     djm       296:        /*
                    297:         * Cache the IP address of the remote connection for use in error
                    298:         * messages that might be generated after the connection has closed.
                    299:         */
                    300:        (void)ssh_remote_ipaddr(ssh);
1.201     markus    301:        return ssh;
1.1       deraadt   302: }
                    303:
1.154     dtucker   304: void
1.201     markus    305: ssh_packet_set_timeout(struct ssh *ssh, int timeout, int count)
1.154     dtucker   306: {
1.201     markus    307:        struct session_state *state = ssh->state;
                    308:
1.174     djm       309:        if (timeout <= 0 || count <= 0) {
1.201     markus    310:                state->packet_timeout_ms = -1;
1.154     dtucker   311:                return;
                    312:        }
                    313:        if ((INT_MAX / 1000) / count < timeout)
1.201     markus    314:                state->packet_timeout_ms = INT_MAX;
1.154     dtucker   315:        else
1.201     markus    316:                state->packet_timeout_ms = timeout * count * 1000;
1.154     dtucker   317: }
                    318:
1.242     markus    319: void
                    320: ssh_packet_set_mux(struct ssh *ssh)
                    321: {
                    322:        ssh->state->mux = 1;
                    323:        ssh->state->rekeying = 0;
                    324: }
                    325:
                    326: int
                    327: ssh_packet_get_mux(struct ssh *ssh)
                    328: {
                    329:        return ssh->state->mux;
                    330: }
                    331:
1.201     markus    332: int
1.245     djm       333: ssh_packet_set_log_preamble(struct ssh *ssh, const char *fmt, ...)
                    334: {
                    335:        va_list args;
                    336:        int r;
                    337:
                    338:        free(ssh->log_preamble);
                    339:        if (fmt == NULL)
                    340:                ssh->log_preamble = NULL;
                    341:        else {
                    342:                va_start(args, fmt);
                    343:                r = vasprintf(&ssh->log_preamble, fmt, args);
                    344:                va_end(args);
                    345:                if (r < 0 || ssh->log_preamble == NULL)
                    346:                        return SSH_ERR_ALLOC_FAIL;
                    347:        }
                    348:        return 0;
                    349: }
                    350:
                    351: int
1.201     markus    352: ssh_packet_stop_discard(struct ssh *ssh)
1.159     markus    353: {
1.201     markus    354:        struct session_state *state = ssh->state;
                    355:        int r;
                    356:
                    357:        if (state->packet_discard_mac) {
1.159     markus    358:                char buf[1024];
1.234     markus    359:                size_t dlen = PACKET_MAX_SIZE;
1.201     markus    360:
1.234     markus    361:                if (dlen > state->packet_discard_mac_already)
                    362:                        dlen -= state->packet_discard_mac_already;
1.159     markus    363:                memset(buf, 'a', sizeof(buf));
1.234     markus    364:                while (sshbuf_len(state->incoming_packet) < dlen)
1.201     markus    365:                        if ((r = sshbuf_put(state->incoming_packet, buf,
                    366:                            sizeof(buf))) != 0)
                    367:                                return r;
                    368:                (void) mac_compute(state->packet_discard_mac,
                    369:                    state->p_read.seqnr,
1.234     markus    370:                    sshbuf_ptr(state->incoming_packet), dlen,
1.201     markus    371:                    NULL, 0);
1.159     markus    372:        }
1.220     djm       373:        logit("Finished discarding for %.200s port %d",
                    374:            ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.201     markus    375:        return SSH_ERR_MAC_INVALID;
1.159     markus    376: }
                    377:
1.201     markus    378: static int
                    379: ssh_packet_start_discard(struct ssh *ssh, struct sshenc *enc,
1.234     markus    380:     struct sshmac *mac, size_t mac_already, u_int discard)
1.159     markus    381: {
1.201     markus    382:        struct session_state *state = ssh->state;
                    383:        int r;
                    384:
                    385:        if (enc == NULL || !cipher_is_cbc(enc->cipher) || (mac && mac->etm)) {
                    386:                if ((r = sshpkt_disconnect(ssh, "Packet corrupt")) != 0)
                    387:                        return r;
                    388:                return SSH_ERR_MAC_INVALID;
                    389:        }
1.234     markus    390:        /*
                    391:         * Record number of bytes over which the mac has already
                    392:         * been computed in order to minimize timing attacks.
                    393:         */
                    394:        if (mac && mac->enabled) {
1.201     markus    395:                state->packet_discard_mac = mac;
1.234     markus    396:                state->packet_discard_mac_already = mac_already;
                    397:        }
                    398:        if (sshbuf_len(state->input) >= discard)
                    399:                return ssh_packet_stop_discard(ssh);
1.201     markus    400:        state->packet_discard = discard - sshbuf_len(state->input);
                    401:        return 0;
1.159     markus    402: }
                    403:
1.19      markus    404: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    405:
                    406: int
1.201     markus    407: ssh_packet_connection_is_on_socket(struct ssh *ssh)
1.19      markus    408: {
1.271     djm       409:        struct session_state *state;
1.19      markus    410:        struct sockaddr_storage from, to;
                    411:        socklen_t fromlen, tolen;
                    412:
1.271     djm       413:        if (ssh == NULL || ssh->state == NULL)
                    414:                return 0;
                    415:
                    416:        state = ssh->state;
1.230     djm       417:        if (state->connection_in == -1 || state->connection_out == -1)
                    418:                return 0;
1.19      markus    419:        /* filedescriptors in and out are the same, so it's a socket */
1.201     markus    420:        if (state->connection_in == state->connection_out)
1.19      markus    421:                return 1;
                    422:        fromlen = sizeof(from);
                    423:        memset(&from, 0, sizeof(from));
1.201     markus    424:        if (getpeername(state->connection_in, (struct sockaddr *)&from,
1.161     andreas   425:            &fromlen) < 0)
1.19      markus    426:                return 0;
                    427:        tolen = sizeof(to);
                    428:        memset(&to, 0, sizeof(to));
1.201     markus    429:        if (getpeername(state->connection_out, (struct sockaddr *)&to,
1.161     andreas   430:            &tolen) < 0)
1.19      markus    431:                return 0;
                    432:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    433:                return 0;
                    434:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    435:                return 0;
                    436:        return 1;
                    437: }
                    438:
1.91      markus    439: void
1.201     markus    440: ssh_packet_get_bytes(struct ssh *ssh, u_int64_t *ibytes, u_int64_t *obytes)
1.91      markus    441: {
1.201     markus    442:        if (ibytes)
                    443:                *ibytes = ssh->state->p_read.bytes;
                    444:        if (obytes)
                    445:                *obytes = ssh->state->p_send.bytes;
1.91      markus    446: }
1.125     deraadt   447:
1.91      markus    448: int
1.201     markus    449: ssh_packet_connection_af(struct ssh *ssh)
1.19      markus    450: {
                    451:        struct sockaddr_storage to;
1.21      deraadt   452:        socklen_t tolen = sizeof(to);
1.19      markus    453:
                    454:        memset(&to, 0, sizeof(to));
1.201     markus    455:        if (getsockname(ssh->state->connection_out, (struct sockaddr *)&to,
1.161     andreas   456:            &tolen) < 0)
1.19      markus    457:                return 0;
1.173     djm       458:        return to.ss_family;
1.19      markus    459: }
                    460:
1.1       deraadt   461: /* Sets the connection into non-blocking mode. */
                    462:
1.2       provos    463: void
1.201     markus    464: ssh_packet_set_nonblocking(struct ssh *ssh)
1.1       deraadt   465: {
1.14      markus    466:        /* Set the socket into non-blocking mode. */
1.201     markus    467:        set_nonblock(ssh->state->connection_in);
1.14      markus    468:
1.201     markus    469:        if (ssh->state->connection_out != ssh->state->connection_in)
                    470:                set_nonblock(ssh->state->connection_out);
1.1       deraadt   471: }
                    472:
                    473: /* Returns the socket used for reading. */
                    474:
1.2       provos    475: int
1.201     markus    476: ssh_packet_get_connection_in(struct ssh *ssh)
1.1       deraadt   477: {
1.201     markus    478:        return ssh->state->connection_in;
1.1       deraadt   479: }
                    480:
                    481: /* Returns the descriptor used for writing. */
                    482:
1.2       provos    483: int
1.201     markus    484: ssh_packet_get_connection_out(struct ssh *ssh)
1.1       deraadt   485: {
1.201     markus    486:        return ssh->state->connection_out;
                    487: }
                    488:
                    489: /*
                    490:  * Returns the IP-address of the remote host as a string.  The returned
                    491:  * string must not be freed.
                    492:  */
                    493:
                    494: const char *
                    495: ssh_remote_ipaddr(struct ssh *ssh)
                    496: {
1.271     djm       497:        int sock;
1.220     djm       498:
1.201     markus    499:        /* Check whether we have cached the ipaddr. */
1.220     djm       500:        if (ssh->remote_ipaddr == NULL) {
                    501:                if (ssh_packet_connection_is_on_socket(ssh)) {
1.271     djm       502:                        sock = ssh->state->connection_in;
1.220     djm       503:                        ssh->remote_ipaddr = get_peer_ipaddr(sock);
1.230     djm       504:                        ssh->remote_port = get_peer_port(sock);
                    505:                        ssh->local_ipaddr = get_local_ipaddr(sock);
                    506:                        ssh->local_port = get_local_port(sock);
1.220     djm       507:                } else {
                    508:                        ssh->remote_ipaddr = strdup("UNKNOWN");
1.230     djm       509:                        ssh->remote_port = 65535;
                    510:                        ssh->local_ipaddr = strdup("UNKNOWN");
                    511:                        ssh->local_port = 65535;
1.220     djm       512:                }
                    513:        }
1.201     markus    514:        return ssh->remote_ipaddr;
1.1       deraadt   515: }
                    516:
1.220     djm       517: /* Returns the port number of the remote host. */
                    518:
                    519: int
                    520: ssh_remote_port(struct ssh *ssh)
                    521: {
                    522:        (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
                    523:        return ssh->remote_port;
1.230     djm       524: }
                    525:
                    526: /*
                    527:  * Returns the IP-address of the local host as a string.  The returned
                    528:  * string must not be freed.
                    529:  */
                    530:
                    531: const char *
                    532: ssh_local_ipaddr(struct ssh *ssh)
                    533: {
                    534:        (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
                    535:        return ssh->local_ipaddr;
                    536: }
                    537:
                    538: /* Returns the port number of the local host. */
                    539:
                    540: int
                    541: ssh_local_port(struct ssh *ssh)
                    542: {
                    543:        (void)ssh_remote_ipaddr(ssh); /* Will lookup and cache. */
                    544:        return ssh->local_port;
1.266     djm       545: }
                    546:
                    547: /* Returns the routing domain of the input socket, or NULL if unavailable */
                    548: const char *
                    549: ssh_packet_rdomain_in(struct ssh *ssh)
                    550: {
                    551:        if (ssh->rdomain_in != NULL)
                    552:                return ssh->rdomain_in;
                    553:        if (!ssh_packet_connection_is_on_socket(ssh))
                    554:                return NULL;
                    555:        ssh->rdomain_in = get_rdomain(ssh->state->connection_in);
                    556:        return ssh->rdomain_in;
1.220     djm       557: }
                    558:
1.1       deraadt   559: /* Closes the connection and clears and frees internal data structures. */
                    560:
1.257     markus    561: static void
                    562: ssh_packet_close_internal(struct ssh *ssh, int do_close)
1.1       deraadt   563: {
1.201     markus    564:        struct session_state *state = ssh->state;
                    565:        u_int mode;
                    566:
                    567:        if (!state->initialized)
1.14      markus    568:                return;
1.201     markus    569:        state->initialized = 0;
1.257     markus    570:        if (do_close) {
                    571:                if (state->connection_in == state->connection_out) {
                    572:                        close(state->connection_out);
                    573:                } else {
                    574:                        close(state->connection_in);
                    575:                        close(state->connection_out);
                    576:                }
1.14      markus    577:        }
1.201     markus    578:        sshbuf_free(state->input);
                    579:        sshbuf_free(state->output);
                    580:        sshbuf_free(state->outgoing_packet);
                    581:        sshbuf_free(state->incoming_packet);
1.257     markus    582:        for (mode = 0; mode < MODE_MAX; mode++) {
                    583:                kex_free_newkeys(state->newkeys[mode]); /* current keys */
                    584:                state->newkeys[mode] = NULL;
                    585:                ssh_clear_newkeys(ssh, mode);           /* next keys */
                    586:        }
                    587:        /* comression state is in shared mem, so we can only release it once */
                    588:        if (do_close && state->compression_buffer) {
1.201     markus    589:                sshbuf_free(state->compression_buffer);
                    590:                if (state->compression_out_started) {
                    591:                        z_streamp stream = &state->compression_out_stream;
                    592:                        debug("compress outgoing: "
                    593:                            "raw data %llu, compressed %llu, factor %.2f",
                    594:                                (unsigned long long)stream->total_in,
                    595:                                (unsigned long long)stream->total_out,
                    596:                                stream->total_in == 0 ? 0.0 :
                    597:                                (double) stream->total_out / stream->total_in);
                    598:                        if (state->compression_out_failures == 0)
                    599:                                deflateEnd(stream);
                    600:                }
                    601:                if (state->compression_in_started) {
1.260     dtucker   602:                        z_streamp stream = &state->compression_in_stream;
1.201     markus    603:                        debug("compress incoming: "
                    604:                            "raw data %llu, compressed %llu, factor %.2f",
                    605:                            (unsigned long long)stream->total_out,
                    606:                            (unsigned long long)stream->total_in,
                    607:                            stream->total_out == 0 ? 0.0 :
                    608:                            (double) stream->total_in / stream->total_out);
                    609:                        if (state->compression_in_failures == 0)
                    610:                                inflateEnd(stream);
                    611:                }
1.14      markus    612:        }
1.235     djm       613:        cipher_free(state->send_context);
                    614:        cipher_free(state->receive_context);
                    615:        state->send_context = state->receive_context = NULL;
1.257     markus    616:        if (do_close) {
                    617:                free(ssh->remote_ipaddr);
                    618:                ssh->remote_ipaddr = NULL;
                    619:                free(ssh->state);
                    620:                ssh->state = NULL;
                    621:        }
                    622: }
                    623:
                    624: void
                    625: ssh_packet_close(struct ssh *ssh)
                    626: {
                    627:        ssh_packet_close_internal(ssh, 1);
                    628: }
                    629:
                    630: void
                    631: ssh_packet_clear_keys(struct ssh *ssh)
                    632: {
                    633:        ssh_packet_close_internal(ssh, 0);
1.1       deraadt   634: }
                    635:
                    636: /* Sets remote side protocol flags. */
                    637:
1.2       provos    638: void
1.201     markus    639: ssh_packet_set_protocol_flags(struct ssh *ssh, u_int protocol_flags)
1.1       deraadt   640: {
1.201     markus    641:        ssh->state->remote_protocol_flags = protocol_flags;
1.1       deraadt   642: }
                    643:
                    644: /* Returns the remote protocol flags set earlier by the above function. */
                    645:
1.40      markus    646: u_int
1.201     markus    647: ssh_packet_get_protocol_flags(struct ssh *ssh)
1.1       deraadt   648: {
1.201     markus    649:        return ssh->state->remote_protocol_flags;
1.1       deraadt   650: }
                    651:
1.16      markus    652: /*
                    653:  * Starts packet compression from the next packet on in both directions.
                    654:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    655:  */
1.1       deraadt   656:
1.201     markus    657: static int
                    658: ssh_packet_init_compression(struct ssh *ssh)
1.60      markus    659: {
1.201     markus    660:        if (!ssh->state->compression_buffer &&
                    661:           ((ssh->state->compression_buffer = sshbuf_new()) == NULL))
                    662:                return SSH_ERR_ALLOC_FAIL;
                    663:        return 0;
1.60      markus    664: }
                    665:
1.201     markus    666: static int
                    667: start_compression_out(struct ssh *ssh, int level)
1.1       deraadt   668: {
1.201     markus    669:        if (level < 1 || level > 9)
                    670:                return SSH_ERR_INVALID_ARGUMENT;
                    671:        debug("Enabling compression at level %d.", level);
                    672:        if (ssh->state->compression_out_started == 1)
                    673:                deflateEnd(&ssh->state->compression_out_stream);
                    674:        switch (deflateInit(&ssh->state->compression_out_stream, level)) {
                    675:        case Z_OK:
                    676:                ssh->state->compression_out_started = 1;
                    677:                break;
                    678:        case Z_MEM_ERROR:
                    679:                return SSH_ERR_ALLOC_FAIL;
                    680:        default:
                    681:                return SSH_ERR_INTERNAL_ERROR;
                    682:        }
                    683:        return 0;
1.1       deraadt   684: }
                    685:
1.201     markus    686: static int
                    687: start_compression_in(struct ssh *ssh)
                    688: {
                    689:        if (ssh->state->compression_in_started == 1)
                    690:                inflateEnd(&ssh->state->compression_in_stream);
                    691:        switch (inflateInit(&ssh->state->compression_in_stream)) {
                    692:        case Z_OK:
                    693:                ssh->state->compression_in_started = 1;
                    694:                break;
                    695:        case Z_MEM_ERROR:
                    696:                return SSH_ERR_ALLOC_FAIL;
                    697:        default:
                    698:                return SSH_ERR_INTERNAL_ERROR;
                    699:        }
                    700:        return 0;
1.95      markus    701: }
                    702:
1.201     markus    703: /* XXX remove need for separate compression buffer */
                    704: static int
                    705: compress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
1.95      markus    706: {
1.201     markus    707:        u_char buf[4096];
                    708:        int r, status;
                    709:
                    710:        if (ssh->state->compression_out_started != 1)
                    711:                return SSH_ERR_INTERNAL_ERROR;
                    712:
                    713:        /* This case is not handled below. */
                    714:        if (sshbuf_len(in) == 0)
                    715:                return 0;
                    716:
                    717:        /* Input is the contents of the input buffer. */
                    718:        if ((ssh->state->compression_out_stream.next_in =
                    719:            sshbuf_mutable_ptr(in)) == NULL)
                    720:                return SSH_ERR_INTERNAL_ERROR;
                    721:        ssh->state->compression_out_stream.avail_in = sshbuf_len(in);
                    722:
                    723:        /* Loop compressing until deflate() returns with avail_out != 0. */
                    724:        do {
                    725:                /* Set up fixed-size output buffer. */
                    726:                ssh->state->compression_out_stream.next_out = buf;
                    727:                ssh->state->compression_out_stream.avail_out = sizeof(buf);
                    728:
                    729:                /* Compress as much data into the buffer as possible. */
                    730:                status = deflate(&ssh->state->compression_out_stream,
                    731:                    Z_PARTIAL_FLUSH);
                    732:                switch (status) {
                    733:                case Z_MEM_ERROR:
                    734:                        return SSH_ERR_ALLOC_FAIL;
                    735:                case Z_OK:
                    736:                        /* Append compressed data to output_buffer. */
                    737:                        if ((r = sshbuf_put(out, buf, sizeof(buf) -
                    738:                            ssh->state->compression_out_stream.avail_out)) != 0)
                    739:                                return r;
                    740:                        break;
                    741:                case Z_STREAM_ERROR:
                    742:                default:
                    743:                        ssh->state->compression_out_failures++;
                    744:                        return SSH_ERR_INVALID_FORMAT;
                    745:                }
                    746:        } while (ssh->state->compression_out_stream.avail_out == 0);
                    747:        return 0;
1.1       deraadt   748: }
                    749:
1.201     markus    750: static int
                    751: uncompress_buffer(struct ssh *ssh, struct sshbuf *in, struct sshbuf *out)
1.1       deraadt   752: {
1.201     markus    753:        u_char buf[4096];
                    754:        int r, status;
1.1       deraadt   755:
1.201     markus    756:        if (ssh->state->compression_in_started != 1)
                    757:                return SSH_ERR_INTERNAL_ERROR;
1.25      markus    758:
1.201     markus    759:        if ((ssh->state->compression_in_stream.next_in =
                    760:            sshbuf_mutable_ptr(in)) == NULL)
                    761:                return SSH_ERR_INTERNAL_ERROR;
                    762:        ssh->state->compression_in_stream.avail_in = sshbuf_len(in);
1.97      deraadt   763:
1.201     markus    764:        for (;;) {
                    765:                /* Set up fixed-size output buffer. */
                    766:                ssh->state->compression_in_stream.next_out = buf;
                    767:                ssh->state->compression_in_stream.avail_out = sizeof(buf);
                    768:
                    769:                status = inflate(&ssh->state->compression_in_stream,
                    770:                    Z_PARTIAL_FLUSH);
                    771:                switch (status) {
                    772:                case Z_OK:
                    773:                        if ((r = sshbuf_put(out, buf, sizeof(buf) -
                    774:                            ssh->state->compression_in_stream.avail_out)) != 0)
                    775:                                return r;
                    776:                        break;
                    777:                case Z_BUF_ERROR:
                    778:                        /*
                    779:                         * Comments in zlib.h say that we should keep calling
                    780:                         * inflate() until we get an error.  This appears to
                    781:                         * be the error that we get.
                    782:                         */
                    783:                        return 0;
                    784:                case Z_DATA_ERROR:
                    785:                        return SSH_ERR_INVALID_FORMAT;
                    786:                case Z_MEM_ERROR:
                    787:                        return SSH_ERR_ALLOC_FAIL;
                    788:                case Z_STREAM_ERROR:
                    789:                default:
                    790:                        ssh->state->compression_in_failures++;
                    791:                        return SSH_ERR_INTERNAL_ERROR;
                    792:                }
                    793:        }
                    794:        /* NOTREACHED */
1.170     djm       795: }
                    796:
1.257     markus    797: void
                    798: ssh_clear_newkeys(struct ssh *ssh, int mode)
                    799: {
1.259     djm       800:        if (ssh->kex && ssh->kex->newkeys[mode]) {
1.257     markus    801:                kex_free_newkeys(ssh->kex->newkeys[mode]);
                    802:                ssh->kex->newkeys[mode] = NULL;
                    803:        }
                    804: }
                    805:
1.201     markus    806: int
                    807: ssh_set_newkeys(struct ssh *ssh, int mode)
1.57      markus    808: {
1.201     markus    809:        struct session_state *state = ssh->state;
                    810:        struct sshenc *enc;
                    811:        struct sshmac *mac;
                    812:        struct sshcomp *comp;
1.235     djm       813:        struct sshcipher_ctx **ccp;
1.236     markus    814:        struct packet_state *ps;
1.105     markus    815:        u_int64_t *max_blocks;
1.259     djm       816:        const char *wmsg;
1.197     djm       817:        int r, crypt_type;
1.57      markus    818:
1.100     markus    819:        debug2("set_newkeys: mode %d", mode);
1.57      markus    820:
1.88      markus    821:        if (mode == MODE_OUT) {
1.235     djm       822:                ccp = &state->send_context;
1.115     avsm      823:                crypt_type = CIPHER_ENCRYPT;
1.236     markus    824:                ps = &state->p_send;
1.201     markus    825:                max_blocks = &state->max_blocks_out;
1.88      markus    826:        } else {
1.235     djm       827:                ccp = &state->receive_context;
1.115     avsm      828:                crypt_type = CIPHER_DECRYPT;
1.236     markus    829:                ps = &state->p_read;
1.201     markus    830:                max_blocks = &state->max_blocks_in;
1.88      markus    831:        }
1.201     markus    832:        if (state->newkeys[mode] != NULL) {
1.257     markus    833:                debug("set_newkeys: rekeying, input %llu bytes %llu blocks, "
                    834:                   "output %llu bytes %llu blocks",
                    835:                   (unsigned long long)state->p_read.bytes,
                    836:                   (unsigned long long)state->p_read.blocks,
                    837:                   (unsigned long long)state->p_send.bytes,
                    838:                   (unsigned long long)state->p_send.blocks);
1.235     djm       839:                cipher_free(*ccp);
                    840:                *ccp = NULL;
1.257     markus    841:                kex_free_newkeys(state->newkeys[mode]);
                    842:                state->newkeys[mode] = NULL;
1.57      markus    843:        }
1.236     markus    844:        /* note that both bytes and the seqnr are not reset */
                    845:        ps->packets = ps->blocks = 0;
1.201     markus    846:        /* move newkeys from kex to state */
                    847:        if ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)
                    848:                return SSH_ERR_INTERNAL_ERROR;
                    849:        ssh->kex->newkeys[mode] = NULL;
                    850:        enc  = &state->newkeys[mode]->enc;
                    851:        mac  = &state->newkeys[mode]->mac;
                    852:        comp = &state->newkeys[mode]->comp;
                    853:        if (cipher_authlen(enc->cipher) == 0) {
                    854:                if ((r = mac_init(mac)) != 0)
                    855:                        return r;
                    856:        }
                    857:        mac->enabled = 1;
1.57      markus    858:        DBG(debug("cipher_init_context: %d", mode));
1.235     djm       859:        if ((r = cipher_init(ccp, enc->cipher, enc->key, enc->key_len,
1.197     djm       860:            enc->iv, enc->iv_len, crypt_type)) != 0)
1.201     markus    861:                return r;
                    862:        if (!state->cipher_warning_done &&
1.235     djm       863:            (wmsg = cipher_warning_message(*ccp)) != NULL) {
1.201     markus    864:                error("Warning: %s", wmsg);
                    865:                state->cipher_warning_done = 1;
                    866:        }
1.91      markus    867:        /* Deleting the keys does not gain extra security */
1.192     djm       868:        /* explicit_bzero(enc->iv,  enc->block_size);
                    869:           explicit_bzero(enc->key, enc->key_len);
                    870:           explicit_bzero(mac->key, mac->key_len); */
1.275   ! sf        871:        if ((comp->type == COMP_ZLIB ||
        !           872:            (comp->type == COMP_DELAYED &&
        !           873:             state->after_authentication)) && comp->enabled == 0) {
1.201     markus    874:                if ((r = ssh_packet_init_compression(ssh)) < 0)
                    875:                        return r;
                    876:                if (mode == MODE_OUT) {
                    877:                        if ((r = start_compression_out(ssh, 6)) != 0)
                    878:                                return r;
                    879:                } else {
                    880:                        if ((r = start_compression_in(ssh)) != 0)
                    881:                                return r;
                    882:                }
1.57      markus    883:                comp->enabled = 1;
                    884:        }
1.109     markus    885:        /*
                    886:         * The 2^(blocksize*2) limit is too expensive for 3DES,
1.254     djm       887:         * so enforce a 1GB limit for small blocksizes.
1.261     dtucker   888:         * See RFC4344 section 3.2.
1.109     markus    889:         */
                    890:        if (enc->block_size >= 16)
                    891:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    892:        else
                    893:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.201     markus    894:        if (state->rekey_limit)
1.237     deraadt   895:                *max_blocks = MINIMUM(*max_blocks,
1.201     markus    896:                    state->rekey_limit / enc->block_size);
1.227     djm       897:        debug("rekey after %llu blocks", (unsigned long long)*max_blocks);
1.201     markus    898:        return 0;
1.57      markus    899: }
                    900:
1.228     djm       901: #define MAX_PACKETS    (1U<<31)
                    902: static int
                    903: ssh_packet_need_rekeying(struct ssh *ssh, u_int outbound_packet_len)
                    904: {
                    905:        struct session_state *state = ssh->state;
                    906:        u_int32_t out_blocks;
                    907:
                    908:        /* XXX client can't cope with rekeying pre-auth */
                    909:        if (!state->after_authentication)
                    910:                return 0;
                    911:
                    912:        /* Haven't keyed yet or KEX in progress. */
                    913:        if (ssh->kex == NULL || ssh_packet_is_rekeying(ssh))
                    914:                return 0;
                    915:
                    916:        /* Peer can't rekey */
                    917:        if (ssh->compat & SSH_BUG_NOREKEY)
                    918:                return 0;
                    919:
                    920:        /*
                    921:         * Permit one packet in or out per rekey - this allows us to
                    922:         * make progress when rekey limits are very small.
                    923:         */
                    924:        if (state->p_send.packets == 0 && state->p_read.packets == 0)
                    925:                return 0;
                    926:
                    927:        /* Time-based rekeying */
                    928:        if (state->rekey_interval != 0 &&
1.244     dtucker   929:            (int64_t)state->rekey_time + state->rekey_interval <= monotime())
1.228     djm       930:                return 1;
                    931:
1.261     dtucker   932:        /*
                    933:         * Always rekey when MAX_PACKETS sent in either direction
                    934:         * As per RFC4344 section 3.1 we do this after 2^31 packets.
                    935:         */
1.228     djm       936:        if (state->p_send.packets > MAX_PACKETS ||
                    937:            state->p_read.packets > MAX_PACKETS)
                    938:                return 1;
                    939:
                    940:        /* Rekey after (cipher-specific) maxiumum blocks */
1.237     deraadt   941:        out_blocks = ROUNDUP(outbound_packet_len,
1.228     djm       942:            state->newkeys[MODE_OUT]->enc.block_size);
                    943:        return (state->max_blocks_out &&
                    944:            (state->p_send.blocks + out_blocks > state->max_blocks_out)) ||
                    945:            (state->max_blocks_in &&
                    946:            (state->p_read.blocks > state->max_blocks_in));
                    947: }
                    948:
1.16      markus    949: /*
1.118     markus    950:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker   951:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus    952:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                    953:  */
1.201     markus    954: static int
                    955: ssh_packet_enable_delayed_compress(struct ssh *ssh)
1.118     markus    956: {
1.201     markus    957:        struct session_state *state = ssh->state;
                    958:        struct sshcomp *comp = NULL;
                    959:        int r, mode;
1.118     markus    960:
                    961:        /*
                    962:         * Remember that we are past the authentication step, so rekeying
1.275   ! sf        963:         * with COMP_DELAYED will turn on compression immediately.
1.118     markus    964:         */
1.201     markus    965:        state->after_authentication = 1;
1.118     markus    966:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus    967:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
1.201     markus    968:                if (state->newkeys[mode] == NULL)
1.145     markus    969:                        continue;
1.201     markus    970:                comp = &state->newkeys[mode]->comp;
1.275   ! sf        971:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.201     markus    972:                        if ((r = ssh_packet_init_compression(ssh)) != 0)
                    973:                                return r;
                    974:                        if (mode == MODE_OUT) {
                    975:                                if ((r = start_compression_out(ssh, 6)) != 0)
                    976:                                        return r;
                    977:                        } else {
                    978:                                if ((r = start_compression_in(ssh)) != 0)
                    979:                                        return r;
                    980:                        }
1.118     markus    981:                        comp->enabled = 1;
                    982:                }
                    983:        }
1.201     markus    984:        return 0;
1.118     markus    985: }
                    986:
1.226     djm       987: /* Used to mute debug logging for noisy packet types */
1.242     markus    988: int
1.226     djm       989: ssh_packet_log_type(u_char type)
                    990: {
                    991:        switch (type) {
                    992:        case SSH2_MSG_CHANNEL_DATA:
                    993:        case SSH2_MSG_CHANNEL_EXTENDED_DATA:
                    994:        case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
                    995:                return 0;
                    996:        default:
                    997:                return 1;
                    998:        }
                    999: }
                   1000:
1.118     markus   1001: /*
1.25      markus   1002:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                   1003:  */
1.201     markus   1004: int
                   1005: ssh_packet_send2_wrapped(struct ssh *ssh)
1.25      markus   1006: {
1.201     markus   1007:        struct session_state *state = ssh->state;
1.200     markus   1008:        u_char type, *cp, macbuf[SSH_DIGEST_MAX_LENGTH];
1.233     djm      1009:        u_char tmp, padlen, pad = 0;
1.201     markus   1010:        u_int authlen = 0, aadlen = 0;
                   1011:        u_int len;
                   1012:        struct sshenc *enc   = NULL;
                   1013:        struct sshmac *mac   = NULL;
                   1014:        struct sshcomp *comp = NULL;
                   1015:        int r, block_size;
                   1016:
                   1017:        if (state->newkeys[MODE_OUT] != NULL) {
                   1018:                enc  = &state->newkeys[MODE_OUT]->enc;
                   1019:                mac  = &state->newkeys[MODE_OUT]->mac;
                   1020:                comp = &state->newkeys[MODE_OUT]->comp;
1.180     markus   1021:                /* disable mac for authenticated encryption */
                   1022:                if ((authlen = cipher_authlen(enc->cipher)) != 0)
                   1023:                        mac = NULL;
1.25      markus   1024:        }
1.88      markus   1025:        block_size = enc ? enc->block_size : 8;
1.180     markus   1026:        aadlen = (mac && mac->enabled && mac->etm) || authlen ? 4 : 0;
1.25      markus   1027:
1.201     markus   1028:        type = (sshbuf_ptr(state->outgoing_packet))[5];
1.226     djm      1029:        if (ssh_packet_log_type(type))
                   1030:                debug3("send packet: type %u", type);
1.25      markus   1031: #ifdef PACKET_DEBUG
                   1032:        fprintf(stderr, "plain:     ");
1.201     markus   1033:        sshbuf_dump(state->outgoing_packet, stderr);
1.25      markus   1034: #endif
                   1035:
                   1036:        if (comp && comp->enabled) {
1.201     markus   1037:                len = sshbuf_len(state->outgoing_packet);
1.25      markus   1038:                /* skip header, compress only payload */
1.201     markus   1039:                if ((r = sshbuf_consume(state->outgoing_packet, 5)) != 0)
                   1040:                        goto out;
                   1041:                sshbuf_reset(state->compression_buffer);
                   1042:                if ((r = compress_buffer(ssh, state->outgoing_packet,
                   1043:                    state->compression_buffer)) != 0)
                   1044:                        goto out;
                   1045:                sshbuf_reset(state->outgoing_packet);
                   1046:                if ((r = sshbuf_put(state->outgoing_packet,
                   1047:                    "\0\0\0\0\0", 5)) != 0 ||
                   1048:                    (r = sshbuf_putb(state->outgoing_packet,
                   1049:                    state->compression_buffer)) != 0)
                   1050:                        goto out;
                   1051:                DBG(debug("compression: raw %d compressed %zd", len,
                   1052:                    sshbuf_len(state->outgoing_packet)));
1.25      markus   1053:        }
                   1054:
                   1055:        /* sizeof (packet_len + pad_len + payload) */
1.201     markus   1056:        len = sshbuf_len(state->outgoing_packet);
1.25      markus   1057:
                   1058:        /*
                   1059:         * calc size of padding, alloc space, get random data,
                   1060:         * minimum padding is 4 bytes
                   1061:         */
1.178     markus   1062:        len -= aadlen; /* packet length is not encrypted for EtM modes */
1.25      markus   1063:        padlen = block_size - (len % block_size);
                   1064:        if (padlen < 4)
                   1065:                padlen += block_size;
1.201     markus   1066:        if (state->extra_pad) {
1.233     djm      1067:                tmp = state->extra_pad;
1.201     markus   1068:                state->extra_pad =
1.237     deraadt  1069:                    ROUNDUP(state->extra_pad, block_size);
1.233     djm      1070:                /* check if roundup overflowed */
                   1071:                if (state->extra_pad < tmp)
                   1072:                        return SSH_ERR_INVALID_ARGUMENT;
                   1073:                tmp = (len + padlen) % state->extra_pad;
                   1074:                /* Check whether pad calculation below will underflow */
                   1075:                if (tmp > state->extra_pad)
                   1076:                        return SSH_ERR_INVALID_ARGUMENT;
                   1077:                pad = state->extra_pad - tmp;
1.193     djm      1078:                DBG(debug3("%s: adding %d (len %d padlen %d extra_pad %d)",
1.201     markus   1079:                    __func__, pad, len, padlen, state->extra_pad));
1.233     djm      1080:                tmp = padlen;
1.71      markus   1081:                padlen += pad;
1.233     djm      1082:                /* Check whether padlen calculation overflowed */
                   1083:                if (padlen < tmp)
                   1084:                        return SSH_ERR_INVALID_ARGUMENT; /* overflow */
1.201     markus   1085:                state->extra_pad = 0;
1.71      markus   1086:        }
1.201     markus   1087:        if ((r = sshbuf_reserve(state->outgoing_packet, padlen, &cp)) != 0)
                   1088:                goto out;
1.235     djm      1089:        if (enc && !cipher_ctx_is_plaintext(state->send_context)) {
1.32      markus   1090:                /* random padding */
1.201     markus   1091:                arc4random_buf(cp, padlen);
1.32      markus   1092:        } else {
                   1093:                /* clear padding */
1.192     djm      1094:                explicit_bzero(cp, padlen);
1.25      markus   1095:        }
1.178     markus   1096:        /* sizeof (packet_len + pad_len + payload + padding) */
1.201     markus   1097:        len = sshbuf_len(state->outgoing_packet);
                   1098:        cp = sshbuf_mutable_ptr(state->outgoing_packet);
                   1099:        if (cp == NULL) {
                   1100:                r = SSH_ERR_INTERNAL_ERROR;
                   1101:                goto out;
                   1102:        }
1.25      markus   1103:        /* packet_length includes payload, padding and padding length field */
1.201     markus   1104:        POKE_U32(cp, len - 4);
1.89      markus   1105:        cp[4] = padlen;
1.178     markus   1106:        DBG(debug("send: len %d (includes padlen %d, aadlen %d)",
                   1107:            len, padlen, aadlen));
1.25      markus   1108:
                   1109:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
1.178     markus   1110:        if (mac && mac->enabled && !mac->etm) {
1.201     markus   1111:                if ((r = mac_compute(mac, state->p_send.seqnr,
                   1112:                    sshbuf_ptr(state->outgoing_packet), len,
1.200     markus   1113:                    macbuf, sizeof(macbuf))) != 0)
1.201     markus   1114:                        goto out;
                   1115:                DBG(debug("done calc MAC out #%d", state->p_send.seqnr));
1.25      markus   1116:        }
                   1117:        /* encrypt packet and append to output buffer. */
1.201     markus   1118:        if ((r = sshbuf_reserve(state->output,
                   1119:            sshbuf_len(state->outgoing_packet) + authlen, &cp)) != 0)
                   1120:                goto out;
1.235     djm      1121:        if ((r = cipher_crypt(state->send_context, state->p_send.seqnr, cp,
1.201     markus   1122:            sshbuf_ptr(state->outgoing_packet),
                   1123:            len - aadlen, aadlen, authlen)) != 0)
                   1124:                goto out;
1.25      markus   1125:        /* append unencrypted MAC */
1.178     markus   1126:        if (mac && mac->enabled) {
                   1127:                if (mac->etm) {
                   1128:                        /* EtM: compute mac over aadlen + cipher text */
1.201     markus   1129:                        if ((r = mac_compute(mac, state->p_send.seqnr,
                   1130:                            cp, len, macbuf, sizeof(macbuf))) != 0)
                   1131:                                goto out;
1.178     markus   1132:                        DBG(debug("done calc MAC(EtM) out #%d",
1.201     markus   1133:                            state->p_send.seqnr));
1.178     markus   1134:                }
1.201     markus   1135:                if ((r = sshbuf_put(state->output, macbuf, mac->mac_len)) != 0)
                   1136:                        goto out;
1.178     markus   1137:        }
1.25      markus   1138: #ifdef PACKET_DEBUG
                   1139:        fprintf(stderr, "encrypted: ");
1.201     markus   1140:        sshbuf_dump(state->output, stderr);
1.25      markus   1141: #endif
1.29      markus   1142:        /* increment sequence number for outgoing packets */
1.201     markus   1143:        if (++state->p_send.seqnr == 0)
1.106     itojun   1144:                logit("outgoing seqnr wraps around");
1.201     markus   1145:        if (++state->p_send.packets == 0)
                   1146:                if (!(ssh->compat & SSH_BUG_NOREKEY))
                   1147:                        return SSH_ERR_NEED_REKEY;
                   1148:        state->p_send.blocks += len / block_size;
                   1149:        state->p_send.bytes += len;
                   1150:        sshbuf_reset(state->outgoing_packet);
1.25      markus   1151:
1.57      markus   1152:        if (type == SSH2_MSG_NEWKEYS)
1.201     markus   1153:                r = ssh_set_newkeys(ssh, MODE_OUT);
                   1154:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && state->server_side)
                   1155:                r = ssh_packet_enable_delayed_compress(ssh);
                   1156:        else
                   1157:                r = 0;
                   1158:  out:
                   1159:        return r;
1.25      markus   1160: }
                   1161:
1.228     djm      1162: /* returns non-zero if the specified packet type is usec by KEX */
                   1163: static int
                   1164: ssh_packet_type_is_kex(u_char type)
                   1165: {
                   1166:        return
                   1167:            type >= SSH2_MSG_TRANSPORT_MIN &&
                   1168:            type <= SSH2_MSG_TRANSPORT_MAX &&
                   1169:            type != SSH2_MSG_SERVICE_REQUEST &&
                   1170:            type != SSH2_MSG_SERVICE_ACCEPT &&
                   1171:            type != SSH2_MSG_EXT_INFO;
                   1172: }
                   1173:
1.201     markus   1174: int
                   1175: ssh_packet_send2(struct ssh *ssh)
1.105     markus   1176: {
1.201     markus   1177:        struct session_state *state = ssh->state;
1.105     markus   1178:        struct packet *p;
1.201     markus   1179:        u_char type;
1.228     djm      1180:        int r, need_rekey;
1.105     markus   1181:
1.228     djm      1182:        if (sshbuf_len(state->outgoing_packet) < 6)
                   1183:                return SSH_ERR_INTERNAL_ERROR;
1.201     markus   1184:        type = sshbuf_ptr(state->outgoing_packet)[5];
1.228     djm      1185:        need_rekey = !ssh_packet_type_is_kex(type) &&
                   1186:            ssh_packet_need_rekeying(ssh, sshbuf_len(state->outgoing_packet));
1.105     markus   1187:
1.228     djm      1188:        /*
                   1189:         * During rekeying we can only send key exchange messages.
                   1190:         * Queue everything else.
                   1191:         */
                   1192:        if ((need_rekey || state->rekeying) && !ssh_packet_type_is_kex(type)) {
                   1193:                if (need_rekey)
                   1194:                        debug3("%s: rekex triggered", __func__);
                   1195:                debug("enqueue packet: %u", type);
                   1196:                p = calloc(1, sizeof(*p));
                   1197:                if (p == NULL)
                   1198:                        return SSH_ERR_ALLOC_FAIL;
                   1199:                p->type = type;
                   1200:                p->payload = state->outgoing_packet;
                   1201:                TAILQ_INSERT_TAIL(&state->outgoing, p, next);
                   1202:                state->outgoing_packet = sshbuf_new();
                   1203:                if (state->outgoing_packet == NULL)
                   1204:                        return SSH_ERR_ALLOC_FAIL;
                   1205:                if (need_rekey) {
                   1206:                        /*
                   1207:                         * This packet triggered a rekey, so send the
                   1208:                         * KEXINIT now.
                   1209:                         * NB. reenters this function via kex_start_rekex().
                   1210:                         */
                   1211:                        return kex_start_rekex(ssh);
1.105     markus   1212:                }
1.228     djm      1213:                return 0;
1.105     markus   1214:        }
                   1215:
                   1216:        /* rekeying starts with sending KEXINIT */
                   1217:        if (type == SSH2_MSG_KEXINIT)
1.201     markus   1218:                state->rekeying = 1;
1.105     markus   1219:
1.201     markus   1220:        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1221:                return r;
1.105     markus   1222:
                   1223:        /* after a NEWKEYS message we can send the complete queue */
                   1224:        if (type == SSH2_MSG_NEWKEYS) {
1.201     markus   1225:                state->rekeying = 0;
                   1226:                state->rekey_time = monotime();
                   1227:                while ((p = TAILQ_FIRST(&state->outgoing))) {
1.105     markus   1228:                        type = p->type;
1.228     djm      1229:                        /*
                   1230:                         * If this packet triggers a rekex, then skip the
                   1231:                         * remaining packets in the queue for now.
                   1232:                         * NB. re-enters this function via kex_start_rekex.
                   1233:                         */
                   1234:                        if (ssh_packet_need_rekeying(ssh,
                   1235:                            sshbuf_len(p->payload))) {
                   1236:                                debug3("%s: queued packet triggered rekex",
                   1237:                                    __func__);
                   1238:                                return kex_start_rekex(ssh);
                   1239:                        }
1.105     markus   1240:                        debug("dequeue packet: %u", type);
1.201     markus   1241:                        sshbuf_free(state->outgoing_packet);
                   1242:                        state->outgoing_packet = p->payload;
                   1243:                        TAILQ_REMOVE(&state->outgoing, p, next);
1.228     djm      1244:                        memset(p, 0, sizeof(*p));
1.186     djm      1245:                        free(p);
1.201     markus   1246:                        if ((r = ssh_packet_send2_wrapped(ssh)) != 0)
                   1247:                                return r;
1.105     markus   1248:                }
                   1249:        }
1.201     markus   1250:        return 0;
1.25      markus   1251: }
                   1252:
                   1253: /*
1.16      markus   1254:  * Waits until a packet has been received, and returns its type.  Note that
                   1255:  * no other data is processed until this returns, so this function should not
                   1256:  * be used during the interactive session.
                   1257:  */
1.1       deraadt  1258:
1.2       provos   1259: int
1.201     markus   1260: ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p)
1.1       deraadt  1261: {
1.201     markus   1262:        struct session_state *state = ssh->state;
1.222     markus   1263:        int len, r, ms_remain;
1.56      millert  1264:        fd_set *setp;
1.14      markus   1265:        char buf[8192];
1.155     deraadt  1266:        struct timeval timeout, start, *timeoutp = NULL;
                   1267:
1.25      markus   1268:        DBG(debug("packet_read()"));
1.14      markus   1269:
1.214     deraadt  1270:        setp = calloc(howmany(state->connection_in + 1,
1.161     andreas  1271:            NFDBITS), sizeof(fd_mask));
1.201     markus   1272:        if (setp == NULL)
                   1273:                return SSH_ERR_ALLOC_FAIL;
1.56      millert  1274:
1.205     djm      1275:        /*
                   1276:         * Since we are blocking, ensure that all written packets have
                   1277:         * been sent.
                   1278:         */
1.210     markus   1279:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   1280:                goto out;
1.14      markus   1281:
                   1282:        /* Stay in the loop until we have received a complete packet. */
                   1283:        for (;;) {
                   1284:                /* Try to read a packet from the buffer. */
1.201     markus   1285:                r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p);
                   1286:                if (r != 0)
                   1287:                        break;
1.14      markus   1288:                /* If we got a packet, return it. */
1.201     markus   1289:                if (*typep != SSH_MSG_NONE)
                   1290:                        break;
1.16      markus   1291:                /*
                   1292:                 * Otherwise, wait for some data to arrive, add it to the
                   1293:                 * buffer, and try again.
                   1294:                 */
1.201     markus   1295:                memset(setp, 0, howmany(state->connection_in + 1,
1.161     andreas  1296:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   1297:                FD_SET(state->connection_in, setp);
1.16      markus   1298:
1.201     markus   1299:                if (state->packet_timeout_ms > 0) {
                   1300:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  1301:                        timeoutp = &timeout;
                   1302:                }
1.14      markus   1303:                /* Wait for some data to arrive. */
1.154     dtucker  1304:                for (;;) {
1.201     markus   1305:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  1306:                                ms_to_timeval(&timeout, ms_remain);
1.267     dtucker  1307:                                monotime_tv(&start);
1.154     dtucker  1308:                        }
1.201     markus   1309:                        if ((r = select(state->connection_in + 1, setp,
1.161     andreas  1310:                            NULL, NULL, timeoutp)) >= 0)
1.154     dtucker  1311:                                break;
1.270     dtucker  1312:                        if (errno != EAGAIN && errno != EINTR) {
                   1313:                                r = SSH_ERR_SYSTEM_ERROR;
                   1314:                                goto out;
                   1315:                        }
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);
1.265     djm      1761:
                   1762:        debug3("sending debug message: %s", buf);
1.14      markus   1763:
1.249     djm      1764:        if ((r = sshpkt_start(ssh, SSH2_MSG_DEBUG)) != 0 ||
                   1765:            (r = sshpkt_put_u8(ssh, 0)) != 0 || /* always display */
                   1766:            (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   1767:            (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   1768:            (r = sshpkt_send(ssh)) != 0 ||
                   1769:            (r = ssh_packet_write_wait(ssh)) != 0)
1.205     djm      1770:                fatal("%s: %s", __func__, ssh_err(r));
                   1771: }
                   1772:
1.268     dtucker  1773: void
                   1774: sshpkt_fmt_connection_id(struct ssh *ssh, char *s, size_t l)
1.245     djm      1775: {
                   1776:        snprintf(s, l, "%.200s%s%s port %d",
                   1777:            ssh->log_preamble ? ssh->log_preamble : "",
                   1778:            ssh->log_preamble ? " " : "",
                   1779:            ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
                   1780: }
                   1781:
1.205     djm      1782: /*
                   1783:  * Pretty-print connection-terminating errors and exit.
                   1784:  */
                   1785: void
                   1786: sshpkt_fatal(struct ssh *ssh, const char *tag, int r)
                   1787: {
1.245     djm      1788:        char remote_id[512];
                   1789:
1.268     dtucker  1790:        sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1.245     djm      1791:
1.205     djm      1792:        switch (r) {
                   1793:        case SSH_ERR_CONN_CLOSED:
1.257     markus   1794:                ssh_packet_clear_keys(ssh);
1.245     djm      1795:                logdie("Connection closed by %s", remote_id);
1.205     djm      1796:        case SSH_ERR_CONN_TIMEOUT:
1.257     markus   1797:                ssh_packet_clear_keys(ssh);
1.245     djm      1798:                logdie("Connection %s %s timed out",
                   1799:                    ssh->state->server_side ? "from" : "to", remote_id);
1.212     djm      1800:        case SSH_ERR_DISCONNECTED:
1.257     markus   1801:                ssh_packet_clear_keys(ssh);
1.245     djm      1802:                logdie("Disconnected from %s", remote_id);
1.212     djm      1803:        case SSH_ERR_SYSTEM_ERROR:
1.257     markus   1804:                if (errno == ECONNRESET) {
                   1805:                        ssh_packet_clear_keys(ssh);
1.245     djm      1806:                        logdie("Connection reset by %s", remote_id);
1.257     markus   1807:                }
1.213     djm      1808:                /* FALLTHROUGH */
                   1809:        case SSH_ERR_NO_CIPHER_ALG_MATCH:
                   1810:        case SSH_ERR_NO_MAC_ALG_MATCH:
                   1811:        case SSH_ERR_NO_COMPRESS_ALG_MATCH:
                   1812:        case SSH_ERR_NO_KEX_ALG_MATCH:
                   1813:        case SSH_ERR_NO_HOSTKEY_ALG_MATCH:
                   1814:                if (ssh && ssh->kex && ssh->kex->failed_choice) {
1.257     markus   1815:                        ssh_packet_clear_keys(ssh);
1.245     djm      1816:                        logdie("Unable to negotiate with %s: %s. "
                   1817:                            "Their offer: %s", remote_id, ssh_err(r),
1.220     djm      1818:                            ssh->kex->failed_choice);
1.212     djm      1819:                }
                   1820:                /* FALLTHROUGH */
1.205     djm      1821:        default:
1.257     markus   1822:                ssh_packet_clear_keys(ssh);
1.245     djm      1823:                logdie("%s%sConnection %s %s: %s",
1.205     djm      1824:                    tag != NULL ? tag : "", tag != NULL ? ": " : "",
1.220     djm      1825:                    ssh->state->server_side ? "from" : "to",
1.245     djm      1826:                    remote_id, ssh_err(r));
1.205     djm      1827:        }
1.1       deraadt  1828: }
                   1829:
1.16      markus   1830: /*
                   1831:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1832:  * connection, and exits.  This function never returns. The error message
                   1833:  * should not contain a newline.  The length of the formatted message must
                   1834:  * not exceed 1024 bytes.
                   1835:  */
1.2       provos   1836: void
1.201     markus   1837: ssh_packet_disconnect(struct ssh *ssh, const char *fmt,...)
1.1       deraadt  1838: {
1.245     djm      1839:        char buf[1024], remote_id[512];
1.14      markus   1840:        va_list args;
                   1841:        static int disconnecting = 0;
1.201     markus   1842:        int r;
1.97      deraadt  1843:
1.14      markus   1844:        if (disconnecting)      /* Guard against recursive invocations. */
                   1845:                fatal("packet_disconnect called recursively.");
                   1846:        disconnecting = 1;
                   1847:
1.16      markus   1848:        /*
                   1849:         * Format the message.  Note that the caller must make sure the
                   1850:         * message is of limited size.
                   1851:         */
1.268     dtucker  1852:        sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1.14      markus   1853:        va_start(args, fmt);
                   1854:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1855:        va_end(args);
                   1856:
1.99      markus   1857:        /* Display the error locally */
1.245     djm      1858:        logit("Disconnecting %s: %.100s", remote_id, buf);
1.99      markus   1859:
1.205     djm      1860:        /*
                   1861:         * Send the disconnect message to the other side, and wait
                   1862:         * for it to get sent.
                   1863:         */
                   1864:        if ((r = sshpkt_disconnect(ssh, "%s", buf)) != 0)
                   1865:                sshpkt_fatal(ssh, __func__, r);
                   1866:
                   1867:        if ((r = ssh_packet_write_wait(ssh)) != 0)
                   1868:                sshpkt_fatal(ssh, __func__, r);
1.14      markus   1869:
                   1870:        /* Close the connection. */
1.201     markus   1871:        ssh_packet_close(ssh);
1.112     markus   1872:        cleanup_exit(255);
1.1       deraadt  1873: }
                   1874:
1.205     djm      1875: /*
                   1876:  * Checks if there is any buffered output, and tries to write some of
                   1877:  * the output.
                   1878:  */
                   1879: int
1.201     markus   1880: ssh_packet_write_poll(struct ssh *ssh)
1.1       deraadt  1881: {
1.201     markus   1882:        struct session_state *state = ssh->state;
                   1883:        int len = sshbuf_len(state->output);
1.222     markus   1884:        int r;
1.97      deraadt  1885:
1.14      markus   1886:        if (len > 0) {
1.222     markus   1887:                len = write(state->connection_out,
                   1888:                    sshbuf_ptr(state->output), len);
1.156     djm      1889:                if (len == -1) {
                   1890:                        if (errno == EINTR || errno == EAGAIN)
1.205     djm      1891:                                return 0;
                   1892:                        return SSH_ERR_SYSTEM_ERROR;
1.14      markus   1893:                }
1.222     markus   1894:                if (len == 0)
1.205     djm      1895:                        return SSH_ERR_CONN_CLOSED;
1.201     markus   1896:                if ((r = sshbuf_consume(state->output, len)) != 0)
1.205     djm      1897:                        return r;
1.14      markus   1898:        }
1.205     djm      1899:        return 0;
1.1       deraadt  1900: }
                   1901:
1.16      markus   1902: /*
                   1903:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1904:  * written.
                   1905:  */
1.205     djm      1906: int
1.201     markus   1907: ssh_packet_write_wait(struct ssh *ssh)
1.1       deraadt  1908: {
1.56      millert  1909:        fd_set *setp;
1.205     djm      1910:        int ret, r, ms_remain = 0;
1.154     dtucker  1911:        struct timeval start, timeout, *timeoutp = NULL;
1.201     markus   1912:        struct session_state *state = ssh->state;
1.56      millert  1913:
1.214     deraadt  1914:        setp = calloc(howmany(state->connection_out + 1,
1.161     andreas  1915:            NFDBITS), sizeof(fd_mask));
1.201     markus   1916:        if (setp == NULL)
1.205     djm      1917:                return SSH_ERR_ALLOC_FAIL;
1.216     gsoares  1918:        if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   1919:                free(setp);
1.215     djm      1920:                return r;
1.216     gsoares  1921:        }
1.201     markus   1922:        while (ssh_packet_have_data_to_write(ssh)) {
                   1923:                memset(setp, 0, howmany(state->connection_out + 1,
1.161     andreas  1924:                    NFDBITS) * sizeof(fd_mask));
1.201     markus   1925:                FD_SET(state->connection_out, setp);
1.154     dtucker  1926:
1.201     markus   1927:                if (state->packet_timeout_ms > 0) {
                   1928:                        ms_remain = state->packet_timeout_ms;
1.154     dtucker  1929:                        timeoutp = &timeout;
                   1930:                }
                   1931:                for (;;) {
1.201     markus   1932:                        if (state->packet_timeout_ms != -1) {
1.154     dtucker  1933:                                ms_to_timeval(&timeout, ms_remain);
1.267     dtucker  1934:                                monotime_tv(&start);
1.154     dtucker  1935:                        }
1.201     markus   1936:                        if ((ret = select(state->connection_out + 1,
1.161     andreas  1937:                            NULL, setp, NULL, timeoutp)) >= 0)
1.154     dtucker  1938:                                break;
1.161     andreas  1939:                        if (errno != EAGAIN && errno != EINTR)
1.154     dtucker  1940:                                break;
1.201     markus   1941:                        if (state->packet_timeout_ms == -1)
1.154     dtucker  1942:                                continue;
                   1943:                        ms_subtract_diff(&start, &ms_remain);
                   1944:                        if (ms_remain <= 0) {
                   1945:                                ret = 0;
                   1946:                                break;
                   1947:                        }
                   1948:                }
                   1949:                if (ret == 0) {
1.205     djm      1950:                        free(setp);
                   1951:                        return SSH_ERR_CONN_TIMEOUT;
                   1952:                }
                   1953:                if ((r = ssh_packet_write_poll(ssh)) != 0) {
                   1954:                        free(setp);
                   1955:                        return r;
1.154     dtucker  1956:                }
1.14      markus   1957:        }
1.186     djm      1958:        free(setp);
1.205     djm      1959:        return 0;
1.1       deraadt  1960: }
                   1961:
                   1962: /* Returns true if there is buffered data to write to the connection. */
                   1963:
1.2       provos   1964: int
1.201     markus   1965: ssh_packet_have_data_to_write(struct ssh *ssh)
1.1       deraadt  1966: {
1.201     markus   1967:        return sshbuf_len(ssh->state->output) != 0;
1.1       deraadt  1968: }
                   1969:
                   1970: /* Returns true if there is not too much data to write to the connection. */
                   1971:
1.2       provos   1972: int
1.201     markus   1973: ssh_packet_not_very_much_data_to_write(struct ssh *ssh)
1.1       deraadt  1974: {
1.201     markus   1975:        if (ssh->state->interactive_mode)
                   1976:                return sshbuf_len(ssh->state->output) < 16384;
1.14      markus   1977:        else
1.201     markus   1978:                return sshbuf_len(ssh->state->output) < 128 * 1024;
1.1       deraadt  1979: }
                   1980:
1.201     markus   1981: void
                   1982: ssh_packet_set_tos(struct ssh *ssh, int tos)
1.101     markus   1983: {
1.263     djm      1984:        if (!ssh_packet_connection_is_on_socket(ssh) || tos == INT_MAX)
1.101     markus   1985:                return;
1.201     markus   1986:        switch (ssh_packet_connection_af(ssh)) {
1.173     djm      1987:        case AF_INET:
                   1988:                debug3("%s: set IP_TOS 0x%02x", __func__, tos);
1.201     markus   1989:                if (setsockopt(ssh->state->connection_in,
1.173     djm      1990:                    IPPROTO_IP, IP_TOS, &tos, sizeof(tos)) < 0)
                   1991:                        error("setsockopt IP_TOS %d: %.100s:",
                   1992:                            tos, strerror(errno));
                   1993:                break;
                   1994:        case AF_INET6:
                   1995:                debug3("%s: set IPV6_TCLASS 0x%02x", __func__, tos);
1.201     markus   1996:                if (setsockopt(ssh->state->connection_in,
1.173     djm      1997:                    IPPROTO_IPV6, IPV6_TCLASS, &tos, sizeof(tos)) < 0)
                   1998:                        error("setsockopt IPV6_TCLASS %d: %.100s:",
                   1999:                            tos, strerror(errno));
                   2000:                break;
                   2001:        }
1.101     markus   2002: }
                   2003:
1.1       deraadt  2004: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   2005:
1.2       provos   2006: void
1.201     markus   2007: ssh_packet_set_interactive(struct ssh *ssh, int interactive, int qos_interactive, int qos_bulk)
1.1       deraadt  2008: {
1.201     markus   2009:        struct session_state *state = ssh->state;
                   2010:
                   2011:        if (state->set_interactive_called)
1.43      markus   2012:                return;
1.201     markus   2013:        state->set_interactive_called = 1;
1.1       deraadt  2014:
1.14      markus   2015:        /* Record that we are in interactive mode. */
1.201     markus   2016:        state->interactive_mode = interactive;
1.1       deraadt  2017:
1.19      markus   2018:        /* Only set socket options if using a socket.  */
1.201     markus   2019:        if (!ssh_packet_connection_is_on_socket(ssh))
1.14      markus   2020:                return;
1.201     markus   2021:        set_nodelay(state->connection_in);
                   2022:        ssh_packet_set_tos(ssh, interactive ? qos_interactive :
                   2023:            qos_bulk);
1.1       deraadt  2024: }
                   2025:
                   2026: /* Returns true if the current connection is interactive. */
                   2027:
1.2       provos   2028: int
1.201     markus   2029: ssh_packet_is_interactive(struct ssh *ssh)
1.1       deraadt  2030: {
1.201     markus   2031:        return ssh->state->interactive_mode;
1.12      markus   2032: }
                   2033:
1.113     deraadt  2034: int
1.201     markus   2035: ssh_packet_set_maxsize(struct ssh *ssh, u_int s)
1.12      markus   2036: {
1.201     markus   2037:        struct session_state *state = ssh->state;
                   2038:
                   2039:        if (state->set_maxsize_called) {
1.106     itojun   2040:                logit("packet_set_maxsize: called twice: old %d new %d",
1.201     markus   2041:                    state->max_packet_size, s);
1.14      markus   2042:                return -1;
                   2043:        }
                   2044:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   2045:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   2046:                return -1;
                   2047:        }
1.201     markus   2048:        state->set_maxsize_called = 1;
1.66      markus   2049:        debug("packet_set_maxsize: setting to %d", s);
1.201     markus   2050:        state->max_packet_size = s;
1.14      markus   2051:        return s;
1.53      markus   2052: }
                   2053:
1.161     andreas  2054: int
1.201     markus   2055: ssh_packet_inc_alive_timeouts(struct ssh *ssh)
1.161     andreas  2056: {
1.201     markus   2057:        return ++ssh->state->keep_alive_timeouts;
1.161     andreas  2058: }
                   2059:
                   2060: void
1.201     markus   2061: ssh_packet_set_alive_timeouts(struct ssh *ssh, int ka)
1.161     andreas  2062: {
1.201     markus   2063:        ssh->state->keep_alive_timeouts = ka;
1.161     andreas  2064: }
                   2065:
                   2066: u_int
1.201     markus   2067: ssh_packet_get_maxsize(struct ssh *ssh)
1.71      markus   2068: {
1.201     markus   2069:        return ssh->state->max_packet_size;
1.71      markus   2070: }
                   2071:
1.105     markus   2072: void
1.244     dtucker  2073: ssh_packet_set_rekey_limits(struct ssh *ssh, u_int64_t bytes, u_int32_t seconds)
1.105     markus   2074: {
1.244     dtucker  2075:        debug3("rekey after %llu bytes, %u seconds", (unsigned long long)bytes,
                   2076:            (unsigned int)seconds);
1.201     markus   2077:        ssh->state->rekey_limit = bytes;
                   2078:        ssh->state->rekey_interval = seconds;
1.184     dtucker  2079: }
                   2080:
                   2081: time_t
1.201     markus   2082: ssh_packet_get_rekey_timeout(struct ssh *ssh)
1.184     dtucker  2083: {
                   2084:        time_t seconds;
                   2085:
1.201     markus   2086:        seconds = ssh->state->rekey_time + ssh->state->rekey_interval -
1.187     dtucker  2087:            monotime();
1.185     dtucker  2088:        return (seconds <= 0 ? 1 : seconds);
1.118     markus   2089: }
                   2090:
                   2091: void
1.201     markus   2092: ssh_packet_set_server(struct ssh *ssh)
1.118     markus   2093: {
1.201     markus   2094:        ssh->state->server_side = 1;
1.118     markus   2095: }
                   2096:
                   2097: void
1.201     markus   2098: ssh_packet_set_authenticated(struct ssh *ssh)
1.118     markus   2099: {
1.201     markus   2100:        ssh->state->after_authentication = 1;
1.161     andreas  2101: }
                   2102:
                   2103: void *
1.201     markus   2104: ssh_packet_get_input(struct ssh *ssh)
1.161     andreas  2105: {
1.201     markus   2106:        return (void *)ssh->state->input;
1.161     andreas  2107: }
                   2108:
                   2109: void *
1.201     markus   2110: ssh_packet_get_output(struct ssh *ssh)
1.161     andreas  2111: {
1.201     markus   2112:        return (void *)ssh->state->output;
1.166     andreas  2113: }
                   2114:
1.196     markus   2115: /* Reset after_authentication and reset compression in post-auth privsep */
1.201     markus   2116: static int
                   2117: ssh_packet_set_postauth(struct ssh *ssh)
1.196     markus   2118: {
1.239     djm      2119:        int r;
1.196     markus   2120:
                   2121:        debug("%s: called", __func__);
                   2122:        /* This was set in net child, but is not visible in user child */
1.201     markus   2123:        ssh->state->after_authentication = 1;
                   2124:        ssh->state->rekeying = 0;
1.239     djm      2125:        if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0)
                   2126:                return r;
1.201     markus   2127:        return 0;
                   2128: }
                   2129:
                   2130: /* Packet state (de-)serialization for privsep */
                   2131:
                   2132: /* turn kex into a blob for packet state serialization */
                   2133: static int
                   2134: kex_to_blob(struct sshbuf *m, struct kex *kex)
                   2135: {
                   2136:        int r;
                   2137:
                   2138:        if ((r = sshbuf_put_string(m, kex->session_id,
                   2139:            kex->session_id_len)) != 0 ||
                   2140:            (r = sshbuf_put_u32(m, kex->we_need)) != 0 ||
1.269     djm      2141:            (r = sshbuf_put_cstring(m, kex->hostkey_alg)) != 0 ||
1.201     markus   2142:            (r = sshbuf_put_u32(m, kex->hostkey_type)) != 0 ||
1.269     djm      2143:            (r = sshbuf_put_u32(m, kex->hostkey_nid)) != 0 ||
1.201     markus   2144:            (r = sshbuf_put_u32(m, kex->kex_type)) != 0 ||
                   2145:            (r = sshbuf_put_stringb(m, kex->my)) != 0 ||
                   2146:            (r = sshbuf_put_stringb(m, kex->peer)) != 0 ||
                   2147:            (r = sshbuf_put_u32(m, kex->flags)) != 0 ||
                   2148:            (r = sshbuf_put_cstring(m, kex->client_version_string)) != 0 ||
                   2149:            (r = sshbuf_put_cstring(m, kex->server_version_string)) != 0)
                   2150:                return r;
                   2151:        return 0;
                   2152: }
                   2153:
                   2154: /* turn key exchange results into a blob for packet state serialization */
                   2155: static int
                   2156: newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2157: {
                   2158:        struct sshbuf *b;
                   2159:        struct sshcipher_ctx *cc;
                   2160:        struct sshcomp *comp;
                   2161:        struct sshenc *enc;
                   2162:        struct sshmac *mac;
                   2163:        struct newkeys *newkey;
                   2164:        int r;
                   2165:
                   2166:        if ((newkey = ssh->state->newkeys[mode]) == NULL)
                   2167:                return SSH_ERR_INTERNAL_ERROR;
                   2168:        enc = &newkey->enc;
                   2169:        mac = &newkey->mac;
                   2170:        comp = &newkey->comp;
1.235     djm      2171:        cc = (mode == MODE_OUT) ? ssh->state->send_context :
                   2172:            ssh->state->receive_context;
1.201     markus   2173:        if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0)
                   2174:                return r;
                   2175:        if ((b = sshbuf_new()) == NULL)
                   2176:                return SSH_ERR_ALLOC_FAIL;
                   2177:        if ((r = sshbuf_put_cstring(b, enc->name)) != 0 ||
                   2178:            (r = sshbuf_put_u32(b, enc->enabled)) != 0 ||
                   2179:            (r = sshbuf_put_u32(b, enc->block_size)) != 0 ||
                   2180:            (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 ||
                   2181:            (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0)
                   2182:                goto out;
                   2183:        if (cipher_authlen(enc->cipher) == 0) {
                   2184:                if ((r = sshbuf_put_cstring(b, mac->name)) != 0 ||
                   2185:                    (r = sshbuf_put_u32(b, mac->enabled)) != 0 ||
                   2186:                    (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0)
                   2187:                        goto out;
                   2188:        }
                   2189:        if ((r = sshbuf_put_u32(b, comp->type)) != 0 ||
                   2190:            (r = sshbuf_put_cstring(b, comp->name)) != 0)
                   2191:                goto out;
                   2192:        r = sshbuf_put_stringb(m, b);
                   2193:  out:
1.221     mmcc     2194:        sshbuf_free(b);
1.201     markus   2195:        return r;
                   2196: }
                   2197:
                   2198: /* serialize packet state into a blob */
                   2199: int
                   2200: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
                   2201: {
                   2202:        struct session_state *state = ssh->state;
1.249     djm      2203:        int r;
1.201     markus   2204:
1.249     djm      2205:        if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
                   2206:            (r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
                   2207:            (r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
                   2208:            (r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
                   2209:            (r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
                   2210:            (r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
                   2211:            (r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
                   2212:            (r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
                   2213:            (r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
                   2214:            (r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
                   2215:            (r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
                   2216:            (r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
1.255     djm      2217:            (r = sshbuf_put_u64(m, state->p_read.bytes)) != 0 ||
                   2218:            (r = sshbuf_put_stringb(m, state->input)) != 0 ||
                   2219:            (r = sshbuf_put_stringb(m, state->output)) != 0)
1.256     djm      2220:                return r;
1.201     markus   2221:
                   2222:        return 0;
                   2223: }
                   2224:
                   2225: /* restore key exchange results from blob for packet state de-serialization */
                   2226: static int
                   2227: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
                   2228: {
                   2229:        struct sshbuf *b = NULL;
                   2230:        struct sshcomp *comp;
                   2231:        struct sshenc *enc;
                   2232:        struct sshmac *mac;
                   2233:        struct newkeys *newkey = NULL;
                   2234:        size_t keylen, ivlen, maclen;
                   2235:        int r;
                   2236:
                   2237:        if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
                   2238:                r = SSH_ERR_ALLOC_FAIL;
                   2239:                goto out;
                   2240:        }
                   2241:        if ((r = sshbuf_froms(m, &b)) != 0)
                   2242:                goto out;
                   2243: #ifdef DEBUG_PK
                   2244:        sshbuf_dump(b, stderr);
                   2245: #endif
                   2246:        enc = &newkey->enc;
                   2247:        mac = &newkey->mac;
                   2248:        comp = &newkey->comp;
                   2249:
                   2250:        if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
                   2251:            (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
                   2252:            (r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
                   2253:            (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
                   2254:            (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
                   2255:                goto out;
1.262     djm      2256:        if ((enc->cipher = cipher_by_name(enc->name)) == NULL) {
                   2257:                r = SSH_ERR_INVALID_FORMAT;
                   2258:                goto out;
                   2259:        }
1.201     markus   2260:        if (cipher_authlen(enc->cipher) == 0) {
                   2261:                if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
                   2262:                        goto out;
                   2263:                if ((r = mac_setup(mac, mac->name)) != 0)
                   2264:                        goto out;
                   2265:                if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
                   2266:                    (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
                   2267:                        goto out;
                   2268:                if (maclen > mac->key_len) {
                   2269:                        r = SSH_ERR_INVALID_FORMAT;
                   2270:                        goto out;
                   2271:                }
                   2272:                mac->key_len = maclen;
                   2273:        }
                   2274:        if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
                   2275:            (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
                   2276:                goto out;
                   2277:        if (sshbuf_len(b) != 0) {
                   2278:                r = SSH_ERR_INVALID_FORMAT;
                   2279:                goto out;
                   2280:        }
                   2281:        enc->key_len = keylen;
                   2282:        enc->iv_len = ivlen;
                   2283:        ssh->kex->newkeys[mode] = newkey;
                   2284:        newkey = NULL;
                   2285:        r = 0;
                   2286:  out:
1.219     mmcc     2287:        free(newkey);
1.221     mmcc     2288:        sshbuf_free(b);
1.201     markus   2289:        return r;
                   2290: }
                   2291:
                   2292: /* restore kex from blob for packet state de-serialization */
                   2293: static int
                   2294: kex_from_blob(struct sshbuf *m, struct kex **kexp)
                   2295: {
                   2296:        struct kex *kex;
                   2297:        int r;
                   2298:
                   2299:        if ((kex = calloc(1, sizeof(struct kex))) == NULL ||
                   2300:            (kex->my = sshbuf_new()) == NULL ||
                   2301:            (kex->peer = sshbuf_new()) == NULL) {
                   2302:                r = SSH_ERR_ALLOC_FAIL;
                   2303:                goto out;
                   2304:        }
                   2305:        if ((r = sshbuf_get_string(m, &kex->session_id, &kex->session_id_len)) != 0 ||
                   2306:            (r = sshbuf_get_u32(m, &kex->we_need)) != 0 ||
1.269     djm      2307:            (r = sshbuf_get_cstring(m, &kex->hostkey_alg, NULL)) != 0 ||
1.201     markus   2308:            (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_type)) != 0 ||
1.269     djm      2309:            (r = sshbuf_get_u32(m, (u_int *)&kex->hostkey_nid)) != 0 ||
1.201     markus   2310:            (r = sshbuf_get_u32(m, &kex->kex_type)) != 0 ||
                   2311:            (r = sshbuf_get_stringb(m, kex->my)) != 0 ||
                   2312:            (r = sshbuf_get_stringb(m, kex->peer)) != 0 ||
                   2313:            (r = sshbuf_get_u32(m, &kex->flags)) != 0 ||
                   2314:            (r = sshbuf_get_cstring(m, &kex->client_version_string, NULL)) != 0 ||
                   2315:            (r = sshbuf_get_cstring(m, &kex->server_version_string, NULL)) != 0)
                   2316:                goto out;
                   2317:        kex->server = 1;
                   2318:        kex->done = 1;
                   2319:        r = 0;
                   2320:  out:
                   2321:        if (r != 0 || kexp == NULL) {
                   2322:                if (kex != NULL) {
1.221     mmcc     2323:                        sshbuf_free(kex->my);
                   2324:                        sshbuf_free(kex->peer);
1.201     markus   2325:                        free(kex);
                   2326:                }
                   2327:                if (kexp != NULL)
                   2328:                        *kexp = NULL;
                   2329:        } else {
                   2330:                *kexp = kex;
                   2331:        }
                   2332:        return r;
                   2333: }
                   2334:
                   2335: /*
                   2336:  * Restore packet state from content of blob 'm' (de-serialization).
                   2337:  * Note that 'm' will be partially consumed on parsing or any other errors.
                   2338:  */
                   2339: int
                   2340: ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m)
                   2341: {
                   2342:        struct session_state *state = ssh->state;
1.254     djm      2343:        const u_char *input, *output;
                   2344:        size_t ilen, olen;
1.201     markus   2345:        int r;
                   2346:
1.249     djm      2347:        if ((r = kex_from_blob(m, &ssh->kex)) != 0 ||
                   2348:            (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 ||
                   2349:            (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 ||
                   2350:            (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 ||
                   2351:            (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 ||
                   2352:            (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 ||
                   2353:            (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 ||
                   2354:            (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 ||
                   2355:            (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 ||
                   2356:            (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 ||
                   2357:            (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 ||
                   2358:            (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 ||
                   2359:            (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0)
                   2360:                return r;
                   2361:        /*
                   2362:         * We set the time here so that in post-auth privsep slave we
                   2363:         * count from the completion of the authentication.
                   2364:         */
                   2365:        state->rekey_time = monotime();
                   2366:        /* XXX ssh_set_newkeys overrides p_read.packets? XXX */
                   2367:        if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 ||
                   2368:            (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0)
                   2369:                return r;
1.201     markus   2370:
1.239     djm      2371:        if ((r = ssh_packet_set_postauth(ssh)) != 0)
1.201     markus   2372:                return r;
                   2373:
                   2374:        sshbuf_reset(state->input);
                   2375:        sshbuf_reset(state->output);
                   2376:        if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 ||
                   2377:            (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 ||
                   2378:            (r = sshbuf_put(state->input, input, ilen)) != 0 ||
                   2379:            (r = sshbuf_put(state->output, output, olen)) != 0)
                   2380:                return r;
                   2381:
                   2382:        if (sshbuf_len(m))
                   2383:                return SSH_ERR_INVALID_FORMAT;
                   2384:        debug3("%s: done", __func__);
                   2385:        return 0;
                   2386: }
                   2387:
                   2388: /* NEW API */
                   2389:
                   2390: /* put data to the outgoing packet */
                   2391:
                   2392: int
                   2393: sshpkt_put(struct ssh *ssh, const void *v, size_t len)
                   2394: {
                   2395:        return sshbuf_put(ssh->state->outgoing_packet, v, len);
                   2396: }
                   2397:
                   2398: int
                   2399: sshpkt_putb(struct ssh *ssh, const struct sshbuf *b)
                   2400: {
                   2401:        return sshbuf_putb(ssh->state->outgoing_packet, b);
                   2402: }
                   2403:
                   2404: int
                   2405: sshpkt_put_u8(struct ssh *ssh, u_char val)
                   2406: {
                   2407:        return sshbuf_put_u8(ssh->state->outgoing_packet, val);
                   2408: }
                   2409:
                   2410: int
                   2411: sshpkt_put_u32(struct ssh *ssh, u_int32_t val)
                   2412: {
                   2413:        return sshbuf_put_u32(ssh->state->outgoing_packet, val);
                   2414: }
                   2415:
                   2416: int
                   2417: sshpkt_put_u64(struct ssh *ssh, u_int64_t val)
                   2418: {
                   2419:        return sshbuf_put_u64(ssh->state->outgoing_packet, val);
                   2420: }
                   2421:
                   2422: int
                   2423: sshpkt_put_string(struct ssh *ssh, const void *v, size_t len)
                   2424: {
                   2425:        return sshbuf_put_string(ssh->state->outgoing_packet, v, len);
                   2426: }
                   2427:
                   2428: int
                   2429: sshpkt_put_cstring(struct ssh *ssh, const void *v)
                   2430: {
                   2431:        return sshbuf_put_cstring(ssh->state->outgoing_packet, v);
                   2432: }
                   2433:
                   2434: int
                   2435: sshpkt_put_stringb(struct ssh *ssh, const struct sshbuf *v)
                   2436: {
                   2437:        return sshbuf_put_stringb(ssh->state->outgoing_packet, v);
                   2438: }
                   2439:
1.211     djm      2440: #ifdef WITH_OPENSSL
1.201     markus   2441: int
                   2442: sshpkt_put_ec(struct ssh *ssh, const EC_POINT *v, const EC_GROUP *g)
                   2443: {
                   2444:        return sshbuf_put_ec(ssh->state->outgoing_packet, v, g);
                   2445: }
                   2446:
                   2447:
                   2448: int
                   2449: sshpkt_put_bignum2(struct ssh *ssh, const BIGNUM *v)
                   2450: {
                   2451:        return sshbuf_put_bignum2(ssh->state->outgoing_packet, v);
                   2452: }
1.211     djm      2453: #endif /* WITH_OPENSSL */
1.201     markus   2454:
                   2455: /* fetch data from the incoming packet */
                   2456:
                   2457: int
                   2458: sshpkt_get(struct ssh *ssh, void *valp, size_t len)
                   2459: {
                   2460:        return sshbuf_get(ssh->state->incoming_packet, valp, len);
                   2461: }
                   2462:
                   2463: int
                   2464: sshpkt_get_u8(struct ssh *ssh, u_char *valp)
                   2465: {
                   2466:        return sshbuf_get_u8(ssh->state->incoming_packet, valp);
                   2467: }
                   2468:
                   2469: int
                   2470: sshpkt_get_u32(struct ssh *ssh, u_int32_t *valp)
                   2471: {
                   2472:        return sshbuf_get_u32(ssh->state->incoming_packet, valp);
                   2473: }
                   2474:
                   2475: int
                   2476: sshpkt_get_u64(struct ssh *ssh, u_int64_t *valp)
                   2477: {
                   2478:        return sshbuf_get_u64(ssh->state->incoming_packet, valp);
                   2479: }
                   2480:
                   2481: int
                   2482: sshpkt_get_string(struct ssh *ssh, u_char **valp, size_t *lenp)
                   2483: {
                   2484:        return sshbuf_get_string(ssh->state->incoming_packet, valp, lenp);
                   2485: }
                   2486:
                   2487: int
                   2488: sshpkt_get_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
                   2489: {
                   2490:        return sshbuf_get_string_direct(ssh->state->incoming_packet, valp, lenp);
                   2491: }
                   2492:
                   2493: int
1.264     djm      2494: sshpkt_peek_string_direct(struct ssh *ssh, const u_char **valp, size_t *lenp)
                   2495: {
                   2496:        return sshbuf_peek_string_direct(ssh->state->incoming_packet, valp, lenp);
                   2497: }
                   2498:
                   2499: int
1.201     markus   2500: sshpkt_get_cstring(struct ssh *ssh, char **valp, size_t *lenp)
                   2501: {
                   2502:        return sshbuf_get_cstring(ssh->state->incoming_packet, valp, lenp);
                   2503: }
                   2504:
1.211     djm      2505: #ifdef WITH_OPENSSL
1.201     markus   2506: int
                   2507: sshpkt_get_ec(struct ssh *ssh, EC_POINT *v, const EC_GROUP *g)
                   2508: {
                   2509:        return sshbuf_get_ec(ssh->state->incoming_packet, v, g);
                   2510: }
                   2511:
                   2512:
                   2513: int
                   2514: sshpkt_get_bignum2(struct ssh *ssh, BIGNUM *v)
                   2515: {
                   2516:        return sshbuf_get_bignum2(ssh->state->incoming_packet, v);
                   2517: }
1.211     djm      2518: #endif /* WITH_OPENSSL */
1.201     markus   2519:
                   2520: int
                   2521: sshpkt_get_end(struct ssh *ssh)
                   2522: {
                   2523:        if (sshbuf_len(ssh->state->incoming_packet) > 0)
                   2524:                return SSH_ERR_UNEXPECTED_TRAILING_DATA;
                   2525:        return 0;
                   2526: }
                   2527:
                   2528: const u_char *
                   2529: sshpkt_ptr(struct ssh *ssh, size_t *lenp)
                   2530: {
                   2531:        if (lenp != NULL)
                   2532:                *lenp = sshbuf_len(ssh->state->incoming_packet);
                   2533:        return sshbuf_ptr(ssh->state->incoming_packet);
                   2534: }
                   2535:
                   2536: /* start a new packet */
                   2537:
                   2538: int
                   2539: sshpkt_start(struct ssh *ssh, u_char type)
                   2540: {
1.249     djm      2541:        u_char buf[6]; /* u32 packet length, u8 pad len, u8 type */
1.201     markus   2542:
                   2543:        DBG(debug("packet_start[%d]", type));
1.249     djm      2544:        memset(buf, 0, sizeof(buf));
                   2545:        buf[sizeof(buf) - 1] = type;
1.201     markus   2546:        sshbuf_reset(ssh->state->outgoing_packet);
1.249     djm      2547:        return sshbuf_put(ssh->state->outgoing_packet, buf, sizeof(buf));
1.201     markus   2548: }
                   2549:
1.242     markus   2550: static int
                   2551: ssh_packet_send_mux(struct ssh *ssh)
                   2552: {
                   2553:        struct session_state *state = ssh->state;
                   2554:        u_char type, *cp;
                   2555:        size_t len;
                   2556:        int r;
                   2557:
                   2558:        if (ssh->kex)
                   2559:                return SSH_ERR_INTERNAL_ERROR;
                   2560:        len = sshbuf_len(state->outgoing_packet);
                   2561:        if (len < 6)
                   2562:                return SSH_ERR_INTERNAL_ERROR;
                   2563:        cp = sshbuf_mutable_ptr(state->outgoing_packet);
                   2564:        type = cp[5];
                   2565:        if (ssh_packet_log_type(type))
                   2566:                debug3("%s: type %u", __func__, type);
                   2567:        /* drop everything, but the connection protocol */
                   2568:        if (type >= SSH2_MSG_CONNECTION_MIN &&
                   2569:            type <= SSH2_MSG_CONNECTION_MAX) {
                   2570:                POKE_U32(cp, len - 4);
                   2571:                if ((r = sshbuf_putb(state->output,
                   2572:                    state->outgoing_packet)) != 0)
                   2573:                        return r;
                   2574:                /* sshbuf_dump(state->output, stderr); */
                   2575:        }
                   2576:        sshbuf_reset(state->outgoing_packet);
1.264     djm      2577:        return 0;
                   2578: }
                   2579:
                   2580: /*
                   2581:  * 9.2.  Ignored Data Message
                   2582:  *
                   2583:  *   byte      SSH_MSG_IGNORE
                   2584:  *   string    data
                   2585:  *
                   2586:  * All implementations MUST understand (and ignore) this message at any
                   2587:  * time (after receiving the protocol version). No implementation is
                   2588:  * required to send them. This message can be used as an additional
                   2589:  * protection measure against advanced traffic analysis techniques.
                   2590:  */
                   2591: int
                   2592: sshpkt_msg_ignore(struct ssh *ssh, u_int nbytes)
                   2593: {
                   2594:        u_int32_t rnd = 0;
                   2595:        int r;
                   2596:        u_int i;
                   2597:
                   2598:        if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
                   2599:            (r = sshpkt_put_u32(ssh, nbytes)) != 0)
                   2600:                return r;
                   2601:        for (i = 0; i < nbytes; i++) {
                   2602:                if (i % 4 == 0)
                   2603:                        rnd = arc4random();
                   2604:                if ((r = sshpkt_put_u8(ssh, (u_char)rnd & 0xff)) != 0)
                   2605:                        return r;
                   2606:                rnd >>= 8;
                   2607:        }
1.242     markus   2608:        return 0;
                   2609: }
                   2610:
1.201     markus   2611: /* send it */
                   2612:
                   2613: int
                   2614: sshpkt_send(struct ssh *ssh)
                   2615: {
1.242     markus   2616:        if (ssh->state && ssh->state->mux)
                   2617:                return ssh_packet_send_mux(ssh);
1.249     djm      2618:        return ssh_packet_send2(ssh);
1.201     markus   2619: }
                   2620:
                   2621: int
                   2622: sshpkt_disconnect(struct ssh *ssh, const char *fmt,...)
                   2623: {
                   2624:        char buf[1024];
                   2625:        va_list args;
                   2626:        int r;
                   2627:
                   2628:        va_start(args, fmt);
                   2629:        vsnprintf(buf, sizeof(buf), fmt, args);
                   2630:        va_end(args);
                   2631:
1.249     djm      2632:        if ((r = sshpkt_start(ssh, SSH2_MSG_DISCONNECT)) != 0 ||
                   2633:            (r = sshpkt_put_u32(ssh, SSH2_DISCONNECT_PROTOCOL_ERROR)) != 0 ||
                   2634:            (r = sshpkt_put_cstring(ssh, buf)) != 0 ||
                   2635:            (r = sshpkt_put_cstring(ssh, "")) != 0 ||
                   2636:            (r = sshpkt_send(ssh)) != 0)
                   2637:                return r;
1.201     markus   2638:        return 0;
                   2639: }
                   2640:
                   2641: /* roundup current message to pad bytes */
                   2642: int
                   2643: sshpkt_add_padding(struct ssh *ssh, u_char pad)
                   2644: {
                   2645:        ssh->state->extra_pad = pad;
                   2646:        return 0;
1.1       deraadt  2647: }