예제 #1
0
 public CoreCsrfTokenAnalyzerAuditTest()
 {
     Options          = ConfigurationTest.CreateAnalyzersOptionsWithConfig("AuditMode: true");
     Expected.Message = "Controller method is vulnerable to CSRF";
 }
예제 #2
0
        public async Task DisabledProperty()
        {
            var cSharpTest = $@"
using System.Xml;
using System.Xml.Xsl;

namespace VulnerableApp
{{
    class Test
    {{
        static void Foo(string xslPath)
        {{
            // Create a reader to read books.xml
            XmlReader reader = XmlReader.Create(""books.xml"");

            // Create a writer for writing the transformed file.
            XmlWriter writer = XmlWriter.Create(""books.html"");

            // Create and load the transform with script execution enabled.
            XslCompiledTransform transform = new XslCompiledTransform();
            XsltSettings settings = new XsltSettings();
            settings.EnableScript = false;
            transform.Load(xslPath, settings, null);

            // Execute the transformation.
            transform.Transform(reader, writer);
        }}
    }}
}}
";

            var visualBasicTest = $@"
Imports System.Xml
Imports System.Xml.Xsl

Namespace VulnerableApp
    Class Test
        Private Shared Sub Foo(xslPath As String)
            Dim reader As XmlReader = XmlReader.Create(""books.xml"")
            Dim writer As XmlWriter = XmlWriter.Create(""books.html"")
            Dim transform As XslCompiledTransform = New XslCompiledTransform()
            Dim settings As XsltSettings = New XsltSettings()
            settings.EnableScript = False
            transform.Load(xslPath, settings, Nothing)
            transform.Transform(reader, writer)
        End Sub
    End Class
End Namespace
";

            var testConfig = @"
TaintEntryPoints:
  VulnerableApp:
    Method:
      Name: Foo
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);

            testConfig = @"
AuditMode: true

TaintEntryPoints:
  VulnerableApp:
    Method:
      Name: Foo
";

            optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);
            await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
        }
예제 #3
0
        public async Task MergePostConditions(string cs, string className, string name, string outParam, string taintFromArguments, bool warn)
        {
            var cSharpTest = $@"
using System.Data.SqlClient;

class Test
{{
    public string Foo(string a, string b)
    {{
        return null;
    }}

    public void Run(string a, string b)
    {{
#pragma warning disable CS0219
        Test o = null;
#pragma warning restore CS0219
        {cs}
        new SqlCommand(query);
    }}
}}
";

            var visualBasicTest = $@"
Imports System.Data.SqlClient

Class Test
    Public Function Foo(ByVal a As String, ByVal b As String) As String
        Return Nothing
    End Function

    Public Sub Run(ByVal a As String, ByVal b As String)
        Dim o As Test = Nothing
        {cs.CSharpReplaceToVBasic()}
        Dim temp = New SqlCommand(query)
    End Sub
End Class
";

            var expected = new DiagnosticResult
            {
                Id       = "SCS0026",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = $@"
TaintEntryPoints:
  AAA:
    ClassName: Test

Behavior:
  BBB:
    ClassName: {className}
    Name: {name}
    Method:
      If:
        Condition: {{1: {{Value: """"}}}}
        Then:
          {outParam}:
            Taint: LocalUrl
      {outParam}:
        {taintFromArguments}
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                await VerifyCSharpDiagnostic(cSharpTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            }
        }
예제 #4
0
        public async Task XssFromEntityFrameworkCore(string sink, bool warn)
        {
            var cSharpTest = $@"
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace sample
{{
    public class SampleContext : DbContext
    {{
        public DbSet<string> TestProp {{ get; set; }}
        public DbSet<string> TestField;
    }}

    class MyFoo
    {{
        private void Sink(string s) {{}}

        public void Run()
        {{
            {sink};
        }}
    }}
}}
";

            sink = sink.CSharpReplaceToVBasic().Replace("==", "Is");

            var visualBasicTest = $@"
Imports Microsoft.EntityFrameworkCore
Imports System.Linq

Namespace sample
    Public Class SampleContext
        Inherits DbContext

        Public Property TestProp As DbSet(Of String)
        Public          TestField As DbSet(Of String)
    End Class

    Class MyFoo
        Private Sub Sink(s As String)
        End Sub

        Public Sub Run()
            {sink}
        End Sub
    End Class
End Namespace
";
            var expected        = new DiagnosticResult
            {
                Id       = "SCS0035",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = @"
Behavior:
  MyKey:
    Namespace: sample
    ClassName: MyFoo
    Name: Sink
    Method:
      InjectableArguments: [SCS0035: 0]

  db3:
    Namespace: Microsoft.EntityFrameworkCore
    ClassName: DbSet
    Method:
      Returns:
        Taint: Tainted
";
            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                await VerifyCSharpDiagnostic(cSharpTest, expected, optionsWithProjectConfig).ConfigureAwait(false);

                await VerifyVisualBasicDiagnostic(visualBasicTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            }
        }
예제 #5
0
        public async Task TransferSqlInitializerUnSafe(string right, string[] csErrors, string[] vbErrors, bool audit)
        {
            var cSharpTest = $@"
using System.Data.SqlClient;

namespace sample
{{
    class MyFoo
    {{
        public void Run(string sql)
        {{
            var sqlCommand = new SqlCommand {{CommandText = {right}}};
        }}

        static MyFoo foo()
        {{
            return null;
        }}

        static string foo2(string a)
        {{
            return null;
        }}
    }}
}}
";

            var visualBasicTest = $@"
Imports System.Data.SqlClient

Namespace sample
    Class MyFoo
        Public Sub Run(sql As System.String)
            Dim com As New SqlCommand With {{.CommandText = {right}}}
        End Sub

        Private Shared Function foo() As MyFoo
            Return Nothing
        End Function

        Private Shared Function foo2(a As String) As String
            Return Nothing
        End Function
    End Class
End Namespace
";

            var testConfig = $@"
AuditMode: {audit}

TaintEntryPoints:
  AAA:
    Namespace: sample
    ClassName: MyFoo
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest,
                                         csErrors.Select(x => new DiagnosticResult {
                Id = x
            }.WithLocation(10)).ToArray(), optionsWithProjectConfig)
            .ConfigureAwait(false);

            await VerifyVisualBasicDiagnostic(visualBasicTest,
                                              vbErrors.Select(x => new DiagnosticResult {
                Id = x
            }.WithLocation(7)).ToArray(), optionsWithProjectConfig)
            .ConfigureAwait(false);
        }
예제 #6
0
        public async Task TaintArgumentsTransfer(string cs, bool warn)
        {
            var cSharpTest = $@"
using System.Data.SqlClient;

class StaticTest
{{
    public static void Foo2(string a, string b)
    {{
    }}

    public static string Get()
    {{
        return null;
    }}
}}

class Test
{{
    public string Foo(string a, string b)
    {{
        return null;
    }}

    public void Foo2(string a, string b) {{ }}

    public string Foo3(string a, out string b)
    {{
        b = null;
        return null;
    }}

    public string Foo4(string a, ref string b)
    {{
        return null;
    }}

    public void Run(string a, string b)
    {{
#pragma warning disable CS0219
        Test o = null;
#pragma warning restore CS0219
        {cs}
        new SqlCommand(query);
    }}
}}
";

            var visualBasicTest = $@"
Imports System.Data.SqlClient

Class StaticTest
    Public Shared Sub Foo2(ByVal a As String, ByVal b As String)
    End Sub

    Public Shared Function [Get]() As String
        Return Nothing
    End Function
End Class

Class Test
    Public Function Foo(ByVal a As String, ByVal b As String) As String
        Return Nothing
    End Function

    Public Sub Foo2(ByVal a As String, ByVal b As String)
    End Sub

    Public Function Foo3(ByVal a As String, <System.Runtime.InteropServices.Out> ByRef b As String) As String
        b = Nothing
        Return Nothing
    End Function

    Public Function Foo4(ByVal a As String, ByRef b As String) As String
        Return Nothing
    End Function

    Public Sub Run(ByVal a As String, ByVal b As String)
        Dim o As Test = Nothing
        {cs.CSharpReplaceToVBasic()}
        Dim temp = New SqlCommand(query)
    End Sub
End Class
";

            var expected = new DiagnosticResult
            {
                Id       = "SCS0026",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = @"
TaintEntryPoints:
  AAA:
    ClassName: Test
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                await VerifyCSharpDiagnostic(cSharpTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            }
        }
예제 #7
0
        public async Task ConditionalOpenRedirect()
        {
            var cSharpTest1 = @"
using Microsoft.AspNetCore.Mvc;

class OpenRedirect : Controller
{
    public ActionResult Vulnerable(string scary)
    {
        return ConditionalRedirect(scary, false);
    }

    public ActionResult Safe(string notScary)
    {
        return ConditionalRedirect(notScary, true);
    }

    private ActionResult ConditionalRedirect(string url, bool internalOnly)
    {
        // pretend this does something
        return null;
    }
}
";
            var cSharpTest2 = @"
using Microsoft.AspNetCore.Mvc;

class OpenRedirect : Controller
{
    public ActionResult Vulnerable(string scary1)
    {
        return ConditionalRedirect(scary1, false);
    }

    public ActionResult VulnerableNamed(string scary2)
    {
        return ConditionalRedirect(internalOnly: false, url: scary2);
    }

    public ActionResult Safe(string notScary1)
    {
        return ConditionalRedirect(notScary1);
    }

    public ActionResult SafeNamed1(string notScary2)
    {
        return ConditionalRedirect(url: notScary2);
    }

    public ActionResult SafeNamed2(string notScary3)
    {
        return ConditionalRedirect(internalOnly: true, url: notScary3);
    }

    private ActionResult ConditionalRedirect(string url, bool internalOnly = true)
    {
        // pretend this does something
        return null;
    }
}
";

            var vbTest1 = @"
Imports Microsoft.AspNetCore.Mvc

Class OpenRedirect
    Inherits Controller

    Public Function Vulnerable(ByVal scary As String) As ActionResult
        Return ConditionalRedirect(scary, False)
    End Function

    Public Function Safe(ByVal notScary As String) As ActionResult
        Return ConditionalRedirect(notScary, True)
    End Function

    Private Function ConditionalRedirect(ByVal url As String, ByVal internalOnly As Boolean) As ActionResult
        Return Nothing
    End Function
End Class
";

            var vbTest2 = @"
Imports Microsoft.AspNetCore.Mvc

Class OpenRedirect
    Inherits Controller

    Public Function Vulnerable(ByVal scary1 As String) As ActionResult
        Return ConditionalRedirect(scary1, False)
    End Function

    Public Function VulnerableNamed(ByVal scary2 As String) As ActionResult
        Return ConditionalRedirect(internalOnly:=False, url:=scary2)
    End Function

    Public Function Safe(ByVal notScary1 As String) As ActionResult
        Return ConditionalRedirect(notScary1)
    End Function

    Public Function SafeNamed1(ByVal notScary2 As String) As ActionResult
        Return ConditionalRedirect(url:=notScary2)
    End Function

    Public Function SafeNamed2(ByVal notScary3 As String) As ActionResult
        Return ConditionalRedirect(internalOnly:=True, url:=notScary3)
    End Function

    Private Function ConditionalRedirect(ByVal url As String, ByVal Optional internalOnly As Boolean = True) As ActionResult
        Return Nothing
    End Function
End Class

";


            var testConfig = @"
Behavior:

  Conditional:
    ClassName: OpenRedirect
    Name: ConditionalRedirect
    Method:
      Condition: {1: { Value: False } }
      ArgTypes: (System.String, System.Boolean)
      InjectableArguments: [SCS0027: 0]
";

            var expectedCSharp1 =
                new[]
            {
                Expected.WithLocation(8, 36)
            };

            var expectedCSharp2 =
                new[]
            {
                Expected.WithLocation(8, 36),
                Expected.WithLocation(13, 62)
            };
            var expectedVB1 =
                new[]
            {
                Expected.WithLocation(8, 36)
            };
            var expectedVB2 =
                new[]
            {
                Expected.WithLocation(8, 36),
                Expected.WithLocation(12, 62)
            };

            var config = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest1, expectedCSharp1, options : config).ConfigureAwait(false);
            await VerifyCSharpDiagnostic(cSharpTest2, expectedCSharp2, options : config).ConfigureAwait(false);

            await VerifyVisualBasicDiagnostic(vbTest1, expectedVB1, options : config).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(vbTest2, expectedVB2, options : config).ConfigureAwait(false);
        }
예제 #8
0
        public async Task TransferMemoryStream()
        {
            var cSharpTest = @"
#pragma warning disable 8019
    using System;
    using System.IO;
    using System.Text;
    using System.Data.SqlClient;
#pragma warning restore 8019

class SqlTransferTesting
{
    public void Run(string input)
    {
        var query = """";
        var bytes = Encoding.ASCII.GetBytes(input);
        using(var stream = new MemoryStream())
        {
            stream.Write(bytes, 0, bytes.Length);
            StreamReader reader = new StreamReader( stream );
            query = reader.ReadToEnd();
        }
        new SqlCommand(query);
    }
}
";

            var visualBasicTest = @"
#Disable Warning BC50001
    Imports System
    Imports System.IO
    Imports System.Text
    Imports System.Data.SqlClient
#Enable Warning BC50001

Friend Class SqlTransferTesting
    Public Sub Run(ByVal input As String)
        Dim query = """"
        Dim bytes = Encoding.ASCII.GetBytes(input)

        Using stream = New MemoryStream()
            stream.Write(bytes, 0, bytes.Length)
            Dim reader As StreamReader = New StreamReader(stream)
            query = reader.ReadToEnd()
        End Using

        Dim a = New SqlCommand(query)
    End Sub
End Class
";

            var expected = new DiagnosticResult
            {
                Id       = "SCS0026",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = @"
TaintEntryPoints:
  AAA:
    ClassName: SqlTransferTesting
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(visualBasicTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
        }
        public async Task TaintArgumentsTransfer(string cs, bool warn, int count = 1)
        {
            var cSharpTest = $@"
using System.Data.SqlClient;

public class StaticTest
{{
    public static void Foo2(string a, string b)
    {{
    }}

    public static string Get()
    {{
        return null;
    }}
}}

public class MemberTest
{{
    public string Foo(string a, string b)
    {{
        return a + b;
    }}

    public void Foo2(string a, string b) {{ }}

    public string Foo3(string a, out string b)
    {{
        b = a;
        return a;
    }}

    public string Foo4(string a, ref string b)
    {{
        b = a;
        return a;
    }}

    public string Foo5(ref string x, params string[] a)
    {{
        foreach(var str in a)
            x += str;

        return x;
    }}

    public string Foo6(params string[] a)
    {{
        string x = """";
        foreach(var str in a)
            x += str;

        return x;
    }}
}}

public class TestInput
{{
    public void Run(string a, string b)
    {{
#pragma warning disable CS0219
        var o = new MemberTest();
#pragma warning restore CS0219
        {cs}
        new SqlCommand(query);
    }}
}}
";

            var visualBasicTest = $@"
Imports System.Data.SqlClient

Public Class StaticTest
    Public Shared Sub Foo2(ByVal a As String, ByVal b As String)
    End Sub

    Public Shared Function [Get]() As String
        Return Nothing
    End Function
End Class

Public Class MemberTest
    Public Function Foo(ByVal a As String, ByVal b As String) As String
        Return a & b
    End Function

    Public Sub Foo2(ByVal a As String, ByVal b As String)
    End Sub

    Public Function Foo3(ByVal a As String, <System.Runtime.InteropServices.Out> ByRef b As String) As String
        b = a
        Return a
    End Function

    Public Function Foo4(ByVal a As String, ByRef b As String) As String
        b = a
        Return a
    End Function

    Public Function Foo5(ByRef x As String, ParamArray a As String()) As String
        For Each str In a
            x += str
        Next

        Return x
    End Function

    Public Function Foo6(ParamArray a As String()) As String
        Dim x As String = ""
        ""

        For Each str In a
            x += str
        Next

        Return x
    End Function
End Class

Public Class TestInput
    Public Sub Run(ByVal a As String, ByVal b As String)
        Dim o = New MemberTest()
        {cs.CSharpReplaceToVBasic()}
        Dim temp = New SqlCommand(query)
    End Sub
End Class
";

            var expected = new DiagnosticResult
            {
                Id       = "SCS0002",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = @"
TaintEntryPoints:
  TestInput:
    Method:
      Name: Run
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                await VerifyCSharpDiagnostic(cSharpTest, Enumerable.Repeat(expected, count).ToArray(), optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, Enumerable.Repeat(expected, count).ToArray(), optionsWithProjectConfig).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            }
        }
예제 #10
0
        public async Task ConditionalConstructorOpenRedirectCSharp(string injectableByDefault, string arguments, string parameters, bool warn)
        {
            var cSharpTest = $@"
using Microsoft.AspNetCore.Mvc;

class OpenRedirect : Controller
{{
    public ActionResult Foo({arguments})
    {{
        return new ConditionallyScaryRedirect{parameters};
    }}
}}

class ConditionallyScaryRedirect : ActionResult
{{
    public ConditionallyScaryRedirect(string maybeTainted = null, bool injectable = {injectableByDefault}) : base()
    {{
        // pretend there's something here
    }}

#pragma warning disable CS0649
    public int x;
#pragma warning restore CS0649
}}
";

            var testConfig = @"
Behavior:

  Conditional:
    ClassName: ConditionallyScaryRedirect
    Name: .ctor
    Method:
      Condition: {1: { Value: True } }
      ArgTypes: (System.String, System.Boolean)
      InjectableArguments: [SCS0027: 0]
";

            var config = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                var expectedCSharp =
                    new[]
                {
                    Expected.WithLocation(8)
                };

                var expectedVB =
                    new[]
                {
                    Expected.WithLocation(8)
                };

                await VerifyCSharpDiagnostic(cSharpTest, expectedCSharp, options : config).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, options : config).ConfigureAwait(false);
            }
        }
예제 #11
0
        public void VerifyTimesClusterSaveLoadTest()
        {
            ConfigurationTest.Initialize();

            using (var io = ConfigurationTest.CreateMemoryIO()) {
                SimpleClusterIO cio = new SimpleClusterIO(io);

                Random             r   = new Random();
                VerifyTimesCluster csc = new VerifyTimesCluster(2);
                csc.Initialize();
                for (int i = 0; i < csc.Count; i++)
                {
                    csc[i] = new DateTime(r.Next());
                }
                csc.NextClusterAddress = Constants.NoAddress;
                cio.Save(csc);

                int       offset = 0;
                DataBlock b      = new DataBlock(io.Bytes, 2 * Configuration.Geometry.BytesPerCluster, Configuration.Geometry.BytesPerCluster);

                byte[] marker = b.ToByteArray(offset, Constants.SrfsMarker.Length);
                Assert.IsTrue(marker.SequenceEqual(Constants.SrfsMarker));
                offset += marker.Length;

                byte[] version = b.ToByteArray(offset, Constants.CurrentVersion.Length);
                Assert.IsTrue(version.SequenceEqual(Constants.CurrentVersion));
                offset += version.Length;

                Guid guid = new Guid(b.ToByteArray(offset, Constants.GuidLength));
                Assert.AreEqual(guid, Configuration.FileSystemID);
                offset += Constants.GuidLength;

                byte[] signatureBytes = b.ToByteArray(offset, Signature.Length);
                offset += Signature.Length;

                byte[] thumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(thumbprintBytes.SequenceEqual(Configuration.CryptoSettings.SigningKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] hashBytes = b.ToByteArray(offset, 32);
                offset += 32;

                ClusterType clusterType = (ClusterType)b.ToByte(offset);
                Assert.AreEqual(clusterType, ClusterType.VerifyTimeTable);
                offset += sizeof(ClusterType);

                int nextClusterAddress = b.ToInt32(offset);
                Assert.AreEqual(nextClusterAddress, Constants.NoAddress);
                offset += sizeof(int);

                long[] cs = new long[csc.Count];
                for (int i = 0; i < csc.Count; i++)
                {
                    cs[i] = b.ToInt64(offset + i * sizeof(long));
                }
                Assert.IsTrue(cs.SequenceEqual(from d in csc select d.Ticks));

                VerifyTimesCluster csc2 = new VerifyTimesCluster(2);
                cio.Load(csc2);
                Assert.AreEqual(csc.VolumeID, csc2.VolumeID);
                Assert.AreEqual(csc.Type, csc2.Type);
                Assert.AreEqual(csc.NextClusterAddress, csc2.NextClusterAddress);

                Assert.IsTrue(csc.SequenceEqual(csc2));
            }
        }
예제 #12
0
        public async Task XPathInjection(string sink, bool warn)
        {
            var cSharpTest = $@"
#pragma warning disable 8019
    using System.Xml;
    using System.Xml.XPath;
    using System.Xml.Linq;
#pragma warning restore 8019

namespace sample
{{
    public class MyFoo
    {{
        public void Run(XmlDocument doc, XPathNavigator nav, XNode element, string input)
        {{
            {sink};
        }}
    }}
}}
";

            sink = sink.CSharpReplaceToVBasic();
            var visualBasicTest = $@"
#Disable Warning BC50001
    Imports System.Xml
    Imports System.Xml.XPath
    Imports System.Xml.Linq
#Enable Warning BC50001

Namespace sample
    Public Class MyFoo
        Public Sub Run(doc As XmlDocument, nav As XPathNavigator, element As XNode, input As System.String)
            {sink}
        End Sub
    End Class
End Namespace
";
            var expected        = new DiagnosticResult
            {
                Id       = "SCS0003",
                Severity = DiagnosticSeverity.Warning,
            };

            var testConfig = @"
TaintEntryPoints:
  sample.MyFoo:
    Method:
      Name: Run
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            if (warn)
            {
                await VerifyCSharpDiagnostic(cSharpTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, expected, optionsWithProjectConfig).ConfigureAwait(false);
            }
            else
            {
                await VerifyCSharpDiagnostic(cSharpTest, null, optionsWithProjectConfig).ConfigureAwait(false);
                await VerifyVisualBasicDiagnostic(visualBasicTest, null, optionsWithProjectConfig).ConfigureAwait(false);
            }
        }
예제 #13
0
        public async Task PasswordValidatorRequiredLength(string property, string type, bool auditMode)
        {
            var cSharpTest = $@"
using Microsoft.AspNet.Identity;

namespace WebApplicationSandbox.Controllers
{{
    public class TestApp
    {{
        public PasswordValidator TestMethod({type} x)
        {{
            var pwdv = new PasswordValidator
            {{
                {property} = x
            }};
            return pwdv;
        }}
    }}
}}
";

            var visualBasicTest = $@"
Imports Microsoft.AspNet.Identity

Namespace WebApplicationSandbox.Controllers
    Public Class TestApp
        Public Function TestMethod(x As {type}) As PasswordValidator
            Dim pwdv As New PasswordValidator() With {{ _
                .{property} = x
            }}
            return pwdv
        End Function
    End Class
End Namespace
";

            var expected = new[]
            {
                new DiagnosticResult
                {
                    Id       = "SCS0034",
                    Severity = DiagnosticSeverity.Warning
                },
                new DiagnosticResult
                {
                    Id       = "SCS0032",
                    Severity = DiagnosticSeverity.Warning
                },
                new DiagnosticResult
                {
                    Id       = "SCS0033",
                    Severity = DiagnosticSeverity.Warning
                }
            };

            var testConfig = $@"
AuditMode: {auditMode}
MinimumPasswordValidatorProperties: 1
PasswordValidatorRequiredProperties: [{property}]
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest,
                                         auditMode?expected : null,
                                         optionsWithProjectConfig).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(visualBasicTest,
                                              auditMode?expected : null,
                                              optionsWithProjectConfig).ConfigureAwait(false);
        }
예제 #14
0
        public void FileDataSaveLoadTest()
        {
            ConfigurationTest.Initialize();

            using (var io = ConfigurationTest.CreateMemoryIO()) {
                SimpleClusterIO cio = new SimpleClusterIO(io);

                Random          r   = new Random(Seed);
                FileDataCluster csc = new FileDataCluster(Address);
                csc.Initialize();

                int      fileID             = r.Next();
                int      nextClusterAddress = r.Next();
                int      bytesUsed          = r.Next();
                DateTime writeTime          = new DateTime(2005, 1, 1);

                // File System Cluster fields
                csc.FileID             = fileID;
                csc.NextClusterAddress = nextClusterAddress;
                csc.BytesUsed          = bytesUsed;
                csc.WriteTime          = writeTime;

                byte[] data = new byte[FileDataCluster.DataSize];
                for (int i = 0; i < data.Length; i++)
                {
                    data[i] = (byte)(r.Next() & byte.MaxValue);
                }

                csc.Data.Set(0, data);
                cio.Save(csc);

                int       offset = 0;
                DataBlock b      = new DataBlock(
                    io.Bytes,
                    Address * Configuration.Geometry.BytesPerCluster,
                    Configuration.Geometry.BytesPerCluster);

                byte[] marker = b.ToByteArray(offset, Constants.SrfsMarker.Length);
                Assert.IsTrue(marker.SequenceEqual(Constants.SrfsMarker));
                offset += marker.Length;

                byte[] version = b.ToByteArray(offset, Constants.CurrentVersion.Length);
                Assert.IsTrue(version.SequenceEqual(Constants.CurrentVersion));
                offset += version.Length;

                Guid guid = new Guid(b.ToByteArray(offset, Constants.GuidLength));
                Assert.AreEqual(guid, Configuration.FileSystemID);
                offset += Constants.GuidLength;

                byte[] signatureBytes = b.ToByteArray(offset, Signature.Length);
                offset += Signature.Length;

                byte[] thumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(thumbprintBytes.SequenceEqual(Configuration.CryptoSettings.SigningKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] hashBytes = b.ToByteArray(offset, 32);
                offset += 32;

                ClusterType clusterType = (ClusterType)b.ToByte(offset);
                Assert.AreEqual(clusterType, ClusterType.FileData);
                offset += sizeof(ClusterType);

                Assert.AreEqual(fileID, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(nextClusterAddress, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(bytesUsed, b.ToInt32(offset));
                offset += sizeof(int);

                Assert.AreEqual(writeTime, new DateTime(b.ToInt64(offset)));
                offset += sizeof(long);

                byte[] encryptionThumbprintBytes = b.ToByteArray(offset, KeyThumbprint.Length);
                Assert.IsTrue(encryptionThumbprintBytes.SequenceEqual(Configuration.CryptoSettings.EncryptionKeyThumbprint.Bytes));
                offset += KeyThumbprint.Length;

                byte[] publicKeyBytes = b.ToByteArray(offset, PublicKey.Length);
                offset += PublicKey.Length;

                int dataLength = Configuration.Geometry.BytesPerCluster - offset;
                int padding    = dataLength % 16;
                dataLength -= padding;
                Assert.AreEqual(data.Length, dataLength);
                offset += padding;

                using (ECDiffieHellmanCng dest = new ECDiffieHellmanCng(Configuration.CryptoSettings.DecryptionKey))
                    using (AesCng aes = new AesCng()) {
                        aes.KeySize   = 256;
                        aes.BlockSize = 128;
                        aes.Mode      = CipherMode.CBC;
                        aes.Padding   = PaddingMode.None;
                        aes.Key       = dest.DeriveKeyMaterial(new PublicKey(publicKeyBytes).GetCngKey());
                        aes.IV        = new byte[16];

                        using (var decryptor = aes.CreateDecryptor()) {
                            byte[] decryptedData = b.TransformFinalBlock(decryptor, offset, dataLength);
                            for (int i = 0; i < dataLength; i++)
                            {
                                Assert.AreEqual(data[i], decryptedData[i]);
                            }
                        }
                    }

                FileDataCluster csc2 = new FileDataCluster(Address);
                cio.Load(csc2);

                Assert.IsTrue(csc2.Marker.SequenceEqual(Constants.SrfsMarker));
                Assert.IsTrue(csc2.Version.SequenceEqual(Constants.CurrentVersion));
                Assert.AreEqual(csc2.VolumeID, Configuration.FileSystemID);
                Assert.AreEqual(csc2.Type, ClusterType.FileData);
                Assert.AreEqual(csc2.FileID, fileID);
                Assert.AreEqual(csc2.NextClusterAddress, nextClusterAddress);
                Assert.AreEqual(csc2.BytesUsed, bytesUsed);
                Assert.AreEqual(csc2.WriteTime, writeTime);

                for (int i = 0; i < dataLength; i++)
                {
                    Assert.AreEqual(data[i], csc2.Data.ToByte(i));
                }
            }
        }
        public async Task CookiePropertyDynamicValue(string sink, string namespace1, string namespace2, string type, string constructor, string property, string constProperty, string code, bool auditMode)
        {
            var cSharpTest = $@"
#pragma warning disable 8019
    using {namespace1};
    using {namespace2};
#pragma warning restore 8019

namespace VulnerableApp
{{
    class CookieCreation : Controller
    {{
        void TestCookie(bool x)
        {{
            var cookie = new {type}{constructor};
            cookie.{property} = x;
            cookie.{constProperty} = true;
            {sink};
        }}
    }}
}}
";

            var visualBasicTest = $@"
#Disable Warning BC50001
    Imports {namespace1}
    Imports {namespace2}
#Enable Warning BC50001

Namespace VulnerableApp
    Class CookieCreation
        Inherits Controller

        Private Sub TestCookie(x As Boolean)
            Dim cookie = New {type}{constructor}
            cookie.{property} = x
            cookie.{constProperty} = True
            {sink}
        End Sub
    End Class
End Namespace
";

            var expected = new DiagnosticResult
            {
                Id       = code,
                Severity = DiagnosticSeverity.Warning
            };

            var testConfig = $@"
AuditMode: {auditMode}
";

            var optionsWithProjectConfig = ConfigurationTest.CreateAnalyzersOptionsWithConfig(testConfig);

            await VerifyCSharpDiagnostic(cSharpTest,
                                         auditMode?new[] { expected } : null,
                                         optionsWithProjectConfig).ConfigureAwait(false);
            await VerifyVisualBasicDiagnostic(visualBasicTest,
                                              auditMode?new[] { expected } : null,
                                              optionsWithProjectConfig).ConfigureAwait(false);
        }