コード例 #1
0
        public void ImplicitObjectCreationSyntax()
        {
            const string code           = @"
                public class A
                {
                    public int X;
                    public A(int y) { }
                }
                public class B
                {
                    void Foo()
                    {
                        A bar =new(1) { X = 2 };
                    }
                }";
            var          snippet        = new SnippetCompiler(code);
            var          syntaxTree     = snippet.SyntaxTree;
            var          objectCreation = (ImplicitObjectCreationExpressionSyntaxWrapper)syntaxTree.GetRoot().DescendantNodes().First((node => node.IsKind(SyntaxKindEx.ImplicitObjectCreationExpression)));
            var          wrapper        = ObjectCreationFactory.Create(objectCreation);

            wrapper.Expression.Should().BeEquivalentTo(objectCreation.SyntaxNode);
            wrapper.Initializer.Should().BeEquivalentTo(objectCreation.Initializer);
            wrapper.ArgumentList.Should().BeEquivalentTo(objectCreation.ArgumentList);
            wrapper.TypeAsString(snippet.SemanticModel).Should().Be("A");
        }
コード例 #2
0
        public void GivenNonConstructor_ThrowsException()
        {
            var    snippet          = new SnippetCompiler("public class A{}");
            var    classDeclaration = snippet.SyntaxTree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>().First();
            Action action           = () => { ObjectCreationFactory.Create(classDeclaration); };

            action.Should().Throw <InvalidOperationException>().WithMessage("Unexpected type: ClassDeclarationSyntax");
        }
コード例 #3
0
        public void GivenImplicitObjectCreationSyntaxWithMissingType_HasEmptyType()
        {
            const string code           = @"
                public class B
                {
                    void Foo()
                    {
                        var bar = new();
                    }
                }";
            var          snippet        = new SnippetCompiler(code, true, AnalyzerLanguage.CSharp);
            var          syntaxTree     = snippet.SyntaxTree;
            var          objectCreation = (ImplicitObjectCreationExpressionSyntaxWrapper)syntaxTree.GetRoot().DescendantNodes().First((node => node.IsKind(SyntaxKindEx.ImplicitObjectCreationExpression)));
            var          wrapper        = ObjectCreationFactory.Create(objectCreation);

            wrapper.TypeAsString(snippet.SemanticModel).Should().BeEmpty();
        }
コード例 #4
0
        public void ObjectCreationSyntax()
        {
            const string code           = @"
                public class A
                {
                    public int X;
                    public A(int y) { }
                }
                public class B
                {
                    void Foo()
                    {
                        var bar = new A(1) { X = 2 };
                    }
                }";
            var          snippet        = new SnippetCompiler(code);
            var          objectCreation = snippet.SyntaxTree.GetRoot().DescendantNodes().OfType <ObjectCreationExpressionSyntax>().First();
            var          wrapper        = ObjectCreationFactory.Create(objectCreation);

            wrapper.Expression.Should().BeEquivalentTo(objectCreation);
            wrapper.Initializer.Should().BeEquivalentTo(objectCreation.Initializer);
            wrapper.ArgumentList.Should().BeEquivalentTo(objectCreation.ArgumentList);
            wrapper.TypeAsString(snippet.SemanticModel).Should().Be("A");
        }
コード例 #5
0
        protected override void Initialize(SonarAnalysisContext context)
        {
            base.Initialize(context);
            context.RegisterCompilationStartAction(
                ccc =>
            {
                if (!IsEnabled(ccc.Options))
                {
                    return;
                }

                var isDefaultConstructorSafe = IsDefaultConstructorSafe(context, ccc.Options);

                ccc.RegisterSyntaxNodeActionInNonGenerated(
                    c =>
                {
                    var objectCreation = ObjectCreationFactory.Create(c.Node);
                    if (ObjectInitializationTracker.ShouldBeReported(objectCreation, c.SemanticModel, isDefaultConstructorSafe))
                    {
                        c.ReportDiagnosticWhenActive(Diagnostic.Create(SupportedDiagnostics[0], objectCreation.Expression.GetLocation()));
                    }
                },
                    SyntaxKind.ObjectCreationExpression, SyntaxKindEx.ImplicitObjectCreationExpression);

                ccc.RegisterSyntaxNodeActionInNonGenerated(
                    c =>
                {
                    var assignment = (AssignmentExpressionSyntax)c.Node;
                    if (ObjectInitializationTracker.ShouldBeReported(assignment, c.SemanticModel))
                    {
                        c.ReportDiagnosticWhenActive(Diagnostic.Create(SupportedDiagnostics[0], assignment.GetLocation()));
                    }
                },
                    SyntaxKind.SimpleAssignmentExpression);
            });
        }
コード例 #6
0
        protected override void Initialize(SonarAnalysisContext context)
        {
            context.RegisterSyntaxNodeActionInNonGenerated(
                c =>
            {
                var invocation     = (InvocationExpressionSyntax)c.Node;
                var methodName     = GetMethodName(invocation);
                var containingType = new Lazy <ITypeSymbol>(() => c.SemanticModel.GetSymbolInfo(invocation).Symbol?.ContainingType);

                switch (methodName)
                {
                case "Create":
                    CheckAlgorithmCreation(containingType.Value, invocation, c);
                    break;

                case "GenerateKey":
                    CheckSystemSecurityEllipticCurve(containingType.Value, invocation, invocation.ArgumentList, c);
                    break;

                case "GetByName":
                    CheckBouncyCastleEllipticCurve(containingType.Value, invocation, c);
                    break;

                case "Init":
                    CheckBouncyCastleParametersGenerators(containingType.Value, invocation, c);
                    break;

                default:
                    // Current method is not related to any cryptographic method of interest
                    break;
                }
            },
                SyntaxKind.InvocationExpression);

            context.RegisterSyntaxNodeActionInNonGenerated(
                c =>
            {
                var objectCreation = ObjectCreationFactory.Create(c.Node);
                var containingType = c.SemanticModel.GetTypeInfo(objectCreation.Expression).Type;
                CheckSystemSecurityEllipticCurve(containingType, objectCreation.Expression, objectCreation.ArgumentList, c);
                CheckSystemSecurityCryptographyAlgorithms(containingType, objectCreation, c);
                CheckBouncyCastleKeyGenerationParameters(containingType, objectCreation, c);
            },
                SyntaxKind.ObjectCreationExpression, SyntaxKindEx.ImplicitObjectCreationExpression);

            context.RegisterSyntaxNodeActionInNonGenerated(
                c =>
            {
                var assignment   = (AssignmentExpressionSyntax)c.Node;
                var propertyName = GetPropertyName(assignment.Left);
                if (propertyName == "KeySize" &&
                    assignment.Left is MemberAccessExpressionSyntax memberAccess &&
                    memberAccess.Expression != null &&
                    c.SemanticModel.GetTypeInfo(memberAccess.Expression).Type is ITypeSymbol containingType)
                {
                    // Using the KeySize setter on DSACryptoServiceProvider/RSACryptoServiceProvider does not actually change the underlying key size
                    // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.dsacryptoserviceprovider.keysize
                    // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsacryptoserviceprovider.keysize
                    if (containingType.IsAny(KnownType.System_Security_Cryptography_DSACryptoServiceProvider, KnownType.System_Security_Cryptography_RSACryptoServiceProvider))
                    {
                        c.ReportDiagnosticWhenActive(Diagnostic.Create(Rule, assignment.GetLocation(), MinimalCommonKeyLength, CipherName(containingType), UselessAssignmentInfo));
                    }
                    else
                    {
                        CheckGenericDsaRsaCryptographyAlgorithms(containingType, assignment, assignment.Right, c);
                    }
                }
            },
                SyntaxKind.SimpleAssignmentExpression);
        }
コード例 #7
0
        public void GivenNull_ThrowsException()
        {
            Action action = () => { ObjectCreationFactory.Create(null); };

            action.Should().Throw <ArgumentNullException>();
        }