Exemplo n.º 1
0
    protected virtual void SendCertificateMessage(Certificate certificate)
    {
        if (certificate == null)
        {
            certificate = Certificate.EmptyChain;
        }
        if (certificate.IsEmpty)
        {
            TlsContext context = Context;
            if (!context.IsServer)
            {
                ProtocolVersion serverVersion = Context.ServerVersion;
                if (serverVersion.IsSsl)
                {
                    string message = serverVersion.ToString() + " client didn't provide credentials";
                    RaiseWarning(41, message);
                    return;
                }
            }
        }
        HandshakeMessage handshakeMessage = new HandshakeMessage(11);

        certificate.Encode(handshakeMessage);
        handshakeMessage.WriteToRecordStream(this);
    }
Exemplo n.º 2
0
 internal static UriIdentifier GetDirectedIdentityUrl(Scenarios scenario, ProtocolVersion providerVersion, bool useSsl)
 {
     return(new UriIdentifier(GetFullUrl("/" + directedIdentityPage, new Dictionary <string, string> {
         { "user", scenario.ToString() },
         { "version", providerVersion.ToString() },
     }, useSsl)));
 }
Exemplo n.º 3
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                .Replace(" ", "")
                .Replace("\\", "")
                .Replace(".", "")
                + "_";

            /*
             * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit
             * of the DTLS server after a fatal alert. As of writing, manual runs show the correct
             * alerts being raised
             */

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
            //    c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadCertificateVerify"));
            //}

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
            //    c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadClientCertificate"));
            //}

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_NONE;
            //    c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
            //    c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadMandatoryCertReqDeclined"));
            //}

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodDefault"));
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodNoCertReq"));
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodOptionalCertReqDeclined"));
            }
        }
Exemplo n.º 4
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                            .Replace(" ", "")
                            .Replace("\\", "")
                            .Replace(".", "")
                            + "_";

            /*
             * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit
             * of the DTLS server after a fatal alert. As of writing, manual runs show the correct
             * alerts being raised
             */

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
            //    c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadCertificateVerify"));
            //}

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
            //    c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadClientCertificate"));
            //}

            //{
            //    TlsTestConfig c = CreateDtlsTestConfig(version);
            //    c.clientAuth = C.CLIENT_AUTH_NONE;
            //    c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
            //    c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

            //    testSuite.Add(new TestCaseData(c).SetName(prefix + "BadMandatoryCertReqDeclined"));
            //}

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodDefault"));
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodNoCertReq"));
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodOptionalCertReqDeclined"));
            }
        }
Exemplo n.º 5
0
        public override string ToString()
        {
            string ret = "";

            ret += "ClientHello: " + ClientVersion.ToString() + "\n";
            ret += "Cipher suites: " + CipherSuites.Count + "\n";
            ret += "Compression methods: " + CompressionMethods.Count;

            return(ret);
        }
Exemplo n.º 6
0
        private static MqttProtocolVersion UnwrapProtocolVersion(ProtocolVersion protocolVersion)
        {
            switch (protocolVersion)
            {
            case ProtocolVersion.ver310: return(MqttProtocolVersion.V310);

            case ProtocolVersion.ver311: return(MqttProtocolVersion.V311);

            default: throw new ArgumentException(protocolVersion.ToString());
            }
        }
Exemplo n.º 7
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                .Replace(" ", "")
                .Replace("\\", "")
                .Replace(".", "")
                + "_";

            {
                TlsTestConfig c = CreateTlsTestConfig(version);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodDefault"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadCertificateVerify"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
                c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadClientCertificate"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;
                c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
                c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadMandatoryCertReqDeclined"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodNoCertReq"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodOptionalCertReqDeclined"));
            }
        }
Exemplo n.º 8
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                            .Replace(" ", "")
                            .Replace("\\", "")
                            .Replace(".", "")
                            + "_";

            {
                TlsTestConfig c = CreateTlsTestConfig(version);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodDefault"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadCertificateVerify"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
                c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadClientCertificate"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth    = C.CLIENT_AUTH_NONE;
                c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
                c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

                testSuite.Add(new TestCaseData(c).SetName(prefix + "BadMandatoryCertReqDeclined"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodNoCertReq"));
            }

            {
                TlsTestConfig c = CreateTlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                testSuite.Add(new TestCaseData(c).SetName(prefix + "GoodOptionalCertReqDeclined"));
            }
        }
        public async ValueTask <Dictionary <string, string> > HelloAsync(CancellationToken token)
        {
            if (_isPubSubMode)
            {
                throw new InvalidOperationException("Cannot send command in PubSub mode");
            }

            string cmd           = PackageCommand("HELLO", ProtocolVersion.ToString());
            int    bytesReceived = await SendCommandAsync(cmd, token);

            List <DataType> result = await _parser.ParseAsync(bytesReceived, token);

            return(ParseDictionaryResponse(result));
        }
Exemplo n.º 10
0
        public override string ToString()
        {
            var queryBuilder = new StringBuilder(512);

            queryBuilder.AppendFormat("{0} {1} RTSP/{2}\r\n", Method, ConnectionUri, ProtocolVersion.ToString(2));
            queryBuilder.AppendFormat("CSeq: {0}\r\n", CSeq);

            if (!string.IsNullOrEmpty(UserAgent))
            {
                queryBuilder.AppendFormat("User-Agent: {0}\r\n", UserAgent);
            }

            foreach (string headerName in Headers.AllKeys)
            {
                queryBuilder.AppendFormat("{0}: {1}\r\n", headerName, Headers[headerName]);
            }

            queryBuilder.Append("\r\n");

            return(queryBuilder.ToString());
        }
Exemplo n.º 11
0
        public string CreateData()
        {
            var dataItems = DataItems.ToArray();

            var stringBuilder = new StringBuilder();

            stringBuilder.Append(ProtocolVersion.ToString(CultureInfo));
            stringBuilder.Append("|");
            stringBuilder.Append(ID.ToString(CultureInfo));
            stringBuilder.Append("|");
            stringBuilder.Append(Origin.ToString(CultureInfo));

            if (dataItems.Length == 0)
            {
                stringBuilder.Append("|0|");
                return(stringBuilder.ToString());
            }

            stringBuilder.Append("|");
            stringBuilder.Append(dataItems.Length.ToString(CultureInfo));
            stringBuilder.Append("|0|");

            var num = 0;

            for (var i = 0; i < dataItems.Length - 1; i++)
            {
                num += dataItems[i].Length;
                stringBuilder.Append(num);
                stringBuilder.Append("|");
            }

            foreach (var dataItem in dataItems)
            {
                stringBuilder.Append(dataItem);
            }

            return(stringBuilder.ToString());
        }
Exemplo n.º 12
0
        public void WriteTo(NetBinaryWriter writer)
        {
            bool isBeta = IsBeta;

            void WriteField(string value, bool delimit = true)
            {
                writer.WriteRaw(value);
                if (delimit)
                {
                    writer.Write((short)(isBeta ? '§' : 0)); // null char delimeter
                }
            }

            writer.Write((byte)0xff);
            writer.Write((short)0); // reserved space for message length

            long startPos = writer.Position;

            if (!isBeta)
            {
                WriteField("§1");
                WriteField(ProtocolVersion.ToString());
                WriteField(MinecraftVersion.ToString());
            }
            WriteField(MessageOfTheDay.ToString());
            WriteField(CurrentPlayerCount.ToString());
            WriteField(MaxPlayers.ToString(), delimit: false);

            int byteLength          = (int)(writer.Position - startPos);
            int reservedSpaceOffset = (int)(startPos - sizeof(short));

            long endPosition = writer.Position;

            writer.Seek(reservedSpaceOffset, SeekOrigin.Begin);
            writer.Write((short)(byteLength / sizeof(char)));

            writer.Seek((int)endPosition, SeekOrigin.Begin);
        }
        /// <summary>Builds rfc-5424 compatible message</summary>
        /// <param name="logEvent">The NLog.LogEventInfo</param>
        /// <param name="facility">Syslog Facility to transmit message from</param>
        /// <param name="severity">Syslog severity level</param>
        /// <param name="body">Message text</param>
        /// <returns>Byte array containing formatted syslog message</returns>
        private byte[] BuildSyslogMessage5424(LogEventInfo logEvent, SyslogFacility facility, SyslogSeverity severity, string body)
        {
            // Calculate PRI field
            var priority = CalculatePriorityValue(facility, severity).ToString(CultureInfo.InvariantCulture);
            var version  = ProtocolVersion.ToString(CultureInfo.InvariantCulture);
            var time     = logEvent.TimeStamp.ToString("o");
            // Get sender machine name
            var machine = Left(MachineName.Render(logEvent), 255);
            var sender  = Left(Sender.Render(logEvent), 48);
            var procId  = Left(ProcId.Render(logEvent), 128);
            var msgId   = Left(MsgId.Render(logEvent), 32);

            var headerData     = Encoding.ASCII.GetBytes($"<{priority}>{version} {time} {machine} {sender} {procId} {msgId} ");
            var structuredData = Encoding.UTF8.GetBytes(StructuredData.Render(logEvent) + " ");
            var messageData    = Encoding.UTF8.GetBytes(body);

            var allData = new List <byte>(headerData.Length + structuredData.Length + _bom.Length + messageData.Length);

            allData.AddRange(headerData);
            allData.AddRange(structuredData);
            allData.AddRange(_bom);
            allData.AddRange(messageData);
            return(allData.ToArray());
        }
Exemplo n.º 14
0
        //--- Auth ---\\

        public AniDBRequest Auth(string user, string pass, bool nat = false,
                                 bool comp = false, int mtu = 0, bool imgServer = false)
        {
            var parValues =
                new Dictionary <string, string>
            {
                { "user", user },
                { "pass", pass },
                { "protover", ProtocolVersion.ToString(CultureInfo.InvariantCulture) },
                { "client", ClientName },
                { "clientver", ClientVer.ToString(CultureInfo.InvariantCulture) },
            };

            if (nat)
            {
                parValues.Add("nat", "1");
            }
            if (comp)
            {
                parValues.Add("comp", "1");
            }
            if (_encoding != null)
            {
                parValues.Add("enc", _encoding.WebName);
            }
            if (mtu > 0)
            {
                parValues.Add("mtu", mtu.ToString(CultureInfo.InvariantCulture));
            }
            if (imgServer)
            {
                parValues.Add("imgserver", "1");
            }

            return(QueueCommand("AUTH", parValues));
        }
Exemplo n.º 15
0
 public override string ToString()
 {
     return($"ClientHello: {ClientVersion.ToString()}, {CipherSuites.Count} cipher suites, {CompressionMethods.Count} compression methods, {Extensions.Count} extensions");
 }
Exemplo n.º 16
0
        public void Handle(NetworkClient Client, Hypercube Core)
        {
            Client.CS.LoginName = Name;
            Client.CS.MPPass    = MOTD;

            if (ProtocolVersion != 7)
            {
                Core.Logger._Log("Info", "Handshake", "Disconnecting client '" + Name + "'. Unsupported protocol verison (" + ProtocolVersion.ToString() + ")");

                var DisconnectPack = new Disconnect();
                DisconnectPack.Reason = "Unsupported protocol version.";
                DisconnectPack.Write(Client);
            }

            if (!Core.ClassicubeHeartbeat.VerifyClientName(Client))
            {
                Core.Logger._Log("Info", "Handshake", "Disconnecting client '" + Name + "'. Failed to verify name.");

                var DisconnectPack = new Disconnect();
                DisconnectPack.Reason = "Name verification incorrect.";
                DisconnectPack.Write(Client);
            }

            if (Libraries.Text.StringMatches(Name))
            {
                Core.Logger._Log("Info", "Handshake", "Disconnecting Client '" + Name + "'. Invalid characters in name.");

                var DisconnectPack = new Disconnect();
                DisconnectPack.Reason = "Invalid characters in name.";
                DisconnectPack.Write(Client);
            }

            if (Name == "")
            {
                Core.Logger._Log("Info", "Handshake", "Disconnecting Client '" + Name + "'. Invalid characters in name.");

                var DisconnectPack = new Disconnect();
                DisconnectPack.Reason = "Invalid characters in name.";
                DisconnectPack.Write(Client);
            }

            if (Core.OnlinePlayers > Core.nh.MaxPlayers)
            {
                var DisconnectPack = new Disconnect();
                DisconnectPack.Reason = "Server is full.";
                DisconnectPack.Write(Client);
            }

            Client.CS.MPPass     = MOTD;
            Client.CS.LastActive = System.DateTime.UtcNow;

            if (Usertype == 66)
            {
                // -- CPE Client
                Core.Logger._Log("Info", "Handshake", "CPE Client Detected.");
                Client.CS.CPE = true;
                CPE.CPEHandshake(Client);
            }
            else
            {
                // -- Normal Client.
                Client.CS.CPE = false;
                Client.Login();
            }
        }
Exemplo n.º 17
0
        private void RejectClientVersion(KPRPCMessage kprpcm)
        {
            KPRPCMessage data2client = new KPRPCMessage();

            data2client.protocol = "error";
            data2client.srp      = new SRPParams();
            data2client.version  = ProtocolVersion;

            // From 1.7 onwards, the client can never be too new but can be too low if we find that it is missing essential features
            data2client.error = new Error(ErrorCode.VERSION_CLIENT_TOO_LOW, new string[] { ProtocolVersion.ToString() });
            AbortWithMessageToClient(data2client);
            return;
        }
Exemplo n.º 18
0
        public static string ToVersionString(this ProtocolVersion version)
        {
            var attr = version.GetPossibleAttribute <ProtocolVersion, ProtocolVersionNameAttribute>();

            return(attr?.Name ?? version.ToString());
        }
Exemplo n.º 19
0
 internal static UriIdentifier GetIdentityUrl(Scenarios scenario, ProtocolVersion providerVersion, bool useSsl)
 {
     return new UriIdentifier(GetFullUrl("/" + identityPage, new Dictionary<string, string> {
         { "user", scenario.ToString() },
         { "version", providerVersion.ToString() },
     }, useSsl));
 }
Exemplo n.º 20
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                .Replace(" ", "")
                .Replace("\\", "")
                .Replace(".", "")
                + "_";

            /*
             * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit
             * of the DTLS server after a fatal alert. As of writing, manual runs show the correct
             * alerts being raised
             */

#if false
            /*
             * Server only declares support for SHA1/RSA, client selects MD5/RSA. Since the client is
             * NOT actually tracking MD5 over the handshake, we expect fatal alert from the client.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.serverCertReqSigAlgs = TlsUtilities.GetDefaultRsaSignatureAlgorithms();
                c.ExpectClientFatalAlert(AlertDescription.internal_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifyHashAlg");
            }

            /*
             * Server only declares support for SHA1/ECDSA, client selects SHA1/RSA. Since the client is
             * actually tracking SHA1 over the handshake, we expect fatal alert to come from the server
             * when it verifies the selected algorithm against the CertificateRequest supported
             * algorithms.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa);
                c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms();
                c.ExpectServerFatalAlert(AlertDescription.illegal_parameter);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlg");
            }

            /*
             * Server only declares support for SHA1/ECDSA, client signs with SHA1/RSA, but sends
             * SHA1/ECDSA in the CertificateVerify. Since the client is actually tracking SHA1 over the
             * handshake, and the claimed algorithm is in the CertificateRequest supported algorithms,
             * we expect fatal alert to come from the server when it finds the claimed algorithm
             * doesn't match the client certificate.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa);
                c.clientAuthSigAlgClaimed = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa);
                c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms();
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlgMismatch");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySignature");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
                c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

                AddTestCase(testSuite, c, prefix + "BadClientCertificate");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;
                c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
                c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

                AddTestCase(testSuite, c, prefix + "BadMandatoryCertReqDeclined");
            }

            /*
             * Server selects MD5/RSA for ServerKeyExchange signature, which is not in the default
             * supported signature algorithms that the client sent. We expect fatal alert from the
             * client when it verifies the selected algorithm against the supported algorithms.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.ExpectClientFatalAlert(AlertDescription.illegal_parameter);

                AddTestCase(testSuite, c, prefix + "BadServerKeyExchangeSigAlg");
            }

            /*
             * Server selects MD5/RSA for ServerKeyExchange signature, which is not the default {sha1,rsa}
             * implied by the absent signature_algorithms extension. We expect fatal alert from the
             * client when it verifies the selected algorithm against the implicit default.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientSendSignatureAlgorithms = false;
                c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.ExpectClientFatalAlert(AlertDescription.illegal_parameter);

                AddTestCaseDebug(testSuite, c, prefix + "BadServerKeyExchangeSigAlg2");
            }
#endif

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);

                AddTestCase(testSuite, c, prefix + "GoodDefault");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                AddTestCase(testSuite, c, prefix + "GoodNoCertReq");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                AddTestCase(testSuite, c, prefix + "GoodOptionalCertReqDeclined");
            }
        }
Exemplo n.º 21
0
        public void ReceiveMessage(string message, KeePassRPCService service)
        {
            // Inspect incoming message
            KPRPCMessage kprpcm;
            int          requiredCommsVersion = 1;

            try
            {
                kprpcm = (KPRPCMessage)Jayrock.Json.Conversion.JsonConvert.Import(typeof(KPRPCMessage), message);
            }
            catch (Exception)
            {
                kprpcm = null;
            }

            if (kprpcm == null)
            {
                KPRPCMessage data2client = new KPRPCMessage();
                data2client.protocol = "error";
                data2client.srp      = new SRPParams();
                data2client.version  = ProtocolVersion;

                data2client.error = new Error(ErrorCode.INVALID_MESSAGE, new string[] { "Contents can't be interpreted as an SRPEncapsulatedMessage" });
                this.Authorised   = false;

                string response = Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client);
                this.WebSocketConnection.Send(response);
                return;
            }

            if (kprpcm.version != ProtocolVersion)
            {
                KPRPCMessage data2client = new KPRPCMessage();
                data2client.protocol = "error";
                data2client.srp      = new SRPParams();
                data2client.version  = ProtocolVersion;

                data2client.error = new Error(kprpcm.version > ProtocolVersion ? ErrorCode.VERSION_CLIENT_TOO_HIGH : ErrorCode.VERSION_CLIENT_TOO_LOW, new string[] { ProtocolVersion.ToString() });
                this.Authorised   = false;

                string response = Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client);
                this.WebSocketConnection.Send(response);
                return;
            }

            //1: Is it an SRP message?
            switch (kprpcm.protocol)
            {
            case "setup": KPRPCReceiveSetup(kprpcm); break;

            case "jsonrpc": KPRPCReceiveJSONRPC(kprpcm.jsonrpc, service); break;

            default: KPRPCMessage data2client = new KPRPCMessage();
                data2client.protocol = "error";
                data2client.srp      = new SRPParams();
                data2client.version  = ProtocolVersion;

                data2client.error = new Error(ErrorCode.UNRECOGNISED_PROTOCOL, new string[] { "Use setup or jsonrpc" });
                this.Authorised   = false;

                string response = Jayrock.Json.Conversion.JsonConvert.ExportToString(data2client);
                this.WebSocketConnection.Send(response);
                return;
            }
        }
Exemplo n.º 22
0
        private static void AddVersionTests(IList testSuite, ProtocolVersion version)
        {
            string prefix = version.ToString()
                            .Replace(" ", "")
                            .Replace("\\", "")
                            .Replace(".", "")
                            + "_";

            /*
             * NOTE: Temporarily disabled automatic test runs because of problems getting a clean exit
             * of the DTLS server after a fatal alert. As of writing, manual runs show the correct
             * alerts being raised
             */

#if false
            /*
             * Server only declares support for SHA1/RSA, client selects MD5/RSA. Since the client is
             * NOT actually tracking MD5 over the handshake, we expect fatal alert from the client.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth           = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg     = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.serverCertReqSigAlgs = TlsUtilities.GetDefaultRsaSignatureAlgorithms();
                c.ExpectClientFatalAlert(AlertDescription.internal_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifyHashAlg");
            }

            /*
             * Server only declares support for SHA1/ECDSA, client selects SHA1/RSA. Since the client is
             * actually tracking SHA1 over the handshake, we expect fatal alert to come from the server
             * when it verifies the selected algorithm against the CertificateRequest supported
             * algorithms.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth           = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg     = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa);
                c.serverCertReqSigAlgs = TlsUtilities.GetDefaultECDsaSignatureAlgorithms();
                c.ExpectServerFatalAlert(AlertDescription.illegal_parameter);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlg");
            }

            /*
             * Server only declares support for SHA1/ECDSA, client signs with SHA1/RSA, but sends
             * SHA1/ECDSA in the CertificateVerify. Since the client is actually tracking SHA1 over the
             * handshake, and the claimed algorithm is in the CertificateRequest supported algorithms,
             * we expect fatal alert to come from the server when it finds the claimed algorithm
             * doesn't match the client certificate.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth              = C.CLIENT_AUTH_VALID;
                c.clientAuthSigAlg        = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.rsa);
                c.clientAuthSigAlgClaimed = new SignatureAndHashAlgorithm(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa);
                c.serverCertReqSigAlgs    = TlsUtilities.GetDefaultECDsaSignatureAlgorithms();
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySigAlgMismatch");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_VERIFY;
                c.ExpectServerFatalAlert(AlertDescription.decrypt_error);

                AddTestCase(testSuite, c, prefix + "BadCertificateVerifySignature");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_INVALID_CERT;
                c.ExpectServerFatalAlert(AlertDescription.bad_certificate);

                AddTestCase(testSuite, c, prefix + "BadClientCertificate");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth    = C.CLIENT_AUTH_NONE;
                c.serverCertReq = C.SERVER_CERT_REQ_MANDATORY;
                c.ExpectServerFatalAlert(AlertDescription.handshake_failure);

                AddTestCase(testSuite, c, prefix + "BadMandatoryCertReqDeclined");
            }

            /*
             * Server selects MD5/RSA for ServerKeyExchange signature, which is not in the default
             * supported signature algorithms that the client sent. We expect fatal alert from the
             * client when it verifies the selected algorithm against the supported algorithms.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.ExpectClientFatalAlert(AlertDescription.illegal_parameter);

                AddTestCase(testSuite, c, prefix + "BadServerKeyExchangeSigAlg");
            }

            /*
             * Server selects MD5/RSA for ServerKeyExchange signature, which is not the default {sha1,rsa}
             * implied by the absent signature_algorithms extension. We expect fatal alert from the
             * client when it verifies the selected algorithm against the implicit default.
             */
            if (TlsUtilities.IsTlsV12(version))
            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientSendSignatureAlgorithms = false;
                c.serverAuthSigAlg = new SignatureAndHashAlgorithm(HashAlgorithm.md5, SignatureAlgorithm.rsa);
                c.ExpectClientFatalAlert(AlertDescription.illegal_parameter);

                AddTestCaseDebug(testSuite, c, prefix + "BadServerKeyExchangeSigAlg2");
            }
#endif

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);

                AddTestCase(testSuite, c, prefix + "GoodDefault");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.serverCertReq = C.SERVER_CERT_REQ_NONE;

                AddTestCase(testSuite, c, prefix + "GoodNoCertReq");
            }

            {
                TlsTestConfig c = CreateDtlsTestConfig(version);
                c.clientAuth = C.CLIENT_AUTH_NONE;

                AddTestCase(testSuite, c, prefix + "GoodOptionalCertReqDeclined");
            }
        }
Exemplo n.º 23
0
 public static string ToText(this ProtocolVersion ver)
 {
     return(ver.ToString().Replace("_", ".").Replace("pre", "-pre").TrimStart(new char[] { 'v' }));
 }
Exemplo n.º 24
0
            //
            // Decode the received frame
            //
            Boolean Decode(out String packetFrame)
            {
                Int32         ptr    = 0;
                Boolean       retVal = false;
                StringBuilder s      = new StringBuilder("|", 4096);

                try
                {
                    //
                    //  Catch any exceptions during decode
                    //
                    ptr = staLink.destinationStation.Decode(inBuf, ptr);
                    ptr = staLink.sourceStation.Decode(inBuf, ptr);

                    s.Append("|" + staLink.sourceStation.stationIDString + "|ch=" + staLink.sourceStation.chBit.ToString());
                    s.Append("|" + staLink.destinationStation.stationIDString + "|ch=" + staLink.destinationStation.chBit.ToString());

                    if (staLink.sourceStation.extBit == 0)
                    {
                        ptr = staLink.relayStation1.Decode(inBuf, ptr);
                        s.Append("|" + staLink.relayStation1.stationIDString + "|ch=" + staLink.relayStation1.chBit.ToString());
                        if (staLink.relayStation1.extBit == 0)
                        {
                            ptr = staLink.relayStation2.Decode(inBuf, ptr);
                            s.Append("|" + staLink.relayStation2.stationIDString + "|ch=" + staLink.relayStation2.chBit.ToString());
                            if (staLink.relayStation2.extBit == 0)
                            {
                                StationAddress tmpR = new StationAddress();
                                s.Append("|r??:(");

                                do
                                {
                                    ptr = tmpR.Decode(inBuf, ptr);
                                    s.Append("\\" + tmpR.stationIDString + ":ch=" + tmpR.chBit.ToString());
                                } while (tmpR.extBit == 0);
                                s.Append(")");
                                //throw new Exception("Too many relay addresses");
                            }
                            else
                            {
                                s.Append("|");
                            }
                        }
                        else
                        {
                            s.Append("||");
                        }
                    }
                    else
                    {
                        s.Append("|||");
                    }
                    cmdOctetPtr = ptr;

                    if ((staLink.destinationStation.chBit == staLink.sourceStation.chBit))
                    {
                        //
                        // Old protocol version
                        //
                        version = ProtocolVersion.V20;
                    }
                    else
                    {
                        //
                        // New protocol version
                        //
                        version = ProtocolVersion.V22;
                    }

                    if (staLink.destinationStation.chBit == 0)
                    {
                        //
                        // Response type
                        //
                        cmdResp = PacketType.Response;
                    }
                    else
                    {
                        //
                        // Command type
                        //
                        cmdResp = PacketType.Command;
                    }

                    //
                    // Get frame type.  I and S frame must be decoded later after we know whether we
                    // are using mod8 or mod128 sequence numbers.
                    //
                    Byte   tmp = inBuf[ptr];
                    String t   = "";

                    pfBit = (tmp >> 4) & 0x01;      //ToDo  change needed to support SABME

                    seqNumMode = SequenceNumberMode.Mod8;

                    //Frame.InformationFrame.Decode(this, rawBuf, ptr, out t);

                    if ((tmp & 0x01) == I)
                    {
                        //
                        // I frame
                        //
                        frameClass = FrameClasses.IClass;
                        frameType  = FrameTypes.IType;
                        ptr        = InformationFrame.Decode(this, inBuf, ptr, out t);
                    }

                    if ((tmp & 0x03) == S)
                    {
                        //
                        // S frame
                        //
                        frameClass = FrameClasses.SClass;
                        frameType  = (FrameTypes)(tmp & 0x0f);
                        ptr        = SupervisoryFrame.Decode(this, inBuf, ptr, out t);
                    }

                    if ((tmp & 0x03) == U)
                    {
                        //
                        // U frame.  We can decode uFrames right away
                        //
                        frameClass = FrameClasses.UClass;
                        frameType  = (FrameTypes)(tmp & 0xef);
                        ptr        = UnnumberedFrame.Decode(this, inBuf, ptr, out t);
                    }
                    s.Append("|" + version.ToString() + "|" + frameType.ToString() + "|" + cmdResp.ToString() + "|pf=" + pfBit.ToString());

                    if (t.Length > 0)
                    {
                        s.Append(t);
                    }
                    s.Append(Support.DumpRawFrame(rawBuf));

                    retVal = true;
                }
                catch (Exception ex)
                {
                    s.Append(ex.Message + CRLF);
                    Support.DbgPrint("Exception during frame decode:" + ex.Message + CRLF);
                    retVal = false;
                }
                finally
                {
                    s.Append("]");
                    packetFrame = s.ToString();
                }

                return(retVal);
            }