protected override void ProcessServerHello(HandshakeServerHello serverHello)
        {
            if (_state != HandshakeState.Initial)
            {
                throw new AlertException(AlertDescription.UnexpectedMessage,
                                         "Client hello received at the wrong time");
            }

            if (serverHello.ServerVersion < _minVersion || serverHello.ServerVersion > _maxVersion)
            {
                throw new AlertException(AlertDescription.ProtocolVersion,
                                         "Server version is not acceptable");
            }

            _version = serverHello.ServerVersion;
            _connectionState.ServerRandom = serverHello.Random.GetBytes();
            _cipherSuite = _pluginManager.GetCipherSuite(_version, (ushort)serverHello.CipherSuite);
            if (_cipherSuite == null)
            {
                throw new AlertException(AlertDescription.HandshakeFailure,
                                         "Got incorrect cipher suite from server");
            }

            // TODO: If we resumed our session, set state to WaitForChangeCipherSpec and return

            // Wait for server certificate (server key exchange in case of DH_anon)
            _state = HandshakeState.ReceivedServerHello;
        }
Example #2
0
        public static HandshakeMessage GetInstance(ProtocolVersion version, byte[] data)
        {
            HandshakeMessage ret = null;

            switch ((HandshakeMessageType) data[0]) {
            case HandshakeMessageType.HelloRequest:
                ret = new HandshakeMessage(HandshakeMessageType.HelloRequest, version);
                break;
            case HandshakeMessageType.ClientHello:
                ret = new HandshakeClientHello();
                break;
            case HandshakeMessageType.ServerHello:
                ret = new HandshakeServerHello();
                break;
            case HandshakeMessageType.HelloVerifyRequest:
                ret = new HandshakeMessage(HandshakeMessageType.HelloVerifyRequest, version);
                break;
            case HandshakeMessageType.NewSessionTicket:
                ret = new HandshakeMessage(HandshakeMessageType.NewSessionTicket, version);
                break;
            case HandshakeMessageType.Certificate:
                ret = new HandshakeCertificate(version);
                break;
            case HandshakeMessageType.ServerKeyExchange:
                ret = new HandshakeMessage(HandshakeMessageType.ServerKeyExchange, version);
                break;
            case HandshakeMessageType.CertificateRequest:
                ret = new HandshakeCertificateRequest(version);
                break;
            case HandshakeMessageType.ServerHelloDone:
                ret = new HandshakeMessage(HandshakeMessageType.ServerHelloDone, version);
                break;
            case HandshakeMessageType.CertificateVerify:
                ret = new HandshakeMessage(HandshakeMessageType.CertificateVerify, version);
                break;
            case HandshakeMessageType.ClientKeyExchange:
                ret = new HandshakeMessage(HandshakeMessageType.ClientKeyExchange, version);
                break;
            case HandshakeMessageType.Finished:
                ret = new HandshakeMessage(HandshakeMessageType.Finished, version);
                break;
            }

            if (ret != null) {
                ret.Decode(data);
                return ret;
            }
            return null;
        }
Example #3
0
 protected virtual void ProcessServerHello(HandshakeServerHello serverHello)
 {
     InvalidMessageReceived();
 }
Example #4
0
 protected virtual void ProcessServerHello(HandshakeServerHello serverHello)
 {
     InvalidMessageReceived();
 }
        protected override void ProcessClientHello(HandshakeClientHello clientHello)
        {
            if (_state == HandshakeState.Finished)
            {
                throw new AlertException(AlertDescription.NoRenegotiation,
                                         "Renegotiation not supported");
            }
            else if (_state != HandshakeState.Initial)
            {
                throw new AlertException(AlertDescription.UnexpectedMessage,
                                         "Client hello received at the wrong time");
            }

            // Find the compressions that match our supported compressions
            List <Byte> matchedCompressions = new List <Byte>();

            foreach (Byte id in _supportedCompressions)
            {
                if (clientHello.CompressionMethods.Contains(id))
                {
                    matchedCompressions.Add(id);
                }
            }
            if (matchedCompressions.Count == 0)
            {
                throw new AlertException(AlertDescription.HandshakeFailure,
                                         "None of the compression methods offered by client is accepted");
            }

            _clientVersion = clientHello.ClientVersion;
            _cipherSuite   = SelectCipherSuite(_pluginManager, _clientVersion, _minVersion, _maxVersion, clientHello.CipherSuites, new List <UInt16>(_supportedCipherSuites), _certificateSelectionCallback, _availableCertificates);
            _version       = _cipherSuite.ProtocolVersion;

            // Select the certificate and private key we are going to send
            int certificateIndex = _certificateSelectionCallback(_cipherSuite, _availableCertificates.ToArray());

            if (certificateIndex >= 0 && certificateIndex < _availableCertificates.Count)
            {
                _serverCertificates.AddRange(_availableCertificates[certificateIndex]);
                _selectedPrivateKey = _availablePrivateKeys[certificateIndex];
            }

            // TODO: Create the server hello message correctly
            HandshakeServerHello serverHello = new HandshakeServerHello(_version);

            serverHello.CipherSuite       = _cipherSuite.CipherSuiteID;
            serverHello.CompressionMethod = matchedCompressions[0];
            OutputMessage(serverHello);

            // Initialize the handshake randoms and cipher suite
            _connectionState.ClientRandom = clientHello.Random.GetBytes();
            _connectionState.ServerRandom = serverHello.Random.GetBytes();

            // TODO: If we resumed our session, set state to SendChangeCipherSpec and return

            // Send certificate if required and valid
            if (!_cipherSuite.IsAnonymous)
            {
                if (_serverCertificates.Count == 0)
                {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Certificate required but not selected");
                }

                string keyexAlg = _cipherSuite.KeyExchangeAlgorithm.CertificateKeyAlgorithm;
                string signAlg  = _cipherSuite.SignatureAlgorithm.CertificateKeyAlgorithm;

                X509Certificate cert = _serverCertificates[0];
                if (keyexAlg != null && !keyexAlg.Equals(cert.GetKeyAlgorithm()))
                {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Selected certificate type " + cert.GetKeyAlgorithm() + " doesn't match key exchange type " + keyexAlg);
                }
                if (signAlg != null && !signAlg.Equals(cert.GetKeyAlgorithm()))
                {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Selected certificate type " + cert.GetKeyAlgorithm() + " doesn't match signature type " + signAlg);
                }

                HandshakeCertificate certificate = new HandshakeCertificate(_version);
                certificate.CertificateList.AddRange(_serverCertificates);
                OutputMessage(certificate);
            }

            byte[] serverKeys = _cipherSuite.KeyExchangeAlgorithm.GetServerKeys(_maxVersion);
            if (serverKeys != null)
            {
                // Generate the signature for server keys
                byte[] dataToSign = new byte[_connectionState.ClientRandom.Length + _connectionState.ServerRandom.Length + serverKeys.Length];
                Buffer.BlockCopy(_connectionState.ClientRandom, 0, dataToSign, 0, _connectionState.ClientRandom.Length);
                Buffer.BlockCopy(_connectionState.ServerRandom, 0, dataToSign, _connectionState.ClientRandom.Length, _connectionState.ServerRandom.Length);
                Buffer.BlockCopy(serverKeys, 0, dataToSign, _connectionState.ClientRandom.Length + _connectionState.ServerRandom.Length, serverKeys.Length);
                byte[] signature = GenerateSignature(_selectedPrivateKey, dataToSign);

                // Combine the server keys with the signature
                byte[] signedKeys = new byte[serverKeys.Length + signature.Length];
                Buffer.BlockCopy(serverKeys, 0, signedKeys, 0, serverKeys.Length);
                Buffer.BlockCopy(signature, 0, signedKeys, serverKeys.Length, signature.Length);

                HandshakeMessage keyex = new HandshakeMessage(HandshakeMessageType.ServerKeyExchange, _version, signedKeys);
                OutputMessage(keyex);
            }

            // Send certificate request if needed
            if (!_cipherSuite.IsAnonymous && _certificateRequest != null)
            {
                OutputMessage(_certificateRequest);
                _certificateRequestSent = true;
            }

            HandshakeMessage serverHelloDone = new HandshakeMessage(HandshakeMessageType.ServerHelloDone, _version);

            OutputMessage(serverHelloDone);

            // Wait for client certificate or client key exchange
            _state = HandshakeState.ReceivedClientHello;
        }
        public bool ReadPacket(Stream stream)
        {
            byte[] header    = new byte[5];
            int    readBytes = 0;

            while (readBytes < header.Length)
            {
                readBytes += stream.Read(header, readBytes, header.Length - readBytes);
            }

            Record record = new Record(header);

            readBytes = 0;
            while (readBytes < record.Fragment.Length)
            {
                readBytes += stream.Read(record.Fragment, readBytes, record.Fragment.Length - readBytes);
            }

            _recordHandler.ProcessInputRecord(record);

            if (record.Type == 22)
            {
                HandshakeMessage hs = HandshakeMessage.GetInstance(VERSION, record.Fragment);
                if (hs == null)
                {
                    Console.WriteLine("Skipped handling packet");
                    return(true);
                }

                Console.WriteLine("adding bytes to hash " + record.Fragment.Length);
                _handshakeStream.Write(record.Fragment, 0, record.Fragment.Length);

                if (hs.Type == HandshakeMessageType.ServerHello)
                {
                    HandshakeServerHello sh = (HandshakeServerHello)hs;
                    _serverRandom = sh.Random.GetBytes();
                    if (sh.ServerVersion != VERSION)
                    {
                        throw new Exception("Version doesn't match");
                    }
                }
                else if (hs.Type == HandshakeMessageType.Certificate)
                {
                    Console.WriteLine("Found certificate");
                    HandshakeCertificate cert = (HandshakeCertificate)hs;

                    _rsaPublicKey = null;
                    foreach (X509Certificate c in cert.CertificateList)
                    {
                        Console.WriteLine(c.ToString(true));

                        if (_rsaPublicKey == null)
                        {
                            X509Certificate c2 = new X509Certificate(c);
                            _rsaPublicKey = new CertificatePublicKey(c2);
                        }
                    }
                }
                else if (hs.Type == HandshakeMessageType.ServerHelloDone)
                {
                    SendClientKey(stream);

                    byte[] seed = new byte[64];
                    Array.Copy(_clientRandom, 0, seed, 0, 32);
                    Array.Copy(_serverRandom, 0, seed, 32, 32);
                    PrintBytes("hash seed", seed);

                    _masterSecret = _cipherSuite.KeyExchangeAlgorithm.GetMasterSecret(_cipherSuite.PseudoRandomFunction, seed);
                    PrintBytes("master secret", _masterSecret);

                    seed = new byte[64];
                    Array.Copy(_serverRandom, 0, seed, 0, 32);
                    Array.Copy(_clientRandom, 0, seed, 32, 32);

                    ConnectionState connectionState = new ConnectionState(_clientRandom, _serverRandom, _masterSecret);
                    _recordHandler.SetCipherSuite(_cipherSuite, connectionState);

                    SendFinished(stream);
                }
                else if (hs.Type == HandshakeMessageType.Finished)
                {
                    Console.WriteLine("Got Finished message!!!");
                    SendHttpGet(stream);
                }
            }
            else if (record.Type == 20)
            {
                Console.WriteLine("Got change cipher spec from server");
                _recordHandler.ChangeRemoteState();
            }
            else if (record.Type == 21)
            {
                // This is an alert
                if (record.Fragment.Length >= 2 && record.Fragment[1] == 0)
                {
                    // Close notify
                    Console.WriteLine("Close notify received");
                    return(false);
                }
            }
            else if (record.Type == 23)
            {
                Console.WriteLine("Got data: " + Encoding.UTF8.GetString(record.Fragment));
            }

            return(true);
        }
        protected override void ProcessServerHello(HandshakeServerHello serverHello)
        {
            if (_state != HandshakeState.Initial) {
                throw new AlertException(AlertDescription.UnexpectedMessage,
                                         "Client hello received at the wrong time");
            }

            if (serverHello.ServerVersion < _minVersion || serverHello.ServerVersion > _maxVersion) {
                throw new AlertException(AlertDescription.ProtocolVersion,
                                         "Server version is not acceptable");
            }

            _version = serverHello.ServerVersion;
            _connectionState.ServerRandom = serverHello.Random.GetBytes();
            _cipherSuite = _pluginManager.GetCipherSuite(_version, serverHello.CipherSuite);
            if (_cipherSuite == null) {
                throw new AlertException(AlertDescription.HandshakeFailure,
                                         "Got incorrect cipher suite from server");
            }

            // TODO: If we resumed our session, set state to WaitForChangeCipherSpec and return

            // Wait for server certificate (server key exchange in case of DH_anon)
            _state = HandshakeState.ReceivedServerHello;
        }
        protected override void ProcessClientHello(HandshakeClientHello clientHello)
        {
            if (_state == HandshakeState.Finished) {
                throw new AlertException(AlertDescription.NoRenegotiation,
                                         "Renegotiation not supported");
            } else if (_state != HandshakeState.Initial) {
                throw new AlertException(AlertDescription.UnexpectedMessage,
                                         "Client hello received at the wrong time");
            }

            // Find the compressions that match our supported compressions
            List<Byte> matchedCompressions = new List<Byte>();
            foreach (Byte id in _supportedCompressions) {
                if (clientHello.CompressionMethods.Contains(id)) {
                    matchedCompressions.Add(id);
                }
            }
            if (matchedCompressions.Count == 0) {
                throw new AlertException(AlertDescription.HandshakeFailure,
                                         "None of the compression methods offered by client is accepted");
            }

            _clientVersion = clientHello.ClientVersion;
            _cipherSuite = SelectCipherSuite(_pluginManager, _clientVersion, _minVersion, _maxVersion, clientHello.CipherSuites, new List<UInt16>(_supportedCipherSuites), _certificateSelectionCallback, _availableCertificates);
            _version = _cipherSuite.ProtocolVersion;

            // Select the certificate and private key we are going to send
            int certificateIndex = _certificateSelectionCallback(_cipherSuite, _availableCertificates.ToArray());
            if (certificateIndex >= 0 && certificateIndex < _availableCertificates.Count) {
                _serverCertificates.AddRange(_availableCertificates[certificateIndex]);
                _selectedPrivateKey = _availablePrivateKeys[certificateIndex];
            }

            // TODO: Create the server hello message correctly
            HandshakeServerHello serverHello = new HandshakeServerHello(_version);
            serverHello.CipherSuite = _cipherSuite.CipherSuiteID;
            serverHello.CompressionMethod = matchedCompressions[0];
            OutputMessage(serverHello);

            // Initialize the handshake randoms and cipher suite
            _connectionState.ClientRandom = clientHello.Random.GetBytes();
            _connectionState.ServerRandom = serverHello.Random.GetBytes();

            // TODO: If we resumed our session, set state to SendChangeCipherSpec and return

            // Send certificate if required and valid
            if (!_cipherSuite.IsAnonymous) {
                if (_serverCertificates.Count == 0) {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Certificate required but not selected");
                }

                string keyexAlg = _cipherSuite.KeyExchangeAlgorithm.CertificateKeyAlgorithm;
                string signAlg = _cipherSuite.SignatureAlgorithm.CertificateKeyAlgorithm;

                X509Certificate cert = _serverCertificates[0];
                if (keyexAlg != null && !keyexAlg.Equals(cert.GetKeyAlgorithm())) {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Selected certificate type " + cert.GetKeyAlgorithm() + " doesn't match key exchange type " + keyexAlg);
                }
                if (signAlg != null && !signAlg.Equals(cert.GetKeyAlgorithm())) {
                    throw new AlertException(AlertDescription.HandshakeFailure,
                                             "Selected certificate type " + cert.GetKeyAlgorithm() + " doesn't match signature type " + signAlg);
                }

                HandshakeCertificate certificate = new HandshakeCertificate(_version);
                certificate.CertificateList.AddRange(_serverCertificates);
                OutputMessage(certificate);
            }

            byte[] serverKeys = _cipherSuite.KeyExchangeAlgorithm.GetServerKeys(_maxVersion);
            if (serverKeys != null) {
                // Generate the signature for server keys
                byte[] dataToSign = new byte[_connectionState.ClientRandom.Length + _connectionState.ServerRandom.Length + serverKeys.Length];
                Buffer.BlockCopy(_connectionState.ClientRandom, 0, dataToSign, 0, _connectionState.ClientRandom.Length);
                Buffer.BlockCopy(_connectionState.ServerRandom, 0, dataToSign, _connectionState.ClientRandom.Length, _connectionState.ServerRandom.Length);
                Buffer.BlockCopy(serverKeys, 0, dataToSign, _connectionState.ClientRandom.Length + _connectionState.ServerRandom.Length, serverKeys.Length);
                byte[] signature = GenerateSignature(_selectedPrivateKey, dataToSign);

                // Combine the server keys with the signature
                byte[] signedKeys = new byte[serverKeys.Length + signature.Length];
                Buffer.BlockCopy(serverKeys, 0, signedKeys, 0, serverKeys.Length);
                Buffer.BlockCopy(signature, 0, signedKeys, serverKeys.Length, signature.Length);

                HandshakeMessage keyex = new HandshakeMessage(HandshakeMessageType.ServerKeyExchange, _version, signedKeys);
                OutputMessage(keyex);
            }

            // Send certificate request if needed
            if (!_cipherSuite.IsAnonymous && _certificateRequest != null) {
                OutputMessage(_certificateRequest);
                _certificateRequestSent = true;
            }

            HandshakeMessage serverHelloDone = new HandshakeMessage(HandshakeMessageType.ServerHelloDone, _version);
            OutputMessage(serverHelloDone);

            // Wait for client certificate or client key exchange
            _state = HandshakeState.ReceivedClientHello;
        }