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

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