ReadUint16() public static méthode

public static ReadUint16 ( Stream input ) : int
input Stream
Résultat int
Exemple #1
0
        protected virtual void ReceiveServerHelloMessage(MemoryStream buf)
        {
            {
                ProtocolVersion server_version = TlsUtilities.ReadVersion(buf);
                if (server_version.IsDtls)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                // Check that this matches what the server is Sending in the record layer
                if (!server_version.Equals(this.mRecordStream.ReadVersion))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                ProtocolVersion client_version = Context.ClientVersion;
                if (!server_version.IsEqualOrEarlierVersionOf(client_version))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                this.mRecordStream.SetWriteVersion(server_version);
                ContextAdmin.SetServerVersion(server_version);
                this.mTlsClient.NotifyServerVersion(server_version);
            }

            /*
             * Read the server random
             */
            this.mSecurityParameters.serverRandom = TlsUtilities.ReadFully(32, buf);

            this.mSelectedSessionID = TlsUtilities.ReadOpaque8(buf);
            if (this.mSelectedSessionID.Length > 32)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            this.mTlsClient.NotifySessionID(this.mSelectedSessionID);
            this.mResumedSession = this.mSelectedSessionID.Length > 0 && this.mTlsSession != null &&
                                   Arrays.AreEqual(this.mSelectedSessionID, this.mTlsSession.SessionID);

            /*
             * Find out which CipherSuite the server has chosen and check that it was one of the offered
             * ones, and is a valid selection for the negotiated version.
             */
            int selectedCipherSuite = TlsUtilities.ReadUint16(buf);

            if (!Arrays.Contains(this.mOfferedCipherSuites, selectedCipherSuite) ||
                selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL ||
                CipherSuite.IsScsv(selectedCipherSuite) ||
                !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, Context.ServerVersion))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            this.mTlsClient.NotifySelectedCipherSuite(selectedCipherSuite);

            /*
             * Find out which CompressionMethod the server has chosen and check that it was one of the
             * offered ones.
             */
            byte selectedCompressionMethod = TlsUtilities.ReadUint8(buf);

            if (!Arrays.Contains(this.mOfferedCompressionMethods, selectedCompressionMethod))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            this.mTlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);

            /*
             * RFC3546 2.2 The extended server hello message format MAY be sent in place of the server
             * hello message when the client has requested extended functionality via the extended
             * client hello message specified in Section 2.1. ... Note that the extended server hello
             * message is only sent in response to an extended client hello message. This prevents the
             * possibility that the extended server hello message could "break" existing TLS 1.0
             * clients.
             */
            this.mServerExtensions = ReadExtensions(buf);

            /*
             * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
             * extended client hello message.
             *
             * However, see RFC 5746 exception below. We always include the SCSV, so an Extended Server
             * Hello is always allowed.
             */
            if (this.mServerExtensions != null)
            {
                foreach (int extType in this.mServerExtensions.Keys)
                {
                    /*
                     * RFC 5746 3.6. Note that Sending a "renegotiation_info" extension in response to a
                     * ClientHello containing only the SCSV is an explicit exception to the prohibition
                     * in RFC 5246, Section 7.4.1.4, on the server Sending unsolicited extensions and is
                     * only allowed because the client is signaling its willingness to receive the
                     * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
                     */
                    if (extType == ExtensionType.renegotiation_info)
                    {
                        continue;
                    }

                    /*
                     * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
                     * same extension type appeared in the corresponding ClientHello. If a client
                     * receives an extension type in ServerHello that it did not request in the
                     * associated ClientHello, it MUST abort the handshake with an unsupported_extension
                     * fatal alert.
                     */
                    if (null == TlsUtilities.GetExtensionData(this.mClientExtensions, extType))
                    {
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);
                    }

                    /*
                     * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and Send a server hello containing no
                     * extensions[.]
                     */
                    if (this.mResumedSession)
                    {
                        // TODO[compat-gnutls] GnuTLS test server Sends server extensions e.g. ec_point_formats
                        // TODO[compat-openssl] OpenSSL test server Sends server extensions e.g. ec_point_formats
                        // TODO[compat-polarssl] PolarSSL test server Sends server extensions e.g. ec_point_formats
                        //                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                }
            }

            /*
             * RFC 5746 3.4. Client Behavior: Initial Handshake
             */
            {
                /*
                 * When a ServerHello is received, the client MUST check if it includes the
                 * "renegotiation_info" extension:
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(this.mServerExtensions, ExtensionType.renegotiation_info);
                if (renegExtData != null)
                {
                    /*
                     * If the extension is present, set the secure_renegotiation flag to TRUE. The
                     * client MUST then verify that the length of the "renegotiated_connection"
                     * field is zero, and if it is not, MUST abort the handshake (by Sending a fatal
                     * handshake_failure alert).
                     */
                    this.mSecureRenegotiation = true;

                    if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                    {
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                    }
                }
            }

            // TODO[compat-gnutls] GnuTLS test server fails to Send renegotiation_info extension when resuming
            this.mTlsClient.NotifySecureRenegotiation(this.mSecureRenegotiation);

            IDictionary sessionClientExtensions = mClientExtensions, sessionServerExtensions = mServerExtensions;

            if (this.mResumedSession)
            {
                if (selectedCipherSuite != this.mSessionParameters.CipherSuite ||
                    selectedCompressionMethod != this.mSessionParameters.CompressionAlgorithm)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                sessionClientExtensions = null;
                sessionServerExtensions = this.mSessionParameters.ReadServerExtensions();
            }

            this.mSecurityParameters.cipherSuite          = selectedCipherSuite;
            this.mSecurityParameters.compressionAlgorithm = selectedCompressionMethod;

            if (sessionServerExtensions != null)
            {
                {
                    /*
                     * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
                     * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
                     * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
                     * client.
                     */
                    bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(sessionServerExtensions);
                    if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(selectedCipherSuite))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }

                    this.mSecurityParameters.encryptThenMac = serverSentEncryptThenMAC;
                }

                this.mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(sessionServerExtensions);

                this.mSecurityParameters.maxFragmentLength = ProcessMaxFragmentLengthExtension(sessionClientExtensions,
                                                                                               sessionServerExtensions, AlertDescription.illegal_parameter);

                this.mSecurityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(sessionServerExtensions);

                /*
                 * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
                 * a session resumption handshake.
                 */
                this.mAllowCertificateStatus = !this.mResumedSession &&
                                               TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.status_request,
                                                                                          AlertDescription.illegal_parameter);

                this.mExpectSessionTicket = !this.mResumedSession &&
                                            TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.session_ticket,
                                                                                       AlertDescription.illegal_parameter);
            }

            /*
             * TODO[session-hash]
             *
             * draft-ietf-tls-session-hash-04 4. Clients and servers SHOULD NOT accept handshakes
             * that do not use the extended master secret [..]. (and see 5.2, 5.3)
             */

            if (sessionClientExtensions != null)
            {
                this.mTlsClient.ProcessServerExtensions(sessionServerExtensions);
            }

            this.mSecurityParameters.prfAlgorithm = GetPrfAlgorithm(Context, this.mSecurityParameters.CipherSuite);

            /*
             * RFC 5264 7.4.9. Any cipher suite which does not explicitly specify
             * verify_data_length has a verify_data_length equal to 12. This includes all
             * existing cipher suites.
             */
            this.mSecurityParameters.verifyDataLength = 12;
        }
        public static ECDomainParameters ReadECParameters(int[] namedCurves, byte[] ecPointFormats, Stream input)
        {
            try
            {
                switch (TlsUtilities.ReadUint8(input))
                {
                case 1:
                {
                    CheckNamedCurve(namedCurves, 65281);
                    BigInteger bigInteger3 = ReadECParameter(input);
                    BigInteger a2          = ReadECFieldElement(bigInteger3.BitLength, input);
                    BigInteger b3          = ReadECFieldElement(bigInteger3.BitLength, input);
                    byte[]     encoding2   = TlsUtilities.ReadOpaque8(input);
                    BigInteger bigInteger4 = ReadECParameter(input);
                    BigInteger bigInteger5 = ReadECParameter(input);
                    ECCurve    curve2      = new FpCurve(bigInteger3, a2, b3, bigInteger4, bigInteger5);
                    ECPoint    g2          = DeserializeECPoint(ecPointFormats, curve2, encoding2);
                    return(new ECDomainParameters(curve2, g2, bigInteger4, bigInteger5));
                }

                case 2:
                {
                    CheckNamedCurve(namedCurves, 65282);
                    int  num = TlsUtilities.ReadUint16(input);
                    byte b   = TlsUtilities.ReadUint8(input);
                    if (!ECBasisType.IsValid(b))
                    {
                        throw new TlsFatalAlert(47);
                    }
                    int num2 = ReadECExponent(num, input);
                    int k    = -1;
                    int k2   = -1;
                    if (b == 2)
                    {
                        k  = ReadECExponent(num, input);
                        k2 = ReadECExponent(num, input);
                    }
                    BigInteger a           = ReadECFieldElement(num, input);
                    BigInteger b2          = ReadECFieldElement(num, input);
                    byte[]     encoding    = TlsUtilities.ReadOpaque8(input);
                    BigInteger bigInteger  = ReadECParameter(input);
                    BigInteger bigInteger2 = ReadECParameter(input);
                    ECCurve    curve       = ((b == 2) ? new F2mCurve(num, num2, k, k2, a, b2, bigInteger, bigInteger2) : new F2mCurve(num, num2, a, b2, bigInteger, bigInteger2));
                    ECPoint    g           = DeserializeECPoint(ecPointFormats, curve, encoding);
                    return(new ECDomainParameters(curve, g, bigInteger, bigInteger2));
                }

                case 3:
                {
                    int namedCurve = TlsUtilities.ReadUint16(input);
                    if (!NamedCurve.RefersToASpecificNamedCurve(namedCurve))
                    {
                        throw new TlsFatalAlert(47);
                    }
                    CheckNamedCurve(namedCurves, namedCurve);
                    return(GetParametersForNamedCurve(namedCurve));
                }

                default:
                    throw new TlsFatalAlert(47);
                }
            }
            catch (global::System.Exception alertCause)
            {
                throw new TlsFatalAlert(47, alertCause);
            }
        }
Exemple #3
0
        public static ECDomainParameters ReadECParameters(int[] namedCurves, byte[] ecPointFormats, Stream input)
        {
            try
            {
                byte curveType = TlsUtilities.ReadUint8(input);

                switch (curveType)
                {
                case ECCurveType.explicit_prime:
                {
                    CheckNamedCurve(namedCurves, NamedCurve.arbitrary_explicit_prime_curves);

                    BigInteger prime_p      = ReadECParameter(input);
                    BigInteger a            = ReadECFieldElement(prime_p.BitLength, input);
                    BigInteger b            = ReadECFieldElement(prime_p.BitLength, input);
                    byte[]     baseEncoding = TlsUtilities.ReadOpaque8(input);
                    BigInteger order        = ReadECParameter(input);
                    BigInteger cofactor     = ReadECParameter(input);
                    ECCurve    curve        = new FpCurve(prime_p, a, b, order, cofactor);
                    ECPoint    basePoint    = DeserializeECPoint(ecPointFormats, curve, baseEncoding);
                    return(new ECDomainParameters(curve, basePoint, order, cofactor));
                }

                case ECCurveType.explicit_char2:
                {
                    CheckNamedCurve(namedCurves, NamedCurve.arbitrary_explicit_char2_curves);

                    int  m     = TlsUtilities.ReadUint16(input);
                    byte basis = TlsUtilities.ReadUint8(input);
                    if (!ECBasisType.IsValid(basis))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }

                    int k1 = ReadECExponent(m, input), k2 = -1, k3 = -1;
                    if (basis == ECBasisType.ec_basis_pentanomial)
                    {
                        k2 = ReadECExponent(m, input);
                        k3 = ReadECExponent(m, input);
                    }

                    BigInteger a            = ReadECFieldElement(m, input);
                    BigInteger b            = ReadECFieldElement(m, input);
                    byte[]     baseEncoding = TlsUtilities.ReadOpaque8(input);
                    BigInteger order        = ReadECParameter(input);
                    BigInteger cofactor     = ReadECParameter(input);

                    ECCurve curve = (basis == ECBasisType.ec_basis_pentanomial)
                        ? new F2mCurve(m, k1, k2, k3, a, b, order, cofactor)
                        : new F2mCurve(m, k1, a, b, order, cofactor);

                    ECPoint basePoint = DeserializeECPoint(ecPointFormats, curve, baseEncoding);

                    return(new ECDomainParameters(curve, basePoint, order, cofactor));
                }

                case ECCurveType.named_curve:
                {
                    int namedCurve = TlsUtilities.ReadUint16(input);
                    if (!NamedCurve.RefersToASpecificNamedCurve(namedCurve))
                    {
                        /*
                         * RFC 4492 5.4. All those values of NamedCurve are allowed that refer to a
                         * specific curve. Values of NamedCurve that indicate support for a class of
                         * explicitly defined curves are not allowed here [...].
                         */
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }

                    CheckNamedCurve(namedCurves, namedCurve);

                    return(GetParametersForNamedCurve(namedCurve));
                }

                default:
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter, e);
            }
        }
Exemple #4
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            byte[] record = null;

            for (;;)
            {
                int receiveLimit = System.Math.Min(len, GetReceiveLimit()) + RECORD_HEADER_LENGTH;
                if (record == null || record.Length < receiveLimit)
                {
                    record = new byte[receiveLimit];
                }

                try
                {
                    if (mRetransmit != null && DateTimeUtilities.CurrentUnixMs() > mRetransmitExpiry)
                    {
                        mRetransmit      = null;
                        mRetransmitEpoch = null;
                    }

                    int received = ReceiveRecord(record, 0, receiveLimit, waitMillis);
                    if (received < 0)
                    {
                        return(received);
                    }
                    if (received < RECORD_HEADER_LENGTH)
                    {
                        continue;
                    }
                    int length = TlsUtilities.ReadUint16(record, 11);
                    if (received != (length + RECORD_HEADER_LENGTH))
                    {
                        continue;
                    }

                    byte type = TlsUtilities.ReadUint8(record, 0);

                    // TODO Support user-specified custom protocols?
                    switch (type)
                    {
                    case ContentType.alert:
                    case ContentType.application_data:
                    case ContentType.change_cipher_spec:
                    case ContentType.handshake:
                    case ContentType.heartbeat:
                        break;

                    default:
                        // TODO Exception?
                        continue;
                    }

                    int epoch = TlsUtilities.ReadUint16(record, 3);

                    DtlsEpoch recordEpoch = null;
                    if (epoch == mReadEpoch.Epoch)
                    {
                        recordEpoch = mReadEpoch;
                    }
                    else if (type == ContentType.handshake && mRetransmitEpoch != null &&
                             epoch == mRetransmitEpoch.Epoch)
                    {
                        recordEpoch = mRetransmitEpoch;
                    }

                    if (recordEpoch == null)
                    {
                        continue;
                    }

                    long seq = TlsUtilities.ReadUint48(record, 5);
                    if (recordEpoch.ReplayWindow.ShouldDiscard(seq))
                    {
                        continue;
                    }

                    ProtocolVersion version = TlsUtilities.ReadVersion(record, 1);
                    if (!version.IsDtls)
                    {
                        continue;
                    }

                    if (mReadVersion != null && !mReadVersion.Equals(version))
                    {
                        continue;
                    }

                    byte[] plaintext = recordEpoch.Cipher.DecodeCiphertext(
                        GetMacSequenceNumber(recordEpoch.Epoch, seq), type, record, RECORD_HEADER_LENGTH,
                        received - RECORD_HEADER_LENGTH);

                    recordEpoch.ReplayWindow.ReportAuthenticated(seq);

                    if (plaintext.Length > this.mPlaintextLimit)
                    {
                        continue;
                    }

                    if (mReadVersion == null)
                    {
                        mReadVersion = version;
                    }

                    switch (type)
                    {
                    case ContentType.alert:
                    {
                        if (plaintext.Length == 2)
                        {
                            byte alertLevel       = plaintext[0];
                            byte alertDescription = plaintext[1];

                            mPeer.NotifyAlertReceived(alertLevel, alertDescription);

                            if (alertLevel == AlertLevel.fatal)
                            {
                                Failed();
                                throw new TlsFatalAlert(alertDescription);
                            }

                            // TODO Can close_notify be a fatal alert?
                            if (alertDescription == AlertDescription.close_notify)
                            {
                                CloseTransport();
                            }
                        }

                        continue;
                    }

                    case ContentType.application_data:
                    {
                        if (mInHandshake)
                        {
                            // TODO Consider buffering application data for new epoch that arrives
                            // out-of-order with the Finished message
                            continue;
                        }
                        break;
                    }

                    case ContentType.change_cipher_spec:
                    {
                        // Implicitly receive change_cipher_spec and change to pending cipher state

                        for (int i = 0; i < plaintext.Length; ++i)
                        {
                            byte message = TlsUtilities.ReadUint8(plaintext, i);
                            if (message != ChangeCipherSpec.change_cipher_spec)
                            {
                                continue;
                            }

                            if (mPendingEpoch != null)
                            {
                                mReadEpoch = mPendingEpoch;
                            }
                        }

                        continue;
                    }

                    case ContentType.handshake:
                    {
                        if (!mInHandshake)
                        {
                            if (mRetransmit != null)
                            {
                                mRetransmit.ReceivedHandshakeRecord(epoch, plaintext, 0, plaintext.Length);
                            }

                            // TODO Consider support for HelloRequest
                            continue;
                        }
                        break;
                    }

                    case ContentType.heartbeat:
                    {
                        // TODO[RFC 6520]
                        continue;
                    }
                    }

                    /*
                     * NOTE: If we receive any non-handshake data in the new epoch implies the peer has
                     * received our final flight.
                     */
                    if (!mInHandshake && mRetransmit != null)
                    {
                        this.mRetransmit      = null;
                        this.mRetransmitEpoch = null;
                    }

                    Array.Copy(plaintext, 0, buf, off, plaintext.Length);
                    return(plaintext.Length);
                }
                catch (IOException e)
                {
                    // NOTE: Assume this is a timeout for the moment
                    throw e;
                }
            }
        }
Exemple #5
0
        private void ProcessHandshakeMessage(HandshakeType type, byte[] buf)
        {
            MemoryStream inStr = new MemoryStream(buf, false);

            /*
             * Check the type.
             */
            switch (type)
            {
            case HandshakeType.certificate:
            {
                switch (connection_state)
                {
                case CS_SERVER_HELLO_RECEIVED:
                {
                    // Parse the Certificate message and send to cipher suite

                    Certificate serverCertificate = Certificate.Parse(inStr);

                    AssertEmpty(inStr);

                    this.keyExchange.ProcessServerCertificate(serverCertificate);

                    this.authentication = tlsClient.GetAuthentication();
                    this.authentication.NotifyServerCertificate(serverCertificate);

                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
                break;
            }

            case HandshakeType.finished:
                switch (connection_state)
                {
                case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
                    /*
                     * Read the checksum from the finished message, it has always 12 bytes.
                     */
                    byte[] serverVerifyData = new byte[12];
                    TlsUtilities.ReadFully(serverVerifyData, inStr);

                    AssertEmpty(inStr);

                    /*
                     * Calculate our own checksum.
                     */
                    byte[] expectedServerVerifyData = TlsUtilities.PRF(
                        securityParameters.masterSecret, "server finished",
                        rs.GetCurrentHash(), 12);

                    /*
                     * Compare both checksums.
                     */
                    if (!Arrays.ConstantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
                    {
                        /*
                         * Wrong checksum in the finished message.
                         */
                        this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    }

                    connection_state = CS_DONE;

                    /*
                     * We are now ready to receive application data.
                     */
                    this.appDataReady = true;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }
                break;

            case HandshakeType.server_hello:
                switch (connection_state)
                {
                case CS_CLIENT_HELLO_SEND:
                    /*
                     * Read the server hello message
                     */
                    TlsUtilities.CheckVersion(inStr, this);

                    /*
                     * Read the server random
                     */
                    securityParameters.serverRandom = new byte[32];
                    TlsUtilities.ReadFully(securityParameters.serverRandom, inStr);

                    byte[] sessionID = TlsUtilities.ReadOpaque8(inStr);
                    if (sessionID.Length > 32)
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySessionID(sessionID);

                    /*
                     * Find out which CipherSuite the server has chosen and check that
                     * it was one of the offered ones.
                     */
                    CipherSuite selectedCipherSuite = (CipherSuite)TlsUtilities.ReadUint16(inStr);
                    if (!ArrayContains(offeredCipherSuites, selectedCipherSuite) ||
                        selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySelectedCipherSuite(selectedCipherSuite);

                    /*
                     * Find out which CompressionMethod the server has chosen and check that
                     * it was one of the offered ones.
                     */
                    CompressionMethod selectedCompressionMethod = (CompressionMethod)TlsUtilities.ReadUint8(inStr);
                    if (!ArrayContains(offeredCompressionMethods, selectedCompressionMethod))
                    {
                        this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                    }

                    this.tlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);

                    /*
                     * RFC3546 2.2 The extended server hello message format MAY be
                     * sent in place of the server hello message when the client has
                     * requested extended functionality via the extended client hello
                     * message specified in Section 2.1.
                     * ...
                     * Note that the extended server hello message is only sent in response
                     * to an extended client hello message.  This prevents the possibility
                     * that the extended server hello message could "break" existing TLS 1.0
                     * clients.
                     */

                    /*
                     * TODO RFC 3546 2.3
                     * If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and send a server hello
                     * containing no extensions.
                     */

                    // ExtensionType -> byte[]
                    IDictionary serverExtensions = Platform.CreateHashtable();

                    if (inStr.Position < inStr.Length)
                    {
                        // Process extensions from extended server hello
                        byte[] extBytes = TlsUtilities.ReadOpaque16(inStr);

                        MemoryStream ext = new MemoryStream(extBytes, false);
                        while (ext.Position < ext.Length)
                        {
                            ExtensionType extType  = (ExtensionType)TlsUtilities.ReadUint16(ext);
                            byte[]        extValue = TlsUtilities.ReadOpaque16(ext);

                            // Note: RFC 5746 makes a special case for EXT_RenegotiationInfo
                            if (extType != ExtensionType.renegotiation_info &&
                                !clientExtensions.Contains(extType))
                            {
                                /*
                                 * RFC 3546 2.3
                                 * Note that for all extension types (including those defined in
                                 * future), the extension type MUST NOT appear in the extended server
                                 * hello unless the same extension type appeared in the corresponding
                                 * client hello.  Thus clients MUST abort the handshake if they receive
                                 * an extension type in the extended server hello that they did not
                                 * request in the associated (extended) client hello.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.unsupported_extension);
                            }

                            if (serverExtensions.Contains(extType))
                            {
                                /*
                                 * RFC 3546 2.3
                                 * Also note that when multiple extensions of different types are
                                 * present in the extended client hello or the extended server hello,
                                 * the extensions may appear in any order. There MUST NOT be more than
                                 * one extension of the same type.
                                 */
                                this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
                            }

                            serverExtensions.Add(extType, extValue);
                        }
                    }

                    AssertEmpty(inStr);

                    /*
                     * RFC 5746 3.4. When a ServerHello is received, the client MUST check if it
                     * includes the "renegotiation_info" extension:
                     */
                    {
                        bool secure_negotiation = serverExtensions.Contains(ExtensionType.renegotiation_info);

                        /*
                         * If the extension is present, set the secure_renegotiation flag
                         * to TRUE.  The client MUST then verify that the length of the
                         * "renegotiated_connection" field is zero, and if it is not, MUST
                         * abort the handshake (by sending a fatal handshake_failure
                         * alert).
                         */
                        if (secure_negotiation)
                        {
                            byte[] renegExtValue = (byte[])serverExtensions[ExtensionType.renegotiation_info];

                            if (!Arrays.ConstantTimeAreEqual(renegExtValue,
                                                             CreateRenegotiationInfo(emptybuf)))
                            {
                                this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                            }
                        }

                        tlsClient.NotifySecureRenegotiation(secure_negotiation);
                    }

                    if (clientExtensions != null)
                    {
                        tlsClient.ProcessServerExtensions(serverExtensions);
                    }

                    this.keyExchange = tlsClient.GetKeyExchange();

                    connection_state = CS_SERVER_HELLO_RECEIVED;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }
                break;

            case HandshakeType.server_hello_done:
                switch (connection_state)
                {
                case CS_SERVER_CERTIFICATE_RECEIVED:
                case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                case CS_CERTIFICATE_REQUEST_RECEIVED:

                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                    {
                        // There was no server key exchange message; check it's OK
                        this.keyExchange.SkipServerKeyExchange();
                    }

                    AssertEmpty(inStr);

                    connection_state = CS_SERVER_HELLO_DONE_RECEIVED;

                    TlsCredentials clientCreds = null;
                    if (certificateRequest == null)
                    {
                        this.keyExchange.SkipClientCredentials();
                    }
                    else
                    {
                        clientCreds = this.authentication.GetClientCredentials(certificateRequest);

                        Certificate clientCert;
                        if (clientCreds == null)
                        {
                            this.keyExchange.SkipClientCredentials();
                            clientCert = Certificate.EmptyChain;
                        }
                        else
                        {
                            this.keyExchange.ProcessClientCredentials(clientCreds);
                            clientCert = clientCreds.Certificate;
                        }

                        SendClientCertificate(clientCert);
                    }

                    /*
                     * Send the client key exchange message, depending on the key
                     * exchange we are using in our CipherSuite.
                     */
                    SendClientKeyExchange();

                    connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;

                    if (clientCreds != null && clientCreds is TlsSignerCredentials)
                    {
                        TlsSignerCredentials signerCreds = (TlsSignerCredentials)clientCreds;
                        byte[] md5andsha1 = rs.GetCurrentHash();
                        byte[] clientCertificateSignature = signerCreds.GenerateCertificateSignature(
                            md5andsha1);
                        SendCertificateVerify(clientCertificateSignature);

                        connection_state = CS_CERTIFICATE_VERIFY_SEND;
                    }

                    /*
                     * Now, we send change cipher state
                     */
                    byte[] cmessage = new byte[1];
                    cmessage[0] = 1;
                    rs.WriteMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.Length);

                    connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;

                    /*
                     * Calculate the master_secret
                     */
                    byte[] pms = this.keyExchange.GeneratePremasterSecret();

                    securityParameters.masterSecret = TlsUtilities.PRF(pms, "master secret",
                                                                       TlsUtilities.Concat(securityParameters.clientRandom, securityParameters.serverRandom),
                                                                       48);

                    // TODO Is there a way to ensure the data is really overwritten?

                    /*
                     * RFC 2246 8.1. The pre_master_secret should be deleted from
                     * memory once the master_secret has been computed.
                     */
                    Array.Clear(pms, 0, pms.Length);

                    /*
                     * Initialize our cipher suite
                     */
                    rs.ClientCipherSpecDecided(tlsClient.GetCompression(), tlsClient.GetCipher());

                    /*
                     * Send our finished message.
                     */
                    byte[] clientVerifyData = TlsUtilities.PRF(securityParameters.masterSecret,
                                                               "client finished", rs.GetCurrentHash(), 12);

                    MemoryStream bos = new MemoryStream();
                    TlsUtilities.WriteUint8((byte)HandshakeType.finished, bos);
                    TlsUtilities.WriteOpaque24(clientVerifyData, bos);
                    byte[] message = bos.ToArray();

                    rs.WriteMessage(ContentType.handshake, message, 0, message.Length);

                    this.connection_state = CS_CLIENT_FINISHED_SEND;
                    break;

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    break;
                }
                break;

            case HandshakeType.server_key_exchange:
            {
                switch (connection_state)
                {
                case CS_SERVER_HELLO_RECEIVED:
                case CS_SERVER_CERTIFICATE_RECEIVED:
                {
                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_HELLO_RECEIVED)
                    {
                        // There was no server certificate message; check it's OK
                        this.keyExchange.SkipServerCertificate();
                        this.authentication = null;
                    }

                    this.keyExchange.ProcessServerKeyExchange(inStr);

                    AssertEmpty(inStr);
                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
                break;
            }

            case HandshakeType.certificate_request:
                switch (connection_state)
                {
                case CS_SERVER_CERTIFICATE_RECEIVED:
                case CS_SERVER_KEY_EXCHANGE_RECEIVED:
                {
                    // NB: Original code used case label fall-through
                    if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED)
                    {
                        // There was no server key exchange message; check it's OK
                        this.keyExchange.SkipServerKeyExchange();
                    }

                    if (this.authentication == null)
                    {
                        /*
                         * RFC 2246 7.4.4. It is a fatal handshake_failure alert
                         * for an anonymous server to request client identification.
                         */
                        this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
                    }

                    int numTypes = TlsUtilities.ReadUint8(inStr);
                    ClientCertificateType[] certificateTypes = new ClientCertificateType[numTypes];
                    for (int i = 0; i < numTypes; ++i)
                    {
                        certificateTypes[i] = (ClientCertificateType)TlsUtilities.ReadUint8(inStr);
                    }

                    byte[] authorities = TlsUtilities.ReadOpaque16(inStr);

                    AssertEmpty(inStr);

                    IList authorityDNs = Platform.CreateArrayList();

                    MemoryStream bis = new MemoryStream(authorities, false);
                    while (bis.Position < bis.Length)
                    {
                        byte[] dnBytes = TlsUtilities.ReadOpaque16(bis);
                        // TODO Switch to X500Name when available
                        authorityDNs.Add(X509Name.GetInstance(Asn1Object.FromByteArray(dnBytes)));
                    }

                    this.certificateRequest = new CertificateRequest(certificateTypes,
                                                                     authorityDNs);
                    this.keyExchange.ValidateCertificateRequest(this.certificateRequest);

                    break;
                }

                default:
                    this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                    break;
                }

                this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
                break;

            case HandshakeType.hello_request:
                /*
                 * RFC 2246 7.4.1.1 Hello request
                 * This message will be ignored by the client if the client is currently
                 * negotiating a session. This message may be ignored by the client if it
                 * does not wish to renegotiate a session, or the client may, if it wishes,
                 * respond with a no_renegotiation alert.
                 */
                if (connection_state == CS_DONE)
                {
                    // Renegotiation not supported yet
                    SendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
                }
                break;

            case HandshakeType.client_key_exchange:
            case HandshakeType.certificate_verify:
            case HandshakeType.client_hello:
            default:
                // We do not support this!
                this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
                break;
            }
        }
Exemple #6
0
        protected virtual void ProcessServerHello(ClientHandshakeState state, byte[] body)
        {
            SecurityParameters securityParameters = state.clientContext.SecurityParameters;

            MemoryStream buf = new MemoryStream(body, false);

            ProtocolVersion server_version = TlsUtilities.ReadVersion(buf);

            ReportServerVersion(state, server_version);

            securityParameters.serverRandom = TlsUtilities.ReadFully(32, buf);

            state.selectedSessionID = TlsUtilities.ReadOpaque8(buf);
            if (state.selectedSessionID.Length > 32)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            state.client.NotifySessionID(state.selectedSessionID);

            state.selectedCipherSuite = TlsUtilities.ReadUint16(buf);
            if (!Arrays.Contains(state.offeredCipherSuites, state.selectedCipherSuite) ||
                state.selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL ||
                CipherSuite.IsScsv(state.selectedCipherSuite) ||
                !TlsUtilities.IsValidCipherSuiteForVersion(state.selectedCipherSuite, server_version))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            ValidateSelectedCipherSuite(state.selectedCipherSuite, AlertDescription.illegal_parameter);

            state.client.NotifySelectedCipherSuite(state.selectedCipherSuite);

            state.selectedCompressionMethod = TlsUtilities.ReadUint8(buf);
            if (!Arrays.Contains(state.offeredCompressionMethods, (byte)state.selectedCompressionMethod))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            state.client.NotifySelectedCompressionMethod((byte)state.selectedCompressionMethod);

            /*
             * RFC3546 2.2 The extended server hello message format MAY be sent in place of the server
             * hello message when the client has requested extended functionality via the extended
             * client hello message specified in Section 2.1. ... Note that the extended server hello
             * message is only sent in response to an extended client hello message. This prevents the
             * possibility that the extended server hello message could "break" existing TLS 1.0
             * clients.
             */

            /*
             * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
             * extensions appearing in the client hello, and send a server hello containing no
             * extensions.
             */

            // Integer -> byte[]
            IDictionary serverExtensions = TlsProtocol.ReadExtensions(buf);

            /*
             * draft-ietf-tls-session-hash-01 5.2. If a server receives the "extended_master_secret"
             * extension, it MUST include the "extended_master_secret" extension in its ServerHello
             * message.
             */
            bool serverSentExtendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(serverExtensions);

            if (serverSentExtendedMasterSecret != securityParameters.extendedMasterSecret)
            {
                throw new TlsFatalAlert(AlertDescription.handshake_failure);
            }

            /*
             * RFC 3546 2.2 Note that the extended server hello message is only sent in response to an
             * extended client hello message. However, see RFC 5746 exception below. We always include
             * the SCSV, so an Extended Server Hello is always allowed.
             */
            if (serverExtensions != null)
            {
                foreach (int extType in serverExtensions.Keys)
                {
                    /*
                     * RFC 5746 3.6. Note that sending a "renegotiation_info" extension in response to a
                     * ClientHello containing only the SCSV is an explicit exception to the prohibition
                     * in RFC 5246, Section 7.4.1.4, on the server sending unsolicited extensions and is
                     * only allowed because the client is signaling its willingness to receive the
                     * extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
                     */
                    if (extType == ExtensionType.renegotiation_info)
                    {
                        continue;
                    }

                    /*
                     * RFC 5246 7.4.1.4 An extension type MUST NOT appear in the ServerHello unless the
                     * same extension type appeared in the corresponding ClientHello. If a client
                     * receives an extension type in ServerHello that it did not request in the
                     * associated ClientHello, it MUST abort the handshake with an unsupported_extension
                     * fatal alert.
                     */
                    if (null == TlsUtilities.GetExtensionData(state.clientExtensions, extType))
                    {
                        throw new TlsFatalAlert(AlertDescription.unsupported_extension);
                    }

                    /*
                     * draft-ietf-tls-session-hash-01 5.2. Implementation note: if the server decides to
                     * proceed with resumption, the extension does not have any effect. Requiring the
                     * extension to be included anyway makes the extension negotiation logic easier,
                     * because it does not depend on whether resumption is accepted or not.
                     */
                    if (extType == ExtensionType.extended_master_secret)
                    {
                        continue;
                    }

                    /*
                     * RFC 3546 2.3. If [...] the older session is resumed, then the server MUST ignore
                     * extensions appearing in the client hello, and send a server hello containing no
                     * extensions[.]
                     */
                    // TODO[sessions]
                    //                if (this.mResumedSession)
                    //                {
                    //                    // TODO[compat-gnutls] GnuTLS test server sends server extensions e.g. ec_point_formats
                    //                    // TODO[compat-openssl] OpenSSL test server sends server extensions e.g. ec_point_formats
                    //                    // TODO[compat-polarssl] PolarSSL test server sends server extensions e.g. ec_point_formats
                    ////                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    //                }
                }

                /*
                 * RFC 5746 3.4. Client Behavior: Initial Handshake
                 */
                {
                    /*
                     * When a ServerHello is received, the client MUST check if it includes the
                     * "renegotiation_info" extension:
                     */
                    byte[] renegExtData = (byte[])serverExtensions[ExtensionType.renegotiation_info];
                    if (renegExtData != null)
                    {
                        /*
                         * If the extension is present, set the secure_renegotiation flag to TRUE. The
                         * client MUST then verify that the length of the "renegotiated_connection"
                         * field is zero, and if it is not, MUST abort the handshake (by sending a fatal
                         * handshake_failure alert).
                         */
                        state.secure_renegotiation = true;

                        if (!Arrays.ConstantTimeAreEqual(renegExtData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                        {
                            throw new TlsFatalAlert(AlertDescription.handshake_failure);
                        }
                    }
                }

                /*
                 * RFC 7366 3. If a server receives an encrypt-then-MAC request extension from a client
                 * and then selects a stream or Authenticated Encryption with Associated Data (AEAD)
                 * ciphersuite, it MUST NOT send an encrypt-then-MAC response extension back to the
                 * client.
                 */
                bool serverSentEncryptThenMAC = TlsExtensionsUtilities.HasEncryptThenMacExtension(serverExtensions);
                if (serverSentEncryptThenMAC && !TlsUtilities.IsBlockCipherSuite(state.selectedCipherSuite))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                securityParameters.encryptThenMac = serverSentEncryptThenMAC;

                state.maxFragmentLength = EvaluateMaxFragmentLengthExtension(state.clientExtensions, serverExtensions,
                                                                             AlertDescription.illegal_parameter);

                securityParameters.truncatedHMac = TlsExtensionsUtilities.HasTruncatedHMacExtension(serverExtensions);

                state.allowCertificateStatus = TlsUtilities.HasExpectedEmptyExtensionData(serverExtensions,
                                                                                          ExtensionType.status_request, AlertDescription.illegal_parameter);

                state.expectSessionTicket = TlsUtilities.HasExpectedEmptyExtensionData(serverExtensions,
                                                                                       ExtensionType.session_ticket, AlertDescription.illegal_parameter);
            }

            state.client.NotifySecureRenegotiation(state.secure_renegotiation);

            if (state.clientExtensions != null)
            {
                state.client.ProcessServerExtensions(serverExtensions);
            }
        }
Exemple #7
0
        protected virtual void ProcessClientHello(ServerHandshakeState state, byte[] body)
        {
            MemoryStream buf = new MemoryStream(body, false);

            // TODO Read RFCs for guidance on the expected record layer version number
            ProtocolVersion client_version = TlsUtilities.ReadVersion(buf);

            if (!client_version.IsDtls)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            /*
             * Read the client random
             */
            byte[] client_random = TlsUtilities.ReadFully(32, buf);

            byte[] sessionID = TlsUtilities.ReadOpaque8(buf);
            if (sessionID.Length > 32)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            // TODO RFC 4347 has the cookie length restricted to 32, but not in RFC 6347
            byte[] cookie = TlsUtilities.ReadOpaque8(buf);

            int cipher_suites_length = TlsUtilities.ReadUint16(buf);

            if (cipher_suites_length < 2 || (cipher_suites_length & 1) != 0)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            /*
             * NOTE: "If the session_id field is not empty (implying a session resumption request) this
             * vector must include at least the cipher_suite from that session."
             */
            state.offeredCipherSuites = TlsUtilities.ReadUint16Array(cipher_suites_length / 2, buf);

            int compression_methods_length = TlsUtilities.ReadUint8(buf);

            if (compression_methods_length < 1)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            state.offeredCompressionMethods = TlsUtilities.ReadUint8Array(compression_methods_length, buf);

            /*
             * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
             * extensions appearing in the client hello, and send a server hello containing no
             * extensions.
             */
            state.clientExtensions = TlsProtocol.ReadExtensions(buf);

            TlsServerContextImpl context            = state.serverContext;
            SecurityParameters   securityParameters = context.SecurityParameters;

            securityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(state.clientExtensions);

            context.SetClientVersion(client_version);

            state.server.NotifyClientVersion(client_version);
            state.server.NotifyFallback(Arrays.Contains(state.offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV));

            securityParameters.clientRandom = client_random;

            state.server.NotifyOfferedCipherSuites(state.offeredCipherSuites);
            state.server.NotifyOfferedCompressionMethods(state.offeredCompressionMethods);

            /*
             * RFC 5746 3.6. Server Behavior: Initial Handshake
             */
            {
                /*
                 * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
                 * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
                 * ClientHello. Including both is NOT RECOMMENDED.
                 */

                /*
                 * When a ClientHello is received, the server MUST check if it includes the
                 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If it does, set the secure_renegotiation flag
                 * to TRUE.
                 */
                if (Arrays.Contains(state.offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV))
                {
                    state.secure_renegotiation = true;
                }

                /*
                 * The server MUST check if the "renegotiation_info" extension is included in the
                 * ClientHello.
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(state.clientExtensions, ExtensionType.renegotiation_info);
                if (renegExtData != null)
                {
                    /*
                     * If the extension is present, set secure_renegotiation flag to TRUE. The
                     * server MUST then verify that the length of the "renegotiated_connection"
                     * field is zero, and if it is not, MUST abort the handshake.
                     */
                    state.secure_renegotiation = true;

                    if (!Arrays.ConstantTimeAreEqual(renegExtData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                    {
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                    }
                }
            }

            state.server.NotifySecureRenegotiation(state.secure_renegotiation);

            if (state.clientExtensions != null)
            {
                state.server.ProcessClientExtensions(state.clientExtensions);
            }
        }
        protected virtual void ReceiveServerHelloMessage(MemoryStream buf)
        {
            ProtocolVersion protocolVersion = TlsUtilities.ReadVersion(buf);

            if (protocolVersion.IsDtls)
            {
                throw new TlsFatalAlert(47);
            }
            if (!protocolVersion.Equals(mRecordStream.ReadVersion))
            {
                throw new TlsFatalAlert(47);
            }
            ProtocolVersion clientVersion = Context.ClientVersion;

            if (!protocolVersion.IsEqualOrEarlierVersionOf(clientVersion))
            {
                throw new TlsFatalAlert(47);
            }
            mRecordStream.SetWriteVersion(protocolVersion);
            ContextAdmin.SetServerVersion(protocolVersion);
            mTlsClient.NotifyServerVersion(protocolVersion);
            mSecurityParameters.serverRandom = TlsUtilities.ReadFully(32, buf);
            mSelectedSessionID = TlsUtilities.ReadOpaque8(buf);
            if (mSelectedSessionID.Length > 32)
            {
                throw new TlsFatalAlert(47);
            }
            mTlsClient.NotifySessionID(mSelectedSessionID);
            mResumedSession = (mSelectedSessionID.Length > 0 && mTlsSession != null && Arrays.AreEqual(mSelectedSessionID, mTlsSession.SessionID));
            int num = TlsUtilities.ReadUint16(buf);

            if (!Arrays.Contains(mOfferedCipherSuites, num) || num == 0 || CipherSuite.IsScsv(num) || !TlsUtilities.IsValidCipherSuiteForVersion(num, Context.ServerVersion))
            {
                throw new TlsFatalAlert(47);
            }
            mTlsClient.NotifySelectedCipherSuite(num);
            byte b = TlsUtilities.ReadUint8(buf);

            if (!Arrays.Contains(mOfferedCompressionMethods, b))
            {
                throw new TlsFatalAlert(47);
            }
            mTlsClient.NotifySelectedCompressionMethod(b);
            mServerExtensions = TlsProtocol.ReadExtensions(buf);
            if (mServerExtensions != null)
            {
                foreach (int key in mServerExtensions.Keys)
                {
                    if (key != 65281)
                    {
                        if (TlsUtilities.GetExtensionData(mClientExtensions, key) == null)
                        {
                            throw new TlsFatalAlert(110);
                        }
                        if (!mResumedSession)
                        {
                        }
                    }
                }
            }
            byte[] extensionData = TlsUtilities.GetExtensionData(mServerExtensions, 65281);
            if (extensionData != null)
            {
                mSecureRenegotiation = true;
                if (!Arrays.ConstantTimeAreEqual(extensionData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                {
                    throw new TlsFatalAlert(40);
                }
            }
            mTlsClient.NotifySecureRenegotiation(mSecureRenegotiation);
            IDictionary dictionary  = mClientExtensions;
            IDictionary dictionary2 = mServerExtensions;

            if (mResumedSession)
            {
                if (num != mSessionParameters.CipherSuite || b != mSessionParameters.CompressionAlgorithm)
                {
                    throw new TlsFatalAlert(47);
                }
                dictionary  = null;
                dictionary2 = mSessionParameters.ReadServerExtensions();
            }
            mSecurityParameters.cipherSuite          = num;
            mSecurityParameters.compressionAlgorithm = b;
            if (dictionary2 != null)
            {
                bool flag = TlsExtensionsUtilities.HasEncryptThenMacExtension(dictionary2);
                if (flag && !TlsUtilities.IsBlockCipherSuite(num))
                {
                    throw new TlsFatalAlert(47);
                }
                mSecurityParameters.encryptThenMac       = flag;
                mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(dictionary2);
                mSecurityParameters.maxFragmentLength    = ProcessMaxFragmentLengthExtension(dictionary, dictionary2, 47);
                mSecurityParameters.truncatedHMac        = TlsExtensionsUtilities.HasTruncatedHMacExtension(dictionary2);
                mAllowCertificateStatus = (!mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(dictionary2, 5, 47));
                mExpectSessionTicket    = (!mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(dictionary2, 35, 47));
            }
            if (dictionary != null)
            {
                mTlsClient.ProcessServerExtensions(dictionary2);
            }
            mSecurityParameters.prfAlgorithm     = TlsProtocol.GetPrfAlgorithm(Context, mSecurityParameters.CipherSuite);
            mSecurityParameters.verifyDataLength = 12;
        }
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            byte[] array = null;
            int    result;

            while (true)
            {
                int num = Math.Min(len, this.GetReceiveLimit()) + 13;
                if (array == null || array.Length < num)
                {
                    array = new byte[num];
                }
                try
                {
                    if (this.mRetransmit != null && DateTimeUtilities.CurrentUnixMs() > this.mRetransmitExpiry)
                    {
                        this.mRetransmit      = null;
                        this.mRetransmitEpoch = null;
                    }
                    int num2 = this.ReceiveRecord(array, 0, num, waitMillis);
                    if (num2 < 0)
                    {
                        result = num2;
                    }
                    else
                    {
                        if (num2 < 13)
                        {
                            continue;
                        }
                        int num3 = TlsUtilities.ReadUint16(array, 11);
                        if (num2 != num3 + 13)
                        {
                            continue;
                        }
                        byte b = TlsUtilities.ReadUint8(array, 0);
                        switch (b)
                        {
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                        case 24:
                        {
                            int       num4      = TlsUtilities.ReadUint16(array, 3);
                            DtlsEpoch dtlsEpoch = null;
                            if (num4 == this.mReadEpoch.Epoch)
                            {
                                dtlsEpoch = this.mReadEpoch;
                            }
                            else if (b == 22 && this.mRetransmitEpoch != null && num4 == this.mRetransmitEpoch.Epoch)
                            {
                                dtlsEpoch = this.mRetransmitEpoch;
                            }
                            if (dtlsEpoch == null)
                            {
                                continue;
                            }
                            long num5 = TlsUtilities.ReadUint48(array, 5);
                            if (dtlsEpoch.ReplayWindow.ShouldDiscard(num5))
                            {
                                continue;
                            }
                            ProtocolVersion other = TlsUtilities.ReadVersion(array, 1);
                            if (this.mDiscoveredPeerVersion != null && !this.mDiscoveredPeerVersion.Equals(other))
                            {
                                continue;
                            }
                            byte[] array2 = dtlsEpoch.Cipher.DecodeCiphertext(DtlsRecordLayer.GetMacSequenceNumber(dtlsEpoch.Epoch, num5), b, array, 13, num2 - 13);
                            dtlsEpoch.ReplayWindow.ReportAuthenticated(num5);
                            if (array2.Length > this.mPlaintextLimit)
                            {
                                continue;
                            }
                            if (this.mDiscoveredPeerVersion == null)
                            {
                                this.mDiscoveredPeerVersion = other;
                            }
                            switch (b)
                            {
                            case 20:
                                for (int i = 0; i < array2.Length; i++)
                                {
                                    byte b2 = TlsUtilities.ReadUint8(array2, i);
                                    if (b2 == 1 && this.mPendingEpoch != null)
                                    {
                                        this.mReadEpoch = this.mPendingEpoch;
                                    }
                                }
                                continue;

                            case 21:
                                if (array2.Length == 2)
                                {
                                    byte b3 = array2[0];
                                    byte b4 = array2[1];
                                    this.mPeer.NotifyAlertReceived(b3, b4);
                                    if (b3 == 2)
                                    {
                                        this.Fail(b4);
                                        throw new TlsFatalAlert(b4);
                                    }
                                    if (b4 == 0)
                                    {
                                        this.CloseTransport();
                                    }
                                }
                                continue;

                            case 22:
                                if (!this.mInHandshake)
                                {
                                    if (this.mRetransmit != null)
                                    {
                                        this.mRetransmit.ReceivedHandshakeRecord(num4, array2, 0, array2.Length);
                                    }
                                    continue;
                                }
                                break;

                            case 23:
                                if (this.mInHandshake)
                                {
                                    continue;
                                }
                                break;

                            case 24:
                                continue;
                            }
                            if (!this.mInHandshake && this.mRetransmit != null)
                            {
                                this.mRetransmit      = null;
                                this.mRetransmitEpoch = null;
                            }
                            Array.Copy(array2, 0, buf, off, array2.Length);
                            result = array2.Length;
                            break;
                        }

                        default:
                            continue;
                        }
                    }
                }
                catch (IOException ex)
                {
                    throw ex;
                }
                break;
            }
            return(result);
        }
        private void ProcessRecord(int windowSize, int epoch, byte[] buf, int off, int len)
        {
            bool checkPreviousFlight = false;

            while (len >= MessageHeaderLength)
            {
                int fragment_length = TlsUtilities.ReadUint24(buf, off + 9);
                int message_length  = fragment_length + MessageHeaderLength;
                if (len < message_length)
                {
                    // NOTE: Truncated message - ignore it
                    break;
                }

                int length          = TlsUtilities.ReadUint24(buf, off + 1);
                int fragment_offset = TlsUtilities.ReadUint24(buf, off + 6);
                if (fragment_offset + fragment_length > length)
                {
                    // NOTE: Malformed fragment - ignore it and the rest of the record
                    break;
                }

                /*
                 * NOTE: This very simple epoch check will only work until we want to support
                 * renegotiation (and we're not likely to do that anyway).
                 */
                byte msg_type      = TlsUtilities.ReadUint8(buf, off + 0);
                int  expectedEpoch = msg_type == HandshakeType.finished ? 1 : 0;
                if (epoch != expectedEpoch)
                {
                    break;
                }

                int message_seq = TlsUtilities.ReadUint16(buf, off + 4);
                if (message_seq >= (mNextReceiveSeq + windowSize))
                {
                    // NOTE: Too far ahead - ignore
                }
                else if (message_seq >= mNextReceiveSeq)
                {
                    DtlsReassembler reassembler = (DtlsReassembler)mCurrentInboundFlight[message_seq];
                    if (reassembler == null)
                    {
                        reassembler = new DtlsReassembler(msg_type, length);
                        mCurrentInboundFlight[message_seq] = reassembler;
                    }

                    reassembler.ContributeFragment(msg_type, length, buf, off + MessageHeaderLength, fragment_offset,
                                                   fragment_length);
                }
                else if (mPreviousInboundFlight != null)
                {
                    /*
                     * NOTE: If we receive the previous flight of incoming messages in full again,
                     * retransmit our last flight
                     */

                    DtlsReassembler reassembler = (DtlsReassembler)mPreviousInboundFlight[message_seq];
                    if (reassembler != null)
                    {
                        reassembler.ContributeFragment(msg_type, length, buf, off + MessageHeaderLength, fragment_offset,
                                                       fragment_length);
                        checkPreviousFlight = true;
                    }
                }

                off += message_length;
                len -= message_length;
            }

            if (checkPreviousFlight && CheckAll(mPreviousInboundFlight))
            {
                ResendOutboundFlight();
                ResetAll(mPreviousInboundFlight);
            }
        }
        private int ProcessRecord(int received, byte[] record, byte[] buf, int off)
        {
            // NOTE: received < 0 (timeout) is covered by this first case
            if (received < RECORD_HEADER_LENGTH)
            {
                return(-1);
            }
            int length = TlsUtilities.ReadUint16(record, 11);

            if (received != (length + RECORD_HEADER_LENGTH))
            {
                return(-1);
            }

            byte type = TlsUtilities.ReadUint8(record, 0);

            switch (type)
            {
            case ContentType.alert:
            case ContentType.application_data:
            case ContentType.change_cipher_spec:
            case ContentType.handshake:
            case ContentType.heartbeat:
                break;

            default:
                return(-1);
            }

            int epoch = TlsUtilities.ReadUint16(record, 3);

            DtlsEpoch recordEpoch = null;

            if (epoch == mReadEpoch.Epoch)
            {
                recordEpoch = mReadEpoch;
            }
            else if (type == ContentType.handshake && mRetransmitEpoch != null &&
                     epoch == mRetransmitEpoch.Epoch)
            {
                recordEpoch = mRetransmitEpoch;
            }

            if (recordEpoch == null)
            {
                return(-1);
            }

            long seq = TlsUtilities.ReadUint48(record, 5);

            if (recordEpoch.ReplayWindow.ShouldDiscard(seq))
            {
                return(-1);
            }

            ProtocolVersion version = TlsUtilities.ReadVersion(record, 1);

            if (!version.IsDtls)
            {
                return(-1);
            }

            if (mReadVersion != null && !mReadVersion.Equals(version))
            {
                return(-1);
            }

            byte[] plaintext = recordEpoch.Cipher.DecodeCiphertext(
                GetMacSequenceNumber(recordEpoch.Epoch, seq), type, record, RECORD_HEADER_LENGTH,
                received - RECORD_HEADER_LENGTH);

            recordEpoch.ReplayWindow.ReportAuthenticated(seq);

            if (plaintext.Length > this.mPlaintextLimit)
            {
                return(-1);
            }

            if (mReadVersion == null)
            {
                mReadVersion = version;
            }

            switch (type)
            {
            case ContentType.alert:
            {
                if (plaintext.Length == 2)
                {
                    byte alertLevel       = plaintext[0];
                    byte alertDescription = plaintext[1];

                    mPeer.NotifyAlertReceived(alertLevel, alertDescription);

                    if (alertLevel == AlertLevel.fatal)
                    {
                        Failed();
                        throw new TlsFatalAlert(alertDescription);
                    }

                    // TODO Can close_notify be a fatal alert?
                    if (alertDescription == AlertDescription.close_notify)
                    {
                        CloseTransport();
                    }
                }

                return(-1);
            }

            case ContentType.application_data:
            {
                if (mInHandshake)
                {
                    // TODO Consider buffering application data for new epoch that arrives
                    // out-of-order with the Finished message
                    return(-1);
                }
                break;
            }

            case ContentType.change_cipher_spec:
            {
                // Implicitly receive change_cipher_spec and change to pending cipher state

                for (int i = 0; i < plaintext.Length; ++i)
                {
                    byte message = TlsUtilities.ReadUint8(plaintext, i);
                    if (message != ChangeCipherSpec.change_cipher_spec)
                    {
                        continue;
                    }

                    if (mPendingEpoch != null)
                    {
                        mReadEpoch = mPendingEpoch;
                    }
                }

                return(-1);
            }

            case ContentType.handshake:
            {
                if (!mInHandshake)
                {
                    if (mRetransmit != null)
                    {
                        mRetransmit.ReceivedHandshakeRecord(epoch, plaintext, 0, plaintext.Length);
                    }

                    // TODO Consider support for HelloRequest
                    return(-1);
                }
                break;
            }

            case ContentType.heartbeat:
            {
                // TODO[RFC 6520]
                return(-1);
            }
            }

            /*
             * NOTE: If we receive any non-handshake data in the new epoch implies the peer has
             * received our final flight.
             */
            if (!mInHandshake && mRetransmit != null)
            {
                this.mRetransmit        = null;
                this.mRetransmitEpoch   = null;
                this.mRetransmitTimeout = null;
            }

            Array.Copy(plaintext, 0, buf, off, plaintext.Length);
            return(plaintext.Length);
        }
        internal Message ReceiveMessage()
        {
            if (mSending)
            {
                mSending = false;
                PrepareInboundFlight();
            }
            DtlsReassembler dtlsReassembler = (DtlsReassembler)mCurrentInboundFlight.get_Item((object)mNextReceiveSeq);

            if (dtlsReassembler != null)
            {
                byte[] bodyIfComplete = dtlsReassembler.GetBodyIfComplete();
                if (bodyIfComplete != null)
                {
                    mPreviousInboundFlight = null;
                    return(UpdateHandshakeMessagesDigest(new Message(mNextReceiveSeq++, dtlsReassembler.MsgType, bodyIfComplete)));
                }
            }
            byte[] array = null;
            int    num   = 1000;

            while (true)
            {
                int receiveLimit = mRecordLayer.GetReceiveLimit();
                if (array == null || array.Length < receiveLimit)
                {
                    array = new byte[receiveLimit];
                }
                try
                {
                    while (true)
                    {
                        int num2 = mRecordLayer.Receive(array, 0, receiveLimit, num);
                        if (num2 < 0)
                        {
                            break;
                        }
                        if (num2 < 12)
                        {
                            continue;
                        }
                        int num3 = TlsUtilities.ReadUint24(array, 9);
                        if (num2 != num3 + 12)
                        {
                            continue;
                        }
                        int num4 = TlsUtilities.ReadUint16(array, 4);
                        if (num4 > mNextReceiveSeq + 10)
                        {
                            continue;
                        }
                        byte msg_type = TlsUtilities.ReadUint8(array, 0);
                        int  num5     = TlsUtilities.ReadUint24(array, 1);
                        int  num6     = TlsUtilities.ReadUint24(array, 6);
                        if (num6 + num3 > num5)
                        {
                            continue;
                        }
                        if (num4 < mNextReceiveSeq)
                        {
                            if (mPreviousInboundFlight == null)
                            {
                                continue;
                            }
                            DtlsReassembler dtlsReassembler2 = (DtlsReassembler)mPreviousInboundFlight.get_Item((object)num4);
                            if (dtlsReassembler2 != null)
                            {
                                dtlsReassembler2.ContributeFragment(msg_type, num5, array, 12, num6, num3);
                                if (CheckAll(mPreviousInboundFlight))
                                {
                                    ResendOutboundFlight();
                                    num = Math.Min(num * 2, 60000);
                                    ResetAll(mPreviousInboundFlight);
                                }
                            }
                            continue;
                        }
                        DtlsReassembler dtlsReassembler3 = (DtlsReassembler)mCurrentInboundFlight.get_Item((object)num4);
                        if (dtlsReassembler3 == null)
                        {
                            dtlsReassembler3 = new DtlsReassembler(msg_type, num5);
                            mCurrentInboundFlight.set_Item((object)num4, (object)dtlsReassembler3);
                        }
                        dtlsReassembler3.ContributeFragment(msg_type, num5, array, 12, num6, num3);
                        if (num4 == mNextReceiveSeq)
                        {
                            byte[] bodyIfComplete2 = dtlsReassembler3.GetBodyIfComplete();
                            if (bodyIfComplete2 != null)
                            {
                                mPreviousInboundFlight = null;
                                return(UpdateHandshakeMessagesDigest(new Message(mNextReceiveSeq++, dtlsReassembler3.MsgType, bodyIfComplete2)));
                            }
                        }
                    }
                }
                catch (IOException)
                {
                }
                ResendOutboundFlight();
                num = Math.Min(num * 2, 60000);
            }
        }
        protected virtual void ReceiveClientHelloMessage(MemoryStream buf)
        {
            ProtocolVersion client_version = TlsUtilities.ReadVersion(buf);

            mRecordStream.SetWriteVersion(client_version);

            if (client_version.IsDtls)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            byte[] client_random = TlsUtilities.ReadFully(32, buf);

            /*
             * TODO RFC 5077 3.4. If a ticket is presented by the client, the server MUST NOT attempt to
             * use the Session ID in the ClientHello for stateful session resumption.
             */
            byte[] sessionID = TlsUtilities.ReadOpaque8(buf);
            if (sessionID.Length > 32)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            /*
             * TODO RFC 5246 7.4.1.2. If the session_id field is not empty (implying a session
             * resumption request), this vector MUST include at least the cipher_suite from that
             * session.
             */
            int cipher_suites_length = TlsUtilities.ReadUint16(buf);

            if (cipher_suites_length < 2 || (cipher_suites_length & 1) != 0)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            this.mOfferedCipherSuites = TlsUtilities.ReadUint16Array(cipher_suites_length / 2, buf);

            /*
             * TODO RFC 5246 7.4.1.2. If the session_id field is not empty (implying a session
             * resumption request), it MUST include the compression_method from that session.
             */
            int compression_methods_length = TlsUtilities.ReadUint8(buf);

            if (compression_methods_length < 1)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            this.mOfferedCompressionMethods = TlsUtilities.ReadUint8Array(compression_methods_length, buf);

            /*
             * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
             * extensions appearing in the client hello, and Send a server hello containing no
             * extensions.
             */
            this.mClientExtensions = ReadExtensions(buf);

            /*
             * TODO[resumption] Check RFC 7627 5.4. for required behaviour
             */

            /*
             * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended
             * master secret [..]. (and see 5.2, 5.3)
             */
            this.mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mClientExtensions);
            if (!mSecurityParameters.IsExtendedMasterSecret && mTlsServer.RequiresExtendedMasterSecret())
            {
                throw new TlsFatalAlert(AlertDescription.handshake_failure);
            }

            ContextAdmin.SetClientVersion(client_version);

            mTlsServer.NotifyClientVersion(client_version);
            mTlsServer.NotifyFallback(Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_FALLBACK_SCSV));

            mSecurityParameters.clientRandom = client_random;

            mTlsServer.NotifyOfferedCipherSuites(mOfferedCipherSuites);
            mTlsServer.NotifyOfferedCompressionMethods(mOfferedCompressionMethods);

            /*
             * RFC 5746 3.6. Server Behavior: Initial Handshake
             */
            {
                /*
                 * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
                 * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
                 * ClientHello. Including both is NOT RECOMMENDED.
                 */

                /*
                 * When a ClientHello is received, the server MUST check if it includes the
                 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If it does, set the secure_renegotiation flag
                 * to TRUE.
                 */
                if (Arrays.Contains(mOfferedCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV))
                {
                    this.mSecureRenegotiation = true;
                }

                /*
                 * The server MUST check if the "renegotiation_info" extension is included in the
                 * ClientHello.
                 */
                byte[] renegExtData = TlsUtilities.GetExtensionData(mClientExtensions, ExtensionType.renegotiation_info);
                if (renegExtData != null)
                {
                    /*
                     * If the extension is present, set secure_renegotiation flag to TRUE. The
                     * server MUST then verify that the length of the "renegotiated_connection"
                     * field is zero, and if it is not, MUST abort the handshake.
                     */
                    this.mSecureRenegotiation = true;

                    if (!Arrays.ConstantTimeAreEqual(renegExtData, CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                    {
                        throw new TlsFatalAlert(AlertDescription.handshake_failure);
                    }
                }
            }

            mTlsServer.NotifySecureRenegotiation(this.mSecureRenegotiation);

            if (mClientExtensions != null)
            {
                // NOTE: Validates the padding extension data, if present
                TlsExtensionsUtilities.GetPaddingExtension(mClientExtensions);

                mTlsServer.ProcessClientExtensions(mClientExtensions);
            }
        }
        protected virtual void ReceiveServerHelloMessage(MemoryStream buf)
        {
            ProtocolVersion writeVersion = TlsUtilities.ReadVersion(buf);

            if (writeVersion.IsDtls)
            {
                throw new TlsFatalAlert(0x2f);
            }
            if (!writeVersion.Equals(base.mRecordStream.ReadVersion))
            {
                throw new TlsFatalAlert(0x2f);
            }
            ProtocolVersion clientVersion = this.Context.ClientVersion;

            if (!writeVersion.IsEqualOrEarlierVersionOf(clientVersion))
            {
                throw new TlsFatalAlert(0x2f);
            }
            base.mRecordStream.SetWriteVersion(writeVersion);
            this.ContextAdmin.SetServerVersion(writeVersion);
            this.mTlsClient.NotifyServerVersion(writeVersion);
            base.mSecurityParameters.serverRandom = TlsUtilities.ReadFully(0x20, buf);
            this.mSelectedSessionID = TlsUtilities.ReadOpaque8(buf);
            if (this.mSelectedSessionID.Length > 0x20)
            {
                throw new TlsFatalAlert(0x2f);
            }
            this.mTlsClient.NotifySessionID(this.mSelectedSessionID);
            base.mResumedSession = ((this.mSelectedSessionID.Length > 0) && (base.mTlsSession != null)) && Arrays.AreEqual(this.mSelectedSessionID, base.mTlsSession.SessionID);
            int n = TlsUtilities.ReadUint16(buf);

            if ((!Arrays.Contains(base.mOfferedCipherSuites, n) || (n == 0)) || (CipherSuite.IsScsv(n) || !TlsUtilities.IsValidCipherSuiteForVersion(n, this.Context.ServerVersion)))
            {
                throw new TlsFatalAlert(0x2f);
            }
            this.mTlsClient.NotifySelectedCipherSuite(n);
            byte num2 = TlsUtilities.ReadUint8(buf);

            if (!Arrays.Contains(base.mOfferedCompressionMethods, num2))
            {
                throw new TlsFatalAlert(0x2f);
            }
            this.mTlsClient.NotifySelectedCompressionMethod(num2);
            base.mServerExtensions = TlsProtocol.ReadExtensions(buf);
            if (base.mServerExtensions != null)
            {
                IEnumerator enumerator = base.mServerExtensions.Keys.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        int current = (int)enumerator.Current;
                        if (current != 0xff01)
                        {
                            if (TlsUtilities.GetExtensionData(base.mClientExtensions, current) == null)
                            {
                                throw new TlsFatalAlert(110);
                            }
                            if (base.mResumedSession)
                            {
                            }
                        }
                    }
                }
                finally
                {
                    if (enumerator is IDisposable disposable)
                    {
                        IDisposable disposable;
                        disposable.Dispose();
                    }
                }
            }
            byte[] extensionData = TlsUtilities.GetExtensionData(base.mServerExtensions, 0xff01);
            if (extensionData != null)
            {
                base.mSecureRenegotiation = true;
                if (!Arrays.ConstantTimeAreEqual(extensionData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
                {
                    throw new TlsFatalAlert(40);
                }
            }
            this.mTlsClient.NotifySecureRenegotiation(base.mSecureRenegotiation);
            IDictionary mClientExtensions = base.mClientExtensions;
            IDictionary mServerExtensions = base.mServerExtensions;

            if (base.mResumedSession)
            {
                if ((n != base.mSessionParameters.CipherSuite) || (num2 != base.mSessionParameters.CompressionAlgorithm))
                {
                    throw new TlsFatalAlert(0x2f);
                }
                mClientExtensions = null;
                mServerExtensions = base.mSessionParameters.ReadServerExtensions();
            }
            base.mSecurityParameters.cipherSuite          = n;
            base.mSecurityParameters.compressionAlgorithm = num2;
            if (mServerExtensions != null)
            {
                bool flag = TlsExtensionsUtilities.HasEncryptThenMacExtension(mServerExtensions);
                if (flag && !TlsUtilities.IsBlockCipherSuite(n))
                {
                    throw new TlsFatalAlert(0x2f);
                }
                base.mSecurityParameters.encryptThenMac       = flag;
                base.mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mServerExtensions);
                base.mSecurityParameters.maxFragmentLength    = this.ProcessMaxFragmentLengthExtension(mClientExtensions, mServerExtensions, 0x2f);
                base.mSecurityParameters.truncatedHMac        = TlsExtensionsUtilities.HasTruncatedHMacExtension(mServerExtensions);
                base.mAllowCertificateStatus = !base.mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(mServerExtensions, 5, 0x2f);
                base.mExpectSessionTicket    = !base.mResumedSession && TlsUtilities.HasExpectedEmptyExtensionData(mServerExtensions, 0x23, 0x2f);
            }
            if (mClientExtensions != null)
            {
                this.mTlsClient.ProcessServerExtensions(mServerExtensions);
            }
            base.mSecurityParameters.prfAlgorithm     = TlsProtocol.GetPrfAlgorithm(this.Context, base.mSecurityParameters.CipherSuite);
            base.mSecurityParameters.verifyDataLength = 12;
        }