Ejemplo n.º 1
0
        public ExpressionResult Resolve(Document document, ExpressionSyntax expressionSyntax, IEnumerable <SyntaxNode> nodes, SemanticModel semanticModel, ExpressionResolver expressionResolverInstance)
        {
            using (MiniProfiler.Current.Step(nameof(InvocationStrategy)))
            {
                var invocationExpression = expressionSyntax as InvocationExpressionSyntax;
                var optionalConst        = semanticModel?.GetConstantValue(expressionSyntax);
                if (optionalConst?.HasValue ?? false)
                {
                    return(new ExpressionResult
                    {
                        CanBeUsedAsQuery = false,
                        ExpressionText = expressionSyntax.ToString(),
                        IsSolved = true,
                        TextResult = optionalConst.Value.Value.ToString(),
                    });
                }
                var nextInvocationExpression = invocationExpression.Expression;
                if (nextInvocationExpression is MemberAccessExpressionSyntax)
                {
                    var knowMethodFactory = new KnownMethodResolverFactory(invocationExpression, nextInvocationExpression, expressionResolverInstance, document, nodes, semanticModel);
                    return(knowMethodFactory.GetResolver().Resolve());
                }

                return(new ExpressionResult
                {
                    IsSolved = false,
                    UnresolvableReason = $"Child expression is not {nameof(MemberAccessExpressionSyntax)}",
                    TextResult = "",
                });
            }
        }
Ejemplo n.º 2
0
        public static bool IsEmptyStringExpression(
            ExpressionSyntax expression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            if (semanticModel == null)
            {
                throw new ArgumentNullException(nameof(semanticModel));
            }

            SyntaxKind kind = expression.Kind();

            if (kind == SyntaxKind.StringLiteralExpression)
            {
                return(((LiteralExpressionSyntax)expression).Token.ValueText.Length == 0);
            }
            else if (kind == SyntaxKind.InterpolatedStringExpression)
            {
                return(!((InterpolatedStringExpressionSyntax)expression).Contents.Any());
            }
            else if (kind == SyntaxKind.SimpleMemberAccessExpression)
            {
                var memberAccess = (MemberAccessExpressionSyntax)expression;

                if (memberAccess.Name?.Identifier.ValueText == "Empty")
                {
                    ISymbol symbol = semanticModel.GetSymbol(memberAccess, cancellationToken);

                    if (symbol?.Kind == SymbolKind.Field)
                    {
                        var fieldSymbol = (IFieldSymbol)symbol;

                        if (SymbolUtility.IsPublicStaticReadOnly(fieldSymbol, "Empty") &&
                            fieldSymbol.ContainingType?.SpecialType == SpecialType.System_String &&
                            fieldSymbol.Type.IsString())
                        {
                            return(true);
                        }
                    }
                }
            }

            Optional <object> optional = semanticModel.GetConstantValue(expression, cancellationToken);

            if (optional.HasValue)
            {
                var value = optional.Value as string;

                return(value?.Length == 0);
            }

            return(false);
        }
Ejemplo n.º 3
0
        public static bool IsEmptyString(
            ExpressionSyntax expression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            if (semanticModel == null)
            {
                throw new ArgumentNullException(nameof(semanticModel));
            }

            SyntaxKind kind = expression.Kind();

            if (kind == SyntaxKind.StringLiteralExpression)
            {
                return(((LiteralExpressionSyntax)expression).Token.ValueText.Length == 0);
            }
            else if (kind == SyntaxKind.SimpleMemberAccessExpression)
            {
                var memberAccess = (MemberAccessExpressionSyntax)expression;

                if (memberAccess.Name?.Identifier.ValueText == "Empty")
                {
                    ISymbol symbol = semanticModel.GetSymbol(memberAccess, cancellationToken);

                    if (symbol?.IsField() == true)
                    {
                        var fieldSymbol = (IFieldSymbol)symbol;

                        if (string.Equals(fieldSymbol.Name, "Empty", StringComparison.Ordinal) &&
                            fieldSymbol.ContainingType?.IsString() == true &&
                            fieldSymbol.IsPublic() &&
                            fieldSymbol.IsStatic &&
                            fieldSymbol.IsReadOnly &&
                            fieldSymbol.Type.IsString())
                        {
                            return(true);
                        }
                    }
                }
            }

            Optional <object> optional = semanticModel.GetConstantValue(expression, cancellationToken);

            if (optional.HasValue)
            {
                var value = optional.Value as string;

                return(value?.Length == 0);
            }

            return(false);
        }
Ejemplo n.º 4
0
 public static bool IsConstant(this ExpressionSyntax expression, SemanticModel semanticModel)
 {
     if (expression == null)
     {
         return(false);
     }
     return(expression.RemoveParentheses().IsAnyKind(LiteralSyntaxKinds) ||
            semanticModel.GetConstantValue(expression).HasValue);
 }
        public static async Task ComputeRefactoringAsync(RefactoringContext context, ExpressionSyntax expression)
        {
            if (expression is LiteralExpressionSyntax)
            {
                return;
            }

            if (CSharpUtility.IsStringLiteralConcatenation(expression as BinaryExpressionSyntax))
            {
                return;
            }

            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            var optional = default(Optional <object>);

            ISymbol symbol = semanticModel.GetSymbol(expression, context.CancellationToken);

            if (symbol?.IsErrorType() != false)
            {
                return;
            }

            if (symbol is IFieldSymbol fieldSymbol)
            {
                if (!fieldSymbol.HasConstantValue)
                {
                    return;
                }

                if (fieldSymbol.ContainingType?.TypeKind == TypeKind.Enum)
                {
                    return;
                }
            }
            else if (symbol is ILocalSymbol localSymbol)
            {
                if (!localSymbol.HasConstantValue)
                {
                    return;
                }
            }
            else
            {
                optional = semanticModel.GetConstantValue(expression, context.CancellationToken);

                if (!optional.HasValue)
                {
                    return;
                }
            }

            context.RegisterRefactoring(
                "Inline constant value",
                ct => RefactorAsync(context.Document, expression, symbol, optional, semanticModel, ct),
                RefactoringDescriptors.InlineConstantValue);
        }
        private bool IsZeroLengthArrayAllocationCSharp(SyntaxToken token)
        {
            var arrayCreationExpression = token.Parent as CS.Syntax.ArrayCreationExpressionSyntax;

            if (arrayCreationExpression == null)
            {
                return(false);
            }

            var arrayType = arrayCreationExpression.Type;

            if (arrayType == null || arrayType.IsMissing)
            {
                return(false);
            }

            if (arrayType.RankSpecifiers.Count != 1)
            {
                return(false);
            }

            var specifier = arrayType.RankSpecifiers[0] as CS.Syntax.ArrayRankSpecifierSyntax;

            if (specifier == null)
            {
                return(false);
            }

            if (specifier.Rank != 1 || specifier.Sizes.Count != 1)
            {
                return(false);
            }

            var sizeExpression = specifier.Sizes[0];

            if (sizeExpression == null)
            {
                return(false);
            }

            if (sizeExpression is CS.Syntax.OmittedArraySizeExpressionSyntax &&
                arrayCreationExpression.Initializer != null &&
                !arrayCreationExpression.Initializer.IsMissing &&
                arrayCreationExpression.Initializer.Expressions.Count == 0)
            {
                return(true);
            }

            var value = SemanticModel.GetConstantValue(sizeExpression);

            if (!value.HasValue || !(value.Value is int))
            {
                return(false);
            }

            return((int)value.Value == 0);
        }
        private string GetStatus(INamedTypeSymbol classSymbol, SyntaxNode root, SemanticModel model, DiagnosticDescriptor descriptor)
        {
            // Some analyzers use multiple descriptors. We analyze the first one and hope that
            // thats enough.
            var members = classSymbol.GetMembers().Where(x => x.Name.Contains("Descriptor")).ToArray();

            foreach (var member in members)
            {
                ObjectCreationExpressionSyntax initializer;
                SyntaxNode node = root.FindNode(member.Locations.FirstOrDefault().SourceSpan);

                if (node != null)
                {
                    initializer = (node as PropertyDeclarationSyntax)?.Initializer?.Value as ObjectCreationExpressionSyntax;
                    if (initializer == null)
                    {
                        initializer = (node as VariableDeclaratorSyntax)?.Initializer?.Value as ObjectCreationExpressionSyntax;

                        if (initializer == null)
                        {
                            continue;
                        }
                    }
                }
                else
                {
                    continue;
                }

                var firstArgument = initializer.ArgumentList.Arguments[0];

                string constantValue = (string)model.GetConstantValue(firstArgument.Expression).Value;

                if (constantValue != descriptor.Id)
                {
                    continue;
                }

                // We use the fact that the only parameter that returns a boolean is the one we are interested in
                var enabledByDefaultParameter = from argument in initializer.ArgumentList.Arguments
                                                where Equals(model.GetTypeInfo(argument.Expression).Type, _booleanType)
                                                select argument.Expression;
                var    parameter              = enabledByDefaultParameter.FirstOrDefault();
                string parameterString        = parameter.ToString();
                var    analyzerConstantLength = "AnalyzerConstants.".Length;

                if (parameterString.Length < analyzerConstantLength)
                {
                    return(parameterString);
                }

                return(parameter.ToString().Substring(analyzerConstantLength));
            }

            return("Unknown");
        }
Ejemplo n.º 8
0
        private static bool IsZeroConstantValue(this SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken = default(CancellationToken))
        {
            Optional <object> optional = semanticModel.GetConstantValue(expression, cancellationToken);

            if (optional.HasValue)
            {
                object value = optional.Value;

                if (value is int)
                {
                    return((int)value == 0);
                }
                else if (value is uint)
                {
                    return((uint)value == 0);
                }
                else if (value is sbyte)
                {
                    return((sbyte)value == 0);
                }
                else if (value is byte)
                {
                    return((byte)value == 0);
                }
                else if (value is short)
                {
                    return((short)value == 0);
                }
                else if (value is ushort)
                {
                    return((ushort)value == 0);
                }
                else if (value is long)
                {
                    return((long)value == 0);
                }
                else if (value is ulong)
                {
                    return((ulong)value == 0);
                }
                else if (value is float)
                {
                    return((float)value == 0);
                }
                else if (value is double)
                {
                    return((double)value == 0);
                }
                else if (value is decimal)
                {
                    return((decimal)value == 0);
                }
            }

            return(false);
        }
Ejemplo n.º 9
0
        private static int GetConstantIntFromExpression(ExpressionSyntax expression, SemanticModel semanticModel)
        {
            var constantValue = semanticModel.GetConstantValue(expression);

            if (!constantValue.HasValue)
            {
                throw new ShaderGenerationException("Expression did not contain a constant value: " + expression.ToFullString());
            }
            return((int)constantValue.Value);
        }
Ejemplo n.º 10
0
        private static void CreateExpressions(ExpressionSyntax ifExpression, ExpressionSyntax elseExpression,
                                              ITypeSymbol ifType, ITypeSymbol elseType,
                                              ITypeSymbol ifConvertedType, ITypeSymbol elseConvertedType,
                                              TypeSyntax typeSyntax, SemanticModel semanticModel,
                                              out ExpressionSyntax trueExpression, out ExpressionSyntax falseExpression)
        {
            var isNullable = false;

            if (ifConvertedType?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
            {
                var constValue = semanticModel.GetConstantValue(ifExpression);
                trueExpression = constValue.HasValue && constValue.Value == null
                    ? SyntaxFactory.CastExpression(typeSyntax, ifExpression)
                    : ifExpression;

                isNullable = true;
            }
            else
            {
                trueExpression = ifExpression;
            }
            if (elseConvertedType?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
            {
                var constValue = semanticModel.GetConstantValue(elseExpression);
                falseExpression = constValue.HasValue && constValue.Value == null
                    ? SyntaxFactory.CastExpression(typeSyntax, elseExpression)
                    : elseExpression;

                isNullable = true;
            }
            else
            {
                falseExpression = elseExpression;
            }
            if (!elseType.HasImplicitNumericConversion(ifType) &&
                !IsEnumAndZero(ifType, elseExpression) &&
                !IsEnumAndZero(elseType, ifExpression) &&
                (!isNullable && !ifType.CanBeAssignedTo(elseType) || !elseType.CanBeAssignedTo(ifType)) &&
                ifType != ifConvertedType)
            {
                trueExpression = CastToConvertedType(ifExpression, ifConvertedType);
            }
        }
Ejemplo n.º 11
0
        public static bool NodeHasConstantValueNull(SyntaxNode node, SemanticModel model)
        {
            if (node == null || model == null)
            {
                return(false);
            }
            Optional <object> value = model.GetConstantValue(node);

            return(value.HasValue && value.Value == null);
        }
Ejemplo n.º 12
0
        public static string GetConstantAttribute(
            this AttributeSyntax attribute,
            string argumentName,
            SemanticModel semanticModel)
        {
            var expression          = attribute.GetArgument <ExpressionSyntax>(argumentName);
            Optional <object> value = semanticModel.GetConstantValue(expression);

            return(value.HasValue ? value.Value.ToString() : null);
        }
Ejemplo n.º 13
0
 public static bool IsBooleanConstant(this SyntaxNode syntaxNode, SemanticModel semanticModel)
 {
     if (syntaxNode is MemberAccessExpressionSyntax ||
         syntaxNode is IdentifierNameSyntax)
     {
         var constant = semanticModel.GetConstantValue(syntaxNode);
         return(constant.HasValue && constant.Value is bool);
     }
     return(false);
 }
Ejemplo n.º 14
0
        private static string GetGuidMetadataConstantValue(this AttributeArgumentSyntax syntax, SemanticModel semanticModel)
        {
            if (syntax == null)
            {
                return(null);
            }
            var constantValue = semanticModel.GetConstantValue(syntax.Expression);

            return(constantValue.Value?.ToString());
        }
Ejemplo n.º 15
0
        private static bool IsStringLiteral(ExpressionSyntax expression, SemanticModel semanticModel)
        {
            if (expression == null)
            {
                return(false);
            }

            var constant = semanticModel.GetConstantValue(expression);

            return(constant.HasValue && constant.Value is string);
        }
Ejemplo n.º 16
0
        public async Task <(IReadOnlyCollection <VariableDeclarationSyntax> Variables, IReadOnlyCollection <CSharpSyntaxNode> Methods)> SplitVariableDeclarations(
            VariableDeclaratorSyntax declarator, bool preferExplicitType = false)
        {
            var vbInitValue             = GetInitializerToConvert(declarator);
            var initializerOrMethodDecl = await vbInitValue.AcceptAsync(TriviaConvertingExpressionVisitor);

            var vbInitializerType = vbInitValue != null?_semanticModel.GetTypeInfo(vbInitValue).Type : null;

            bool          requireExplicitTypeForAll = declarator.Names.Count > 1;
            IMethodSymbol initSymbol = null;

            if (vbInitValue != null)
            {
                var vbInitConstantValue    = _semanticModel.GetConstantValue(vbInitValue);
                var vbInitIsNothingLiteral = vbInitConstantValue.HasValue && vbInitConstantValue.Value == null;
                preferExplicitType |= vbInitializerType != null && vbInitializerType.HasCsKeyword();
                initSymbol          = _semanticModel.GetSymbolInfo(vbInitValue).Symbol as IMethodSymbol;
                bool isAnonymousFunction = initSymbol?.IsAnonymousFunction() == true;
                requireExplicitTypeForAll |= vbInitIsNothingLiteral || isAnonymousFunction;
            }

            var csVars    = new Dictionary <string, VariableDeclarationSyntax>();
            var csMethods = new List <CSharpSyntaxNode>();

            foreach (var name in declarator.Names)
            {
                var declaredSymbol          = _semanticModel.GetDeclaredSymbol(name);
                var declaredSymbolType      = declaredSymbol.GetSymbolType();
                var equalsValueClauseSyntax = await ConvertEqualsValueClauseSyntax(declarator, name, vbInitValue, declaredSymbolType, declaredSymbol, initializerOrMethodDecl);

                var    v = SyntaxFactory.VariableDeclarator(ConvertIdentifier(name.Identifier), null, equalsValueClauseSyntax);
                string k = declaredSymbolType?.GetFullMetadataName() ?? name.ToString();//Use likely unique key if the type symbol isn't available

                if (csVars.TryGetValue(k, out var decl))
                {
                    csVars[k] = decl.AddVariables(v);
                    continue;
                }

                if (initializerOrMethodDecl == null || initializerOrMethodDecl is ExpressionSyntax)
                {
                    var variableDeclaration = CreateVariableDeclaration(declarator, preferExplicitType,
                                                                        requireExplicitTypeForAll, vbInitializerType, declaredSymbolType, equalsValueClauseSyntax,
                                                                        initSymbol, v);
                    csVars[k] = variableDeclaration;
                }
                else
                {
                    csMethods.Add(initializerOrMethodDecl);
                }
            }

            return(csVars.Values, csMethods);
        }
Ejemplo n.º 17
0
        private bool TryGenerateLiteral(ExpressionSyntax expression)
        {
            /*
             *  <ElementType name="Literal" content="eltOnly">
             *  - <group order="one">
             *      <element type="Null" />
             *      <element type="Number" />
             *      <element type="Boolean" />
             *      <element type="Char" />
             *      <element type="String" />
             *      <element type="Array" />
             *      <element type="Type" />
             *      </group>
             *  </ElementType>
             */

            using (LiteralTag())
            {
                var constantValue = SemanticModel.GetConstantValue(expression);
                if (!constantValue.HasValue)
                {
                    return(false);
                }

                var type = SemanticModel.GetTypeInfo(expression).Type;
                if (type == null)
                {
                    return(false);
                }

                switch (expression.Kind())
                {
                case SyntaxKind.UnaryMinusExpression:
                case SyntaxKind.NumericLiteralExpression:
                    GenerateNumber(constantValue.Value, type);
                    return(true);

                case SyntaxKind.CharacterLiteralExpression:
                    GenerateChar((char)constantValue.Value);
                    return(true);

                case SyntaxKind.StringLiteralExpression:
                    GenerateString((string)constantValue.Value);
                    return(true);

                case SyntaxKind.TrueLiteralExpression:
                case SyntaxKind.FalseLiteralExpression:
                    GenerateBoolean((bool)constantValue.Value);
                    return(true);
                }

                return(false);
            }
        }
Ejemplo n.º 18
0
            protected bool HasNullConstantValue(SyntaxNode expression, SemanticModel model, CancellationToken cancellationToken)
            {
                if (expression == null)
                {
                    return(false);
                }

                Optional <object> constantValue = model.GetConstantValue(expression, cancellationToken);

                return(constantValue.HasValue && constantValue.Value == null);
            }
Ejemplo n.º 19
0
        internal static bool IsPositiveInfinity(SemanticModel semanticModel, SyntaxNode node)
        {
            var rr = semanticModel.GetConstantValue(node);

            if (!rr.HasValue)
            {
                return(false);
            }

            return(rr.Value is double && double.IsPositiveInfinity((double)rr.Value) || rr.Value is float && float.IsPositiveInfinity((float)rr.Value));
        }
Ejemplo n.º 20
0
        public static bool NodeHasConstantValueIntZero(SyntaxNode node, SemanticModel model)
        {
            if (node == null || model == null)
            {
                return(false);
            }
            var value = model.GetConstantValue(node);

            return(value.HasValue &&
                   value.Value is int &&
                   (int)value.Value == 0);
        }
Ejemplo n.º 21
0
        private static bool IsStringEmptyConst(ExpressionSyntax expression, SemanticModel semanticModel)
        {
            var constValue = semanticModel.GetConstantValue(expression);

            if (!constValue.HasValue)
            {
                return(false);
            }


            return(constValue.Value is string stringConstValue && stringConstValue == string.Empty);
        }
Ejemplo n.º 22
0
        public static bool NodeHasConstantValueBoolFalse(SyntaxNode node, SemanticModel model)
        {
            if (node == null || model == null)
            {
                return(false);
            }
            var value = model.GetConstantValue(node);

            return(value.HasValue &&
                   value.Value is bool &&
                   (bool)value.Value == false);
        }
        private static bool SupportsConstant(
            TypeSyntax type,
            VariableDeclaratorSyntax declarator,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            ExpressionSyntax value = declarator.Initializer?.Value;

            return(value != null &&
                   semanticModel.GetTypeSymbol(type, cancellationToken)?.SupportsConstantValue() == true &&
                   semanticModel.GetConstantValue(value, cancellationToken).HasValue);
        }
Ejemplo n.º 24
0
        public static bool NodeHasConstantValue <T>(SyntaxNode node, SemanticModel model, T expectedValue) where T : struct
        {
            if (node == null || model == null)
            {
                return(false);
            }
            Optional <object> value = model.GetConstantValue(node);

            return(value.HasValue &&
                   value.Value is T &&
                   ((T)value.Value).Equals(expectedValue));
        }
Ejemplo n.º 25
0
        // Instantiate a binding attribute
        public static Attribute MakeAttr(IJobHostMetadataProvider tooling, SemanticModel semantics, AttributeSyntax attrSyntax)
        {
            IMethodSymbol symAttributeCtor = (IMethodSymbol)semantics.GetSymbolInfo(attrSyntax).Symbol;
            var           syntaxParams     = symAttributeCtor.Parameters;

            INamedTypeSymbol attrType = symAttributeCtor.ContainingType;

            if (!IsBindingAttribute(attrType))
            {
                return(null);
            }

            Type typeReflection = GetAttributeType(attrType);

            JObject args = new JObject();

            int idx = 0;

            if (attrSyntax.ArgumentList != null)
            {
                foreach (var arg in attrSyntax.ArgumentList.Arguments)
                {
                    var val = semantics.GetConstantValue(arg.Expression);
                    if (!val.HasValue)
                    {
                        return(null);
                    }
                    var v2 = val.Value;

                    string argName = null;
                    if (arg.NameColon != null)
                    {
                        argName = arg.NameColon.Name.ToString();
                    }
                    else if (arg.NameEquals != null)
                    {
                        argName = arg.NameEquals.Name.ToString();
                    }
                    else
                    {
                        argName = syntaxParams[idx].Name; // Positional
                    }

                    args[argName] = JToken.FromObject(v2);

                    idx++;
                }
            }

            var attr = tooling.GetAttribute(typeReflection, args);

            return(attr);
        }
 protected static ExpressionSyntax MakeTernaryOperand(ExpressionSyntax expression, SemanticModel semanticModel, ITypeSymbol type, TypeSyntax typeSyntax)
 {
     if (type?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
     {
         var constValue = semanticModel.GetConstantValue(expression);
         if (constValue.HasValue && constValue.Value == null)
         {
             return(SyntaxFactory.CastExpression(typeSyntax, expression));
         }
     }
     return(expression);
 }
 static bool IsConstantExpression(SemanticModel context, ExpressionSyntax expr)
 {
     if (expr is LiteralExpressionSyntax)
     {
         return(true);
     }
     if (expr is DefaultExpressionSyntax)
     {
         return(true);
     }
     return(context.GetConstantValue(expr).HasValue);
 }
        private bool isValidPasswordComplexity(SemanticModel model, InitializerExpressionSyntax syntax)
        {
            if (syntax == null || syntax.Expressions.Count == 0)
            {
                return(false);
            }

            //Accouting for the inline assignment expression
            int  minLength = 0;
            bool requireSpecialCharacter = false;
            bool requireNumber           = false;
            bool requireUpperChar        = false;
            bool requireLowerChar        = false;

            foreach (AssignmentExpressionSyntax expression in syntax.Expressions)
            {
                //Get the property value
                var value = model.GetConstantValue(expression.Right);

                //If we have a value, set them to the local var
                if (value.HasValue)
                {
                    switch (expression.Left.ToString())
                    {
                    case "RequiredLength":
                        minLength = (int)value.Value;
                        break;

                    case "RequireNonLetterOrDigit":
                        requireSpecialCharacter = (bool)value.Value;
                        break;

                    case "RequireDigit":
                        requireNumber = (bool)value.Value;
                        break;

                    case "RequireLowercase":
                        requireLowerChar = (bool)value.Value;
                        break;

                    case "RequireUppercase":
                        requireUpperChar = (bool)value.Value;
                        break;

                    default:
                        break;
                    }
                }
            }

            return(!isValidPasswordComplexity(minLength, requireSpecialCharacter, requireNumber, requireUpperChar, requireLowerChar));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Detremines Password Lockout vulnerabilities
        /// </summary>
        /// <param name="syntaxNode"></param>
        /// <param name="filePath"></param>
        /// <param name="model"></param>
        /// <param name="solution"></param>
        /// <returns></returns>
        public IEnumerable <VulnerabilityDetail> FindVulnerabilties(SyntaxNode syntaxNode, string filePath, SemanticModel model = null, Solution solution = null)
        {
            List <VulnerabilityDetail> vulnerabilities = new List <VulnerabilityDetail>();
            var invocationExpressions = syntaxNode.DescendantNodes().OfType <InvocationExpressionSyntax>();

            foreach (var item in invocationExpressions)
            {
                if (!(item.Expression is MemberAccessExpressionSyntax memberAccess) || !memberAccess.ToString().Contains("PasswordSignIn"))
                {
                    continue;
                }

                ISymbol symbol = model.GetSymbol(memberAccess);
                if (symbol == null)
                {
                    continue;
                }

                if (symbol.ContainingNamespace.ToString() != KnownType.Microsoft_AspNet_Identity_Owin &&
                    symbol.ContainingNamespace.ToString() != KnownType.Microsoft_AspNetCore_Identity)
                {
                    continue;
                }
                int    argCount      = symbol.Name == "CheckPasswordSignInAsync" ? 3 : 4;
                string parameterName = symbol.ContainingNamespace.ToString() == KnownType.Microsoft_AspNet_Identity_Owin ? "shouldLockout" : "lockoutOnFailure";
                if (item.ArgumentList == null || item.ArgumentList.Arguments.Count < argCount)
                {
                    continue;
                }
                int i = -1;
                foreach (var argument in item.ArgumentList.Arguments)
                {
                    i++;
                    if (argument.NameColon == null && i != argCount - 1)
                    {
                        continue;
                    }
                    else if (argument.NameColon != null && argument.NameColon.Name.ToString() != parameterName)
                    {
                        continue;
                    }

                    var lockoutValue = model.GetConstantValue(argument.Expression);
                    if (lockoutValue.HasValue && lockoutValue.Value is bool value && !value)
                    {
                        vulnerabilities.Add(VulnerabilityDetail.Create(filePath, argument, Enums.ScannerType.PasswordLockout));
                    }
                    break;
                }
            }
            return(vulnerabilities);
        }
Ejemplo n.º 30
0
        public override void VisitAssignmentExpression(AssignmentExpressionSyntax node)
        {
            base.VisitAssignmentExpression(node);

            var rightSymbol = _semanticModel.GetSymbolInfo(node.Right).Symbol;

            if (node.Left is ElementAccessExpressionSyntax)
            {
                // TODO
            }
            else
            {
                var leftSymbol = _semanticModel.GetSymbolInfo(node.Left).Symbol;
                if (!IsUsedSymbol(leftSymbol) || !IsUsedSymbol(rightSymbol))
                {
                    return;
                }

                var constValue = _semanticModel.GetConstantValue(node.Right);
                if (rightSymbol != null && leftSymbol != null) // rightSymbol may be null if we have a boolean expression
                {
                    AbstractNode rightSymbolNode;
                    if (rightSymbol is IMethodSymbol)
                    {
                        rightSymbolNode = new MethodReturnSymbol(rightSymbol as IMethodSymbol);
                    }
                    else
                    {
                        rightSymbolNode = new VariableSymbol(rightSymbol);
                    }

                    AddSubtypingRelation(new VariableSymbol(leftSymbol), rightSymbolNode);
                }
                else if (constValue.HasValue && leftSymbol != null)
                {
                    AddSubtypingRelation(new VariableSymbol(leftSymbol), new LiteralSymbol(constValue.Value, node.GetLocation()));
                }
            }
        }
        private static bool InsideNameOfExpression(ExpressionSyntax expr, SemanticModel semanticModel)
        {
            var nameOfInvocationExpr = expr.FirstAncestorOrSelf<InvocationExpressionSyntax>(
                invocationExpr =>
                {
                    var expression = invocationExpr.Expression as IdentifierNameSyntax;
                    return (expression != null) && (expression.Identifier.Text == "nameof") &&
                        semanticModel.GetConstantValue(invocationExpr).HasValue &&
                        (semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String);
                });

            return nameOfInvocationExpr != null;
        }
        private bool CanSimplifyToLengthEqualsZeroExpression(
            ExpressionSyntax variableExpression,
            LiteralExpressionSyntax numericLiteralExpression,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            var numericValue = semanticModel.GetConstantValue(numericLiteralExpression, cancellationToken);
            if (numericValue.HasValue && numericValue.Value is int && (int)numericValue.Value == 0)
            {
                var symbol = semanticModel.GetSymbolInfo(variableExpression, cancellationToken).Symbol;

                if (symbol != null && (symbol.Name == "Length" || symbol.Name == "LongLength"))
                {
                    var containingType = symbol.ContainingType;
                    if (containingType != null &&
                        (containingType.SpecialType == SpecialType.System_Array ||
                         containingType.SpecialType == SpecialType.System_String))
                    {
                        return true;
                    }
                }

                var typeInfo = semanticModel.GetTypeInfo(variableExpression, cancellationToken);
                if (typeInfo.Type != null)
                {
                    switch (typeInfo.Type.SpecialType)
                    {
                        case SpecialType.System_Byte:
                        case SpecialType.System_UInt16:
                        case SpecialType.System_UInt32:
                        case SpecialType.System_UInt64:
                            return true;
                    }
                }
            }

            return false;
        }