Exemplo n.º 1
0
        internal void PerformKeyExchange(SSHPacket packet)
        {
            lock (kexlock)
            {
                if (localkex == null)
                {
                    SendKeyExchangeInit();
                }

                SSH2Context context = (SSH2Context)client.Context;

                currentState = TransportProtocolState.PERFORMING_KEYEXCHANGE;

                remotekex = packet.Payload;

                // Ignore the cookie
                packet.Skip(16);

                String remoteKeyExchanges = packet.ReadString();
                String remotePublicKeys   = packet.ReadString();
                String remoteCiphersCS    = packet.ReadString();
                String remoteCiphersSC    = packet.ReadString();
                String remoteHMacCS       = packet.ReadString();
                String remoteHMacSC       = packet.ReadString();


                String cipherCS = SelectNegotiatedComponent(context.SupportedCiphers.List(
                                                                context.PreferredCipherCS), remoteCiphersCS);

                String cipherSC = SelectNegotiatedComponent(context.SupportedCiphers.List(
                                                                context.PreferredCipherSC), remoteCiphersSC);

                Cipher encryption = (Cipher)context.SupportedCiphers.GetInstance(cipherCS);

                Cipher decryption = (Cipher)context.SupportedCiphers.GetInstance(cipherSC);

                String macCS = SelectNegotiatedComponent(context.SupportedMACs.List(
                                                             context.PreferredMacCS), remoteHMacCS);

                String macSC = SelectNegotiatedComponent(context.SupportedMACs.List(
                                                             context.PreferredMacSC), remoteHMacSC);

                SSH2Hmac outgoingMac = (SSH2Hmac)context.SupportedMACs.GetInstance(macCS);

                SSH2Hmac incomingMac = (SSH2Hmac)context.SupportedMACs.GetInstance(macSC);

                // Ignore compression and languages as were not interested in that atm

                // Create a Key Exchange instance
                String kex = SelectNegotiatedComponent(context.SupportedKeyExchanges.List(
                                                           context.PreferredKeyExchange), remoteKeyExchanges);

                String publickey = SelectNegotiatedComponent(context.SupportedPublicKeys.List(
                                                                 context.PreferredPublicKey), remotePublicKeys);

#if DEBUG
                // Output the local settings
                System.Diagnostics.Trace.WriteLine("Local Key exchange settings follow:");
                System.Diagnostics.Trace.WriteLine("Key exchange: " + context.SupportedKeyExchanges.List(
                                                       context.PreferredKeyExchange));
                System.Diagnostics.Trace.WriteLine("Public keys : " + context.SupportedPublicKeys.List(
                                                       context.PreferredPublicKey));
                System.Diagnostics.Trace.WriteLine("Ciphers client->server: " + context.SupportedCiphers.List(
                                                       context.PreferredCipherCS));
                System.Diagnostics.Trace.WriteLine("Ciphers server->client: " + context.SupportedCiphers.List(
                                                       context.PreferredCipherSC));
                System.Diagnostics.Trace.WriteLine("HMAC client->server: " + context.SupportedMACs.List(
                                                       context.PreferredMacCS));
                System.Diagnostics.Trace.WriteLine("HMAC server->client: " + context.SupportedMACs.List(
                                                       context.PreferredMacSC));

                // Output the remote settings
                System.Diagnostics.Trace.WriteLine("Remote Key exchange settings follow:");
                System.Diagnostics.Trace.WriteLine("Key exchange: " + remoteKeyExchanges);
                System.Diagnostics.Trace.WriteLine("Public keys : " + remotePublicKeys);
                System.Diagnostics.Trace.WriteLine("Ciphers client->server: " + remoteCiphersCS);
                System.Diagnostics.Trace.WriteLine("Ciphers server->client: " + remoteCiphersSC);
                System.Diagnostics.Trace.WriteLine("HMAC client->server: " + remoteHMacCS);
                System.Diagnostics.Trace.WriteLine("HMAC server->client: " + remoteHMacSC);

                // Output the selected settigns
                System.Diagnostics.Trace.WriteLine("Selected kex exchange: " + kex);
                System.Diagnostics.Trace.WriteLine("Selected public key: " + publickey);
                System.Diagnostics.Trace.WriteLine("Selected cipher client->server: " + cipherCS);
                System.Diagnostics.Trace.WriteLine("Selected cipher server->client: " + cipherSC);
                System.Diagnostics.Trace.WriteLine("Selected HMAC client->server: " + macCS);
                System.Diagnostics.Trace.WriteLine("Selected HMAC server->client: " + macSC);
#endif
                keyexchange = (SSH2KeyExchange)context.SupportedKeyExchanges.GetInstance(kex);

                keyexchange.Init(this);

                // Perform the key exchange
                keyexchange.PerformClientExchange(client.LocalIdentification,
                                                  client.RemoteIdentification,
                                                  localkex,
                                                  remotekex);

                SSHPublicKey hostkey = (SSHPublicKey)context.SupportedPublicKeys.GetInstance(publickey);

                hostkey.Init(keyexchange.HostKey, 0, keyexchange.HostKey.Length);

                if (context.KnownHosts != null)
                {
                    if (!context.KnownHosts.VerifyHost(transport.Hostname, hostkey))
                    {
                        Disconnect("Host key not accepted", DisconnectionReason.HOST_KEY_NOT_VERIFIABLE);
                        throw new SSHException("The host key was not accepted",
                                               SSHException.CANCELLED_CONNECTION);
                    }
                }

                if (!hostkey.VerifySignature(keyexchange.Signature,
                                             keyexchange.ExchangeHash))
                {
                    Disconnect("The host key signature is invalid",
                               DisconnectionReason.HOST_KEY_NOT_VERIFIABLE);
                    throw new SSHException("The host key signature is invalid",
                                           SSHException.PROTOCOL_VIOLATION);
                }

                if (sessionIdentifier == null)
                {
                    sessionIdentifier = keyexchange.ExchangeHash;
                }

                packet = GetSSHPacket(true);
                packet.WriteByte(SSH_MSG_NEWKEYS);
#if DEBUG
                System.Diagnostics.Trace.WriteLine("Sending SSH_MSG_NEWKEYS");
#endif
                SendMessage(packet);


                encryption.Init(Cipher.ENCRYPT_MODE,
                                MakeSSHKey('A'),
                                MakeSSHKey('C'));

                outgoingCipherLength = encryption.BlockSize;

                outgoingMac.Init(MakeSSHKey('E'));
                outgoingMacLength = outgoingMac.MacLength;

                this.encryption  = encryption;
                this.outgoingMac = outgoingMac;

                do
                {
                    packet = ReadMessage();

                    // Process the transport protocol message, must only be
                    // SSH_MSH_INGORE, SSH_MSG_DEBUG, SSH_MSG_DISCONNECT or SSH_MSG_NEWKEYS
                    if (!ProcessMessage(packet))
                    {
                        Disconnect("Invalid message received during key exchange",
                                   DisconnectionReason.PROTOCOL_ERROR);
                        throw new SSHException(
                                  "Invalid message received during key exchange",
                                  SSHException.PROTOCOL_VIOLATION);
                    }
                }while(packet.MessageID != SSH_MSG_NEWKEYS);

                // Put the incoming components into use
                decryption.Init(Cipher.DECRYPT_MODE,
                                MakeSSHKey('B'),
                                MakeSSHKey('D'));
                incomingCipherLength = decryption.BlockSize;

                incomingMac.Init(MakeSSHKey('F'));
                incomingMacLength = incomingMac.MacLength;

                this.decryption  = decryption;
                this.incomingMac = incomingMac;
                //this.incomingCompression = incomingCompression;

                currentState = TransportProtocolState.CONNECTED;

                FireStateChange(TransportProtocolState.CONNECTED);

                lock (kexqueue)
                {
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Sending queued messages");
#endif
                    for (System.Collections.IEnumerator e = kexqueue.GetEnumerator(); e.MoveNext();)
                    {
                        SendMessage((SSHPacket)e.Current);
                    }

                    kexqueue.Clear();
                }

                // Clean up and reset any parameters
                localkex  = null;
                remotekex = null;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Send a message to the remote side of the connection.
        /// </summary>
        /// <param name="packet"></param>
        /// <param name="returnPayload">Return the unecrypted payload of this packet.</param>
        public byte[]  SendMessage(SSHPacket packet, bool returnPayload)
        {
            byte[] payload = null;

            lock (this)
            {
                if (currentState == TransportProtocolState.PERFORMING_KEYEXCHANGE &&
                    !IsTransportMessage(packet.MessageID))
                {
                    lock (kexqueue)
                    {
                        kexqueue.Add(packet);
                        return(payload);
                    }
                }


                try
                {
                    int padding = 4;

                    // Compress the payload if necersary

                    /*if (outgoingCompression != null)
                     * {
                     *      msgdata = outgoingCompression.compress(msgdata, 0, msgdata.Length);
                     * }*/

                    // Determine the padding length
                    padding += ((outgoingCipherLength - ((packet.Length + padding) % outgoingCipherLength)) % outgoingCipherLength);

                    packet.MoveToPosition(0);
                    // Write the packet length field
                    packet.WriteUINT32(packet.Length - 4 + padding);
                    // Write the padding length
                    packet.WriteByte((byte)padding);

                    // Now skip back up to the end of the packet
                    packet.MoveToEnd();

                    if (returnPayload)
                    {
                        payload = packet.Payload;
                    }

                    // Create some random data for the padding
                    byte[] pad = new byte[padding];
                    rnd.GetBytes(pad);
                    packet.WriteBytes(pad);


                    // Generate the MAC
                    if (outgoingMac != null)
                    {
                        outgoingMac.Generate(outgoingSequence, packet.Array, 0, packet.Length, packet.Array, packet.Length);
                    }

                    // Perfrom encrpytion
                    if (encryption != null)
                    {
                        encryption.Transform(packet.Array, 0, packet.Array, 0, packet.Length);
                    }

                    packet.Skip(outgoingMacLength);
                    outgoingBytes += packet.Length;

                    // Send!
                    packet.WriteToStream(transport.GetStream());

                    outgoingSequence++;
                    numOutgoingBytesSinceKEX += (uint)packet.Length;
                    numOutgoingSSHPacketsSinceKEX++;

                    ReleaseSSHPacket(packet);

                    if (outgoingSequence > 4294967295)
                    {
                        outgoingSequence = 0;
                    }

                    if (numOutgoingBytesSinceKEX >= MAX_NUM_BYTES_BEFORE_REKEY ||
                        numOutgoingSSHPacketsSinceKEX >= MAX_NUM_PACKETS_BEFORE_REKEY)
                    {
                        SendKeyExchangeInit();
                    }
                }
                catch (System.IO.IOException ex)
                {
                    InternalDisconnect();

                    throw new SSHException("Unexpected termination: " + ex.Message, SSHException.UNEXPECTED_TERMINATION);
                }
                catch (System.ObjectDisposedException ex)
                {
                    InternalDisconnect();

                    throw new SSHException("Unexpected terminaton: " + ex.Message,
                                           SSHException.UNEXPECTED_TERMINATION);
                }
            }

            return(payload);
        }
Exemplo n.º 3
0
        internal bool ProcessMessage(SSHPacket packet)
        {
            try
            {
                if (packet.Length < 1)
                {
                    Disconnect("Invalid message received", DisconnectionReason.PROTOCOL_ERROR);
                    throw new SSHException("Invalid transport protocol message", SSHException.INTERNAL_ERROR);
                }

                switch (packet.MessageID)
                {
                case SSH_MSG_DISCONNECT:
                {
                    packet.ReadInt();
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Received SSH_MSG_DISCONNECT: " + packet.ReadString());
#endif
                    InternalDisconnect();
                    throw new SSHException(packet.ReadString(), SSHException.REMOTE_HOST_DISCONNECTED);
                }

                case SSH_MSG_IGNORE:
                {
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Received SSH_MSG_IGNORE");
#endif
                    return(true);
                }

                case SSH_MSG_DEBUG:
                {
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Received SSH_MSG_DEBUG");
                    packet.Skip(1);
                    System.Diagnostics.Trace.WriteLine(packet.ReadString());
#endif
                    return(true);
                }

                case SSH_MSG_NEWKEYS:
                {
                    // This lightweight implemention ignores these messages
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Received SSH_MSG_NEWKEYS");
#endif
                    return(true);
                }

                case SSH_MSG_KEX_INIT:
                {
#if DEBUG
                    System.Diagnostics.Trace.WriteLine("Received SSH_MSG_KEX_INIT");
#endif
                    if (remotekex != null)
                    {
                        Disconnect("Key exchange already in progress!",
                                   DisconnectionReason.PROTOCOL_ERROR);
                        throw new SSHException("Key exchange already in progress!", SSHException.PROTOCOL_VIOLATION);
                    }

                    PerformKeyExchange(packet);

                    return(true);
                }

                default:
                {
                    // Not a transport protocol message
                    return(false);
                }
                }
            }
            catch (System.IO.IOException ex1)
            {
                throw new SSHException(ex1.Message, SSHException.INTERNAL_ERROR);
            }
        }