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

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