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

1.153   ! djm         1: /* $OpenBSD: packet.c,v 1.152 2008/05/08 06:59:01 markus Exp $ */
1.1       deraadt     2: /*
1.15      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.35      deraadt     6:  * This file contains code implementing the packet protocol and communication
                      7:  * with the other side.  This same code is used both on client and server side.
1.29      markus      8:  *
1.35      deraadt     9:  * As far as I am concerned, the code I have written for this software
                     10:  * can be used freely for any purpose.  Any derived versions of this
                     11:  * software must be clearly marked as such, and if the derived work is
                     12:  * incompatible with the protocol description in the RFC file, it must be
                     13:  * called by a name other than "ssh" or "Secure Shell".
1.29      markus     14:  *
1.25      markus     15:  *
                     16:  * SSH2 packet format added by Markus Friedl.
1.69      markus     17:  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
1.25      markus     18:  *
1.35      deraadt    19:  * Redistribution and use in source and binary forms, with or without
                     20:  * modification, are permitted provided that the following conditions
                     21:  * are met:
                     22:  * 1. Redistributions of source code must retain the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer.
                     24:  * 2. Redistributions in binary form must reproduce the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer in the
                     26:  *    documentation and/or other materials provided with the distribution.
                     27:  *
                     28:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     29:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     30:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     31:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     32:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     33:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     34:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     35:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     36:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     37:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.15      deraadt    38:  */
1.1       deraadt    39:
1.142     deraadt    40: #include <sys/types.h>
1.105     markus     41: #include <sys/queue.h>
1.132     stevesk    42: #include <sys/socket.h>
1.138     stevesk    43: #include <sys/time.h>
1.139     stevesk    44: #include <sys/param.h>
1.121     stevesk    45:
                     46: #include <netinet/in_systm.h>
1.132     stevesk    47: #include <netinet/in.h>
1.121     stevesk    48: #include <netinet/ip.h>
1.134     stevesk    49:
1.135     stevesk    50: #include <errno.h>
1.134     stevesk    51: #include <stdarg.h>
1.141     stevesk    52: #include <stdio.h>
1.140     stevesk    53: #include <stdlib.h>
1.137     stevesk    54: #include <string.h>
1.136     stevesk    55: #include <unistd.h>
1.142     deraadt    56: #include <signal.h>
1.1       deraadt    57:
                     58: #include "xmalloc.h"
                     59: #include "buffer.h"
                     60: #include "packet.h"
                     61: #include "crc32.h"
                     62: #include "compress.h"
1.9       dugsong    63: #include "deattack.h"
1.64      markus     64: #include "channels.h"
1.25      markus     65: #include "compat.h"
1.45      markus     66: #include "ssh1.h"
1.25      markus     67: #include "ssh2.h"
1.37      markus     68: #include "cipher.h"
1.142     deraadt    69: #include "key.h"
1.25      markus     70: #include "kex.h"
1.50      markus     71: #include "mac.h"
1.46      markus     72: #include "log.h"
                     73: #include "canohost.h"
1.87      stevesk    74: #include "misc.h"
1.95      markus     75: #include "ssh.h"
1.25      markus     76:
                     77: #ifdef PACKET_DEBUG
                     78: #define DBG(x) x
                     79: #else
                     80: #define DBG(x)
                     81: #endif
                     82:
1.16      markus     83: /*
                     84:  * This variable contains the file descriptors used for communicating with
                     85:  * the other side.  connection_in is used for reading; connection_out for
                     86:  * writing.  These can be the same descriptor, in which case it is assumed to
                     87:  * be a socket.
                     88:  */
1.1       deraadt    89: static int connection_in = -1;
                     90: static int connection_out = -1;
                     91:
                     92: /* Protocol flags for the remote side. */
1.40      markus     93: static u_int remote_protocol_flags = 0;
1.1       deraadt    94:
                     95: /* Encryption context for receiving data.  This is only used for decryption. */
                     96: static CipherContext receive_context;
1.14      markus     97:
                     98: /* Encryption context for sending data.  This is only used for encryption. */
1.1       deraadt    99: static CipherContext send_context;
                    100:
                    101: /* Buffer for raw input data from the socket. */
1.91      markus    102: Buffer input;
1.1       deraadt   103:
                    104: /* Buffer for raw output data going to the socket. */
1.91      markus    105: Buffer output;
1.1       deraadt   106:
                    107: /* Buffer for the partial outgoing packet being constructed. */
                    108: static Buffer outgoing_packet;
                    109:
                    110: /* Buffer for the incoming packet currently being processed. */
                    111: static Buffer incoming_packet;
                    112:
                    113: /* Scratch buffer for packet compression/decompression. */
                    114: static Buffer compression_buffer;
1.60      markus    115: static int compression_buffer_ready = 0;
1.1       deraadt   116:
                    117: /* Flag indicating whether packet compression/decompression is enabled. */
                    118: static int packet_compression = 0;
                    119:
1.12      markus    120: /* default maximum packet size */
1.108     markus    121: u_int max_packet_size = 32768;
1.12      markus    122:
1.1       deraadt   123: /* Flag indicating whether this module has been initialized. */
                    124: static int initialized = 0;
                    125:
                    126: /* Set to true if the connection is interactive. */
                    127: static int interactive_mode = 0;
                    128:
1.118     markus    129: /* Set to true if we are the server side. */
                    130: static int server_side = 0;
                    131:
                    132: /* Set to true if we are authenticated. */
                    133: static int after_authentication = 0;
                    134:
1.151     dtucker   135: int keep_alive_timeouts = 0;
                    136:
1.25      markus    137: /* Session key information for Encryption and MAC */
1.57      markus    138: Newkeys *newkeys[MODE_MAX];
1.105     markus    139: static struct packet_state {
                    140:        u_int32_t seqnr;
                    141:        u_int32_t packets;
                    142:        u_int64_t blocks;
                    143: } p_read, p_send;
                    144:
                    145: static u_int64_t max_blocks_in, max_blocks_out;
                    146: static u_int32_t rekey_limit;
1.25      markus    147:
1.95      markus    148: /* Session key for protocol v1 */
                    149: static u_char ssh1_key[SSH_SESSION_KEY_LENGTH];
                    150: static u_int ssh1_keylen;
                    151:
1.71      markus    152: /* roundup current message to extra_pad bytes */
                    153: static u_char extra_pad = 0;
                    154:
1.105     markus    155: struct packet {
                    156:        TAILQ_ENTRY(packet) next;
                    157:        u_char type;
                    158:        Buffer payload;
                    159: };
                    160: TAILQ_HEAD(, packet) outgoing;
                    161:
1.16      markus    162: /*
                    163:  * Sets the descriptors used for communication.  Disables encryption until
                    164:  * packet_set_encryption_key is called.
                    165:  */
1.2       provos    166: void
                    167: packet_set_connection(int fd_in, int fd_out)
1.1       deraadt   168: {
1.37      markus    169:        Cipher *none = cipher_by_name("none");
1.97      deraadt   170:
1.37      markus    171:        if (none == NULL)
                    172:                fatal("packet_set_connection: cannot load cipher 'none'");
1.14      markus    173:        connection_in = fd_in;
                    174:        connection_out = fd_out;
1.113     deraadt   175:        cipher_init(&send_context, none, (const u_char *)"",
                    176:            0, NULL, 0, CIPHER_ENCRYPT);
                    177:        cipher_init(&receive_context, none, (const u_char *)"",
                    178:            0, NULL, 0, CIPHER_DECRYPT);
1.62      markus    179:        newkeys[MODE_IN] = newkeys[MODE_OUT] = NULL;
1.14      markus    180:        if (!initialized) {
                    181:                initialized = 1;
                    182:                buffer_init(&input);
                    183:                buffer_init(&output);
                    184:                buffer_init(&outgoing_packet);
                    185:                buffer_init(&incoming_packet);
1.105     markus    186:                TAILQ_INIT(&outgoing);
1.14      markus    187:        }
1.1       deraadt   188: }
                    189:
1.19      markus    190: /* Returns 1 if remote host is connected via socket, 0 if not. */
                    191:
                    192: int
1.73      itojun    193: packet_connection_is_on_socket(void)
1.19      markus    194: {
                    195:        struct sockaddr_storage from, to;
                    196:        socklen_t fromlen, tolen;
                    197:
                    198:        /* filedescriptors in and out are the same, so it's a socket */
                    199:        if (connection_in == connection_out)
                    200:                return 1;
                    201:        fromlen = sizeof(from);
                    202:        memset(&from, 0, sizeof(from));
1.20      markus    203:        if (getpeername(connection_in, (struct sockaddr *)&from, &fromlen) < 0)
1.19      markus    204:                return 0;
                    205:        tolen = sizeof(to);
                    206:        memset(&to, 0, sizeof(to));
1.20      markus    207:        if (getpeername(connection_out, (struct sockaddr *)&to, &tolen) < 0)
1.19      markus    208:                return 0;
                    209:        if (fromlen != tolen || memcmp(&from, &to, fromlen) != 0)
                    210:                return 0;
                    211:        if (from.ss_family != AF_INET && from.ss_family != AF_INET6)
                    212:                return 0;
                    213:        return 1;
                    214: }
                    215:
1.92      markus    216: /*
1.91      markus    217:  * Exports an IV from the CipherContext required to export the key
                    218:  * state back from the unprivileged child to the privileged parent
                    219:  * process.
                    220:  */
                    221:
                    222: void
                    223: packet_get_keyiv(int mode, u_char *iv, u_int len)
                    224: {
                    225:        CipherContext *cc;
                    226:
                    227:        if (mode == MODE_OUT)
                    228:                cc = &send_context;
                    229:        else
                    230:                cc = &receive_context;
                    231:
                    232:        cipher_get_keyiv(cc, iv, len);
                    233: }
                    234:
                    235: int
                    236: packet_get_keycontext(int mode, u_char *dat)
                    237: {
                    238:        CipherContext *cc;
1.92      markus    239:
1.91      markus    240:        if (mode == MODE_OUT)
                    241:                cc = &send_context;
                    242:        else
                    243:                cc = &receive_context;
                    244:
                    245:        return (cipher_get_keycontext(cc, dat));
                    246: }
                    247:
                    248: void
                    249: packet_set_keycontext(int mode, u_char *dat)
                    250: {
                    251:        CipherContext *cc;
1.92      markus    252:
1.91      markus    253:        if (mode == MODE_OUT)
                    254:                cc = &send_context;
                    255:        else
                    256:                cc = &receive_context;
                    257:
                    258:        cipher_set_keycontext(cc, dat);
                    259: }
                    260:
                    261: int
                    262: packet_get_keyiv_len(int mode)
                    263: {
                    264:        CipherContext *cc;
                    265:
                    266:        if (mode == MODE_OUT)
                    267:                cc = &send_context;
                    268:        else
                    269:                cc = &receive_context;
                    270:
                    271:        return (cipher_get_keyiv_len(cc));
                    272: }
1.125     deraadt   273:
1.91      markus    274: void
                    275: packet_set_iv(int mode, u_char *dat)
                    276: {
                    277:        CipherContext *cc;
                    278:
                    279:        if (mode == MODE_OUT)
                    280:                cc = &send_context;
                    281:        else
                    282:                cc = &receive_context;
                    283:
                    284:        cipher_set_keyiv(cc, dat);
                    285: }
1.125     deraadt   286:
1.91      markus    287: int
1.107     deraadt   288: packet_get_ssh1_cipher(void)
1.91      markus    289: {
                    290:        return (cipher_get_number(receive_context.cipher));
                    291: }
                    292:
1.105     markus    293: void
                    294: packet_get_state(int mode, u_int32_t *seqnr, u_int64_t *blocks, u_int32_t *packets)
                    295: {
                    296:        struct packet_state *state;
1.104     markus    297:
1.105     markus    298:        state = (mode == MODE_IN) ? &p_read : &p_send;
                    299:        *seqnr = state->seqnr;
                    300:        *blocks = state->blocks;
                    301:        *packets = state->packets;
1.91      markus    302: }
                    303:
                    304: void
1.105     markus    305: packet_set_state(int mode, u_int32_t seqnr, u_int64_t blocks, u_int32_t packets)
1.91      markus    306: {
1.105     markus    307:        struct packet_state *state;
                    308:
                    309:        state = (mode == MODE_IN) ? &p_read : &p_send;
                    310:        state->seqnr = seqnr;
                    311:        state->blocks = blocks;
                    312:        state->packets = packets;
1.91      markus    313: }
                    314:
1.19      markus    315: /* returns 1 if connection is via ipv4 */
                    316:
                    317: int
1.73      itojun    318: packet_connection_is_ipv4(void)
1.19      markus    319: {
                    320:        struct sockaddr_storage to;
1.21      deraadt   321:        socklen_t tolen = sizeof(to);
1.19      markus    322:
                    323:        memset(&to, 0, sizeof(to));
                    324:        if (getsockname(connection_out, (struct sockaddr *)&to, &tolen) < 0)
                    325:                return 0;
                    326:        if (to.ss_family != AF_INET)
                    327:                return 0;
                    328:        return 1;
                    329: }
                    330:
1.1       deraadt   331: /* Sets the connection into non-blocking mode. */
                    332:
1.2       provos    333: void
1.73      itojun    334: packet_set_nonblocking(void)
1.1       deraadt   335: {
1.14      markus    336:        /* Set the socket into non-blocking mode. */
1.114     djm       337:        set_nonblock(connection_in);
1.14      markus    338:
1.114     djm       339:        if (connection_out != connection_in)
                    340:                set_nonblock(connection_out);
1.1       deraadt   341: }
                    342:
                    343: /* Returns the socket used for reading. */
                    344:
1.2       provos    345: int
1.73      itojun    346: packet_get_connection_in(void)
1.1       deraadt   347: {
1.14      markus    348:        return connection_in;
1.1       deraadt   349: }
                    350:
                    351: /* Returns the descriptor used for writing. */
                    352:
1.2       provos    353: int
1.73      itojun    354: packet_get_connection_out(void)
1.1       deraadt   355: {
1.14      markus    356:        return connection_out;
1.1       deraadt   357: }
                    358:
                    359: /* Closes the connection and clears and frees internal data structures. */
                    360:
1.2       provos    361: void
1.73      itojun    362: packet_close(void)
1.1       deraadt   363: {
1.14      markus    364:        if (!initialized)
                    365:                return;
                    366:        initialized = 0;
                    367:        if (connection_in == connection_out) {
                    368:                shutdown(connection_out, SHUT_RDWR);
                    369:                close(connection_out);
                    370:        } else {
                    371:                close(connection_in);
                    372:                close(connection_out);
                    373:        }
                    374:        buffer_free(&input);
                    375:        buffer_free(&output);
                    376:        buffer_free(&outgoing_packet);
                    377:        buffer_free(&incoming_packet);
1.60      markus    378:        if (compression_buffer_ready) {
1.14      markus    379:                buffer_free(&compression_buffer);
                    380:                buffer_compress_uninit();
                    381:        }
1.88      markus    382:        cipher_cleanup(&send_context);
                    383:        cipher_cleanup(&receive_context);
1.1       deraadt   384: }
                    385:
                    386: /* Sets remote side protocol flags. */
                    387:
1.2       provos    388: void
1.40      markus    389: packet_set_protocol_flags(u_int protocol_flags)
1.1       deraadt   390: {
1.14      markus    391:        remote_protocol_flags = protocol_flags;
1.1       deraadt   392: }
                    393:
                    394: /* Returns the remote protocol flags set earlier by the above function. */
                    395:
1.40      markus    396: u_int
1.73      itojun    397: packet_get_protocol_flags(void)
1.1       deraadt   398: {
1.14      markus    399:        return remote_protocol_flags;
1.1       deraadt   400: }
                    401:
1.16      markus    402: /*
                    403:  * Starts packet compression from the next packet on in both directions.
                    404:  * Level is compression level 1 (fastest) - 9 (slow, best) as in gzip.
                    405:  */
1.1       deraadt   406:
1.68      itojun    407: static void
                    408: packet_init_compression(void)
1.60      markus    409: {
                    410:        if (compression_buffer_ready == 1)
                    411:                return;
                    412:        compression_buffer_ready = 1;
                    413:        buffer_init(&compression_buffer);
                    414: }
                    415:
1.2       provos    416: void
                    417: packet_start_compression(int level)
1.1       deraadt   418: {
1.62      markus    419:        if (packet_compression && !compat20)
1.14      markus    420:                fatal("Compression already enabled.");
                    421:        packet_compression = 1;
1.60      markus    422:        packet_init_compression();
                    423:        buffer_compress_init_send(level);
                    424:        buffer_compress_init_recv();
1.1       deraadt   425: }
                    426:
1.16      markus    427: /*
                    428:  * Causes any further packets to be encrypted using the given key.  The same
                    429:  * key is used for both sending and reception.  However, both directions are
                    430:  * encrypted independently of each other.
                    431:  */
1.95      markus    432:
1.2       provos    433: void
1.40      markus    434: packet_set_encryption_key(const u_char *key, u_int keylen,
1.37      markus    435:     int number)
1.1       deraadt   436: {
1.37      markus    437:        Cipher *cipher = cipher_by_number(number);
1.97      deraadt   438:
1.37      markus    439:        if (cipher == NULL)
                    440:                fatal("packet_set_encryption_key: unknown cipher number %d", number);
1.25      markus    441:        if (keylen < 20)
1.37      markus    442:                fatal("packet_set_encryption_key: keylen too small: %d", keylen);
1.95      markus    443:        if (keylen > SSH_SESSION_KEY_LENGTH)
                    444:                fatal("packet_set_encryption_key: keylen too big: %d", keylen);
                    445:        memcpy(ssh1_key, key, keylen);
                    446:        ssh1_keylen = keylen;
1.88      markus    447:        cipher_init(&send_context, cipher, key, keylen, NULL, 0, CIPHER_ENCRYPT);
                    448:        cipher_init(&receive_context, cipher, key, keylen, NULL, 0, CIPHER_DECRYPT);
1.95      markus    449: }
                    450:
                    451: u_int
                    452: packet_get_encryption_key(u_char *key)
                    453: {
                    454:        if (key == NULL)
                    455:                return (ssh1_keylen);
                    456:        memcpy(key, ssh1_key, ssh1_keylen);
                    457:        return (ssh1_keylen);
1.1       deraadt   458: }
                    459:
1.62      markus    460: /* Start constructing a packet to send. */
1.2       provos    461: void
1.62      markus    462: packet_start(u_char type)
1.1       deraadt   463: {
1.62      markus    464:        u_char buf[9];
                    465:        int len;
1.1       deraadt   466:
1.62      markus    467:        DBG(debug("packet_start[%d]", type));
                    468:        len = compat20 ? 6 : 9;
                    469:        memset(buf, 0, len - 1);
                    470:        buf[len - 1] = type;
1.14      markus    471:        buffer_clear(&outgoing_packet);
1.62      markus    472:        buffer_append(&outgoing_packet, buf, len);
1.25      markus    473: }
                    474:
1.62      markus    475: /* Append payload. */
1.2       provos    476: void
                    477: packet_put_char(int value)
1.1       deraadt   478: {
1.14      markus    479:        char ch = value;
1.97      deraadt   480:
1.14      markus    481:        buffer_append(&outgoing_packet, &ch, 1);
1.1       deraadt   482: }
1.125     deraadt   483:
1.2       provos    484: void
1.40      markus    485: packet_put_int(u_int value)
1.1       deraadt   486: {
1.14      markus    487:        buffer_put_int(&outgoing_packet, value);
1.1       deraadt   488: }
1.125     deraadt   489:
1.2       provos    490: void
1.76      stevesk   491: packet_put_string(const void *buf, u_int len)
1.1       deraadt   492: {
1.14      markus    493:        buffer_put_string(&outgoing_packet, buf, len);
1.1       deraadt   494: }
1.125     deraadt   495:
1.24      markus    496: void
                    497: packet_put_cstring(const char *str)
                    498: {
1.65      markus    499:        buffer_put_cstring(&outgoing_packet, str);
1.24      markus    500: }
1.125     deraadt   501:
1.24      markus    502: void
1.76      stevesk   503: packet_put_raw(const void *buf, u_int len)
1.24      markus    504: {
                    505:        buffer_append(&outgoing_packet, buf, len);
                    506: }
1.125     deraadt   507:
1.2       provos    508: void
1.14      markus    509: packet_put_bignum(BIGNUM * value)
1.1       deraadt   510: {
1.14      markus    511:        buffer_put_bignum(&outgoing_packet, value);
1.1       deraadt   512: }
1.125     deraadt   513:
1.24      markus    514: void
                    515: packet_put_bignum2(BIGNUM * value)
                    516: {
                    517:        buffer_put_bignum2(&outgoing_packet, value);
                    518: }
1.1       deraadt   519:
1.16      markus    520: /*
                    521:  * Finalizes and sends the packet.  If the encryption key has been set,
                    522:  * encrypts the packet before sending.
                    523:  */
1.14      markus    524:
1.68      itojun    525: static void
1.49      itojun    526: packet_send1(void)
1.1       deraadt   527: {
1.89      markus    528:        u_char buf[8], *cp;
1.14      markus    529:        int i, padding, len;
1.40      markus    530:        u_int checksum;
1.115     avsm      531:        u_int32_t rnd = 0;
1.14      markus    532:
1.16      markus    533:        /*
                    534:         * If using packet compression, compress the payload of the outgoing
                    535:         * packet.
                    536:         */
1.14      markus    537:        if (packet_compression) {
                    538:                buffer_clear(&compression_buffer);
                    539:                /* Skip padding. */
                    540:                buffer_consume(&outgoing_packet, 8);
                    541:                /* padding */
                    542:                buffer_append(&compression_buffer, "\0\0\0\0\0\0\0\0", 8);
                    543:                buffer_compress(&outgoing_packet, &compression_buffer);
                    544:                buffer_clear(&outgoing_packet);
                    545:                buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
1.75      deraadt   546:                    buffer_len(&compression_buffer));
1.14      markus    547:        }
                    548:        /* Compute packet length without padding (add checksum, remove padding). */
                    549:        len = buffer_len(&outgoing_packet) + 4 - 8;
                    550:
1.32      markus    551:        /* Insert padding. Initialized to zero in packet_start1() */
1.14      markus    552:        padding = 8 - len % 8;
1.88      markus    553:        if (!send_context.plaintext) {
1.14      markus    554:                cp = buffer_ptr(&outgoing_packet);
                    555:                for (i = 0; i < padding; i++) {
                    556:                        if (i % 4 == 0)
1.115     avsm      557:                                rnd = arc4random();
                    558:                        cp[7 - i] = rnd & 0xff;
                    559:                        rnd >>= 8;
1.14      markus    560:                }
                    561:        }
                    562:        buffer_consume(&outgoing_packet, 8 - padding);
                    563:
                    564:        /* Add check bytes. */
1.83      stevesk   565:        checksum = ssh_crc32(buffer_ptr(&outgoing_packet),
1.34      deraadt   566:            buffer_len(&outgoing_packet));
1.131     djm       567:        put_u32(buf, checksum);
1.14      markus    568:        buffer_append(&outgoing_packet, buf, 4);
1.1       deraadt   569:
                    570: #ifdef PACKET_DEBUG
1.14      markus    571:        fprintf(stderr, "packet_send plain: ");
                    572:        buffer_dump(&outgoing_packet);
1.1       deraadt   573: #endif
                    574:
1.14      markus    575:        /* Append to output. */
1.131     djm       576:        put_u32(buf, len);
1.14      markus    577:        buffer_append(&output, buf, 4);
1.76      stevesk   578:        cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
1.88      markus    579:        cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
1.75      deraadt   580:            buffer_len(&outgoing_packet));
1.14      markus    581:
1.1       deraadt   582: #ifdef PACKET_DEBUG
1.14      markus    583:        fprintf(stderr, "encrypted: ");
                    584:        buffer_dump(&output);
1.1       deraadt   585: #endif
                    586:
1.14      markus    587:        buffer_clear(&outgoing_packet);
1.1       deraadt   588:
1.16      markus    589:        /*
1.120     djm       590:         * Note that the packet is now only buffered in output.  It won't be
1.16      markus    591:         * actually sent until packet_write_wait or packet_write_poll is
                    592:         * called.
                    593:         */
1.1       deraadt   594: }
                    595:
1.91      markus    596: void
1.57      markus    597: set_newkeys(int mode)
                    598: {
                    599:        Enc *enc;
                    600:        Mac *mac;
                    601:        Comp *comp;
                    602:        CipherContext *cc;
1.105     markus    603:        u_int64_t *max_blocks;
1.115     avsm      604:        int crypt_type;
1.57      markus    605:
1.100     markus    606:        debug2("set_newkeys: mode %d", mode);
1.57      markus    607:
1.88      markus    608:        if (mode == MODE_OUT) {
                    609:                cc = &send_context;
1.115     avsm      610:                crypt_type = CIPHER_ENCRYPT;
1.105     markus    611:                p_send.packets = p_send.blocks = 0;
                    612:                max_blocks = &max_blocks_out;
1.88      markus    613:        } else {
                    614:                cc = &receive_context;
1.115     avsm      615:                crypt_type = CIPHER_DECRYPT;
1.105     markus    616:                p_read.packets = p_read.blocks = 0;
                    617:                max_blocks = &max_blocks_in;
1.88      markus    618:        }
1.57      markus    619:        if (newkeys[mode] != NULL) {
1.100     markus    620:                debug("set_newkeys: rekeying");
1.88      markus    621:                cipher_cleanup(cc);
1.59      markus    622:                enc  = &newkeys[mode]->enc;
                    623:                mac  = &newkeys[mode]->mac;
                    624:                comp = &newkeys[mode]->comp;
1.148     pvalchev  625:                mac_clear(mac);
1.59      markus    626:                xfree(enc->name);
                    627:                xfree(enc->iv);
                    628:                xfree(enc->key);
                    629:                xfree(mac->name);
                    630:                xfree(mac->key);
                    631:                xfree(comp->name);
1.58      markus    632:                xfree(newkeys[mode]);
1.57      markus    633:        }
                    634:        newkeys[mode] = kex_get_newkeys(mode);
                    635:        if (newkeys[mode] == NULL)
                    636:                fatal("newkeys: no keys for mode %d", mode);
                    637:        enc  = &newkeys[mode]->enc;
                    638:        mac  = &newkeys[mode]->mac;
                    639:        comp = &newkeys[mode]->comp;
1.148     pvalchev  640:        if (mac_init(mac) == 0)
1.57      markus    641:                mac->enabled = 1;
                    642:        DBG(debug("cipher_init_context: %d", mode));
1.88      markus    643:        cipher_init(cc, enc->cipher, enc->key, enc->key_len,
1.115     avsm      644:            enc->iv, enc->block_size, crypt_type);
1.91      markus    645:        /* Deleting the keys does not gain extra security */
                    646:        /* memset(enc->iv,  0, enc->block_size);
1.147     djm       647:           memset(enc->key, 0, enc->key_len);
                    648:           memset(mac->key, 0, mac->key_len); */
1.118     markus    649:        if ((comp->type == COMP_ZLIB ||
                    650:            (comp->type == COMP_DELAYED && after_authentication)) &&
                    651:            comp->enabled == 0) {
1.60      markus    652:                packet_init_compression();
                    653:                if (mode == MODE_OUT)
                    654:                        buffer_compress_init_send(6);
                    655:                else
                    656:                        buffer_compress_init_recv();
1.57      markus    657:                comp->enabled = 1;
                    658:        }
1.109     markus    659:        /*
                    660:         * The 2^(blocksize*2) limit is too expensive for 3DES,
                    661:         * blowfish, etc, so enforce a 1GB limit for small blocksizes.
                    662:         */
                    663:        if (enc->block_size >= 16)
                    664:                *max_blocks = (u_int64_t)1 << (enc->block_size*2);
                    665:        else
                    666:                *max_blocks = ((u_int64_t)1 << 30) / enc->block_size;
1.105     markus    667:        if (rekey_limit)
                    668:                *max_blocks = MIN(*max_blocks, rekey_limit / enc->block_size);
1.57      markus    669: }
                    670:
1.16      markus    671: /*
1.118     markus    672:  * Delayed compression for SSH2 is enabled after authentication:
1.143     dtucker   673:  * This happens on the server side after a SSH2_MSG_USERAUTH_SUCCESS is sent,
1.118     markus    674:  * and on the client side after a SSH2_MSG_USERAUTH_SUCCESS is received.
                    675:  */
                    676: static void
                    677: packet_enable_delayed_compress(void)
                    678: {
                    679:        Comp *comp = NULL;
                    680:        int mode;
                    681:
                    682:        /*
                    683:         * Remember that we are past the authentication step, so rekeying
                    684:         * with COMP_DELAYED will turn on compression immediately.
                    685:         */
                    686:        after_authentication = 1;
                    687:        for (mode = 0; mode < MODE_MAX; mode++) {
1.145     markus    688:                /* protocol error: USERAUTH_SUCCESS received before NEWKEYS */
                    689:                if (newkeys[mode] == NULL)
                    690:                        continue;
1.118     markus    691:                comp = &newkeys[mode]->comp;
                    692:                if (comp && !comp->enabled && comp->type == COMP_DELAYED) {
1.119     markus    693:                        packet_init_compression();
1.118     markus    694:                        if (mode == MODE_OUT)
                    695:                                buffer_compress_init_send(6);
                    696:                        else
                    697:                                buffer_compress_init_recv();
                    698:                        comp->enabled = 1;
                    699:                }
                    700:        }
                    701: }
                    702:
                    703: /*
1.25      markus    704:  * Finalize packet in SSH2 format (compress, mac, encrypt, enqueue)
                    705:  */
1.68      itojun    706: static void
1.105     markus    707: packet_send2_wrapped(void)
1.25      markus    708: {
1.89      markus    709:        u_char type, *cp, *macbuf = NULL;
1.71      markus    710:        u_char padlen, pad;
1.40      markus    711:        u_int packet_length = 0;
1.71      markus    712:        u_int i, len;
1.115     avsm      713:        u_int32_t rnd = 0;
1.25      markus    714:        Enc *enc   = NULL;
                    715:        Mac *mac   = NULL;
                    716:        Comp *comp = NULL;
                    717:        int block_size;
                    718:
1.57      markus    719:        if (newkeys[MODE_OUT] != NULL) {
                    720:                enc  = &newkeys[MODE_OUT]->enc;
                    721:                mac  = &newkeys[MODE_OUT]->mac;
                    722:                comp = &newkeys[MODE_OUT]->comp;
1.25      markus    723:        }
1.88      markus    724:        block_size = enc ? enc->block_size : 8;
1.25      markus    725:
1.89      markus    726:        cp = buffer_ptr(&outgoing_packet);
                    727:        type = cp[5];
1.25      markus    728:
                    729: #ifdef PACKET_DEBUG
                    730:        fprintf(stderr, "plain:     ");
                    731:        buffer_dump(&outgoing_packet);
                    732: #endif
                    733:
                    734:        if (comp && comp->enabled) {
                    735:                len = buffer_len(&outgoing_packet);
                    736:                /* skip header, compress only payload */
                    737:                buffer_consume(&outgoing_packet, 5);
                    738:                buffer_clear(&compression_buffer);
                    739:                buffer_compress(&outgoing_packet, &compression_buffer);
                    740:                buffer_clear(&outgoing_packet);
                    741:                buffer_append(&outgoing_packet, "\0\0\0\0\0", 5);
                    742:                buffer_append(&outgoing_packet, buffer_ptr(&compression_buffer),
                    743:                    buffer_len(&compression_buffer));
                    744:                DBG(debug("compression: raw %d compressed %d", len,
                    745:                    buffer_len(&outgoing_packet)));
                    746:        }
                    747:
                    748:        /* sizeof (packet_len + pad_len + payload) */
                    749:        len = buffer_len(&outgoing_packet);
                    750:
                    751:        /*
                    752:         * calc size of padding, alloc space, get random data,
                    753:         * minimum padding is 4 bytes
                    754:         */
                    755:        padlen = block_size - (len % block_size);
                    756:        if (padlen < 4)
                    757:                padlen += block_size;
1.71      markus    758:        if (extra_pad) {
                    759:                /* will wrap if extra_pad+padlen > 255 */
                    760:                extra_pad  = roundup(extra_pad, block_size);
                    761:                pad = extra_pad - ((len + padlen) % extra_pad);
1.93      markus    762:                debug3("packet_send2: adding %d (len %d padlen %d extra_pad %d)",
1.71      markus    763:                    pad, len, padlen, extra_pad);
                    764:                padlen += pad;
                    765:                extra_pad = 0;
                    766:        }
1.76      stevesk   767:        cp = buffer_append_space(&outgoing_packet, padlen);
1.88      markus    768:        if (enc && !send_context.plaintext) {
1.32      markus    769:                /* random padding */
1.25      markus    770:                for (i = 0; i < padlen; i++) {
                    771:                        if (i % 4 == 0)
1.115     avsm      772:                                rnd = arc4random();
                    773:                        cp[i] = rnd & 0xff;
                    774:                        rnd >>= 8;
1.25      markus    775:                }
1.32      markus    776:        } else {
                    777:                /* clear padding */
                    778:                memset(cp, 0, padlen);
1.25      markus    779:        }
                    780:        /* packet_length includes payload, padding and padding length field */
                    781:        packet_length = buffer_len(&outgoing_packet) - 4;
1.89      markus    782:        cp = buffer_ptr(&outgoing_packet);
1.131     djm       783:        put_u32(cp, packet_length);
1.89      markus    784:        cp[4] = padlen;
1.25      markus    785:        DBG(debug("send: len %d (includes padlen %d)", packet_length+4, padlen));
                    786:
                    787:        /* compute MAC over seqnr and packet(length fields, payload, padding) */
                    788:        if (mac && mac->enabled) {
1.105     markus    789:                macbuf = mac_compute(mac, p_send.seqnr,
1.83      stevesk   790:                    buffer_ptr(&outgoing_packet),
1.50      markus    791:                    buffer_len(&outgoing_packet));
1.105     markus    792:                DBG(debug("done calc MAC out #%d", p_send.seqnr));
1.25      markus    793:        }
                    794:        /* encrypt packet and append to output buffer. */
1.76      stevesk   795:        cp = buffer_append_space(&output, buffer_len(&outgoing_packet));
1.88      markus    796:        cipher_crypt(&send_context, cp, buffer_ptr(&outgoing_packet),
1.25      markus    797:            buffer_len(&outgoing_packet));
                    798:        /* append unencrypted MAC */
                    799:        if (mac && mac->enabled)
1.130     deraadt   800:                buffer_append(&output, macbuf, mac->mac_len);
1.25      markus    801: #ifdef PACKET_DEBUG
                    802:        fprintf(stderr, "encrypted: ");
                    803:        buffer_dump(&output);
                    804: #endif
1.29      markus    805:        /* increment sequence number for outgoing packets */
1.105     markus    806:        if (++p_send.seqnr == 0)
1.106     itojun    807:                logit("outgoing seqnr wraps around");
1.105     markus    808:        if (++p_send.packets == 0)
                    809:                if (!(datafellows & SSH_BUG_NOREKEY))
                    810:                        fatal("XXX too many packets with same key");
                    811:        p_send.blocks += (packet_length + 4) / block_size;
1.25      markus    812:        buffer_clear(&outgoing_packet);
                    813:
1.57      markus    814:        if (type == SSH2_MSG_NEWKEYS)
                    815:                set_newkeys(MODE_OUT);
1.118     markus    816:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && server_side)
                    817:                packet_enable_delayed_compress();
1.25      markus    818: }
                    819:
1.105     markus    820: static void
                    821: packet_send2(void)
                    822: {
                    823:        static int rekeying = 0;
                    824:        struct packet *p;
                    825:        u_char type, *cp;
                    826:
                    827:        cp = buffer_ptr(&outgoing_packet);
                    828:        type = cp[5];
                    829:
                    830:        /* during rekeying we can only send key exchange messages */
                    831:        if (rekeying) {
                    832:                if (!((type >= SSH2_MSG_TRANSPORT_MIN) &&
                    833:                    (type <= SSH2_MSG_TRANSPORT_MAX))) {
                    834:                        debug("enqueue packet: %u", type);
                    835:                        p = xmalloc(sizeof(*p));
                    836:                        p->type = type;
                    837:                        memcpy(&p->payload, &outgoing_packet, sizeof(Buffer));
                    838:                        buffer_init(&outgoing_packet);
                    839:                        TAILQ_INSERT_TAIL(&outgoing, p, next);
                    840:                        return;
                    841:                }
                    842:        }
                    843:
                    844:        /* rekeying starts with sending KEXINIT */
                    845:        if (type == SSH2_MSG_KEXINIT)
                    846:                rekeying = 1;
                    847:
                    848:        packet_send2_wrapped();
                    849:
                    850:        /* after a NEWKEYS message we can send the complete queue */
                    851:        if (type == SSH2_MSG_NEWKEYS) {
                    852:                rekeying = 0;
                    853:                while ((p = TAILQ_FIRST(&outgoing))) {
                    854:                        type = p->type;
                    855:                        debug("dequeue packet: %u", type);
                    856:                        buffer_free(&outgoing_packet);
                    857:                        memcpy(&outgoing_packet, &p->payload,
                    858:                            sizeof(Buffer));
                    859:                        TAILQ_REMOVE(&outgoing, p, next);
                    860:                        xfree(p);
                    861:                        packet_send2_wrapped();
                    862:                }
                    863:        }
                    864: }
                    865:
1.25      markus    866: void
1.73      itojun    867: packet_send(void)
1.25      markus    868: {
1.62      markus    869:        if (compat20)
1.25      markus    870:                packet_send2();
                    871:        else
                    872:                packet_send1();
                    873:        DBG(debug("packet_send done"));
                    874: }
                    875:
                    876: /*
1.16      markus    877:  * Waits until a packet has been received, and returns its type.  Note that
                    878:  * no other data is processed until this returns, so this function should not
                    879:  * be used during the interactive session.
                    880:  */
1.1       deraadt   881:
1.2       provos    882: int
1.82      markus    883: packet_read_seqnr(u_int32_t *seqnr_p)
1.1       deraadt   884: {
1.14      markus    885:        int type, len;
1.56      millert   886:        fd_set *setp;
1.14      markus    887:        char buf[8192];
1.25      markus    888:        DBG(debug("packet_read()"));
1.14      markus    889:
1.127     djm       890:        setp = (fd_set *)xcalloc(howmany(connection_in+1, NFDBITS),
1.56      millert   891:            sizeof(fd_mask));
                    892:
1.14      markus    893:        /* Since we are blocking, ensure that all written packets have been sent. */
                    894:        packet_write_wait();
                    895:
                    896:        /* Stay in the loop until we have received a complete packet. */
                    897:        for (;;) {
                    898:                /* Try to read a packet from the buffer. */
1.82      markus    899:                type = packet_read_poll_seqnr(seqnr_p);
1.62      markus    900:                if (!compat20 && (
1.32      markus    901:                    type == SSH_SMSG_SUCCESS
1.14      markus    902:                    || type == SSH_SMSG_FAILURE
                    903:                    || type == SSH_CMSG_EOF
1.32      markus    904:                    || type == SSH_CMSG_EXIT_CONFIRMATION))
1.79      markus    905:                        packet_check_eom();
1.14      markus    906:                /* If we got a packet, return it. */
1.56      millert   907:                if (type != SSH_MSG_NONE) {
                    908:                        xfree(setp);
1.14      markus    909:                        return type;
1.56      millert   910:                }
1.16      markus    911:                /*
                    912:                 * Otherwise, wait for some data to arrive, add it to the
                    913:                 * buffer, and try again.
                    914:                 */
1.56      millert   915:                memset(setp, 0, howmany(connection_in + 1, NFDBITS) *
                    916:                    sizeof(fd_mask));
                    917:                FD_SET(connection_in, setp);
1.16      markus    918:
1.14      markus    919:                /* Wait for some data to arrive. */
1.56      millert   920:                while (select(connection_in + 1, setp, NULL, NULL, NULL) == -1 &&
1.51      deraadt   921:                    (errno == EAGAIN || errno == EINTR))
                    922:                        ;
1.16      markus    923:
1.14      markus    924:                /* Read data from the socket. */
                    925:                len = read(connection_in, buf, sizeof(buf));
1.18      markus    926:                if (len == 0) {
1.106     itojun    927:                        logit("Connection closed by %.200s", get_remote_ipaddr());
1.112     markus    928:                        cleanup_exit(255);
1.18      markus    929:                }
1.14      markus    930:                if (len < 0)
                    931:                        fatal("Read from socket failed: %.100s", strerror(errno));
                    932:                /* Append it to the buffer. */
                    933:                packet_process_incoming(buf, len);
                    934:        }
                    935:        /* NOTREACHED */
1.1       deraadt   936: }
                    937:
1.77      djm       938: int
1.82      markus    939: packet_read(void)
1.77      djm       940: {
1.82      markus    941:        return packet_read_seqnr(NULL);
1.77      djm       942: }
                    943:
1.16      markus    944: /*
                    945:  * Waits until a packet has been received, verifies that its type matches
                    946:  * that given, and gives a fatal error and exits if there is a mismatch.
                    947:  */
1.1       deraadt   948:
1.2       provos    949: void
1.82      markus    950: packet_read_expect(int expected_type)
1.1       deraadt   951: {
1.14      markus    952:        int type;
1.1       deraadt   953:
1.82      markus    954:        type = packet_read();
1.14      markus    955:        if (type != expected_type)
                    956:                packet_disconnect("Protocol error: expected packet type %d, got %d",
1.25      markus    957:                    expected_type, type);
1.1       deraadt   958: }
                    959:
                    960: /* Checks if a full packet is available in the data received so far via
1.14      markus    961:  * packet_process_incoming.  If so, reads the packet; otherwise returns
                    962:  * SSH_MSG_NONE.  This does not wait for data from the connection.
                    963:  *
1.150     dtucker   964:  * SSH_MSG_DISCONNECT is handled specially here.  Also,
                    965:  * SSH_MSG_IGNORE messages are skipped by this function and are never returned
                    966:  * to higher levels.
1.14      markus    967:  */
1.1       deraadt   968:
1.68      itojun    969: static int
1.82      markus    970: packet_read_poll1(void)
1.1       deraadt   971: {
1.40      markus    972:        u_int len, padded_len;
1.89      markus    973:        u_char *cp, type;
1.40      markus    974:        u_int checksum, stored_checksum;
1.14      markus    975:
                    976:        /* Check if input size is less than minimum packet size. */
                    977:        if (buffer_len(&input) < 4 + 8)
                    978:                return SSH_MSG_NONE;
                    979:        /* Get length of incoming packet. */
1.89      markus    980:        cp = buffer_ptr(&input);
1.131     djm       981:        len = get_u32(cp);
1.14      markus    982:        if (len < 1 + 2 + 2 || len > 256 * 1024)
1.98      markus    983:                packet_disconnect("Bad packet length %u.", len);
1.14      markus    984:        padded_len = (len + 8) & ~7;
                    985:
                    986:        /* Check if the packet has been entirely received. */
                    987:        if (buffer_len(&input) < 4 + padded_len)
                    988:                return SSH_MSG_NONE;
                    989:
                    990:        /* The entire packet is in buffer. */
                    991:
                    992:        /* Consume packet length. */
                    993:        buffer_consume(&input, 4);
                    994:
1.62      markus    995:        /*
                    996:         * Cryptographic attack detector for ssh
                    997:         * (C)1998 CORE-SDI, Buenos Aires Argentina
                    998:         * Ariel Futoransky(futo@core-sdi.com)
                    999:         */
1.144     djm      1000:        if (!receive_context.plaintext) {
                   1001:                switch (detect_attack(buffer_ptr(&input), padded_len)) {
                   1002:                case DEATTACK_DETECTED:
                   1003:                        packet_disconnect("crc32 compensation attack: "
                   1004:                            "network attack detected");
                   1005:                case DEATTACK_DOS_DETECTED:
                   1006:                        packet_disconnect("deattack denial of "
                   1007:                            "service detected");
                   1008:                }
                   1009:        }
1.62      markus   1010:
                   1011:        /* Decrypt data to incoming_packet. */
1.14      markus   1012:        buffer_clear(&incoming_packet);
1.76      stevesk  1013:        cp = buffer_append_space(&incoming_packet, padded_len);
1.88      markus   1014:        cipher_crypt(&receive_context, cp, buffer_ptr(&input), padded_len);
1.62      markus   1015:
1.14      markus   1016:        buffer_consume(&input, padded_len);
1.1       deraadt  1017:
                   1018: #ifdef PACKET_DEBUG
1.14      markus   1019:        fprintf(stderr, "read_poll plain: ");
                   1020:        buffer_dump(&incoming_packet);
1.1       deraadt  1021: #endif
                   1022:
1.14      markus   1023:        /* Compute packet checksum. */
1.83      stevesk  1024:        checksum = ssh_crc32(buffer_ptr(&incoming_packet),
1.25      markus   1025:            buffer_len(&incoming_packet) - 4);
1.14      markus   1026:
                   1027:        /* Skip padding. */
                   1028:        buffer_consume(&incoming_packet, 8 - len % 8);
                   1029:
                   1030:        /* Test check bytes. */
                   1031:        if (len != buffer_len(&incoming_packet))
1.77      djm      1032:                packet_disconnect("packet_read_poll1: len %d != buffer_len %d.",
1.25      markus   1033:                    len, buffer_len(&incoming_packet));
1.14      markus   1034:
1.89      markus   1035:        cp = (u_char *)buffer_ptr(&incoming_packet) + len - 4;
1.131     djm      1036:        stored_checksum = get_u32(cp);
1.14      markus   1037:        if (checksum != stored_checksum)
                   1038:                packet_disconnect("Corrupted check bytes on input.");
                   1039:        buffer_consume_end(&incoming_packet, 4);
                   1040:
                   1041:        if (packet_compression) {
                   1042:                buffer_clear(&compression_buffer);
                   1043:                buffer_uncompress(&incoming_packet, &compression_buffer);
                   1044:                buffer_clear(&incoming_packet);
                   1045:                buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
1.25      markus   1046:                    buffer_len(&compression_buffer));
1.14      markus   1047:        }
1.62      markus   1048:        type = buffer_get_char(&incoming_packet);
1.116     markus   1049:        if (type < SSH_MSG_MIN || type > SSH_MSG_MAX)
                   1050:                packet_disconnect("Invalid ssh1 packet type: %d", type);
1.62      markus   1051:        return type;
1.1       deraadt  1052: }
1.14      markus   1053:
1.68      itojun   1054: static int
1.82      markus   1055: packet_read_poll2(u_int32_t *seqnr_p)
1.25      markus   1056: {
1.50      markus   1057:        static u_int packet_length = 0;
1.40      markus   1058:        u_int padlen, need;
1.89      markus   1059:        u_char *macbuf, *cp, type;
1.117     djm      1060:        u_int maclen, block_size;
1.25      markus   1061:        Enc *enc   = NULL;
                   1062:        Mac *mac   = NULL;
                   1063:        Comp *comp = NULL;
                   1064:
1.57      markus   1065:        if (newkeys[MODE_IN] != NULL) {
                   1066:                enc  = &newkeys[MODE_IN]->enc;
                   1067:                mac  = &newkeys[MODE_IN]->mac;
                   1068:                comp = &newkeys[MODE_IN]->comp;
1.25      markus   1069:        }
                   1070:        maclen = mac && mac->enabled ? mac->mac_len : 0;
1.88      markus   1071:        block_size = enc ? enc->block_size : 8;
1.25      markus   1072:
                   1073:        if (packet_length == 0) {
                   1074:                /*
                   1075:                 * check if input size is less than the cipher block size,
                   1076:                 * decrypt first block and extract length of incoming packet
                   1077:                 */
                   1078:                if (buffer_len(&input) < block_size)
                   1079:                        return SSH_MSG_NONE;
                   1080:                buffer_clear(&incoming_packet);
1.76      stevesk  1081:                cp = buffer_append_space(&incoming_packet, block_size);
1.88      markus   1082:                cipher_crypt(&receive_context, cp, buffer_ptr(&input),
1.25      markus   1083:                    block_size);
1.89      markus   1084:                cp = buffer_ptr(&incoming_packet);
1.131     djm      1085:                packet_length = get_u32(cp);
1.25      markus   1086:                if (packet_length < 1 + 4 || packet_length > 256 * 1024) {
1.110     markus   1087: #ifdef PACKET_DEBUG
1.25      markus   1088:                        buffer_dump(&incoming_packet);
1.110     markus   1089: #endif
1.98      markus   1090:                        packet_disconnect("Bad packet length %u.", packet_length);
1.25      markus   1091:                }
1.98      markus   1092:                DBG(debug("input: packet len %u", packet_length+4));
1.25      markus   1093:                buffer_consume(&input, block_size);
                   1094:        }
                   1095:        /* we have a partial packet of block_size bytes */
                   1096:        need = 4 + packet_length - block_size;
                   1097:        DBG(debug("partial packet %d, need %d, maclen %d", block_size,
                   1098:            need, maclen));
                   1099:        if (need % block_size != 0)
                   1100:                fatal("padding error: need %d block %d mod %d",
                   1101:                    need, block_size, need % block_size);
                   1102:        /*
                   1103:         * check if the entire packet has been received and
                   1104:         * decrypt into incoming_packet
                   1105:         */
                   1106:        if (buffer_len(&input) < need + maclen)
                   1107:                return SSH_MSG_NONE;
                   1108: #ifdef PACKET_DEBUG
                   1109:        fprintf(stderr, "read_poll enc/full: ");
                   1110:        buffer_dump(&input);
                   1111: #endif
1.76      stevesk  1112:        cp = buffer_append_space(&incoming_packet, need);
1.88      markus   1113:        cipher_crypt(&receive_context, cp, buffer_ptr(&input), need);
1.25      markus   1114:        buffer_consume(&input, need);
                   1115:        /*
                   1116:         * compute MAC over seqnr and packet,
                   1117:         * increment sequence number for incoming packet
                   1118:         */
1.29      markus   1119:        if (mac && mac->enabled) {
1.105     markus   1120:                macbuf = mac_compute(mac, p_read.seqnr,
1.83      stevesk  1121:                    buffer_ptr(&incoming_packet),
1.50      markus   1122:                    buffer_len(&incoming_packet));
1.25      markus   1123:                if (memcmp(macbuf, buffer_ptr(&input), mac->mac_len) != 0)
1.36      markus   1124:                        packet_disconnect("Corrupted MAC on input.");
1.105     markus   1125:                DBG(debug("MAC #%d ok", p_read.seqnr));
1.25      markus   1126:                buffer_consume(&input, mac->mac_len);
                   1127:        }
1.77      djm      1128:        if (seqnr_p != NULL)
1.105     markus   1129:                *seqnr_p = p_read.seqnr;
                   1130:        if (++p_read.seqnr == 0)
1.106     itojun   1131:                logit("incoming seqnr wraps around");
1.105     markus   1132:        if (++p_read.packets == 0)
                   1133:                if (!(datafellows & SSH_BUG_NOREKEY))
                   1134:                        fatal("XXX too many packets with same key");
                   1135:        p_read.blocks += (packet_length + 4) / block_size;
1.25      markus   1136:
                   1137:        /* get padlen */
1.76      stevesk  1138:        cp = buffer_ptr(&incoming_packet);
1.89      markus   1139:        padlen = cp[4];
1.25      markus   1140:        DBG(debug("input: padlen %d", padlen));
                   1141:        if (padlen < 4)
                   1142:                packet_disconnect("Corrupted padlen %d on input.", padlen);
                   1143:
                   1144:        /* skip packet size + padlen, discard padding */
                   1145:        buffer_consume(&incoming_packet, 4 + 1);
                   1146:        buffer_consume_end(&incoming_packet, padlen);
                   1147:
                   1148:        DBG(debug("input: len before de-compress %d", buffer_len(&incoming_packet)));
                   1149:        if (comp && comp->enabled) {
                   1150:                buffer_clear(&compression_buffer);
                   1151:                buffer_uncompress(&incoming_packet, &compression_buffer);
                   1152:                buffer_clear(&incoming_packet);
                   1153:                buffer_append(&incoming_packet, buffer_ptr(&compression_buffer),
                   1154:                    buffer_len(&compression_buffer));
1.97      deraadt  1155:                DBG(debug("input: len after de-compress %d",
                   1156:                    buffer_len(&incoming_packet)));
1.25      markus   1157:        }
                   1158:        /*
                   1159:         * get packet type, implies consume.
                   1160:         * return length of payload (without type field)
                   1161:         */
1.62      markus   1162:        type = buffer_get_char(&incoming_packet);
1.116     markus   1163:        if (type < SSH2_MSG_MIN || type >= SSH2_MSG_LOCAL_MIN)
                   1164:                packet_disconnect("Invalid ssh2 packet type: %d", type);
1.57      markus   1165:        if (type == SSH2_MSG_NEWKEYS)
                   1166:                set_newkeys(MODE_IN);
1.118     markus   1167:        else if (type == SSH2_MSG_USERAUTH_SUCCESS && !server_side)
                   1168:                packet_enable_delayed_compress();
1.25      markus   1169: #ifdef PACKET_DEBUG
1.55      deraadt  1170:        fprintf(stderr, "read/plain[%d]:\r\n", type);
1.25      markus   1171:        buffer_dump(&incoming_packet);
                   1172: #endif
1.62      markus   1173:        /* reset for next packet */
                   1174:        packet_length = 0;
                   1175:        return type;
1.25      markus   1176: }
                   1177:
                   1178: int
1.82      markus   1179: packet_read_poll_seqnr(u_int32_t *seqnr_p)
1.25      markus   1180: {
1.96      deraadt  1181:        u_int reason, seqnr;
1.62      markus   1182:        u_char type;
1.25      markus   1183:        char *msg;
1.62      markus   1184:
1.25      markus   1185:        for (;;) {
1.62      markus   1186:                if (compat20) {
1.82      markus   1187:                        type = packet_read_poll2(seqnr_p);
1.153   ! djm      1188:                        if (type) {
        !          1189:                                keep_alive_timeouts = 0;
1.25      markus   1190:                                DBG(debug("received packet type %d", type));
1.153   ! djm      1191:                        }
1.74      deraadt  1192:                        switch (type) {
1.150     dtucker  1193:                        case SSH2_MSG_IGNORE:
1.151     dtucker  1194:                                debug3("Received SSH2_MSG_IGNORE");
1.150     dtucker  1195:                                break;
1.25      markus   1196:                        case SSH2_MSG_DEBUG:
                   1197:                                packet_get_char();
                   1198:                                msg = packet_get_string(NULL);
                   1199:                                debug("Remote: %.900s", msg);
                   1200:                                xfree(msg);
                   1201:                                msg = packet_get_string(NULL);
                   1202:                                xfree(msg);
                   1203:                                break;
                   1204:                        case SSH2_MSG_DISCONNECT:
                   1205:                                reason = packet_get_int();
                   1206:                                msg = packet_get_string(NULL);
1.106     itojun   1207:                                logit("Received disconnect from %s: %u: %.400s",
1.96      deraadt  1208:                                    get_remote_ipaddr(), reason, msg);
1.25      markus   1209:                                xfree(msg);
1.112     markus   1210:                                cleanup_exit(255);
1.84      markus   1211:                                break;
                   1212:                        case SSH2_MSG_UNIMPLEMENTED:
                   1213:                                seqnr = packet_get_int();
1.96      deraadt  1214:                                debug("Received SSH2_MSG_UNIMPLEMENTED for %u",
                   1215:                                    seqnr);
1.150     dtucker  1216:                                break;
1.25      markus   1217:                        default:
                   1218:                                return type;
1.48      stevesk  1219:                        }
1.25      markus   1220:                } else {
1.82      markus   1221:                        type = packet_read_poll1();
1.74      deraadt  1222:                        switch (type) {
1.25      markus   1223:                        case SSH_MSG_IGNORE:
                   1224:                                break;
                   1225:                        case SSH_MSG_DEBUG:
                   1226:                                msg = packet_get_string(NULL);
                   1227:                                debug("Remote: %.900s", msg);
                   1228:                                xfree(msg);
                   1229:                                break;
                   1230:                        case SSH_MSG_DISCONNECT:
                   1231:                                msg = packet_get_string(NULL);
1.106     itojun   1232:                                logit("Received disconnect from %s: %.400s",
1.96      deraadt  1233:                                    get_remote_ipaddr(), msg);
1.112     markus   1234:                                cleanup_exit(255);
1.25      markus   1235:                                break;
                   1236:                        default:
1.62      markus   1237:                                if (type)
1.25      markus   1238:                                        DBG(debug("received packet type %d", type));
                   1239:                                return type;
1.48      stevesk  1240:                        }
1.25      markus   1241:                }
                   1242:        }
1.77      djm      1243: }
                   1244:
                   1245: int
1.82      markus   1246: packet_read_poll(void)
1.77      djm      1247: {
1.82      markus   1248:        return packet_read_poll_seqnr(NULL);
1.25      markus   1249: }
                   1250:
1.16      markus   1251: /*
                   1252:  * Buffers the given amount of input characters.  This is intended to be used
                   1253:  * together with packet_read_poll.
                   1254:  */
1.1       deraadt  1255:
1.2       provos   1256: void
1.40      markus   1257: packet_process_incoming(const char *buf, u_int len)
1.1       deraadt  1258: {
1.14      markus   1259:        buffer_append(&input, buf, len);
1.1       deraadt  1260: }
                   1261:
                   1262: /* Returns a character from the packet. */
                   1263:
1.40      markus   1264: u_int
1.73      itojun   1265: packet_get_char(void)
1.1       deraadt  1266: {
1.14      markus   1267:        char ch;
1.97      deraadt  1268:
1.14      markus   1269:        buffer_get(&incoming_packet, &ch, 1);
1.40      markus   1270:        return (u_char) ch;
1.1       deraadt  1271: }
                   1272:
                   1273: /* Returns an integer from the packet data. */
                   1274:
1.40      markus   1275: u_int
1.73      itojun   1276: packet_get_int(void)
1.1       deraadt  1277: {
1.14      markus   1278:        return buffer_get_int(&incoming_packet);
1.1       deraadt  1279: }
                   1280:
1.16      markus   1281: /*
                   1282:  * Returns an arbitrary precision integer from the packet data.  The integer
                   1283:  * must have been initialized before this call.
                   1284:  */
1.1       deraadt  1285:
1.2       provos   1286: void
1.80      markus   1287: packet_get_bignum(BIGNUM * value)
1.1       deraadt  1288: {
1.81      markus   1289:        buffer_get_bignum(&incoming_packet, value);
1.24      markus   1290: }
                   1291:
                   1292: void
1.80      markus   1293: packet_get_bignum2(BIGNUM * value)
1.24      markus   1294: {
1.81      markus   1295:        buffer_get_bignum2(&incoming_packet, value);
1.24      markus   1296: }
                   1297:
1.76      stevesk  1298: void *
1.117     djm      1299: packet_get_raw(u_int *length_ptr)
1.24      markus   1300: {
1.117     djm      1301:        u_int bytes = buffer_len(&incoming_packet);
1.97      deraadt  1302:
1.24      markus   1303:        if (length_ptr != NULL)
                   1304:                *length_ptr = bytes;
                   1305:        return buffer_ptr(&incoming_packet);
1.28      markus   1306: }
                   1307:
                   1308: int
                   1309: packet_remaining(void)
                   1310: {
                   1311:        return buffer_len(&incoming_packet);
1.1       deraadt  1312: }
                   1313:
1.16      markus   1314: /*
                   1315:  * Returns a string from the packet data.  The string is allocated using
                   1316:  * xmalloc; it is the responsibility of the calling program to free it when
                   1317:  * no longer needed.  The length_ptr argument may be NULL, or point to an
                   1318:  * integer into which the length of the string is stored.
                   1319:  */
1.1       deraadt  1320:
1.76      stevesk  1321: void *
1.40      markus   1322: packet_get_string(u_int *length_ptr)
1.1       deraadt  1323: {
1.14      markus   1324:        return buffer_get_string(&incoming_packet, length_ptr);
1.152     markus   1325: }
                   1326:
                   1327: void *
                   1328: packet_get_string_ptr(u_int *length_ptr)
                   1329: {
                   1330:        return buffer_get_string_ptr(&incoming_packet, length_ptr);
1.1       deraadt  1331: }
                   1332:
1.16      markus   1333: /*
                   1334:  * Sends a diagnostic message from the server to the client.  This message
                   1335:  * can be sent at any time (but not while constructing another message). The
                   1336:  * message is printed immediately, but only if the client is being executed
                   1337:  * in verbose mode.  These messages are primarily intended to ease debugging
                   1338:  * authentication problems.   The length of the formatted message must not
                   1339:  * exceed 1024 bytes.  This will automatically call packet_write_wait.
                   1340:  */
1.1       deraadt  1341:
1.2       provos   1342: void
1.14      markus   1343: packet_send_debug(const char *fmt,...)
1.1       deraadt  1344: {
1.14      markus   1345:        char buf[1024];
                   1346:        va_list args;
1.39      markus   1347:
                   1348:        if (compat20 && (datafellows & SSH_BUG_DEBUG))
                   1349:                return;
1.14      markus   1350:
                   1351:        va_start(args, fmt);
                   1352:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1353:        va_end(args);
                   1354:
1.30      markus   1355:        if (compat20) {
                   1356:                packet_start(SSH2_MSG_DEBUG);
                   1357:                packet_put_char(0);     /* bool: always display */
                   1358:                packet_put_cstring(buf);
                   1359:                packet_put_cstring("");
                   1360:        } else {
                   1361:                packet_start(SSH_MSG_DEBUG);
                   1362:                packet_put_cstring(buf);
                   1363:        }
1.14      markus   1364:        packet_send();
                   1365:        packet_write_wait();
1.1       deraadt  1366: }
                   1367:
1.16      markus   1368: /*
                   1369:  * Logs the error plus constructs and sends a disconnect packet, closes the
                   1370:  * connection, and exits.  This function never returns. The error message
                   1371:  * should not contain a newline.  The length of the formatted message must
                   1372:  * not exceed 1024 bytes.
                   1373:  */
1.1       deraadt  1374:
1.2       provos   1375: void
1.14      markus   1376: packet_disconnect(const char *fmt,...)
1.1       deraadt  1377: {
1.14      markus   1378:        char buf[1024];
                   1379:        va_list args;
                   1380:        static int disconnecting = 0;
1.97      deraadt  1381:
1.14      markus   1382:        if (disconnecting)      /* Guard against recursive invocations. */
                   1383:                fatal("packet_disconnect called recursively.");
                   1384:        disconnecting = 1;
                   1385:
1.16      markus   1386:        /*
                   1387:         * Format the message.  Note that the caller must make sure the
                   1388:         * message is of limited size.
                   1389:         */
1.14      markus   1390:        va_start(args, fmt);
                   1391:        vsnprintf(buf, sizeof(buf), fmt, args);
                   1392:        va_end(args);
                   1393:
1.99      markus   1394:        /* Display the error locally */
1.106     itojun   1395:        logit("Disconnecting: %.100s", buf);
1.99      markus   1396:
1.14      markus   1397:        /* Send the disconnect message to the other side, and wait for it to get sent. */
1.25      markus   1398:        if (compat20) {
                   1399:                packet_start(SSH2_MSG_DISCONNECT);
                   1400:                packet_put_int(SSH2_DISCONNECT_PROTOCOL_ERROR);
                   1401:                packet_put_cstring(buf);
                   1402:                packet_put_cstring("");
                   1403:        } else {
                   1404:                packet_start(SSH_MSG_DISCONNECT);
1.65      markus   1405:                packet_put_cstring(buf);
1.25      markus   1406:        }
1.14      markus   1407:        packet_send();
                   1408:        packet_write_wait();
                   1409:
                   1410:        /* Stop listening for connections. */
1.67      markus   1411:        channel_close_all();
1.14      markus   1412:
                   1413:        /* Close the connection. */
                   1414:        packet_close();
1.112     markus   1415:        cleanup_exit(255);
1.1       deraadt  1416: }
                   1417:
1.16      markus   1418: /* Checks if there is any buffered output, and tries to write some of the output. */
1.1       deraadt  1419:
1.2       provos   1420: void
1.73      itojun   1421: packet_write_poll(void)
1.1       deraadt  1422: {
1.14      markus   1423:        int len = buffer_len(&output);
1.97      deraadt  1424:
1.14      markus   1425:        if (len > 0) {
                   1426:                len = write(connection_out, buffer_ptr(&output), len);
                   1427:                if (len <= 0) {
                   1428:                        if (errno == EAGAIN)
                   1429:                                return;
                   1430:                        else
                   1431:                                fatal("Write failed: %.100s", strerror(errno));
                   1432:                }
                   1433:                buffer_consume(&output, len);
                   1434:        }
1.1       deraadt  1435: }
                   1436:
1.16      markus   1437: /*
                   1438:  * Calls packet_write_poll repeatedly until all pending output data has been
                   1439:  * written.
                   1440:  */
1.1       deraadt  1441:
1.2       provos   1442: void
1.73      itojun   1443: packet_write_wait(void)
1.1       deraadt  1444: {
1.56      millert  1445:        fd_set *setp;
                   1446:
1.127     djm      1447:        setp = (fd_set *)xcalloc(howmany(connection_out + 1, NFDBITS),
1.56      millert  1448:            sizeof(fd_mask));
1.14      markus   1449:        packet_write_poll();
                   1450:        while (packet_have_data_to_write()) {
1.56      millert  1451:                memset(setp, 0, howmany(connection_out + 1, NFDBITS) *
                   1452:                    sizeof(fd_mask));
                   1453:                FD_SET(connection_out, setp);
                   1454:                while (select(connection_out + 1, NULL, setp, NULL, NULL) == -1 &&
1.51      deraadt  1455:                    (errno == EAGAIN || errno == EINTR))
                   1456:                        ;
1.14      markus   1457:                packet_write_poll();
                   1458:        }
1.56      millert  1459:        xfree(setp);
1.1       deraadt  1460: }
                   1461:
                   1462: /* Returns true if there is buffered data to write to the connection. */
                   1463:
1.2       provos   1464: int
1.73      itojun   1465: packet_have_data_to_write(void)
1.1       deraadt  1466: {
1.14      markus   1467:        return buffer_len(&output) != 0;
1.1       deraadt  1468: }
                   1469:
                   1470: /* Returns true if there is not too much data to write to the connection. */
                   1471:
1.2       provos   1472: int
1.73      itojun   1473: packet_not_very_much_data_to_write(void)
1.1       deraadt  1474: {
1.14      markus   1475:        if (interactive_mode)
                   1476:                return buffer_len(&output) < 16384;
                   1477:        else
                   1478:                return buffer_len(&output) < 128 * 1024;
1.1       deraadt  1479: }
                   1480:
1.102     markus   1481: static void
1.101     markus   1482: packet_set_tos(int interactive)
                   1483: {
                   1484:        int tos = interactive ? IPTOS_LOWDELAY : IPTOS_THROUGHPUT;
                   1485:
                   1486:        if (!packet_connection_is_on_socket() ||
                   1487:            !packet_connection_is_ipv4())
                   1488:                return;
                   1489:        if (setsockopt(connection_in, IPPROTO_IP, IP_TOS, &tos,
                   1490:            sizeof(tos)) < 0)
                   1491:                error("setsockopt IP_TOS %d: %.100s:",
                   1492:                    tos, strerror(errno));
                   1493: }
                   1494:
1.1       deraadt  1495: /* Informs that the current session is interactive.  Sets IP flags for that. */
                   1496:
1.2       provos   1497: void
1.43      markus   1498: packet_set_interactive(int interactive)
1.1       deraadt  1499: {
1.43      markus   1500:        static int called = 0;
1.44      markus   1501:
1.43      markus   1502:        if (called)
                   1503:                return;
                   1504:        called = 1;
1.1       deraadt  1505:
1.14      markus   1506:        /* Record that we are in interactive mode. */
                   1507:        interactive_mode = interactive;
1.1       deraadt  1508:
1.19      markus   1509:        /* Only set socket options if using a socket.  */
                   1510:        if (!packet_connection_is_on_socket())
1.14      markus   1511:                return;
1.122     dtucker  1512:        set_nodelay(connection_in);
1.101     markus   1513:        packet_set_tos(interactive);
1.1       deraadt  1514: }
                   1515:
                   1516: /* Returns true if the current connection is interactive. */
                   1517:
1.2       provos   1518: int
1.73      itojun   1519: packet_is_interactive(void)
1.1       deraadt  1520: {
1.14      markus   1521:        return interactive_mode;
1.12      markus   1522: }
                   1523:
1.113     deraadt  1524: int
1.108     markus   1525: packet_set_maxsize(u_int s)
1.12      markus   1526: {
1.14      markus   1527:        static int called = 0;
1.97      deraadt  1528:
1.14      markus   1529:        if (called) {
1.106     itojun   1530:                logit("packet_set_maxsize: called twice: old %d new %d",
1.25      markus   1531:                    max_packet_size, s);
1.14      markus   1532:                return -1;
                   1533:        }
                   1534:        if (s < 4 * 1024 || s > 1024 * 1024) {
1.106     itojun   1535:                logit("packet_set_maxsize: bad size %d", s);
1.14      markus   1536:                return -1;
                   1537:        }
1.70      markus   1538:        called = 1;
1.66      markus   1539:        debug("packet_set_maxsize: setting to %d", s);
1.14      markus   1540:        max_packet_size = s;
                   1541:        return s;
1.53      markus   1542: }
                   1543:
1.71      markus   1544: /* roundup current message to pad bytes */
                   1545: void
                   1546: packet_add_padding(u_char pad)
                   1547: {
                   1548:        extra_pad = pad;
                   1549: }
                   1550:
1.53      markus   1551: /*
                   1552:  * 9.2.  Ignored Data Message
1.61      markus   1553:  *
1.53      markus   1554:  *   byte      SSH_MSG_IGNORE
                   1555:  *   string    data
1.61      markus   1556:  *
1.53      markus   1557:  * All implementations MUST understand (and ignore) this message at any
                   1558:  * time (after receiving the protocol version). No implementation is
                   1559:  * required to send them. This message can be used as an additional
                   1560:  * protection measure against advanced traffic analysis techniques.
                   1561:  */
1.54      markus   1562: void
                   1563: packet_send_ignore(int nbytes)
                   1564: {
1.115     avsm     1565:        u_int32_t rnd = 0;
1.54      markus   1566:        int i;
                   1567:
                   1568:        packet_start(compat20 ? SSH2_MSG_IGNORE : SSH_MSG_IGNORE);
1.53      markus   1569:        packet_put_int(nbytes);
1.75      deraadt  1570:        for (i = 0; i < nbytes; i++) {
1.53      markus   1571:                if (i % 4 == 0)
1.115     avsm     1572:                        rnd = arc4random();
1.129     deraadt  1573:                packet_put_char((u_char)rnd & 0xff);
1.115     avsm     1574:                rnd >>= 8;
1.53      markus   1575:        }
1.105     markus   1576: }
                   1577:
1.113     deraadt  1578: #define MAX_PACKETS    (1U<<31)
1.105     markus   1579: int
                   1580: packet_need_rekeying(void)
                   1581: {
                   1582:        if (datafellows & SSH_BUG_NOREKEY)
                   1583:                return 0;
                   1584:        return
                   1585:            (p_send.packets > MAX_PACKETS) ||
                   1586:            (p_read.packets > MAX_PACKETS) ||
                   1587:            (max_blocks_out && (p_send.blocks > max_blocks_out)) ||
                   1588:            (max_blocks_in  && (p_read.blocks > max_blocks_in));
                   1589: }
                   1590:
                   1591: void
                   1592: packet_set_rekey_limit(u_int32_t bytes)
                   1593: {
                   1594:        rekey_limit = bytes;
1.118     markus   1595: }
                   1596:
                   1597: void
                   1598: packet_set_server(void)
                   1599: {
                   1600:        server_side = 1;
                   1601: }
                   1602:
                   1603: void
                   1604: packet_set_authenticated(void)
                   1605: {
                   1606:        after_authentication = 1;
1.1       deraadt  1607: }