Exemple #1
0
        /**
         * Parse a {@link ServerNameList} from a {@link Stream}.
         *
         * @param input
         *            the {@link Stream} to parse from.
         * @return a {@link ServerNameList} object.
         * @throws IOException
         */
        public static ServerNameList Parse(Stream input)
        {
            int length = TlsUtilities.ReadUint16(input);

            if (length < 1)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            byte[] data = TlsUtilities.ReadFully(length, input);

            MemoryStream buf = new MemoryStream(data, false);

            byte[] nameTypesSeen    = TlsUtilities.EmptyBytes;
            IList  server_name_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();

            while (buf.Position < buf.Length)
            {
                ServerName entry = ServerName.Parse(buf);

                nameTypesSeen = CheckNameType(nameTypesSeen, entry.NameType);
                if (nameTypesSeen == null)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                server_name_list.Add(entry);
            }

            return(new ServerNameList(server_name_list));
        }
    public static OcspStatusRequest Parse(Stream input)
    {
        IList list = Platform.CreateArrayList();
        int   num  = TlsUtilities.ReadUint16(input);

        if (num > 0)
        {
            byte[]       buffer       = TlsUtilities.ReadFully(num, input);
            MemoryStream memoryStream = new MemoryStream(buffer, writable: false);
            do
            {
                byte[]      encoding = TlsUtilities.ReadOpaque16(memoryStream);
                ResponderID instance = ResponderID.GetInstance(TlsUtilities.ReadDerObject(encoding));
                list.Add(instance);
            }while (memoryStream.Position < memoryStream.Length);
        }
        X509Extensions requestExtensions = null;
        int            num2 = TlsUtilities.ReadUint16(input);

        if (num2 > 0)
        {
            byte[] encoding2 = TlsUtilities.ReadFully(num2, input);
            requestExtensions = X509Extensions.GetInstance(TlsUtilities.ReadDerObject(encoding2));
        }
        return(new OcspStatusRequest(list, requestExtensions));
    }
Exemple #3
0
        /**
         * Parse a {@link OcspStatusRequest} from a {@link Stream}.
         *
         * @param input
         *            the {@link Stream} to parse from.
         * @return an {@link OcspStatusRequest} object.
         * @throws IOException
         */
        public static OcspStatusRequest Parse(Stream input)
        {
            IList responderIDList = Platform.CreateArrayList();
            {
                int length = TlsUtilities.ReadUint16(input);
                if (length > 0)
                {
                    byte[]       data = TlsUtilities.ReadFully(length, input);
                    MemoryStream buf  = new MemoryStream(data, false);
                    do
                    {
                        byte[]      derEncoding = TlsUtilities.ReadOpaque16(buf);
                        ResponderID responderID = ResponderID.GetInstance(TlsUtilities.ReadDerObject(derEncoding));
                        responderIDList.Add(responderID);
                    }while (buf.Position < buf.Length);
                }
            }

            X509Extensions requestExtensions = null;

            {
                int length = TlsUtilities.ReadUint16(input);
                if (length > 0)
                {
                    byte[] derEncoding = TlsUtilities.ReadFully(length, input);
                    requestExtensions = X509Extensions.GetInstance(TlsUtilities.ReadDerObject(derEncoding));
                }
            }

            return(new OcspStatusRequest(responderIDList, requestExtensions));
        }
    public static Certificate Parse(Stream input)
    {
        int num = TlsUtilities.ReadUint24(input);

        if (num == 0)
        {
            return(EmptyChain);
        }
        byte[]       buffer       = TlsUtilities.ReadFully(num, input);
        MemoryStream memoryStream = new MemoryStream(buffer, writable: false);
        IList        list         = Platform.CreateArrayList();

        while (memoryStream.Position < memoryStream.Length)
        {
            byte[]     encoding = TlsUtilities.ReadOpaque24(memoryStream);
            Asn1Object obj      = TlsUtilities.ReadDerObject(encoding);
            list.Add(X509CertificateStructure.GetInstance(obj));
        }
        X509CertificateStructure[] array = new X509CertificateStructure[list.Count];
        for (int i = 0; i < list.Count; i++)
        {
            array[i] = (X509CertificateStructure)list[i];
        }
        return(new Certificate(array));
    }
Exemple #5
0
        /**
         * Parse a {@link Certificate} from a {@link Stream}.
         *
         * @param input the {@link Stream} to parse from.
         * @return a {@link Certificate} object.
         * @throws IOException
         */
        public static Certificate Parse(Stream input)
        {
            int totalLength = TlsUtilities.ReadUint24(input);

            if (totalLength == 0)
            {
                return(EmptyChain);
            }

            byte[] certListData = TlsUtilities.ReadFully(totalLength, input);

            MemoryStream buf = new MemoryStream(certListData, false);

            IList certificate_list = Platform.CreateArrayList();

            while (buf.Position < buf.Length)
            {
                byte[]     derEncoding = TlsUtilities.ReadOpaque24(buf);
                Asn1Object asn1Cert    = TlsUtilities.ReadDerObject(derEncoding);
                certificate_list.Add(X509CertificateStructure.GetInstance(asn1Cert));
            }

            X509CertificateStructure[] certificateList = new X509CertificateStructure[certificate_list.Count];
            for (int i = 0; i < certificate_list.Count; ++i)
            {
                certificateList[i] = (X509CertificateStructure)certificate_list[i];
            }
            return(new Certificate(certificateList));
        }
Exemple #6
0
    public static CertificateUrl parse(TlsContext context, Stream input)
    {
        byte b = TlsUtilities.ReadUint8(input);

        if (!CertChainType.IsValid(b))
        {
            throw new TlsFatalAlert(50);
        }
        int num = TlsUtilities.ReadUint16(input);

        if (num < 1)
        {
            throw new TlsFatalAlert(50);
        }
        byte[]       buffer       = TlsUtilities.ReadFully(num, input);
        MemoryStream memoryStream = new MemoryStream(buffer, writable: false);
        IList        list         = Platform.CreateArrayList();

        while (memoryStream.Position < memoryStream.Length)
        {
            UrlAndHash value = UrlAndHash.Parse(context, memoryStream);
            list.Add(value);
        }
        return(new CertificateUrl(b, list));
    }
Exemple #7
0
        /**
         * Parse a {@link UrlAndHash} from a {@link Stream}.
         *
         * @param context
         *            the {@link TlsContext} of the current connection.
         * @param input
         *            the {@link Stream} to parse from.
         * @return a {@link UrlAndHash} object.
         * @throws IOException
         */
        public static UrlAndHash Parse(TlsContext context, Stream input)
        {
            byte[] urlEncoding = TlsUtilities.ReadOpaque16(input);
            if (urlEncoding.Length < 1)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            string url = Strings.FromByteArray(urlEncoding);

            byte[] sha1Hash = null;
            byte   padding  = TlsUtilities.ReadUint8(input);

            switch (padding)
            {
            case 0:
                if (TlsUtilities.IsTlsV12(context))
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }
                break;

            case 1:
                sha1Hash = TlsUtilities.ReadFully(20, input);
                break;

            default:
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            return(new UrlAndHash(url, sha1Hash));
        }
Exemple #8
0
        /**
         * Parse a {@link CertificateUrl} from a {@link Stream}.
         *
         * @param context
         *            the {@link TlsContext} of the current connection.
         * @param input
         *            the {@link Stream} to parse from.
         * @return a {@link CertificateUrl} object.
         * @throws IOException
         */
        public static CertificateUrl parse(TlsContext context, Stream input)
        {
            byte type = TlsUtilities.ReadUint8(input);

            if (!CertChainType.IsValid(type))
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            int totalLength = TlsUtilities.ReadUint16(input);

            if (totalLength < 1)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            byte[] urlAndHashListData = TlsUtilities.ReadFully(totalLength, input);

            MemoryStream buf = new MemoryStream(urlAndHashListData, false);

            IList url_and_hash_list = Platform.CreateArrayList();

            while (buf.Position < buf.Length)
            {
                UrlAndHash url_and_hash = UrlAndHash.Parse(context, buf);
                url_and_hash_list.Add(url_and_hash);
            }

            return(new CertificateUrl(type, url_and_hash_list));
        }
    public static UrlAndHash Parse(TlsContext context, Stream input)
    {
        byte[] array = TlsUtilities.ReadOpaque16(input);
        if (array.Length < 1)
        {
            throw new TlsFatalAlert(47);
        }
        string url = Strings.FromByteArray(array);

        byte[] sha1Hash = null;
        switch (TlsUtilities.ReadUint8(input))
        {
        case 0:
            if (TlsUtilities.IsTlsV12(context))
            {
                throw new TlsFatalAlert(47);
            }
            break;

        case 1:
            sha1Hash = TlsUtilities.ReadFully(20, input);
            break;

        default:
            throw new TlsFatalAlert(47);
        }
        return(new UrlAndHash(url, sha1Hash));
    }
    protected virtual void ReceiveClientHelloMessage(MemoryStream buf)
    {
        ProtocolVersion protocolVersion = TlsUtilities.ReadVersion(buf);

        mRecordStream.SetWriteVersion(protocolVersion);
        if (protocolVersion.IsDtls)
        {
            throw new TlsFatalAlert(47);
        }
        byte[] clientRandom = TlsUtilities.ReadFully(32, buf);
        byte[] array        = TlsUtilities.ReadOpaque8(buf);
        if (array.Length > 32)
        {
            throw new TlsFatalAlert(47);
        }
        int num = TlsUtilities.ReadUint16(buf);

        if (num < 2 || (num & 1) != 0)
        {
            throw new TlsFatalAlert(50);
        }
        mOfferedCipherSuites = TlsUtilities.ReadUint16Array(num / 2, buf);
        int num2 = TlsUtilities.ReadUint8(buf);

        if (num2 < 1)
        {
            throw new TlsFatalAlert(47);
        }
        mOfferedCompressionMethods = TlsUtilities.ReadUint8Array(num2, buf);
        mClientExtensions          = TlsProtocol.ReadExtensions(buf);
        mSecurityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mClientExtensions);
        ContextAdmin.SetClientVersion(protocolVersion);
        mTlsServer.NotifyClientVersion(protocolVersion);
        mTlsServer.NotifyFallback(Arrays.Contains(mOfferedCipherSuites, 22016));
        mSecurityParameters.clientRandom = clientRandom;
        mTlsServer.NotifyOfferedCipherSuites(mOfferedCipherSuites);
        mTlsServer.NotifyOfferedCompressionMethods(mOfferedCompressionMethods);
        if (Arrays.Contains(mOfferedCipherSuites, 255))
        {
            mSecureRenegotiation = true;
        }
        byte[] extensionData = TlsUtilities.GetExtensionData(mClientExtensions, 65281);
        if (extensionData != null)
        {
            mSecureRenegotiation = true;
            if (!Arrays.ConstantTimeAreEqual(extensionData, TlsProtocol.CreateRenegotiationInfo(TlsUtilities.EmptyBytes)))
            {
                throw new TlsFatalAlert(40);
            }
        }
        mTlsServer.NotifySecureRenegotiation(mSecureRenegotiation);
        if (mClientExtensions != null)
        {
            mTlsServer.ProcessClientExtensions(mClientExtensions);
        }
    }
    protected virtual void ProcessFinished(byte[] body, byte[] expected_verify_data)
    {
        MemoryStream memoryStream = new MemoryStream(body, writable: false);

        byte[] b = TlsUtilities.ReadFully(expected_verify_data.Length, memoryStream);
        TlsProtocol.AssertEmpty(memoryStream);
        if (!Arrays.ConstantTimeAreEqual(expected_verify_data, b))
        {
            throw new TlsFatalAlert(40);
        }
    }
        /// <exception cref="IOException"/>
        protected virtual void ProcessFinished(byte[] body, byte[] expected_verify_data)
        {
            MemoryStream buf = new MemoryStream(body, false);

            byte[] verify_data = TlsUtilities.ReadFully(expected_verify_data.Length, buf);

            TlsProtocol.AssertEmpty(buf);

            if (!Arrays.ConstantTimeAreEqual(expected_verify_data, verify_data))
            {
                throw new TlsFatalAlert(AlertDescription.handshake_failure);
            }
        }
Exemple #13
0
 protected virtual void ProcessFinishedMessage(MemoryStream buf)
 {
     if (mExpectedVerifyData == null)
     {
         throw new TlsFatalAlert(80);
     }
     byte[] b = TlsUtilities.ReadFully(mExpectedVerifyData.Length, buf);
     AssertEmpty(buf);
     if (!Arrays.ConstantTimeAreEqual(mExpectedVerifyData, b))
     {
         throw new TlsFatalAlert(51);
     }
 }
Exemple #14
0
        internal virtual byte[] DecodeAndVerify(byte type, Stream input, int len)
        {
            byte[] buf = TlsUtilities.ReadFully(len, input);

            long seqNo = mReadSeqNo.NextValue(AlertDescription.unexpected_message);

            byte[] decoded = mReadCipher.DecodeCiphertext(seqNo, type, buf, 0, buf.Length);

            CheckLength(decoded.Length, mCompressedLimit, AlertDescription.record_overflow);

            /*
             * TODO 5246 6.2.2. Implementation note: Decompression functions are responsible for
             * ensuring that messages cannot cause internal buffer overflows.
             */
            Stream cOut = mReadCompression.Decompress(mBuffer);

            if (cOut != mBuffer)
            {
                cOut.Write(decoded, 0, decoded.Length);
                cOut.Flush();
                decoded = GetBufferContents();
            }

            /*
             * RFC 5246 6.2.2. If the decompression function encounters a TLSCompressed.fragment that
             * would decompress to a length in excess of 2^14 bytes, it should report a fatal
             * decompression failure error.
             */
            CheckLength(decoded.Length, mPlaintextLimit, AlertDescription.decompression_failure);

            /*
             * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
             * or ChangeCipherSpec content types.
             */
            if (decoded.Length < 1 && type != ContentType.application_data)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }

            return(decoded);
        }
Exemple #15
0
    internal virtual byte[] DecodeAndVerify(byte type, Stream input, int len)
    {
        CheckLength(len, mCiphertextLimit, 22);
        byte[] array  = TlsUtilities.ReadFully(len, input);
        byte[] array2 = mReadCipher.DecodeCiphertext(mReadSeqNo++, type, array, 0, array.Length);
        CheckLength(array2.Length, mCompressedLimit, 22);
        Stream stream = mReadCompression.Decompress(mBuffer);

        if (stream != mBuffer)
        {
            stream.Write(array2, 0, array2.Length);
            stream.Flush();
            array2 = GetBufferContents();
        }
        CheckLength(array2.Length, mPlaintextLimit, 30);
        if (array2.Length < 1 && type != 23)
        {
            throw new TlsFatalAlert(47);
        }
        return(array2);
    }
Exemple #16
0
        /**
         * Parse a {@link ServerNameList} from a {@link Stream}.
         *
         * @param input
         *            the {@link Stream} to parse from.
         * @return a {@link ServerNameList} object.
         * @throws IOException
         */
        public static ServerNameList Parse(Stream input)
        {
            int length = TlsUtilities.ReadUint16(input);

            if (length < 1)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            byte[] data = TlsUtilities.ReadFully(length, input);

            MemoryStream buf = new MemoryStream(data, false);

            IList server_name_list = Platform.CreateArrayList();

            while (buf.Position < buf.Length)
            {
                ServerName entry = ServerName.Parse(buf);
                server_name_list.Add(entry);
            }

            return(new ServerNameList(server_name_list));
        }
        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.resumedSession = state.selectedSessionID.Length > 0 && state.tlsSession != null &&
                                   Arrays.AreEqual(state.selectedSessionID, state.tlsSession.SessionID);

            int selectedCipherSuite = TlsUtilities.ReadUint16(buf);

            if (!Arrays.Contains(state.offeredCipherSuites, selectedCipherSuite) ||
                selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL ||
                CipherSuite.IsScsv(selectedCipherSuite) ||
                !TlsUtilities.IsValidCipherSuiteForVersion(selectedCipherSuite, state.clientContext.ServerVersion))
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            ValidateSelectedCipherSuite(selectedCipherSuite, AlertDescription.illegal_parameter);
            state.client.NotifySelectedCipherSuite(selectedCipherSuite);

            byte selectedCompressionMethod = TlsUtilities.ReadUint8(buf);

            if (CompressionMethod.cls_null != selectedCompressionMethod)
            {
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);
            }
            state.client.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.
             */

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

            /*
             * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended
             * master secret [..]. (and see 5.2, 5.3)
             */
            securityParameters.extendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension(state.serverExtensions);

            if (!securityParameters.IsExtendedMasterSecret &&
                (state.resumedSession || state.client.RequiresExtendedMasterSecret()))
            {
                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 (state.serverExtensions != null)
            {
                foreach (int extType in state.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);
                    }

                    /*
                     * 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 (state.resumedSession)
                    {
                        // 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(state.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);
                    }
                }
            }

            // TODO[compat-gnutls] GnuTLS test server fails to send renegotiation_info extension when resuming
            state.client.NotifySecureRenegotiation(state.secure_renegotiation);

            IDictionary sessionClientExtensions = state.clientExtensions, sessionServerExtensions = state.serverExtensions;

            if (state.resumedSession)
            {
                if (selectedCipherSuite != state.sessionParameters.CipherSuite ||
                    selectedCompressionMethod != state.sessionParameters.CompressionAlgorithm)
                {
                    throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                }

                sessionClientExtensions = null;
                sessionServerExtensions = state.sessionParameters.ReadServerExtensions();
            }

            securityParameters.cipherSuite          = selectedCipherSuite;
            securityParameters.compressionAlgorithm = selectedCompressionMethod;

            if (sessionServerExtensions != null && sessionServerExtensions.Count > 0)
            {
                {
                    /*
                     * 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(securityParameters.CipherSuite))
                    {
                        throw new TlsFatalAlert(AlertDescription.illegal_parameter);
                    }
                    securityParameters.encryptThenMac = serverSentEncryptThenMAC;
                }

                securityParameters.maxFragmentLength = EvaluateMaxFragmentLengthExtension(state.resumedSession,
                                                                                          sessionClientExtensions, sessionServerExtensions, AlertDescription.illegal_parameter);

                securityParameters.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.
                 */
                state.allowCertificateStatus = !state.resumedSession &&
                                               TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.status_request,
                                                                                          AlertDescription.illegal_parameter);

                state.expectSessionTicket = !state.resumedSession &&
                                            TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, ExtensionType.session_ticket,
                                                                                       AlertDescription.illegal_parameter);
            }

            if (sessionClientExtensions != null)
            {
                state.client.ProcessServerExtensions(sessionServerExtensions);
            }

            securityParameters.prfAlgorithm = TlsProtocol.GetPrfAlgorithm(state.clientContext,
                                                                          securityParameters.CipherSuite);

            /*
             * RFC 5246 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.
             */
            securityParameters.verifyDataLength = 12;
        }
        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);

                if (HTTPManager.Logger.Level <= Loglevels.All)
                {
                    HTTPManager.Logger.Verbose("TlsClientProtocol", "ReceiveServerHelloMessage server_version: " + server_version.ToString(), this.LoggingContext);
                }
            }

            /*
             * 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);
            }

            if (HTTPManager.Logger.Level <= Loglevels.All)
            {
                HTTPManager.Logger.Verbose("TlsClientProtocol", "ReceiveServerHelloMessage selectedCipherSuite: " + selectedCipherSuite.ToString("X"), this.LoggingContext);
            }

            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);
            }

            if (HTTPManager.Logger.Level <= Loglevels.All)
            {
                HTTPManager.Logger.Verbose("TlsClientProtocol", "ReceiveServerHelloMessage selectedCompressionMethod: " + selectedCompressionMethod.ToString(), this.LoggingContext);
            }

            this.mTlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod);

            /*
             * RFC 3546 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 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 = !TlsUtilities.IsSsl(mTlsClientContext) &&
                                                            TlsExtensionsUtilities.HasExtendedMasterSecretExtension(mServerExtensions);

            if (!mSecurityParameters.IsExtendedMasterSecret &&
                (mResumedSession || mTlsClient.RequiresExtendedMasterSecret()))
            {
                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 (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);
                    }

                    if (HTTPManager.Logger.Level <= Loglevels.All)
                    {
                        HTTPManager.Logger.Verbose("TlsClientProtocol", "ReceiveServerHelloMessage mServerExtensions: " + extType.ToString(), this.LoggingContext);
                    }
                }
            }

            /*
             * 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 && sessionServerExtensions.Count > 0)
            {
                {
                    /*
                     * 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.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);
            }

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

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

            /*
             * RFC 5246 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;
        }
        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;

            /*
             * 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)
             */
            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 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);
            }
        }