Beispiel #1
0
        /// <exception cref="IOException"/>
        protected static byte[] GenerateCertificate(AbstractCertificate certificate)
        {
            MemoryStream buf = new MemoryStream();

            certificate.Encode(buf);
            return(buf.ToArray());
        }
        public DefaultTlsEncryptionCredentials(TlsContext context, AbstractCertificate certificate,
                                               AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
            if (certificate.IsEmpty)
            {
                throw new ArgumentException("cannot be empty", "certificate");
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException("'privateKey' cannot be null");
            }
            if (!privateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "privateKey");
            }

            if (privateKey is RsaKeyParameters)
            {
            }
            else
            {
                throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
            }

            this.mContext     = context;
            this.mCertificate = certificate;
            this.mPrivateKey  = privateKey;
        }
Beispiel #3
0
        protected virtual void ReceiveCertificateMessage(MemoryStream buf)
        {
            AbstractCertificate clientCertificate = ParseClientCertificate(buf);

            AssertEmpty(buf);

            NotifyClientCertificate(clientCertificate);
        }
Beispiel #4
0
        public override void ProcessClientCertificate(AbstractCertificate clientCertificate)
        {
            if (mKeyExchange == KeyExchangeAlgorithm.DH_anon)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            // TODO Extract the public key
            // TODO If the certificate is 'fixed', take the public key as dhAgreePublicKey
        }
Beispiel #5
0
        protected virtual void ProcessClientCertificate(ServerHandshakeState state, byte[] body)
        {
            MemoryStream buf = new MemoryStream(body, false);

            AbstractCertificate clientCertificate = ParseCertificate(state, buf);

            TlsProtocol.AssertEmpty(buf);

            NotifyClientCertificate(state, clientCertificate);
        }
Beispiel #6
0
 private SessionParameters(int cipherSuite, byte compressionAlgorithm, byte[] masterSecret,
                           AbstractCertificate peerCertificate, byte[] pskIdentity, byte[] srpIdentity, byte[] encodedServerExtensions,
                           bool extendedMasterSecret)
 {
     this.mCipherSuite             = cipherSuite;
     this.mCompressionAlgorithm    = compressionAlgorithm;
     this.mMasterSecret            = Arrays.Clone(masterSecret);
     this.mPeerCertificate         = peerCertificate;
     this.mPskIdentity             = Arrays.Clone(pskIdentity);
     this.mSrpIdentity             = Arrays.Clone(srpIdentity);
     this.mEncodedServerExtensions = encodedServerExtensions;
     this.mExtendedMasterSecret    = extendedMasterSecret;
 }
        public DefaultTlsSignerCredentials(TlsContext context, AbstractCertificate certificate, AsymmetricKeyParameter privateKey,
                                           SignatureAndHashAlgorithm signatureAndHashAlgorithm)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
            if (certificate.IsEmpty)
            {
                throw new ArgumentException("cannot be empty", "clientCertificate");
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }
            if (!privateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "privateKey");
            }
            if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null)
            {
                throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm");
            }

            if (privateKey is RsaKeyParameters)
            {
                mSigner = new TlsRsaSigner();
            }
            else if (privateKey is DsaPrivateKeyParameters)
            {
                mSigner = new TlsDssSigner();
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mSigner = new TlsECDsaSigner();
            }
            else
            {
                throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
            }

            this.mSigner.Init(context);

            this.mContext     = context;
            this.mCertificate = certificate;
            this.mPrivateKey  = privateKey;
            this.mSignatureAndHashAlgorithm = signatureAndHashAlgorithm;
        }
Beispiel #8
0
        public override void ProcessServerCertificate(AbstractCertificate serverCertificate)
        {
            if (mKeyExchange != KeyExchangeAlgorithm.RSA_PSK)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            Certificate realCertificate       = serverCertificate as Certificate;
            X509CertificateStructure x509Cert = null;

            if (realCertificate != null)
            {
                x509Cert = realCertificate.GetCertificateAt(0);
            }

            SubjectPublicKeyInfo keyInfo = serverCertificate.SubjectPublicKeyInfo();

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            // Sanity check the PublicKeyFactory
            if (this.mServerPublicKey.IsPrivate)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.mRsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.mServerPublicKey);

            if (x509Cert != null)
            {
                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);
            }

            base.ProcessServerCertificate(serverCertificate);
        }
 public virtual void ProcessServerCertificate(AbstractCertificate serverCertificate)
 {
     if (mSupportedSignatureAlgorithms == null)
     {
         /*
          * TODO RFC 2246 7.4.2. Unless otherwise specified, the signing algorithm for the
          * certificate must be the same as the algorithm for the certificate key.
          */
     }
     else
     {
         /*
          * TODO RFC 5246 7.4.2. If the client provided a "signature_algorithms" extension, then
          * all certificates provided by the server MUST be signed by a hash/signature algorithm
          * pair that appears in that extension.
          */
     }
 }
Beispiel #10
0
        protected virtual AbstractCertificate ProcessServerCertificate2(ClientHandshakeState state, byte[] body)
        {
            MemoryStream buf = new MemoryStream(body, false);

            AbstractCertificate serverCertificate = ParseServerCertificate(state, buf);

            TlsProtocol.AssertEmpty(buf);

            state.keyExchange.ProcessServerCertificate(serverCertificate);
            state.authentication = state.client.GetAuthentication();
            if (serverCertificate is Certificate)
            {
                state.authentication.NotifyServerCertificate((Certificate)serverCertificate);
            }
            state.authentication.NotifyServerCertificate(serverCertificate);

            return(serverCertificate);
        }
Beispiel #11
0
        protected virtual void NotifyClientCertificate(ServerHandshakeState state, AbstractCertificate clientCertificate)
        {
            if (state.certificateRequest == null)
            {
                throw new InvalidOperationException();
            }

            if (state.clientCertificate != null)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            state.clientCertificate = clientCertificate;

            if (clientCertificate.IsEmpty)
            {
                state.keyExchange.SkipClientCredentials();
            }
            else
            {
                /*
                 * TODO RFC 5246 7.4.6. If the certificate_authorities list in the certificate request
                 * message was non-empty, one of the certificates in the certificate chain SHOULD be
                 * issued by one of the listed CAs.
                 */

                state.clientCertificateType = TlsUtilities.GetClientCertificateType(clientCertificate,
                                                                                    state.serverCredentials.Certificate);

                state.keyExchange.ProcessClientCertificate(clientCertificate);
            }

            /*
             * RFC 5246 7.4.6. If the client does not send any certificates, the server MAY at its
             * discretion either continue the handshake without client authentication, or respond with a
             * fatal handshake_failure alert. Also, if some aspect of the certificate chain was
             * unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its
             * discretion either continue the handshake (considering the client unauthenticated) or send
             * a fatal alert.
             */
            state.server.NotifyClientCertificate(clientCertificate);
        }
Beispiel #12
0
        public override void ProcessServerCertificate(AbstractCertificate serverCertificate)
        {
            if (mTlsSigner == null)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            Certificate realCertificate       = serverCertificate as Certificate;
            X509CertificateStructure x509Cert = null;

            if (realCertificate != null)
            {
                x509Cert = realCertificate.GetCertificateAt(0);
            }

            SubjectPublicKeyInfo keyInfo = serverCertificate.SubjectPublicKeyInfo();

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }

            if (x509Cert != null)
            {
                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
            }

            base.ProcessServerCertificate(serverCertificate);
        }
Beispiel #13
0
        protected virtual AbstractCertificate ParseCertificate(ServerHandshakeState state, Stream buf)
        {
            AbstractCertificate cert = state.server.ParseCertificate(state.clientCertificateType, buf);

            if (cert != null)
            {
                return(cert);
            }

            switch (state.clientCertificateType)
            {
            case CertificateType.X509:
                return(Certificate.Parse(buf));

            case CertificateType.RawPublicKey:
                return(RawPublicKey.Parse(buf));

            default:
                throw new TlsFatalAlert(AlertDescription.bad_certificate);
            }
        }
Beispiel #14
0
        public DefaultTlsAgreementCredentials(AbstractCertificate certificate, AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }
            if (certificate.IsEmpty)
            {
                throw new ArgumentException("cannot be empty", "certificate");
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }
            if (!privateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "privateKey");
            }

            if (privateKey is DHPrivateKeyParameters)
            {
                mBasicAgreement    = new DHBasicAgreement();
                mTruncateAgreement = true;
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mBasicAgreement    = new ECDHBasicAgreement();
                mTruncateAgreement = false;
            }
            else
            {
                throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
            }

            this.mCertificate = certificate;
            this.mPrivateKey  = privateKey;
        }
Beispiel #15
0
 public abstract void NotifyServerCertificate(AbstractCertificate serverCertificate);
Beispiel #16
0
        protected override void HandleHandshakeMessage(byte type, MemoryStream buf)
        {
            switch (type)
            {
            case HandshakeType.client_hello:
            {
                switch (this.mConnectionState)
                {
                case CS_START:
                {
                    ReceiveClientHelloMessage(buf);
                    this.mConnectionState = CS_CLIENT_HELLO;

                    SendServerHelloMessage();
                    this.mConnectionState = CS_SERVER_HELLO;

                    mRecordStream.NotifyHelloComplete();

                    IList serverSupplementalData = mTlsServer.GetServerSupplementalData();
                    if (serverSupplementalData != null)
                    {
                        SendSupplementalDataMessage(serverSupplementalData);
                    }
                    this.mConnectionState = CS_SERVER_SUPPLEMENTAL_DATA;

                    this.mKeyExchange = mTlsServer.GetKeyExchange();
                    this.mKeyExchange.Init(Context);

                    this.mServerCredentials = mTlsServer.GetCredentials();

                    AbstractCertificate serverCertificate = null;

                    if (this.mServerCredentials == null)
                    {
                        this.mKeyExchange.SkipServerCredentials();
                    }
                    else
                    {
                        this.mKeyExchange.ProcessServerCredentials(this.mServerCredentials);

                        serverCertificate = this.mServerCredentials.Certificate;
                        SendCertificateMessage(serverCertificate);
                    }
                    this.mConnectionState = CS_SERVER_CERTIFICATE;

                    // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
                    if (serverCertificate == null || serverCertificate.IsEmpty)
                    {
                        this.mAllowCertificateStatus = false;
                    }

                    if (this.mAllowCertificateStatus)
                    {
                        CertificateStatus certificateStatus = mTlsServer.GetCertificateStatus();
                        if (certificateStatus != null)
                        {
                            SendCertificateStatusMessage(certificateStatus);
                        }
                    }

                    this.mConnectionState = CS_CERTIFICATE_STATUS;

                    byte[] serverKeyExchange = this.mKeyExchange.GenerateServerKeyExchange();
                    if (serverKeyExchange != null)
                    {
                        SendServerKeyExchangeMessage(serverKeyExchange);
                    }
                    this.mConnectionState = CS_SERVER_KEY_EXCHANGE;

                    if (this.mServerCredentials != null)
                    {
                        this.mCertificateRequest = mTlsServer.GetCertificateRequest();
                        if (this.mCertificateRequest != null)
                        {
                            if (TlsUtilities.IsTlsV12(Context) != (mCertificateRequest.SupportedSignatureAlgorithms != null))
                            {
                                throw new TlsFatalAlert(AlertDescription.internal_error);
                            }

                            this.mKeyExchange.ValidateCertificateRequest(mCertificateRequest);

                            SendCertificateRequestMessage(mCertificateRequest);

                            TlsUtilities.TrackHashAlgorithms(this.mRecordStream.HandshakeHash,
                                                             this.mCertificateRequest.SupportedSignatureAlgorithms);
                        }
                    }
                    this.mConnectionState = CS_CERTIFICATE_REQUEST;

                    SendServerHelloDoneMessage();
                    this.mConnectionState = CS_SERVER_HELLO_DONE;

                    this.mRecordStream.HandshakeHash.SealHashAlgorithms();

                    break;
                }

                case CS_END:
                {
                    RefuseRenegotiation();
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.supplemental_data:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO_DONE:
                {
                    mTlsServer.ProcessClientSupplementalData(ReadSupplementalDataMessage(buf));
                    this.mConnectionState = CS_CLIENT_SUPPLEMENTAL_DATA;
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.certificate:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO_DONE:
                case CS_CLIENT_SUPPLEMENTAL_DATA:
                {
                    if (mConnectionState < CS_CLIENT_SUPPLEMENTAL_DATA)
                    {
                        mTlsServer.ProcessClientSupplementalData(null);
                    }

                    if (this.mCertificateRequest == null)
                    {
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    ReceiveCertificateMessage(buf);
                    this.mConnectionState = CS_CLIENT_CERTIFICATE;
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.client_key_exchange:
            {
                switch (this.mConnectionState)
                {
                case CS_SERVER_HELLO_DONE:
                case CS_CLIENT_SUPPLEMENTAL_DATA:
                case CS_CLIENT_CERTIFICATE:
                {
                    if (mConnectionState < CS_CLIENT_SUPPLEMENTAL_DATA)
                    {
                        mTlsServer.ProcessClientSupplementalData(null);
                    }

                    if (mConnectionState < CS_CLIENT_CERTIFICATE)
                    {
                        if (this.mCertificateRequest == null)
                        {
                            this.mKeyExchange.SkipClientCredentials();
                        }
                        else
                        {
                            if (TlsUtilities.IsTlsV12(Context))
                            {
                                /*
                                 * RFC 5246 If no suitable certificate is available, the client MUST Send a
                                 * certificate message containing no certificates.
                                 *
                                 * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                                 */
                                throw new TlsFatalAlert(AlertDescription.unexpected_message);
                            }
                            else if (TlsUtilities.IsSsl(Context))
                            {
                                if (this.mPeerCertificate == null)
                                {
                                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                                }
                            }
                            else
                            {
                                NotifyClientCertificate(Certificate.EmptyChain);
                            }
                        }
                    }

                    ReceiveClientKeyExchangeMessage(buf);
                    this.mConnectionState = CS_CLIENT_KEY_EXCHANGE;
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.certificate_verify:
            {
                switch (this.mConnectionState)
                {
                case CS_CLIENT_KEY_EXCHANGE:
                {
                    /*
                     * RFC 5246 7.4.8 This message is only sent following a client certificate that has
                     * signing capability (i.e., all certificates except those containing fixed
                     * Diffie-Hellman parameters).
                     */
                    if (!ExpectCertificateVerifyMessage())
                    {
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    ReceiveCertificateVerifyMessage(buf);
                    this.mConnectionState = CS_CERTIFICATE_VERIFY;

                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.finished:
            {
                switch (this.mConnectionState)
                {
                case CS_CLIENT_KEY_EXCHANGE:
                case CS_CERTIFICATE_VERIFY:
                {
                    if (mConnectionState < CS_CERTIFICATE_VERIFY && ExpectCertificateVerifyMessage())
                    {
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    ProcessFinishedMessage(buf);
                    this.mConnectionState = CS_CLIENT_FINISHED;

                    if (this.mExpectSessionTicket)
                    {
                        SendNewSessionTicketMessage(mTlsServer.GetNewSessionTicket());
                    }
                    this.mConnectionState = CS_SERVER_SESSION_TICKET;

                    SendChangeCipherSpecMessage();
                    SendFinishedMessage();
                    this.mConnectionState = CS_SERVER_FINISHED;

                    CompleteHandshake();
                    break;
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
                break;
            }

            case HandshakeType.hello_request:
            case HandshakeType.hello_verify_request:
            case HandshakeType.server_hello:
            case HandshakeType.server_key_exchange:
            case HandshakeType.certificate_request:
            case HandshakeType.server_hello_done:
            case HandshakeType.session_ticket:
            default:
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
        }
 public virtual void ProcessClientCertificate(AbstractCertificate clientCertificate)
 {
 }
Beispiel #18
0
        public override void ProcessServerCertificate(AbstractCertificate serverCertificate)
        {
            if (mKeyExchange == KeyExchangeAlgorithm.DH_anon)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }
            if (serverCertificate.IsEmpty)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            Certificate real = serverCertificate  as Certificate;
            X509CertificateStructure x509Cert = null;

            if (real != null)
            {
                x509Cert = real.GetCertificateAt(0);
            }

            SubjectPublicKeyInfo keyInfo = serverCertificate.SubjectPublicKeyInfo();

            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (mTlsSigner == null)
            {
                try
                {
                    this.mDHAgreePublicKey = (DHPublicKeyParameters)this.mServerPublicKey;
                    this.mDHParameters     = mDHAgreePublicKey.Parameters;
                }
                catch (InvalidCastException e)
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown, e);
                }

                if (x509Cert != null)
                {
                    TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
                }
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                if (x509Cert != null)
                {
                    TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
                }
            }

            base.ProcessServerCertificate(serverCertificate);
        }
Beispiel #19
0
        internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsRecordLayer recordLayer)
        {
            SecurityParameters    securityParameters = state.serverContext.SecurityParameters;
            DtlsReliableHandshake handshake          = new DtlsReliableHandshake(state.serverContext, recordLayer,
                                                                                 state.server.GetHandshakeTimeoutMillis());

            DtlsReliableHandshake.Message clientMessage = handshake.ReceiveMessage();

            // NOTE: DTLSRecordLayer requires any DTLS version, we don't otherwise constrain this
            //ProtocolVersion recordLayerVersion = recordLayer.ReadVersion;

            if (clientMessage.Type == HandshakeType.client_hello)
            {
                ProcessClientHello(state, clientMessage.Body);
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            {
                byte[] serverHelloBody = GenerateServerHello(state);

                ApplyMaxFragmentLengthExtension(recordLayer, securityParameters.maxFragmentLength);

                ProtocolVersion recordLayerVersion = state.serverContext.ServerVersion;
                recordLayer.ReadVersion = recordLayerVersion;
                recordLayer.SetWriteVersion(recordLayerVersion);

                handshake.SendMessage(HandshakeType.server_hello, serverHelloBody);
            }

            handshake.NotifyHelloComplete();

            IList serverSupplementalData = state.server.GetServerSupplementalData();

            if (serverSupplementalData != null)
            {
                byte[] supplementalDataBody = GenerateSupplementalData(serverSupplementalData);
                handshake.SendMessage(HandshakeType.supplemental_data, supplementalDataBody);
            }

            state.keyExchange = state.server.GetKeyExchange();
            state.keyExchange.Init(state.serverContext);

            state.serverCredentials = state.server.GetCredentials();

            AbstractCertificate serverCertificate = null;

            if (state.serverCredentials == null)
            {
                state.keyExchange.SkipServerCredentials();
            }
            else
            {
                state.keyExchange.ProcessServerCredentials(state.serverCredentials);

                serverCertificate = state.serverCredentials.Certificate;
                byte[] certificateBody = GenerateCertificate(serverCertificate);
                handshake.SendMessage(HandshakeType.certificate, certificateBody);
            }

            // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
            if (serverCertificate == null || serverCertificate.IsEmpty)
            {
                state.allowCertificateStatus = false;
            }

            if (state.allowCertificateStatus)
            {
                CertificateStatus certificateStatus = state.server.GetCertificateStatus();
                if (certificateStatus != null)
                {
                    byte[] certificateStatusBody = GenerateCertificateStatus(state, certificateStatus);
                    handshake.SendMessage(HandshakeType.certificate_status, certificateStatusBody);
                }
            }

            byte[] serverKeyExchange = state.keyExchange.GenerateServerKeyExchange();
            if (serverKeyExchange != null)
            {
                handshake.SendMessage(HandshakeType.server_key_exchange, serverKeyExchange);
            }

            if (state.serverCredentials != null)
            {
                state.certificateRequest = state.server.GetCertificateRequest();
                if (state.certificateRequest != null)
                {
                    if (TlsUtilities.IsTlsV12(state.serverContext) != (state.certificateRequest.SupportedSignatureAlgorithms != null))
                    {
                        throw new TlsFatalAlert(AlertDescription.internal_error);
                    }

                    state.keyExchange.ValidateCertificateRequest(state.certificateRequest);

                    byte[] certificateRequestBody = GenerateCertificateRequest(state, state.certificateRequest);
                    handshake.SendMessage(HandshakeType.certificate_request, certificateRequestBody);

                    TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash,
                                                     state.certificateRequest.SupportedSignatureAlgorithms);
                }
            }

            handshake.SendMessage(HandshakeType.server_hello_done, TlsUtilities.EmptyBytes);

            handshake.HandshakeHash.SealHashAlgorithms();

            clientMessage = handshake.ReceiveMessage();

            if (clientMessage.Type == HandshakeType.supplemental_data)
            {
                ProcessClientSupplementalData(state, clientMessage.Body);
                clientMessage = handshake.ReceiveMessage();
            }
            else
            {
                state.server.ProcessClientSupplementalData(null);
            }

            if (state.certificateRequest == null)
            {
                state.keyExchange.SkipClientCredentials();
            }
            else
            {
                if (clientMessage.Type == HandshakeType.certificate)
                {
                    ProcessClientCertificate(state, clientMessage.Body);
                    clientMessage = handshake.ReceiveMessage();
                }
                else
                {
                    if (TlsUtilities.IsTlsV12(state.serverContext))
                    {
                        /*
                         * RFC 5246 If no suitable certificate is available, the client MUST send a
                         * certificate message containing no certificates.
                         *
                         * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                         */
                        throw new TlsFatalAlert(AlertDescription.unexpected_message);
                    }

                    NotifyClientCertificate(state, Certificate.EmptyChain);
                }
            }

            if (clientMessage.Type == HandshakeType.client_key_exchange)
            {
                ProcessClientKeyExchange(state, clientMessage.Body);
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            TlsHandshakeHash prepareFinishHash = handshake.PrepareToFinish();

            securityParameters.sessionHash = TlsProtocol.GetCurrentPrfHash(state.serverContext, prepareFinishHash, null);

            TlsProtocol.EstablishMasterSecret(state.serverContext, state.keyExchange);
            recordLayer.InitPendingEpoch(state.server.GetCipher());

            /*
             * RFC 5246 7.4.8 This message is only sent following a client certificate that has signing
             * capability (i.e., all certificates except those containing fixed Diffie-Hellman
             * parameters).
             */
            if (ExpectCertificateVerifyMessage(state))
            {
                byte[] certificateVerifyBody = handshake.ReceiveMessageBody(HandshakeType.certificate_verify);
                ProcessCertificateVerify(state, certificateVerifyBody, prepareFinishHash);
            }

            // NOTE: Calculated exclusive of the actual Finished message from the client
            byte[] expectedClientVerifyData = TlsUtilities.CalculateVerifyData(state.serverContext, ExporterLabel.client_finished,
                                                                               TlsProtocol.GetCurrentPrfHash(state.serverContext, handshake.HandshakeHash, null));
            ProcessFinished(handshake.ReceiveMessageBody(HandshakeType.finished), expectedClientVerifyData);

            if (state.expectSessionTicket)
            {
                NewSessionTicket newSessionTicket     = state.server.GetNewSessionTicket();
                byte[]           newSessionTicketBody = GenerateNewSessionTicket(state, newSessionTicket);
                handshake.SendMessage(HandshakeType.session_ticket, newSessionTicketBody);
            }

            // NOTE: Calculated exclusive of the Finished message itself
            byte[] serverVerifyData = TlsUtilities.CalculateVerifyData(state.serverContext, ExporterLabel.server_finished,
                                                                       TlsProtocol.GetCurrentPrfHash(state.serverContext, handshake.HandshakeHash, null));
            handshake.SendMessage(HandshakeType.finished, serverVerifyData);

            handshake.Finish();

            //{
            //    state.sessionParameters = new SessionParameters.Builder()
            //        .SetCipherSuite(securityParameters.CipherSuite)
            //        .SetCompressionAlgorithm(securityParameters.CompressionAlgorithm)
            //        .SetExtendedMasterSecret(securityParameters.IsExtendedMasterSecret)
            //        .SetMasterSecret(securityParameters.MasterSecret)
            //        .SetPeerCertificate(state.clientCertificate)
            //        .SetPskIdentity(securityParameters.PskIdentity)
            //        .SetSrpIdentity(securityParameters.SrpIdentity)
            //        // TODO Consider filtering extensions that aren't relevant to resumed sessions
            //        .SetServerExtensions(state.serverExtensions)
            //        .Build();

            //    state.tlsSession = TlsUtilities.ImportSession(state.tlsSession.SessionID, state.sessionParameters);

            //    state.serverContext.SetResumableSession(state.tlsSession);
            //}

            state.server.NotifyHandshakeComplete();

            return(new DtlsTransport(recordLayer));
        }
Beispiel #20
0
 public Builder SetPeerCertificate(AbstractCertificate peerCertificate)
 {
     this.mPeerCertificate = peerCertificate;
     return(this);
 }
Beispiel #21
0
 public virtual void NotifyClientCertificate(AbstractCertificate clientCertificate)
 {
     throw new TlsFatalAlert(AlertDescription.internal_error);
 }
 public DefaultTlsSignerCredentials(TlsContext context, AbstractCertificate certificate, AsymmetricKeyParameter privateKey)
     :   this(context, certificate, privateKey, null)
 {
 }
Beispiel #23
0
        internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsRecordLayer recordLayer)
        {
            SecurityParameters    securityParameters = state.clientContext.SecurityParameters;
            DtlsReliableHandshake handshake          = new DtlsReliableHandshake(state.clientContext, recordLayer,
                                                                                 state.client.GetHandshakeTimeoutMillis());

            byte[] clientHelloBody = GenerateClientHello(state, state.client);

            recordLayer.SetWriteVersion(ProtocolVersion.DTLSv10);

            handshake.SendMessage(HandshakeType.client_hello, clientHelloBody);

            DtlsReliableHandshake.Message serverMessage = handshake.ReceiveMessage();

            while (serverMessage.Type == HandshakeType.hello_verify_request)
            {
                ProtocolVersion recordLayerVersion = recordLayer.ReadVersion;
                ProtocolVersion client_version     = state.clientContext.ClientVersion;

                /*
                 * RFC 6347 4.2.1 DTLS 1.2 server implementations SHOULD use DTLS version 1.0 regardless of
                 * the version of TLS that is expected to be negotiated. DTLS 1.2 and 1.0 clients MUST use
                 * the version solely to indicate packet formatting (which is the same in both DTLS 1.2 and
                 * 1.0) and not as part of version negotiation.
                 */
                if (!recordLayerVersion.IsEqualOrEarlierVersionOf(client_version))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                recordLayer.ReadVersion = null;

                byte[] cookie  = ProcessHelloVerifyRequest(state, serverMessage.Body);
                byte[] patched = PatchClientHelloWithCookie(clientHelloBody, cookie);

                handshake.ResetHandshakeMessagesDigest();
                handshake.SendMessage(HandshakeType.client_hello, patched);

                serverMessage = handshake.ReceiveMessage();
            }

            if (serverMessage.Type == HandshakeType.server_hello)
            {
                ProtocolVersion recordLayerVersion = recordLayer.ReadVersion;
                ReportServerVersion(state, recordLayerVersion);
                recordLayer.SetWriteVersion(recordLayerVersion);

                ProcessServerHello(state, serverMessage.Body);
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            handshake.NotifyHelloComplete();

            ApplyMaxFragmentLengthExtension(recordLayer, securityParameters.maxFragmentLength);

            if (state.resumedSession)
            {
                securityParameters.masterSecret = Arrays.Clone(state.sessionParameters.MasterSecret);
                recordLayer.InitPendingEpoch(state.client.GetCipher());

                // NOTE: Calculated exclusive of the actual Finished message from the server
                byte[] resExpectedServerVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.server_finished,
                                                                                      TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
                ProcessFinished(handshake.ReceiveMessageBody(HandshakeType.finished), resExpectedServerVerifyData);

                // NOTE: Calculated exclusive of the Finished message itself
                byte[] resClientVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.client_finished,
                                                                              TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
                handshake.SendMessage(HandshakeType.finished, resClientVerifyData);

                handshake.Finish();

                state.clientContext.SetResumableSession(state.tlsSession);

                state.client.NotifyHandshakeComplete();

                return(new DtlsTransport(recordLayer));
            }

            InvalidateSession(state);

            if (state.selectedSessionID.Length > 0)
            {
                state.tlsSession = new TlsSessionImpl(state.selectedSessionID, null);
            }

            serverMessage = handshake.ReceiveMessage();

            if (serverMessage.Type == HandshakeType.supplemental_data)
            {
                ProcessServerSupplementalData(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                state.client.ProcessServerSupplementalData(null);
            }

            state.keyExchange = state.client.GetKeyExchange();
            state.keyExchange.Init(state.clientContext);

            AbstractCertificate serverCertificate = null;

            if (serverMessage.Type == HandshakeType.certificate)
            {
                serverCertificate = ProcessServerCertificate2(state, serverMessage.Body);
                serverMessage     = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, Certificate is optional
                state.keyExchange.SkipServerCredentials();
            }

            // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
            if (serverCertificate == null || serverCertificate.IsEmpty)
            {
                state.allowCertificateStatus = false;
            }

            if (serverMessage.Type == HandshakeType.certificate_status)
            {
                ProcessCertificateStatus(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, CertificateStatus is optional
            }

            if (serverMessage.Type == HandshakeType.server_key_exchange)
            {
                ProcessServerKeyExchange(state, serverMessage.Body);
                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, ServerKeyExchange is optional
                state.keyExchange.SkipServerKeyExchange();
            }

            if (serverMessage.Type == HandshakeType.certificate_request)
            {
                ProcessCertificateRequest(state, serverMessage.Body);

                /*
                 * TODO Give the client a chance to immediately select the CertificateVerify hash
                 * algorithm here to avoid tracking the other hash algorithms unnecessarily?
                 */
                TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash,
                                                 state.certificateRequest.SupportedSignatureAlgorithms);

                serverMessage = handshake.ReceiveMessage();
            }
            else
            {
                // Okay, CertificateRequest is optional
            }

            if (serverMessage.Type == HandshakeType.server_hello_done)
            {
                if (serverMessage.Body.Length != 0)
                {
                    throw new TlsFatalAlert(AlertDescription.decode_error);
                }
            }
            else
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            handshake.HandshakeHash.SealHashAlgorithms();

            IList clientSupplementalData = state.client.GetClientSupplementalData();

            if (clientSupplementalData != null)
            {
                byte[] supplementalDataBody = GenerateSupplementalData(clientSupplementalData);
                handshake.SendMessage(HandshakeType.supplemental_data, supplementalDataBody);
            }

            if (state.certificateRequest != null)
            {
                state.clientCredentials = state.authentication.GetClientCredentials(state.certificateRequest);

                /*
                 * RFC 5246 If no suitable certificate is available, the client MUST send a certificate
                 * message containing no certificates.
                 *
                 * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                 */
                AbstractCertificate clientCertificate = null;
                if (state.clientCredentials != null)
                {
                    clientCertificate = state.clientCredentials.Certificate;
                }
                if (clientCertificate == null)
                {
                    clientCertificate = Certificate.EmptyChain;
                }

                byte[] certificateBody = GenerateCertificate(clientCertificate);
                handshake.SendMessage(HandshakeType.certificate, certificateBody);
            }

            if (state.clientCredentials != null)
            {
                state.keyExchange.ProcessClientCredentials(state.clientCredentials);
            }
            else
            {
                state.keyExchange.SkipClientCredentials();
            }

            byte[] clientKeyExchangeBody = GenerateClientKeyExchange(state);
            handshake.SendMessage(HandshakeType.client_key_exchange, clientKeyExchangeBody);

            TlsHandshakeHash prepareFinishHash = handshake.PrepareToFinish();

            securityParameters.sessionHash = TlsProtocol.GetCurrentPrfHash(state.clientContext, prepareFinishHash, null);

            TlsProtocol.EstablishMasterSecret(state.clientContext, state.keyExchange);
            recordLayer.InitPendingEpoch(state.client.GetCipher());

            if (state.clientCredentials != null && state.clientCredentials is TlsSignerCredentials)
            {
                TlsSignerCredentials signerCredentials = (TlsSignerCredentials)state.clientCredentials;

                /*
                 * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
                 */
                SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(
                    state.clientContext, signerCredentials);

                byte[] hash;
                if (signatureAndHashAlgorithm == null)
                {
                    hash = securityParameters.SessionHash;
                }
                else
                {
                    hash = prepareFinishHash.GetFinalHash(signatureAndHashAlgorithm.Hash);
                }

                byte[]          signature             = signerCredentials.GenerateCertificateSignature(hash);
                DigitallySigned certificateVerify     = new DigitallySigned(signatureAndHashAlgorithm, signature);
                byte[]          certificateVerifyBody = GenerateCertificateVerify(state, certificateVerify);
                handshake.SendMessage(HandshakeType.certificate_verify, certificateVerifyBody);
            }

            // NOTE: Calculated exclusive of the Finished message itself
            byte[] clientVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.client_finished,
                                                                       TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
            handshake.SendMessage(HandshakeType.finished, clientVerifyData);

            if (state.expectSessionTicket)
            {
                serverMessage = handshake.ReceiveMessage();
                if (serverMessage.Type == HandshakeType.session_ticket)
                {
                    ProcessNewSessionTicket(state, serverMessage.Body);
                }
                else
                {
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }
            }

            // NOTE: Calculated exclusive of the actual Finished message from the server
            byte[] expectedServerVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, ExporterLabel.server_finished,
                                                                               TlsProtocol.GetCurrentPrfHash(state.clientContext, handshake.HandshakeHash, null));
            ProcessFinished(handshake.ReceiveMessageBody(HandshakeType.finished), expectedServerVerifyData);

            handshake.Finish();

            if (state.tlsSession != null)
            {
                state.sessionParameters = new SessionParameters.Builder()
                                          .SetCipherSuite(securityParameters.CipherSuite)
                                          .SetCompressionAlgorithm(securityParameters.CompressionAlgorithm)
                                          .SetExtendedMasterSecret(securityParameters.IsExtendedMasterSecret)
                                          .SetMasterSecret(securityParameters.MasterSecret)
                                          .SetPeerCertificate(serverCertificate)
                                          .SetPskIdentity(securityParameters.PskIdentity)
                                          .SetSrpIdentity(securityParameters.SrpIdentity)
                                          // TODO Consider filtering extensions that aren't relevant to resumed sessions
                                          .SetServerExtensions(state.serverExtensions)
                                          .Build();

                state.tlsSession = TlsUtilities.ImportSession(state.tlsSession.SessionID, state.sessionParameters);

                state.clientContext.SetResumableSession(state.tlsSession);
            }

            state.client.NotifyHandshakeComplete();

            return(new DtlsTransport(recordLayer));
        }