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

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