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

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