Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ We have some common analyses that you may likely want to consume for your custom

ValueContentAnalysis will compute that variables `c1`, `c2` and `c3` have identical `ValueContentAbstractValue` with a single literal value `0` and `ValueContainsNonLiteralState.No` to indicate it cannot contain a non-literal value. It will compute that `c4` has a different `ValueContentAbstractValue` with a single literal value `0` and `ValueContainsNonLiteralState.Maybe` to indicate that it may contain some non-literal value(s) in some code path(s).

[ValueContentAbstractValue](../src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/ValueContentAnalysis/ValueContentAbstractValue.cs) bounds each set to 10 distinct literals. Both control-flow merges and binary operations widen to an unknown value when their result exceeds this bound. Binary operations enforce the bound while constructing the result, rather than materializing an unbounded Cartesian product first; repeated results do not count toward the bound.

4. [TaintedDataAnalysis](../src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/TaintedDataAnalysis/TaintedDataAnalysis.cs): Dataflow analysis to track tainted state of AnalysisEntity and IOperation instances.

5. [PropertySetAnalysis](../src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysis.cs): Dataflow analysis to track values assigned to one or more properties of an object to identify and flag incorrect/insecure object state. The upstream `Utilities.UnitTests` project, which held its worked examples, did not migrate into `dotnet/sdk`; the security rules under `Microsoft.NetCore.Analyzers/Security` are the live consumers to read instead.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ internal ValueContentAbstractValue MergeBinaryOperation(
}

// Merge Literals
var builder = PooledHashSet<object?>.GetInstance();
using var builder = PooledHashSet<object?>.GetInstance();
foreach (var leftLiteral in LiteralValues)
{
foreach (var rightLiteral in otherState.LiteralValues)
Expand All @@ -288,10 +288,14 @@ internal ValueContentAbstractValue MergeBinaryOperation(
}

builder.Add(result);
if (builder.Count > LiteralsBound)
{
return MayBeContainsNonLiteralState;
}
}
}

ImmutableHashSet<object?> mergedLiteralValues = builder.ToImmutableAndFree();
ImmutableHashSet<object?> mergedLiteralValues = builder.ToImmutable();
ValueContainsNonLiteralState mergedNonLiteralState = Merge(NonLiteralState, otherState.NonLiteralState);

return Create(mergedLiteralValues, mergedNonLiteralState);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ public class DoNotHardCodeCertificateTests : TaintedDataAnalyzerTestBase<DoNotHa
{
protected override DiagnosticDescriptor Rule => DoNotHardCodeCertificate.Rule;

[TestMethod]
public async Task ConstantSeedXorshiftWithReachableSinkAsync()
{
var test = new VerifyCS.Test
{
TestCode = XorshiftGeneratorWithSink("new X509Certificate2(bytes);"),
LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
};
await VerifyCS.RunTestAsync(test);
}

[TestMethod]
public async Task SinkReachedThroughConstructorInitializerAsync()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ public class DoNotHardCodeEncryptionKeyTests : TaintedDataAnalyzerTestBase<DoNot
{
protected override DiagnosticDescriptor Rule => DoNotHardCodeEncryptionKey.Rule;

[TestMethod]
public async Task ConstantSeedXorshiftWithReachableSinkAsync()
{
var test = new VerifyCS.Test
{
TestCode = XorshiftGeneratorWithSink("algorithm.Key = bytes;"),
LanguageVersion = Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8,
};
await VerifyCS.RunTestAsync(test);
}

[TestMethod]
[DataRow(0)]
[DataRow(8)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,42 @@ public abstract class TaintedDataAnalyzerTestBase<TCSharpAnalyzer, TVisualBasicA

protected virtual IEnumerable<string> AdditionalVisualBasicSources { get; }

protected static string XorshiftGeneratorWithSink(string sink) => $$"""
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public static class Repro
{
public static int Run(int count, SymmetricAlgorithm algorithm, byte[] bytes)
{
var state = 0x9E3779B97F4A7C15UL;
var length = 0;
for (var i = 0; i < count; i++)
{
var text = Next(ref state).ToString();
if (Next(ref state) % 2 == 0)
{
text = "-";
}

length += Encoding.UTF8.GetBytes(text).Length;
}

{{sink}}
return length;

static ulong Next(ref ulong state)
{
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
return state;
}
}
}
""";

protected static string RepeatedByteArraySourcesWithoutReachableSink()
{
string calls = string.Concat(Enumerable.Repeat(" Bytes(1, 2, 3, 4, 5, 6, 7, 8);\n", 64));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,9 @@ ValueContentAbstractValue Merge(int[] literals)
.Aggregate((first, second) => first.Merge(second));
var product = Merge(new[] { 2, 3, 5, 7 }).MergeBinaryOperation(
Merge(new[] { 11, 13, 17, 19 }), BinaryOperatorKind.Multiply, type, type, type);
Assert.HasCount(width * width, product.LiteralValues);
var merged = product.Merge(product);
Assert.HasCount(expectedCount, merged.LiteralValues);
Assert.AreEqual(expectedState, merged.NonLiteralState);
Assert.HasCount(expectedCount, product.LiteralValues);
Assert.AreEqual(expectedState, product.NonLiteralState);
Assert.AreSame(product, product.Merge(product));
}

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Microsoft.CodeAnalysis.Operations;

namespace Microsoft.CodeAnalysis.NetAnalyzers.UnitTests
{
[TestClass]
public class ValueContentAbstractValueTests
{
[TestMethod]
[DataRow(5, 2, 100, BinaryOperatorKind.Add, 10)]
[DataRow(6, 2, 100, BinaryOperatorKind.Add, 0)]
[DataRow(10, 10, 1, BinaryOperatorKind.And, 10)]
public void BinaryOperationBoundsDistinctResults(
int leftCount, int rightCount, int rightMultiplier, BinaryOperatorKind operatorKind, int expectedCount)
{
var compilation = CSharpCompilation.Create("Test");
var type = compilation.GetSpecialType(SpecialType.System_Int32);
var left = ValueContentAbstractValue.UndefinedState;
var right = ValueContentAbstractValue.UndefinedState;
for (int i = 0; i < leftCount; i++)
{
left = left.Merge(ValueContentAbstractValue.Create(i, type));
}

for (int i = 0; i < rightCount; i++)
{
right = right.Merge(ValueContentAbstractValue.Create(i * rightMultiplier, type));
}

var result = left.MergeBinaryOperation(right, operatorKind, type, type, type);

if (expectedCount == 0)
{
Assert.AreSame(ValueContentAbstractValue.MayBeContainsNonLiteralState, result);
}
else
{
Assert.IsTrue(result.IsLiteralState);
var expected = Enumerable.Range(0, leftCount)
.SelectMany(l => Enumerable.Range(0, rightCount)
.Select(r => operatorKind == BinaryOperatorKind.Add ? l + r * rightMultiplier : l & r))
.Distinct()
.Cast<object>()
.ToArray();
Assert.HasCount(expectedCount, result.LiteralValues);
Assert.IsTrue(result.LiteralValues.SetEquals(expected));
}
}
}
}