Beispiel #1
0
 private IDisposable EnterFunction(string name)
 {
     var fn = scope = function = new AnalysisScope.Function(scope, name);
     return new Disposable(() =>
     {
         Assert.IsTrue(() => scope == function && function == fn);
         scope = function.ParentScope;
         if (scope is AnalysisScope.Function)
         {
             function = (AnalysisScope.Function)scope;
         }
         else
         {
             var s = scope.ParentScope;
             var set = false;
             while (s != null)
             {
                 if (s is AnalysisScope.Function)
                 {
                     function = (AnalysisScope.Function)s;
                     set = true;
                     break;
                 }
                 s = s.ParentScope;
             }
             if (!set)
                 throw new InvalidOperationException("Invalid scope-chain");
         }
     });
 }
Beispiel #2
0
        private void StartAnalyzeCompilation([NotNull] CompilationStartAnalysisContext context)
        {
            Guard.NotNull(context, nameof(context));

            AnalyzerSettings settings = SettingsProvider.LoadSettings(context.Options, context.CancellationToken);

            NullabilityAttributeSymbols nullSymbols = NullabilityAttributeProvider.GetCached()
                                                      .GetSymbols(context.Compilation, context.CancellationToken);

            if (nullSymbols == null)
            {
                // Nullability attributes not found; keep silent.
                return;
            }

            IExternalAnnotationsResolver resolver = ExternalAnnotationsResolver.GetCached();

            resolver.EnsureScanned();

            var generatedCodeCache = new GeneratedCodeDocumentCache();
            var typeCache          = new FrameworkTypeCache(context.Compilation);

            var nullabilityContext = new AnalysisScope(resolver, generatedCodeCache, typeCache, settings,
                                                       disableReportOnNullableValueTypesRule, appliesToItem);

            var factory = new SymbolAnalyzerFactory(nullabilityContext);

            ImmutableDictionary <string, string> properties = nullSymbols.GetMetadataNamesAsProperties();

            context.RegisterSymbolAction(c => AnalyzeField(c, factory, properties), SymbolKind.Field);
            context.RegisterSymbolAction(c => AnalyzeProperty(c, factory, properties), SymbolKind.Property);
            context.RegisterSymbolAction(c => AnalyzeMethod(c, factory, properties), SymbolKind.Method);
            context.RegisterSyntaxNodeAction(c => AnalyzeParameter(SyntaxToSymbolContext(c), factory, properties),
                                             SyntaxKind.Parameter);
        }
Beispiel #3
0
 public ConditionTaintAnalyser(AnalysisScope scope, IIncludeResolver inclusionResolver, Stack <File> includeStack, FunctionsHandler fh)
 {
     this._analysisScope  = scope;
     this.includeResolver = inclusionResolver;
     this._includeStack   = includeStack;
     this._funcHandler    = fh;
 }
Beispiel #4
0
        public VariableResolver(IVariableStorage varStorage, AnalysisScope scope = AnalysisScope.File)
        {
            Preconditions.NotNull(varStorage, "varStorage");
            this._variableStorage = varStorage;
            this._scope           = scope;

            variableScope = scope == AnalysisScope.File ? VariableScope.File : VariableScope.Function;
        }
Beispiel #5
0
 private IDictionary <string, Variable> GetLocalScope(AnalysisScope scope)
 {
     if (scope == AnalysisScope.File)
     {
         return(_variableStorage.GlobalVariables);
     }
     return(_variableStorage.LocalVariables);
 }
Beispiel #6
0
 private IDisposable EnterBlock()
 {
     scope = new AnalysisScope.Block(scope);
     return new Disposable(() =>
     {
         scope = scope.ParentScope;
     });
 }
Beispiel #7
0
        public VariableResolver(IVariableStorage varStorage, AnalysisScope scope = AnalysisScope.File)
        {
            Preconditions.NotNull(varStorage, "varStorage");
            this._variableStorage = varStorage;
            this._scope = scope;

            variableScope = scope == AnalysisScope.File ? VariableScope.File : VariableScope.Function;
        }
        public MethodCall ExtractMethodCall(XmlNode node, IVariableStorage varStorage, AnalysisScope scope = AnalysisScope.File)
        {
            int startLine = AstNode.GetStartLine(node);
            int endLine = AstNode.GetEndLine(node);
            string methodName = "";

            //Get the varNode which includes either (new ClassName())->MethodName or $var->MethodName
            var varNode = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Var);
            var classNames = new List<string>();

            if (varNode.FirstChild.LocalName == AstConstants.Nodes.Expr_New)
            {
                //PHP: (new ClassName(args))->MethodName(args);
                //Extract the ClassName directly, in this case there can be only one ClassName!
                var className = varNode.FirstChild
                    .GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Class)
                    .GetSubNode(AstConstants.Node + ":" + AstConstants.Nodes.Name)
                    .GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Parts).FirstChild.FirstChild.InnerText;
                classNames.Add(className);

                methodName = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Name).InnerText;
                return new MethodCall(methodName, classNames, node, startLine, endLine) { Arguments = ExtractArgumentNodes(node) };
            }
            else
            {
                //PHP: $var->MethodName(args);
                //Resolve the variable, and get all the possible class names!
                VariableResolver vr = new VariableResolver(varStorage, scope);
                VariableResolveResult variableResult = null;
                if (vr.IsResolvableNode(varNode.FirstChild))
                {
                    variableResult = vr.ResolveVariable(varNode.FirstChild);
                    classNames.AddRange(variableResult.Variable.Info.ClassNames.Where(className => !classNames.Contains(className)));
                }

                var nameSubnode = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Name);
                XmlNode nameNode = null;
                bool success = nameSubnode.TryGetSubNode(AstConstants.Node + ":" + AstConstants.Nodes.Name, out nameNode);
                if (success)
                {
                    methodName = nameNode.InnerText;
                }
                else
                {
                    if (nameSubnode.FirstChild.LocalName == AstConstants.Scalars.String)
                    {
                        methodName = nameSubnode.FirstChild.InnerText;
                    }
                }

                return variableResult == null ?
                    new MethodCall(methodName, classNames, node, startLine, endLine) { Arguments = ExtractArgumentNodes(node) } :
                    new MethodCall(methodName, classNames, node, startLine, endLine, variableResult.Variable) { Arguments = ExtractArgumentNodes(node) };
            }
        }
Beispiel #9
0
        public TaintBlockAnalyzer(IVulnerabilityStorage vulnerabilityStorage, IIncludeResolver inclusionResolver, AnalysisScope scope,
            Func<ImmutableVariableStorage, IIncludeResolver, AnalysisScope, AnalysisStacks, ImmutableVariableStorage> analyzeTaint, 
            AnalysisStacks stacks, FunctionAndMethodAnalyzerFactory subroutineAnalyzerFactory)
            : this()
        {
            Preconditions.NotNull(vulnerabilityStorage, "vulnerabilityStorage");
            Preconditions.NotNull(inclusionResolver, "inclusionResolver");
            Preconditions.NotNull(analyzeTaint, "analyzeTaint");
            Preconditions.NotNull(stacks, "stacks");
            Preconditions.NotNull(subroutineAnalyzerFactory, "subroutineAnalyzerFactory");

            this._vulnerabilityStorage = vulnerabilityStorage;
            this._inclusionResolver = inclusionResolver;
            this._analyzer = analyzeTaint;
            this._analysisScope = scope;
            this.ReturnInfos = new List<ExpressionInfo>();
            this._analysisStacks = stacks;
            this._subroutineAnalyzerFactory = subroutineAnalyzerFactory;
        }
Beispiel #10
0
        ParseExprToLambda(TextReader reader)
        {
            var scanner    = new VB.Scanner(reader);
            var errorTable = new List <VB.SyntaxError>();
            var ast        = new VB.Parser().ParseScriptFile(scanner, errorTable);

            VBScriptSourceCodeReader sourceReader = reader as VBScriptSourceCodeReader;
            ISourceMapper            mapper       = null;

            if (sourceReader != null)
            {
                mapper = sourceReader.SourceMapper;
            }

            var scope = new AnalysisScope(
                null,
                "__snippet__",
                this,
                Expression.Parameter(typeof(VBScript), "vbscriptRuntime"),
                Expression.Parameter(typeof(IDynamicMetaObjectProvider), "fileModule"),
                mapper
                );

            List <Expression> body = new List <Expression>();

            body.Add(Expression.Convert(VBScriptGenerator.GenerateExpr(ast, scope), typeof(object)));

            if (scope.Errors.Count > 0)
            {
                throw new VBScriptCompilerException(scope.Errors);
            }

            var moduleFun = Expression.Lambda <Action <VBScript, IDynamicMetaObjectProvider> >(
                Expression.Block(body),
                scope.RuntimeExpr,
                scope.ModuleExpr
                );

            return(moduleFun.Compile());
        }
Beispiel #11
0
 private IDictionary<string, Variable> GetLocalScope(AnalysisScope scope)
 {
     if (scope == AnalysisScope.File)
     {
         return _variableStorage.GlobalVariables;
     }
     return _variableStorage.LocalVariables;
 }
Beispiel #12
0
 public static Expression Generate(SourceUnitTree tree, AnalysisScope.TopLevel global)
 {
     return new AstGenerator(global).Generate(tree);
 }
Beispiel #13
0
        public MethodCall ExtractMethodCall(XmlNode node, IVariableStorage varStorage, AnalysisScope scope = AnalysisScope.File)
        {
            int    startLine  = AstNode.GetStartLine(node);
            int    endLine    = AstNode.GetEndLine(node);
            string methodName = "";

            //Get the varNode which includes either (new ClassName())->MethodName or $var->MethodName
            var varNode    = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Var);
            var classNames = new List <string>();

            if (varNode.FirstChild.LocalName == AstConstants.Nodes.Expr_New)
            {
                //PHP: (new ClassName(args))->MethodName(args);
                //Extract the ClassName directly, in this case there can be only one ClassName!
                var className = varNode.FirstChild
                                .GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Class)
                                .GetSubNode(AstConstants.Node + ":" + AstConstants.Nodes.Name)
                                .GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Parts).FirstChild.FirstChild.InnerText;
                classNames.Add(className);

                methodName = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Name).InnerText;
                return(new MethodCall(methodName, classNames, node, startLine, endLine)
                {
                    Arguments = ExtractArgumentNodes(node)
                });
            }
            else
            {
                //PHP: $var->MethodName(args);
                //Resolve the variable, and get all the possible class names!
                VariableResolver      vr             = new VariableResolver(varStorage, scope);
                VariableResolveResult variableResult = null;
                if (vr.IsResolvableNode(varNode.FirstChild))
                {
                    variableResult = vr.ResolveVariable(varNode.FirstChild);
                    classNames.AddRange(variableResult.Variable.Info.ClassNames.Where(className => !classNames.Contains(className)));
                }

                var     nameSubnode = node.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Name);
                XmlNode nameNode    = null;
                bool    success     = nameSubnode.TryGetSubNode(AstConstants.Node + ":" + AstConstants.Nodes.Name, out nameNode);
                if (success)
                {
                    methodName = nameNode.InnerText;
                }
                else
                {
                    if (nameSubnode.FirstChild.LocalName == AstConstants.Scalars.String)
                    {
                        methodName = nameSubnode.FirstChild.InnerText;
                    }
                }

                return(variableResult == null ?
                       new MethodCall(methodName, classNames, node, startLine, endLine)
                {
                    Arguments = ExtractArgumentNodes(node)
                } :
                       new MethodCall(methodName, classNames, node, startLine, endLine, variableResult.Variable)
                {
                    Arguments = ExtractArgumentNodes(node)
                });
            }
        }
Beispiel #14
0
 private IEnumerable<Expression> FunctionBlock(AnalysisScope.Function functionScope, IEnumerable<Expression> body)
 {
     List<Expression> _body = new List<Expression>();
     _body.AddRange(Write(functionScope.ReturnValue, engine.UndefinedExpr));
     _body.AddRange(body);
     _body.Add(Expression.Label(functionScope.ReturnTarget));
     if (functionScope.Globalize)
     {
         _body.AddRange(functionScope.Variables.Select(
             var => Utils.LightDynamic(
                 engine.GetSetMemberBinder(var.Name),
                 global.GlobalExpr,
                 var
             )
         ));
     }
     _body.Add(functionScope.ReturnValue);
     yield return Expression.Block(
         typeof(TotemObject),
         new ParameterExpression[] { functionScope.ReturnValue }
             .Concat(functionScope.Variables),
         _body
     );
 }
 public ConditionTaintAnalyser(AnalysisScope scope, IIncludeResolver inclusionResolver, Stack<File> includeStack)
 {
     this._analysisScope = scope;
     this.includeResolver = inclusionResolver;
     this._includeStack = includeStack;
 }
Beispiel #16
0
        ParseFileToLambda(string filename, TextReader reader)
        {
            var scanner    = new VB.Scanner(reader);
            var errorTable = new List <VB.SyntaxError>();

            var block = new VB.Parser().ParseScriptFile(scanner, errorTable);

            if (errorTable.Count > 0)
            {
                List <VBScriptSyntaxError> errors = new List <VBScriptSyntaxError>();
                foreach (VB.SyntaxError error in errorTable)
                {
                    errors.Add(new VBScriptSyntaxError(
                                   filename,
                                   SourceUtil.ConvertSpan(error.Span),
                                   (int)error.Type,
                                   error.Type.ToString())
                               );
                }
                throw new VBScriptCompilerException(errors);
            }

            VBScriptSourceCodeReader sourceReader = reader as VBScriptSourceCodeReader;
            ISourceMapper            mapper       = null;

            if (sourceReader != null)
            {
                mapper = sourceReader.SourceMapper;
            }

            var scope = new AnalysisScope(
                null,
                filename,
                this,
                Expression.Parameter(typeof(VBScript), "vbscriptRuntime"),
                Expression.Parameter(typeof(IDynamicMetaObjectProvider), "fileModule"),
                mapper);

            //Generate function table
            List <Expression> body = new List <Expression>();

            //Add the built in globals
            ParameterExpression err = Expression.Parameter(typeof(ErrObject), ERR_PARAMETER);

            scope.Names.Add(ERR_PARAMETER, err);
            body.Add(
                Expression.Assign(
                    err,
                    Expression.New(typeof(ErrObject))
                    )
                );

            if (Trace)
            {
                ParameterExpression trace = Expression.Parameter(typeof(ITrace), TRACE_PARAMETER);
                scope.Names.Add(TRACE_PARAMETER, trace);
                body.Add(
                    Expression.Assign(
                        trace,
                        Expression.Convert(
                            Expression.Dynamic(
                                scope.GetRuntime().GetGetMemberBinder(TRACE_PARAMETER),
                                typeof(object),
                                scope.GetModuleExpr()
                                ),
                            typeof(ITrace)
                            )
                        )
                    );
            }

            //Put module variables and functions into the scope
            VBScriptAnalyzer.AnalyzeFile(block, scope);

            //Generate the module level code other than the methods:
            if (block.Statements != null)
            {
                foreach (var s in block.Statements)
                {
                    if (s is VB.MethodDeclaration)
                    {
                        //Make sure methods are created first before being executed
                        body.Insert(0, VBScriptGenerator.GenerateExpr(s, scope));
                    }
                    else
                    {
                        Expression stmt = VBScriptGenerator.GenerateExpr(s, scope);
                        if (scope.VariableScope.IsOnErrorResumeNextOn)
                        {
                            stmt = VBScriptGenerator.WrapTryCatchExpression(stmt, scope);
                        }
                        Expression debugInfo      = null;
                        Expression clearDebugInfo = null;
                        if (Trace && s is VB.Statement && !(s is VB.BlockStatement))
                        {
                            debugInfo = VBScriptGenerator.GenerateDebugInfo(s, scope, out clearDebugInfo);
                            body.Add(debugInfo);
                        }

                        body.Add(stmt);

                        if (clearDebugInfo != null)
                        {
                            body.Add(clearDebugInfo);
                        }
                    }
                }
            }

            body.Add(Expression.Constant(null)); //Stop anything from returning

            if (scope.Errors.Count > 0)
            {
                throw new VBScriptCompilerException(scope.Errors);
            }

            //if (Debug)
            //{
            //    Expression registerRuntimeVariables = VBScriptGenerator.GenerateRuntimeVariablesExpression(scope);

            //    body.Insert(0, registerRuntimeVariables);
            //}

            var moduleFun = Expression.Lambda <Action <VBScript, IDynamicMetaObjectProvider> >(
                Expression.Block(
                    scope.Names.Values,
                    body),
                scope.RuntimeExpr,
                scope.ModuleExpr);

            //if (!Debug)
            //{
            return(moduleFun.Compile());
            //}
            //else
            //{
            //    Expression<Action<VBScript, IDynamicMetaObjectProvider>> lambda =  (Expression<Action<VBScript, IDynamicMetaObjectProvider>>)DebugContext.TransformLambda(moduleFun);
            //    return lambda.Compile();
            //}
        }
Beispiel #17
0
 private AstGenerator(AnalysisScope.TopLevel global)
 {
     this.global = global;
     this.engine = global.Engine;
     this.scope = this.function = new AnalysisScope.Function(global, "module", true);
 }
Beispiel #18
0
 public static VariableScope ToVariableScope(this AnalysisScope analysisScope)
 {
     return(analysisScope == AnalysisScope.File ? VariableScope.File : VariableScope.Function);
 }
        public SymbolAnalyzerFactory([NotNull] AnalysisScope scope)
        {
            Guard.NotNull(scope, nameof(scope));

            this.scope = scope;
        }