From 7f5d6720f0c31ae430faad3f3907e3eb93d9a639 Mon Sep 17 00:00:00 2001 From: Gregory Paidis <115458417+gregory-paidis-sonarsource@users.noreply.github.com> Date: Thu, 30 May 2024 10:45:36 +0200 Subject: [PATCH] S4347: Implement ShouldExecute (#9342) --- ...SecureRandomSeedsShouldNotBePredictable.cs | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/analyzers/src/SonarAnalyzer.CSharp/SymbolicExecution/Roslyn/SecureRandomSeedsShouldNotBePredictable.cs b/analyzers/src/SonarAnalyzer.CSharp/SymbolicExecution/Roslyn/SecureRandomSeedsShouldNotBePredictable.cs index 79651dc9ac7..4187979f60b 100644 --- a/analyzers/src/SonarAnalyzer.CSharp/SymbolicExecution/Roslyn/SecureRandomSeedsShouldNotBePredictable.cs +++ b/analyzers/src/SonarAnalyzer.CSharp/SymbolicExecution/Roslyn/SecureRandomSeedsShouldNotBePredictable.cs @@ -18,6 +18,7 @@ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +using SonarAnalyzer.Common.Walkers; using SonarAnalyzer.SymbolicExecution.Constraints; namespace SonarAnalyzer.SymbolicExecution.Roslyn.RuleChecks.CSharp; @@ -38,7 +39,12 @@ public sealed class SecureRandomSeedsShouldNotBePredictable : HardcodedBytesRule protected override SymbolicConstraint Hardcoded => CryptographicSeedConstraint.Predictable; protected override SymbolicConstraint NotHardcoded => CryptographicSeedConstraint.Unpredictable; - public override bool ShouldExecute() => true; + public override bool ShouldExecute() + { + var walker = new Walker(); + walker.SafeVisit(Node); + return walker.Result; + } protected override ProgramState PreProcessSimple(SymbolicContext context) { @@ -158,4 +164,31 @@ private static bool IsSecureRandom(IInvocationOperationWrapper invocation) => private static bool IsIRandomGenerator(IInvocationOperationWrapper invocation) => invocation.TargetMethod.ContainingType.DerivesOrImplements(KnownType.Org_BouncyCastle_Crypto_Prng_IRandomGenerator); + + private sealed class Walker : SafeCSharpSyntaxWalker + { + public bool Result { get; private set; } + + public override void Visit(SyntaxNode node) + { + if (!Result) + { + base.Visit(node); + } + } + + public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) + { + Result |= node.Expression.NameIs("SecureRandom") && node.Name.NameIs("GetInstance"); + + base.VisitMemberAccessExpression(node); + } + + public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) + { + Result |= node.Type.GetName() is "DigestRandomGenerator" or "VmpcRandomGenerator"; + + base.VisitObjectCreationExpression(node); + } + } }