예제 #1
0
        public void CFGCreator_RootAndExitIsClousure(string phpCode)
        {
            var extract = ParseAndExtract(phpCode);

            foreach (var closure in extract.Closures)
            {
                var ast        = closure.AstNode;
                var traverser  = new XmlTraverser();
                var cfgcreator = new CFGCreator();
                traverser.AddVisitor(cfgcreator);
                traverser.Traverse(ast);

                var graph = cfgcreator.Graph;

                //Root
                Assert.IsTrue(graph.Vertices.First().IsRoot, "the first vertix is not the root node");
                Assert.IsTrue(graph.Vertices.First().IsSpecialBlock, "The first node was not marked with IsSpecialBlock");
                graph.AssertInEdges(graph.Vertices.First(), 0, "Entry node contains in edges");
                graph.AssertOutEdges(graph.Vertices.First(), 1, "Entry node did not have exactly one out edge");
                Assert.AreEqual(AstConstants.Nodes.Expr_Closure, graph.Vertices.First().ToString(), "The root node was not a closure, and was expected to be a closure");

                //Leaf
                Assert.IsTrue(graph.Vertices.ElementAt(1).IsLeaf, "The element at position one was not the exit block");
                Assert.IsTrue(graph.Vertices.ElementAt(1).IsSpecialBlock, "The element at position one was not marked with IsSpecialBlock");
                graph.AssertOutEdges(graph.Vertices.ElementAt(1), 0, "The exit block contained out edged");
                Assert.AreEqual(AstConstants.Nodes.Expr_Closure, graph.Vertices.ElementAt(1).ToString());
            }
        }
예제 #2
0
        public void CFGCreator_RootAndExitIsStmtClassMethod(string phpcode)
        {
            var extract = ParseAndExtract(phpcode);

            foreach (var @class in extract.Classes)
            {
                foreach (var method in @class.Methods)
                {
                    var ast        = method.AstNode;
                    var traverser  = new XmlTraverser();
                    var cfgcreator = new CFGCreator();
                    traverser.AddVisitor(cfgcreator);
                    traverser.Traverse(ast);

                    var graph = cfgcreator.Graph;

                    //Root assertions
                    Assert.AreEqual(AstConstants.Nodes.Stmt_ClassMethod, graph.Vertices.First().ToString());
                    graph.AssertInEdges(graph.Vertices.First(), 0, "Entry node - in edges");
                    graph.AssertOutEdges(graph.Vertices.First(), 1, "Entry node - out edges");
                    Assert.AreEqual(true, graph.Vertices.First().IsRoot);

                    //Leaf assertions
                    graph.AssertOutEdges(graph.Vertices.ElementAt(1), 0, "Exit node - out edges");
                    Assert.AreEqual(true, graph.Vertices.ElementAt(1).IsLeaf);
                }
            }
        }
예제 #3
0
        public void CFGCreator_RootAndExitIsStmtFunction(string phpcode)
        {
            var extract = ParseAndExtract(phpcode);

            foreach (var func in extract.Functions)
            {
                var ast        = func.AstNode;
                var traverser  = new XmlTraverser();
                var cfgcreator = new CFGCreator();
                traverser.AddVisitor(cfgcreator);
                traverser.Traverse(ast);

                var graph = cfgcreator.Graph;

                //Root assertions
                Assert.IsTrue(graph.Vertices.First().IsRoot, "first node was not the root node");
                Assert.IsTrue(graph.Vertices.First().IsSpecialBlock, "first node was not marked as IsSpecialBlock");
                graph.AssertInEdges(graph.Vertices.First(), 0, "Entry node - in edges");
                graph.AssertOutEdges(graph.Vertices.First(), 1, "Entry node - out edges");
                Assert.AreEqual(AstConstants.Nodes.Stmt_Function, graph.Vertices.First().ToString());

                //Leaf assertions
                Assert.IsTrue(graph.Vertices.ElementAt(1).IsSpecialBlock, "The element at position 1 was not marked with IsSpecialBlock");
                Assert.AreEqual(true, graph.Vertices.ElementAt(1).IsLeaf, "The element at position 1 was not marked with IsLeaf");
                graph.AssertOutEdges(graph.Vertices.ElementAt(1), 0, "Exit node - out edges");
            }
        }
예제 #4
0
파일: Program.cs 프로젝트: river0825/Eir
        private static File BuildFileCFGAndExtractFileInformation(KeyValuePair <string, XmlDocument> parsedFile)
        {
            var traverser      = new XmlTraverser();
            var metricAnalyzer = new MetricVisitor();
            var extractor      = new ClassAndFunctionExtractor();
            var printer        = new ASTPrinter(Console.Out);
            var cfgcreator     = new CFGCreator();

            traverser.AddVisitor(extractor);
            traverser.AddVisitor(metricAnalyzer);
            traverser.AddVisitor(cfgcreator);
            //traverser.AddVisitor(printer);
            traverser.AddVisitors(_components.AstVisitors.ToArray());

            traverser.Traverse(parsedFile.Value.FirstChild.NextSibling);

            foreach (var function in extractor.Functions)
            {
                function.File = parsedFile.Key;
            }
            foreach (var closure in extractor.Closures)
            {
                closure.File = parsedFile.Key;
            }

            _funcHandler.CustomFunctions.AddRange(extractor.Functions);

            foreach (var @class in extractor.Classes)
            {
                @class.File = parsedFile.Key;
                foreach (var method in @class.Methods)
                {
                    //HACK: This is not a good way to handle this! Should we add a new derived function class called method that includes the class name
                    //-||-: and make a special list for them in the function handler, or is this okay?
                    method.Name = @class.Name + "->" + method.Name;
                    method.File = parsedFile.Key;
                    _funcHandler.CustomFunctions.Add(method);
                }
            }

            //cfgcreator.Graph.VisualizeGraph("graph", Program.Configuration.GraphSettings);
            var cfgPruner = new CFGPruner();

            cfgPruner.Prune(cfgcreator.Graph);
            //cfgcreator.Graph.VisualizeGraph("graph-pruned", Configuration.GraphSettings);

            File file = new File(parsedFile.Value)
            {
                CFG        = cfgcreator.Graph,
                FullPath   = parsedFile.Key,
                Interfaces = extractor.Interfaces.GroupBy(i => i.Name, i => i).ToDictionary(i => i.Key, i => i.ToList()),
                Classes    = extractor.Classes.GroupBy(c => c.Name, c => c).ToDictionary(c => c.Key, c => c.ToList()),
                Closures   = extractor.Closures.ToArray(),
                Functions  = extractor.Functions.GroupBy(i => i.Name, i => i).ToDictionary(i => i.Key, i => i.ToList())
            };

            return(file);
        }
예제 #5
0
        /// <summary>
        /// Analyses a custom function in for security issues, with the currenctly known taint for actual parameters.
        /// </summary>
        /// <returns>A TainSets for the custom function that is being analyzed</returns>
        /// <param name="customFunction">Custom function object to perform the analysis on</param>
        /// <param name="varStorage">The currently known variable storage (this is to included because of superglobals, globals etc.)</param>
        /// <param name="paramActualVals">Parameter actual values</param>
        /// <param name="resolver">File inclusion resolver</param>
        /// <param name="includeStack">Currently known includes</param>
        /// <param name="functionCalls">Currently known function calls</param>
        internal ExpressionInfo AnalyseCustomFunction(Function customFunction, ImmutableVariableStorage varStorage, IVulnerabilityStorage vulnerabilityStorage,
                                                      IList <ExpressionInfo> paramActualVals, IIncludeResolver resolver, AnalysisStacks stacks)
        {
            var stmts = customFunction.AstNode.GetSubNode(AstConstants.Subnode + ":" + AstConstants.Subnodes.Stmts).FirstChild;

            var traverser  = new XmlTraverser();
            var cfgcreator = new CFGCreator();

            traverser.AddVisitor(cfgcreator);
            traverser.Traverse(stmts);

            var cfgPruner = new CFGPruner();

            cfgPruner.Prune(cfgcreator.Graph);

            var initialTaint = varStorage.ToMutable();

            initialTaint.SuperGlobals.Clear();
            initialTaint.SuperGlobals.AddRange(varStorage.SuperGlobals);
            initialTaint.LocalVariables.Clear();
            initialTaint.LocalAccessibleGlobals.Clear();

            for (int i = 1; i <= paramActualVals.Count; i++)
            {
                var paramFormal = customFunction.Parameters.FirstOrDefault(x => x.Key.Item1 == i);
                if (paramFormal.Value == null)
                {
                    continue;
                }
                var @var = new Variable(paramFormal.Value.Name, VariableScope.Function)
                {
                    Info = paramActualVals[i - 1].ValueInfo
                };
                initialTaint.LocalVariables.Add(paramFormal.Value.Name, @var);
            }

            var blockAnalyzer = new TaintBlockAnalyzer(vulnerabilityStorage, resolver, AnalysisScope.Function, fileAnalyzer, stacks, subroutineAnalyzerFactory, _funcHandler);

            blockAnalyzer.AnalysisExtensions.AddRange(AnalysisExtensions);
            var condAnalyser     = new ConditionTaintAnalyser(AnalysisScope.Function, resolver, stacks.IncludeStack, _funcHandler);
            var cfgTaintAnalysis = new TaintAnalysis(blockAnalyzer, condAnalyser, ImmutableVariableStorage.CreateFromMutable(initialTaint));
            //var taintAnalysis = new CFGTraverser(new ForwardTraversal(), cfgTaintAnalysis, new QueueWorklist());
            var taintAnalysis = new CFGTraverser(new ForwardTraversal(), cfgTaintAnalysis, new ReversePostOrderWorkList(cfgcreator.Graph));

            taintAnalysis.Analyze(cfgcreator.Graph);

            var exprInfoAll = new ExpressionInfo();

            foreach (ExpressionInfo exprInfo in blockAnalyzer.ReturnInfos)
            {
                exprInfoAll = exprInfoAll.Merge(exprInfo);
            }

            return(exprInfoAll);
        }
예제 #6
0
        private void LoadGraphFromTemp()
        {
            var result = MessageBox.Show("New SEViz graph is available. Do you want to load it?", "SEViz notification", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                var dialogFactory = ViewerWindowCommand.Instance.ServiceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

                IVsThreadedWaitDialog2 dialog = null;
                if (dialogFactory != null)
                {
                    dialogFactory.CreateInstance(out dialog);
                }
                if (dialog != null)
                {
                    bw = new BackgroundWorker();
                    bw.WorkerSupportsCancellation = true;
                    bw.DoWork += (p1, p2) =>
                    {
                        dialog.StartWaitDialog("SEViz", "SEViz is loading", "Please wait while SEViz loads the graph...", null, "Waiting status bar text", 0, false, true);
                        while (true)
                        {
                            if (!bw.CancellationPending)
                            {
                                Thread.Sleep(500);
                            }
                            else
                            {
                                break;
                            }
                        }
                    };
                    bw.RunWorkerCompleted += (p1, p2) =>
                    {
                        int isCanceled = -1;
                        dialog.EndWaitDialog(out isCanceled);
                    };
                    bw.RunWorkerAsync();

                    // Loading the graph
                    LoadGraph(CFGCreator.Deserialize(Path.GetTempPath() + "SEViz/" + "temp.graphml"));

                    // Setting the caption of the tool window
                    ViewerWindowCommand.Instance.FindToolWindow().Caption = Graph.Vertices.Where(v => !v.SourceCodeMappingString.Equals("")).FirstOrDefault().MethodName + " - SEViz";

                    // Showing the tool window
                    ViewerWindowCommand.Instance.ShowToolWindow(null, null);
                }
            }

            fsw.EnableRaisingEvents = true;
        }
예제 #7
0
        public void LoadGraphFromUri(string fileUri)
        {
            // Loading the graph
            LoadGraph(CFGCreator.Deserialize(fileUri));

            // Setting the caption of the tool window (making sure with the loop that the node has a method)
            for (int i = 0; i < 10; i++)
            {
                var methodName = Graph.Vertices.Where(v => v.Id == i).FirstOrDefault().MethodName;
                if (methodName != "")
                {
                    ViewerWindowCommand.Instance.FindToolWindow().Caption = methodName + " - SEViz";
                    break;
                }
            }
        }
예제 #8
0
        public SEVizAttribute(string dllPath, string functionName)
        {
            MessageBox.Show("CTOR");

            DllPath      = dllPath;
            FunctionName = functionName;

            CFGCreator myCreator = new CFGCreator();

            myCreator.Create(DllPath, functionName);

            MyCreator = myCreator;

            foreach (var item in MyCreator.edges)
            {
                MessageBox.Show(item.Id.ToString());
            }
        }
예제 #9
0
        public void AfterExploration(IPexExplorationComponent host, object data)
        {
            MessageBox.Show("AfterExploration");

            foreach (var vertex in Vertices.Values)
            {
                // Modifying shape based on Z3 calls
                if (Z3CallLocations.Contains(vertex.MethodName + ":" + vertex.ILOffset))
                {
                    vertex.Shape = CFGNode.NodeShape.Ellipse;
                }

                // Adding the path condition
                var t = PrettyPathConditionTasks [vertex.Id];
                t.Wait();
                vertex.PathCondition = t.Result;
            }

            foreach (var vertex in Vertices.Values)
            {
                // Adding the incremental path condition
                if (ParentNodes.ContainsKey(vertex.Id))
                {
                    vertex.IncrementalPathCondition = CalculateIncrementalPathCondition(vertex.PathCondition, Vertices [ParentNodes [vertex.Id]].PathCondition);
                }
                else
                {
                    // If the node is the first one (has no parents), then the incremental equals the full PC
                    vertex.IncrementalPathCondition = vertex.PathCondition;
                }
            }
            // +++
            // Adding vertices and edges to the graph
            Graph.AddVertexRange(Vertices.Values);
            foreach (var edgeDictionary in Edges.Values)
            {
                Graph.AddEdgeRange(edgeDictionary.Values);
            }



            //đ
            ////Graph.AddVertexRange(MyCreator.graph.Vertices);

            ////Graph.AddEdgeRange(MyCreator.graph.Edges);



            // Checking if temporary SEViz folder exists
            if (!Directory.Exists(Path.GetTempPath() + "SEViz"))
            {
                var dir = Directory.CreateDirectory(Path.GetTempPath() + "SEViz");
            }

            //đ
            //[SEViz(typeof(string).)]
            // Getting the temporary folder
            var tempDir = Path.GetTempPath() + "SEViz\\";

            // Serializing the graph into graphml
            CFGCreator.Serialize(Graph, tempDir);
        }