Ejemplo n.º 1
0
 public static List<IO2Finding> createO2FindingsFromCirFunction(ICirFunction cirFunction, bool createNewFindingOnExternalCall)
 {
     var o2FindingsCreated = new List<IO2Finding>();
     var filteredSignature = new FilteredSignature(cirFunction);
     var functionSignature = filteredSignature.sSignature;
     var rootO2Finding = new O2Finding
                             {
                                 method = cirFunction.ClassNameFunctionNameAndParameters,
                                 vulnName = functionSignature,
                                 vulnType = "O2.CirGeneratedTrace",
                                 severity = 2,
                                 confidence = 2,
                                 file= cirFunction.File                                        
                             };
     if (cirFunction.File != null)
     {
         UInt32 lineNumber;
         if (UInt32.TryParse(cirFunction.FileLine, out lineNumber))
             rootO2Finding.lineNumber = lineNumber;
     }
     createTracesAndFindingsFromCirFunction(cirFunction, rootO2Finding.file, rootO2Finding.lineNumber, rootO2Finding.o2Traces, new List<IO2Trace>(), rootO2Finding, o2FindingsCreated, createNewFindingOnExternalCall);
     // make the first trace a Source
     rootO2Finding.o2Traces[0].traceType = TraceType.Source;
     // and add it to the list of Findings Created
     o2FindingsCreated.Add(rootO2Finding);
     return o2FindingsCreated;
 }
Ejemplo n.º 2
0
        public static FilteredSignature createFilteredSignatureFromJavaMethod(string className, string functionName, string methodDescriptor)
        {
            var newFilteredSignature = new FilteredSignature();

            newFilteredSignature.sFunctionClass = className;
            newFilteredSignature.sFunctionName  = functionName;
            // process descriptor
            var lastParentesis = methodDescriptor.LastIndexOf(')');

            if (lastParentesis > -1)
            {
                methodDescriptor = methodDescriptor.Replace('/', '.');
                lastParentesis++;
                newFilteredSignature.sParameters  = methodDescriptor.Substring(0, lastParentesis);
                newFilteredSignature.sReturnClass = methodDescriptor.Substring(lastParentesis);
                // BUG: Major hack to fix the sParameters created by JavaMethod descriptors
                if (newFilteredSignature.sReturnClass == "V")
                {
                    newFilteredSignature.sReturnClass = "void";
                }
                newFilteredSignature.sParameters = newFilteredSignature.sParameters.Replace("(I)", "(int)").Replace("(IL", "(int;").Replace(";IL", ";int;");
                newFilteredSignature.sParameters = newFilteredSignature.sParameters.Replace("(L", "(").Replace("(IL", "(").Replace(";L", ";").Replace(";)", ")");
                if (newFilteredSignature.sParameters[0] == '(' && newFilteredSignature.sParameters[newFilteredSignature.sParameters.Length - 1] == ')')
                {
                    newFilteredSignature.sParameters = newFilteredSignature.sParameters.Substring(1, newFilteredSignature.sParameters.Length - 2);
                }
                // fix the sReturnClass
                if (newFilteredSignature.sReturnClass[0] == 'L' && newFilteredSignature.sReturnClass[newFilteredSignature.sReturnClass.Length - 1] == ';')
                {
                    newFilteredSignature.sReturnClass = newFilteredSignature.sReturnClass.Substring(1, newFilteredSignature.sReturnClass.Length - 2);
                }
                newFilteredSignature.sSignature = newFilteredSignature.getSignature();
            }
            return(newFilteredSignature);
        }
Ejemplo n.º 3
0
        public static String filterSignature(String sStringToFilter, bool bShowParameters, bool bShowReturnClass,
                                             bool bShowNamespace, int iNamespaceDepth)
        {
            if (DI.dFilteredFuntionSignatures.ContainsKey(sStringToFilter))
            {
                return(DI.dFilteredFuntionSignatures[sStringToFilter].getFilteredSignature(
                           bShowParameters, bShowReturnClass, bShowNamespace, iNamespaceDepth));
            }

            var fsFilteredSignature = new FilteredSignature(sStringToFilter);

            DI.dFilteredFuntionSignatures.Add(sStringToFilter, fsFilteredSignature);
            return(fsFilteredSignature.getFilteredSignature(bShowParameters, bShowReturnClass, bShowNamespace,
                                                            iNamespaceDepth));
        }
Ejemplo n.º 4
0
 private static void fixFunctionsCalledXRefs(ICirData cirData)
 {
     if (cirData != null && cirData.dFunctions_bySignature != null)
     {
         var timer = new O2Timer("fixFunctionsCalledXRefs").start();
         foreach (CirFunction cirFunction in cirData.dFunctions_bySignature.Values)
         {
             if (cirFunction.FunctionName == null)
             {
                 var filteredSignature = new FilteredSignature(cirFunction.FunctionSignature);
                 cirFunction.FunctionName = filteredSignature.sFunctionName;
                 cirFunction.FunctionNameAndParameters = filteredSignature.sFunctionNameAndParams;
                 cirFunction.ClassNameFunctionNameAndParameters = filteredSignature.sFunctionClass + "." +
                                                                  filteredSignature.sFunctionNameAndParams;
             }
         }
         timer.stop();
     }
 }
Ejemplo n.º 5
0
            public static void mapDotNetWebServices(TreeView tvRawData)
            {
                String sDotNetWebServicesSinkToFind =
                    "System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(string;object[]):object[]";
                var ltnNodesWithSink = new List<TreeNode>();
                analyzer.calculateListOfNodesWithSink_recursive(tvRawData.Nodes, sDotNetWebServicesSinkToFind,
                                                                ltnNodesWithSink);
                foreach (TreeNode tnTreeNodeWithInvokeSink in ltnNodesWithSink)
                {
                    var otbO2TraceBlockWithSink = (O2TraceBlock_OunceV6) tnTreeNodeWithInvokeSink.Tag;
                    foreach (AssessmentAssessmentFileFinding fFinding in otbO2TraceBlockWithSink.dSources.Keys)
                    {
                        //FindingViewItem fviFindingViewItem
                        //String sSink = o2.analysis.Analysis.getSink(fFinding,otbO2TraceBlockWithSink.dSources[fFinding]);
                        //String sSource = o2.analysis.Analysis.getSource(fFinding, otbO2TraceBlockWithSink.dSources[fFinding]);
                        var lcaReverseListOfCallInvocation = new List<CallInvocation>();
                        AnalysisSearch.findTraceTypeInSmartTrace_Recursive_returnReverseListOfCallInvocation(
                            fFinding.Trace, TraceType.Known_Sink, lcaReverseListOfCallInvocation);
                        if (lcaReverseListOfCallInvocation.Count > 1)
                        {
                            var fsFilteredSignature =
                                new FilteredSignature(
                                    OzasmtUtils_OunceV6.getStringIndexValue(lcaReverseListOfCallInvocation[1].sig_id,
                                                                            otbO2TraceBlockWithSink.dSources[fFinding]));
                            String sSignatureToMatch = fsFilteredSignature.getFilteredSignature(true, false, false, -1);
                            // we really should also check the return class, but there are some diferences in the ways the objects are mapped (object[] on the client and ArrayList() on the server)                    
                            bool bFoundWebServiceSink = false;
                            foreach (TreeNode tnRawNode in tvRawData.Nodes)
                            {
                                var otbO2TraceBlock = (O2TraceBlock_OunceV6) tnRawNode.Tag;
                                String sRawTraceSignature =
                                    new FilteredSignature(otbO2TraceBlock.sSignature).getFilteredSignature(true, false,
                                                                                                           false, -1);
                                if (sRawTraceSignature == sSignatureToMatch)
                                {
                                    if (otbO2TraceBlock.dSources.Count == 0)
                                    {
                                        bFoundWebServiceSink = true;

                                        foreach (
                                            AssessmentAssessmentFileFinding fFindingInMappedSink in
                                                otbO2TraceBlock.dSinks.Keys)
                                        {
                                            String sSource = AnalysisUtils.getSource(fFindingInMappedSink,
                                                                                     otbO2TraceBlock.dSinks[
                                                                                         fFindingInMappedSink]);
                                            String sSink = AnalysisUtils.getSink(fFindingInMappedSink,
                                                                                 otbO2TraceBlock.dSinks[
                                                                                     fFindingInMappedSink]);
                                            DI.log.info("Adding {0} to {1}", sSource,
                                                        otbO2TraceBlockWithSink.sUniqueName);
                                            // add to dGluedSinks
                                            if (false ==
                                                otbO2TraceBlockWithSink.dGluedSinks.ContainsKey(fFindingInMappedSink))
                                            {
                                                otbO2TraceBlockWithSink.dGluedSinks.Add(fFindingInMappedSink,
                                                                                        otbO2TraceBlock.dSinks[
                                                                                            fFindingInMappedSink]);
                                                otbO2TraceBlockWithSink.dSinks.Add(fFindingInMappedSink,
                                                                                   otbO2TraceBlock.dSinks[
                                                                                       fFindingInMappedSink]);
                                            }
                                            // add to dGluedSinks                                        
                                            if (false == otbO2TraceBlock.dGluedSinks.ContainsKey(fFinding))
                                            {
                                                //otbO2TraceBlock.dGluedSinks.Add(fFinding, otbO2TraceBlockWithSink.dSources[fFinding]);
                                                //otbO2TraceBlock.dSinks.Add(fFinding, otbO2TraceBlockWithSink.dSources[fFinding]);
                                            }
                                        }

                                        /*              foreach (AssessmentAssessmentFileFinding fFinding in otbO2TraceBlock.dSinks.Keys)
                                                      {
                                                           DI.log.info("Adding trace to : {0} on Root node: {1}", tnTreeNodeWithInvokeSink.Text, O2Forms.getRootNode(tnTreeNodeWithInvokeSink).Text);
                                                          TreeNode tnTreeNodeToAdd = tnTreeNodeWithInvokeSink;
                                                          if (tnTreeNodeToAdd.Nodes.Count >0)
                                                              tnTreeNodeToAdd = tnTreeNodeToAdd.Nodes[0];
                                                          tnTreeNodeToAdd.Nodes.Add(O2Forms.newTreeNode("TEST", "TEST", 0, new FindingViewItem(fFinding, otbO2TraceBlock.dSinks[fFinding])));
                                                      }
                                         * */
                                        //tnTreeNodeWithInvokeSink
                                        //    DI.log.debug("  Found Possible match : {0}", otbO2TraceBlock.sSignature);
                                    }
                                    else
                                    {
                                        DI.log.debug("  Found FALSE POSITIVE match : {0}", otbO2TraceBlock.sSignature);
                                    }
                                }
                            }
                            if (false == bFoundWebServiceSink)
                                DI.log.error("in mapDotNetWebServices, could not find a match for: {0}",
                                             sSignatureToMatch);
                        }
                    }
                }
            }
Ejemplo n.º 6
0
            public static void addVelocityMappings(TreeView tvRawData)
            {
                String sFunctionSignature = "ModelMap.addAttribute";
                O2Timer tTimer = new O2Timer("Adding Velocity Mappings : {0} ").start();
                Dictionary<AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> dMatches =
                    analyzer.getSinksFindingsThatMatchRegEx(tvRawData, sFunctionSignature);
                foreach (AssessmentAssessmentFileFinding fFinding in dMatches.Keys)
                {
                    // resolve addAddtibute name
                    String sSinkContext = AnalysisUtils.getSinkContext(fFinding, dMatches[fFinding]);
                    var fsFilteredSignature = new FilteredSignature(sSinkContext);
                    String sParameters = fsFilteredSignature.sParameters.Replace("\"", "");
                    String sSpringParameter = sParameters.Substring(0, sParameters.IndexOf(',')).Trim();

                    // create a unique name for it:
                    String sSink = AnalysisUtils.getSink(fFinding, dMatches[fFinding]);
                    // String sSinkWithAttributeName = sSink.Replace("(", "_" + sSpringParameter + "(");
                    String sVelocityMapping = String.Format("{0}            0", sSink);

                    TreeNode tnVelocityNode = tvRawData.Nodes[sSink];
                    if (tnVelocityNode != null)
                    {
                        var otbO2TraceBlockWithVelocityMappings = (O2TraceBlock_OunceV6) tnVelocityNode.Tag;

                        String sUniqueSignature = analyzer.getUniqueSignature(fFinding, TraceType.Known_Sink,
                                                                              dMatches[fFinding], true);
                        var otbO2TraceBlockToAddVelocityMappings = (O2TraceBlock_OunceV6) tvRawData.Nodes[sUniqueSignature].Tag;
                        //   sUniqueSignature = sUniqueSignature.Replace("_" + sSpringParameter + "(", "(");
                        //  O2TraceBlock_OunceV6 otbO2TraceBlockToAddVelocityMappings = (O2TraceBlock_OunceV6)tvRawData.Nodes[sUniqueSignature].Tag;

                        if (otbO2TraceBlockWithVelocityMappings.dSinks.Count > 1)
                        {
                        }

                        foreach (
                            AssessmentAssessmentFileFinding fVelocityFinding in
                                otbO2TraceBlockWithVelocityMappings.dSinks.Keys)
                        {
                            if (false == otbO2TraceBlockToAddVelocityMappings.dGluedSinks.ContainsKey(fVelocityFinding))
                                otbO2TraceBlockToAddVelocityMappings.dGluedSinks.Add(fVelocityFinding,
                                                                                     otbO2TraceBlockWithVelocityMappings
                                                                                         .dSinks[fVelocityFinding]);
                            if (false == otbO2TraceBlockToAddVelocityMappings.dSinks.ContainsKey(fVelocityFinding))
                                otbO2TraceBlockToAddVelocityMappings.dSinks.Add(fVelocityFinding,
                                                                                otbO2TraceBlockWithVelocityMappings.
                                                                                    dSinks[fVelocityFinding]);
                        }
                    }
                }
            }
        public void onAfterSelectTreeView(TreeNode selectedNode)
        {
            try
            {
                if (selectedNode != null)
                {
                    // populate selectedFilteredSignature object
                    if (selectedNode.Tag != null && selectedNode.Tag.GetType().Name == "FilteredSignature")
                        selectedFilteredSignature = (FilteredSignature) selectedNode.Tag;
                    else
                        selectedFilteredSignature = null;

                    // get fucntion's signature
                    var signature = (selectedFilteredSignature!=null)
                                        ?
                                            selectedFilteredSignature.sOriginalSignature
                                        :                                            
                                            selectedNode.Name;

                    // raise callbacks
                    Callbacks.raiseRegistedCallbacks(eNodeEvent_AfterSelect, new object[] { signature });

                    Callbacks.raiseRegistedCallbacks(_onAfterSelect, new [] { selectedNode.Tag });
                    
                    

                    // need to manual handle this backcolor stuff because we lose it when multiple function's viewers are used at the same time
                    /*            if (selectedNode != null)
                                {
                                    selectedNode.BackColor = Color.White;
                                    selectedNode.ForeColor = Color.Black;
                                }
                                //tnSelectedNode = tvTreeView.SelectedNode;
                                tvTreeView.SelectedNode.BackColor = Color.DarkBlue;
                                tnSelectedNode.ForeColor = Color.White;*/

                    

                    /*if (onTreNodeAfterSelect != null)
                        foreach (Delegate dDelegate in onTreNodeAfterSelect.GetInvocationList())
                        {
                            if (selectedNode.Tag != null &&
                                selectedNode.Tag.GetType().Name == "FilteredSignature")
                                dDelegate.DynamicInvoke(new[]
                                                            {
                                                                ((FilteredSignature) selectedNode.Tag).sOriginalSignature
                                                            });
                            else
                                dDelegate.DynamicInvoke(new[] { selectedNode.Text });

                        }*/
                }
            }
            catch (Exception ex)
            {
                PublicDI.log.error("In tvTreeView_AfterSelect: {0}", ex.Message);
            }
        }
Ejemplo n.º 8
0
        public void showDataForSignature_thread(String sSignatureToShow)
        {
            if (cirDataAnalysis == null)
                DI.log.error("in ascx_CirViewer_Signature.showDataForSignature , fcdAnalysis == null");
            else
            {
                lbClassesBeingViewed.Text = sSignatureToShow;
                if (false == cirDataAnalysis.dCirFunction_bySignature.ContainsKey(sSignatureToShow) ||
                    cirDataAnalysis.dCirFunction_bySignature.ContainsKey(sSignatureToShow) &&
                    cirDataAnalysis.dCirFunction_bySignature[sSignatureToShow].HasControlFlowGraph == false)
                {
                    DI.log.debug("{0} is not recognized as a full signature, trying to resolve it by name",
                                 sSignatureToShow);
                    foreach (CirFunction ccFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    {
                        String sFunctionFullNameWithNoParamsAndReturnvalue =
                            new FilteredSignature(ccFunction.FunctionSignature).sFunctionFullName;
                        if (sFunctionFullNameWithNoParamsAndReturnvalue.IndexOf(sSignatureToShow) > -1)
                        {
                            DI.log.debug("Found a match:{0}", ccFunction.FunctionSignature);
                            sSignatureToShow = ccFunction.FunctionSignature;
                            break;
                        }
                    }
                }
                if (cirDataAnalysis.dCirFunction_bySignature.ContainsKey(sSignatureToShow))
                {
                    ICirFunction ccCirFunction = cirDataAnalysis.dCirFunction_bySignature[sSignatureToShow];                    
                    afv_Calls.showSignatures(ViewHelpers.getCirFunctionStringList(ccCirFunction.FunctionsCalledUniqueList));
                    afv_IsCalledBy.showSignatures(ViewHelpers.getCirFunctionStringList(ccCirFunction.FunctionIsCalledBy));

                    lbBoxSsaVariables.Items.Clear();
                    lBoxVariables.Items.Clear();

                    foreach (SsaVariable cfSSaVariable in ccCirFunction.dSsaVariables.Values)
                    {
                        String sVariableMapping = String.Format("{0} = {1}", cfSSaVariable.sBaseName,
                                                                cfSSaVariable.sPrintableType);
                        lbBoxSsaVariables.Items.Add(sVariableMapping);
                        //           DI.log.debug(sVariableMapping);
                    }
                    foreach (FunctionVariable fvVariable in ccCirFunction.dVariables.Values)
                    {
                        lBoxVariables.Items.Add(String.Format("[def:{0}] [ref:{1}] {2}", fvVariable.sSymbolDef,
                                                              fvVariable.refSymbol, fvVariable.sUniqueID));
                    }
                    ViewHelpers.showFunctionBlocksInWebBrower(((CirFunction)ccCirFunction).lcfgBasicBlocks,
                                                              wbControlFlowGraphsOFSelectedMethod);

                    asv_CalledFunctions.showDataForSignature(sSignatureToShow);
                    asv_IsCalledBy.showDataForSignature(sSignatureToShow);
                }
                else
                {
                    var lsEmpty = new List<string>();
                    afv_Calls.showSignatures(lsEmpty);
                    afv_IsCalledBy.showSignatures(lsEmpty);
                    lbBoxSsaVariables.Items.Clear();
                    lBoxVariables.Items.Clear();
                    asv_CalledFunctions.showDataForSignature(sSignatureToShow);
                    asv_IsCalledBy.showDataForSignature(sSignatureToShow);
                }
            }
            //    lBoxVariables.Items.Add(fcdO2CirData_ofThisFunction.getSymbol(sVariable));
        }
 private void showClassAttributes(ICirClass cirClass)
 {
     if (cirClass != null)
     {
         tvClassAttributes.Nodes.Clear();
         foreach (var attribute in cirClass.ClassAttributes)
         {
             var signature = new FilteredSignature(attribute.AttributeClass).sSignature;
             var treeNode = tvClassAttributes.Nodes.Add(signature);
             foreach (var parameter in attribute.Parameters)
                 treeNode.Nodes.Add(parameter.Key);
         }
     }
 }
Ejemplo n.º 10
0
        public static String filterSignature(String sStringToFilter, bool bShowParameters, bool bShowReturnClass,
                                             bool bShowNamespace, int iNamespaceDepth)
        {
            if (DI.dFilteredFuntionSignatures.ContainsKey(sStringToFilter))
                return DI.dFilteredFuntionSignatures[sStringToFilter].getFilteredSignature(
                    bShowParameters, bShowReturnClass, bShowNamespace, iNamespaceDepth);

            var fsFilteredSignature = new FilteredSignature(sStringToFilter);
            DI.dFilteredFuntionSignatures.Add(sStringToFilter, fsFilteredSignature);
            return fsFilteredSignature.getFilteredSignature(bShowParameters, bShowReturnClass, bShowNamespace,
                                                            iNamespaceDepth);
        }
 public static void mapMethodsToFilteredSignatures(List<MethodInfo> methodsToMap, ref List<FilteredSignature> filteredSignatures, ref Dictionary<string, MethodInfo> methods_bySignature, bool hideCSharpGeneratedMethods)
 {
     filteredSignatures = new List<FilteredSignature>();
     methods_bySignature = new Dictionary<string, MethodInfo>();
     foreach (var method in methodsToMap)
     {
         var filteredSignature = new FilteredSignature(method);
         if (hideCSharpGeneratedMethods == false || (filteredSignature.sSignature.IndexOf("<>") == -1 &&
                                                      false == filteredSignature.sFunctionName.StartsWith("b__")))
         {
             filteredSignatures.Add(filteredSignature);
             // create methodsLoaded_bySignature                       
             if (methods_bySignature.ContainsKey(filteredSignature.sSignature))
             {
                 PublicDI.log.error("in mapMethodsToFilteredSignatures, repeated signature: {0}", filteredSignature.sSignature);
             }
             else
                 methods_bySignature.Add(filteredSignature.sSignature, method);
         }
         else
         {
             //PublicDI.log.info("Skipping: {0}", method.Name);
         }
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// This will populate the parent finding with all traces from the provided ICirFunction
        /// caution: use the createNewFindingOnExternalCall carefully since it can create a stupid amount of traces (and it is much slower)
        /// </summary>
        /// <param name="cirFunction"></param>
        /// <param name="lineNumber"></param>
        /// <param name="o2Traces"></param>
        /// <param name="parentTraces"></param>
        /// <param name="rootO2Finding"></param>
        /// <param name="o2FindingsCreated"></param>
        /// <param name="createNewFindingOnExternalCall"></param>
        /// <param name="fileName"></param>
        public static void createTracesAndFindingsFromCirFunction(ICirFunction cirFunction, string fileName, UInt32 lineNumber,List<IO2Trace> o2Traces, List<IO2Trace> parentTraces, IO2Finding rootO2Finding, List<IO2Finding> o2FindingsCreated, bool createNewFindingOnExternalCall)
        {
            int maxParentDepth = 10; //30; //10;
            var maxNumberOfTraces = 20; //50; //300; //50
            var filteredSignature = new FilteredSignature(cirFunction);
            var functionSignature = filteredSignature.sSignature;

            var o2Trace = new O2Trace(functionSignature, cirFunction.ClassNameFunctionNameAndParameters)
                              {
                                  file = fileName,
                                  lineNumber = lineNumber
                              };

            // add file references

            // handle the case where this is a recursive call or a call to a method already added in the current tree
            var recursiveCall = false;
            foreach(var o2ParentTrace in parentTraces)
                if (o2ParentTrace.signature == functionSignature)
                {
                    recursiveCall = true;
                    break;
                }
            parentTraces.Add(o2Trace);
            // add this trace to the current trace tree (since we might need to create a copy of it below
            o2Traces.Add(o2Trace);
            if (recursiveCall)
            {
                var nodeText = String.Format("{0} : {1} : {2}", cirFunction, "....(Recursive Call so not expanding child traces", functionSignature);
                o2Trace.childTraces.Add(new O2Trace(nodeText));
            }
            else
            {
                if (parentTraces.Count > maxParentDepth)
                    o2Trace.childTraces.Add(new O2Trace(" ... {Max trace depth reached} (" + maxParentDepth + ")"));
                else
                {
                    // 
                    var numberOfTraces = OzasmtUtils.getAllTraces(rootO2Finding.o2Traces);                    
                    if (numberOfTraces.Count > maxNumberOfTraces)
                    {
                        o2Trace.childTraces.Add(new O2Trace("**** Max number of traces reached(" + maxNumberOfTraces + ") aborting trace execution"));
                        return; 
                    }               

                    if (cirFunction.FunctionsCalled.Count == 0) // means we don't have the code for this one, so 
                    {                   
                        // let make it a lost sink
                        var originalTraceTypeValue = o2Trace.traceType;     // we might need this below
                        o2Trace.traceType = TraceType.Lost_Sink;
                        if (createNewFindingOnExternalCall)   // and if createNewFindingOnExternalCall add it as finding                           
                        {
                            // create a copy of the parent finding (which incudes the above trace
                            var newFinding = OzasmtCopy.createCopy(rootO2Finding);
                            // make the first call a source (so that we have a source-> pair
                            newFinding.o2Traces[0].traceType = TraceType.Source;
                            // add it 
                            o2FindingsCreated.Add(newFinding);
                            // since the crawl will continue we must restore the originalTraceTypeValue
                            o2Trace.traceType = originalTraceTypeValue;
                        }
                    }
                    else
                        foreach (var functionCalled in cirFunction.FunctionsCalled)
                            createTracesAndFindingsFromCirFunction(functionCalled.cirFunction, functionCalled.fileName, (UInt32)functionCalled.lineNumber, o2Trace.childTraces, parentTraces, rootO2Finding, o2FindingsCreated, createNewFindingOnExternalCall);
                }
            }
            
            // now remove the signature since we are only interrested in non repeats on the same parent
            parentTraces.Remove(o2Trace);
        }
 public ICirFunction getCirFunctionFromSelectedItem(object selectedItem)
 {
     if (selectedItem != null && selectedItem is FilteredSignature)
     {
         var filteredSignature = (FilteredSignature)selectedItem;
         var functionSignature = filteredSignature.sOriginalSignature;
         if (cirDataAnalysis.dCirFunction_bySignature.ContainsKey(functionSignature))
             return cirDataAnalysis.dCirFunction_bySignature[functionSignature];
         // if we could not find using the originalSignature, try the signature
         foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
         {
             var s = new FilteredSignature(cirFunction).sSignature;
             var d = filteredSignature.sSignature;
             if (new FilteredSignature(cirFunction).sSignature == filteredSignature.sSignature)
             {
                 return cirFunction;
             }
             if (cirFunction.FunctionName == filteredSignature.sFunctionName)
             { 
             }
         }
     }
     return null;
 }
        public void showSignatures(List<FilteredSignature> filteredSignatures)
        {
            var signaturesToShow = new List<String>();            
            // get them all in one collection
            var filteredSignaturesAsStrings = new List<String>();
            foreach (var filteredSignature in filteredSignatures)
                filteredSignaturesAsStrings.Add(filteredSignature.sOriginalSignature);

            // now search for them on all loaded CirFunctions
            foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
            {
                var cirFunctionFilteredSignature = new FilteredSignature(cirFunction);
                if (filteredSignaturesAsStrings.Contains(cirFunctionFilteredSignature.sOriginalSignature))
                {
                    signaturesToShow.Add(cirFunction.FunctionSignature);
                    filteredSignaturesAsStrings.Remove(cirFunctionFilteredSignature.sOriginalSignature);
                }
                if (filteredSignaturesAsStrings.Contains(cirFunctionFilteredSignature.sSignature))
                {
                    signaturesToShow.Add(cirFunction.FunctionSignature);
                    filteredSignaturesAsStrings.Remove(cirFunctionFilteredSignature.sSignature);
                }
            }
            
          /*  foreach (var filteredSignature in filteredSignatures)
            {
                if (cirDataAnalysis.dCirFunction_bySignature.ContainsKey(filteredSignature.sOriginalSignature))
                    signaturesToShow.Add(filteredSignature.sOriginalSignature);
                else

                    DI.log.error("dropped signature is currently not loaded: {0}", filteredSignature);
            }*/
            if (filteredSignaturesAsStrings.Count > 0)
            {
                DI.log.error("There were {0} dropped signatures that could not be resolved", filteredSignaturesAsStrings.Count);
                foreach (var signatureNotFound in filteredSignaturesAsStrings)
                    DI.log.error("   {0}", signatureNotFound);
            }

            if (signaturesToShow.Count == 0)
                DI.log.error("None of the dropped signature was resolved, you need to load their CIR");
            else
                showSignatures(signaturesToShow);
        }
 public void showSignatures(FilteredSignature filteredSignature)
 { 
 }
Ejemplo n.º 16
0
 private static String MakeSignatureCompatibleWithOunceRules(string signatureToFix)
 {
     if (signatureToFix.IndexOf("..ctor") > -1)
     {
         var filteredSiganture = new FilteredSignature(signatureToFix);
         if (filteredSiganture.lsFunctionClass_Parsed.Count > 1)
             signatureToFix = signatureToFix.Replace(".ctor", filteredSiganture.lsFunctionClass_Parsed[filteredSiganture.lsFunctionClass_Parsed.Count - 2]).Replace(".(", "("); ;
     }
     signatureToFix = signatureToFix.Replace("..ctor", "");
     return FilteredSignature.makeDotNetSignatureCompatibleWithOunceRules(signatureToFix);
 }
Ejemplo n.º 17
0
 public Reflection_MethodInfo(MethodInfo method)
 {
     Method = method;
     filteredSignature = new FilteredSignature(method);
 }
 public void showSelectedMethodDetails(FilteredSignature filteredSignature)
 {
     if (filteredSignature != null)
     {
         tbMethodDetails_Name.invokeOnThread(
             () =>
             {
                 tbMethodDetails_Name.Text = filteredSignature.sFunctionName;
                 tbMethodDetails_OriginalSignature.Text = filteredSignature.sOriginalSignature;
                 tbMethodDetails_Parameters.Text = filteredSignature.sParameters;
                 tbMethodDetails_ReturnType.Text = filteredSignature.sReturnClass;
                 tbMethodDetails_Signature.Text = filteredSignature.sSignature;
                 tbMethodDetails_Type.Text = filteredSignature.sFunctionClass;
             });
     }
 }
Ejemplo n.º 19
0
 public static FilteredSignature createFilteredSignatureFromJavaMethod(string className, string functionName, string methodDescriptor)
 {
     var newFilteredSignature = new FilteredSignature();
     newFilteredSignature.sFunctionClass = className;
     newFilteredSignature.sFunctionName = functionName;
     // process descriptor
     var lastParentesis = methodDescriptor.LastIndexOf(')');
     if (lastParentesis > -1)
     {
         methodDescriptor = methodDescriptor.Replace('/', '.');
         lastParentesis++;
         newFilteredSignature.sParameters = methodDescriptor.Substring(0, lastParentesis);
         newFilteredSignature.sReturnClass = methodDescriptor.Substring(lastParentesis);
         // BUG: Major hack to fix the sParameters created by JavaMethod descriptors                
         if (newFilteredSignature.sReturnClass == "V")
         {
             newFilteredSignature.sReturnClass = "void";
         }
         newFilteredSignature.sParameters = newFilteredSignature.sParameters.Replace("(I)", "(int)").Replace("(IL", "(int;").Replace(";IL", ";int;");
         newFilteredSignature.sParameters = newFilteredSignature.sParameters.Replace("(L", "(").Replace("(IL", "(").Replace(";L", ";").Replace(";)", ")");
         if (newFilteredSignature.sParameters[0] == '(' && newFilteredSignature.sParameters[newFilteredSignature.sParameters.Length -1] == ')')
             newFilteredSignature.sParameters = newFilteredSignature.sParameters.Substring(1, newFilteredSignature.sParameters.Length - 2);
         // fix the sReturnClass
         if (newFilteredSignature.sReturnClass[0] == 'L' && newFilteredSignature.sReturnClass[newFilteredSignature.sReturnClass.Length - 1] == ';')
             newFilteredSignature.sReturnClass = newFilteredSignature.sReturnClass.Substring(1,newFilteredSignature.sReturnClass.Length - 2);
         newFilteredSignature.sSignature = newFilteredSignature.getSignature();
     }
     return newFilteredSignature;
 }
Ejemplo n.º 20
0
        public static void mapJavaAttributesToTraces(IO2Assessment o2Assessment, Dictionary<string, string> attributesXmlFiles)
        {
            DI.log.debug("Mapping Java Attributes to Traces");
            //var testFindings = from O2Finding finding in o2Assessment.o2Findings where finding.Source.Contains("BugController") select (IO2Finding)finding;
            //var testFindings = o2Assessment.o2Findings;
            DI.log.debug("There are {0} findings to process", o2Assessment.o2Findings.Count());

            foreach (O2Finding finding in o2Assessment.o2Findings)
            {
                var filteredSignature = new FilteredSignature(finding.Source);
                var className = filteredSignature.sFunctionClass;
                var fileToFind = string.Format("{0}.class.JavaAttributes.xml", className.Replace(".", "\\"));
                if (attributesXmlFiles.ContainsKey(fileToFind))
                    mapJavaAttributesToFinding(finding, attributesXmlFiles[fileToFind]);
                //DI.log.info("Found: {0} - > {1}", 	fileToFind , attributesXmlFiles[fileToFind]);
                //else
                //	DI.log.error("could NOT find Xml Attribute file for: {0}", 	fileToFind);
                //DI.log.info(fileToFind);
            }

            //var findingsWithSpringMVCControllersAsSources = new List<IO2Finding>();


            // save temp assessment file			
//            var o2FindingsOfTypeO2SpringMvcController = (from o2Finding in o2Assessment.o2Findings where o2Finding.vulnType == "O2.SpringMvc.Controller" select o2Finding).ToList();
//            DI.log.debug("There are {0}  o2FindingsOfTypeO2SpringMvcController");

/*            O2.Views.ASCX.O2Findings.ascx_FindingsViewer.openInFloatWindow(o2FindingsOfTypeO2SpringMvcController);
            saveFindingsInNewO2AssessmentFile(o2FindingsOfTypeO2SpringMvcController, pathToOzasmtFile + "_SpringMvcController.ozasmt");
 * */
        }
 private void showFunctionAttributes(ICirFunction _rootCirFunction)
 {
     showClassAttributes(_rootCirFunction.ParentClass);
     tvFunctionAttributes.Nodes.Clear();
     foreach (var attribute in _rootCirFunction.FunctionAttributes)
     {
         var signature = new FilteredSignature(attribute.AttributeClass).sSignature;
         var treeNode = tvFunctionAttributes.Nodes.Add(signature);
         foreach (var parameter in attribute.Parameters)
             treeNode.Nodes.Add(parameter.Key);
     }
 }
Ejemplo n.º 22
0
        public static bool mapJavaAttributesToFinding(O2Finding o2Finding, string xmlAttributeFile)
        {
            var source = o2Finding.Source;
            var filteredSignature = new FilteredSignature(source);
            //DI.log.info(filteredSignature.sFunctionClass + "  -  " + filteredSignature.sFunctionName);

            var xClassElement = getClassDataFromXmlAttributeFile(xmlAttributeFile, filteredSignature.sFunctionClass);
            if (xClassElement != null)
            {
                SpringMVCAttributes.addClassAttributesToFinding(xClassElement, o2Finding);
                var xMethodElement = getMethodDataFromXmlAttributeFile(xClassElement, filteredSignature.sFunctionName);
                if (xMethodElement != null)
                {
                    SpringMVCAttributes.addMethodAttributesToFinding(xMethodElement, o2Finding);
                    return true;
                    // DI.log.info("have xElement");
                }
            }
            return false;
            //DI.log.info("mapping finding {0} with xml file {1}", o2Finding.ToString(), xmlAttributeFile);
        }
Ejemplo n.º 23
0
 public CirFunction(string functionSignature) : this()
 {
     FunctionSignature = functionSignature;
     var filteredSignature = new FilteredSignature(FunctionSignature);
     FunctionName = filteredSignature.sFunctionName;
     FunctionNameAndParameters = filteredSignature.sFunctionNameAndParams;
     ClassNameFunctionNameAndParameters = filteredSignature.sFunctionClass + "." + filteredSignature.sFunctionNameAndParams;
     ReturnType = filteredSignature.sReturnClass;
 }
        private void addCirFunctionsAsRules(
            List<ICirFunction> cirFunctionsToProcess, bool keepRulesLoadedFromDatabase, 
            bool bAddExternalMethodsAsSourcesAndSinks,bool bAddInternalMethodsWithNoCallersAsCallbacks,
            bool bDontMarkAsCallbackOrSinksMethodsWithNoParameters,
            bool bdontAddIfRuleSignatureAlreadyExists, bool bDontAddIfThereAreNoCallersAndCallees,
            string newRulesVulnType)
        {            
            // for performance reasons run this on a separade thread
            O2Thread.mtaThread(
                () =>
                    {
                        // before adding more rules, clear the current list (the return null is to force the Sync version  of invokeOnThread )
                        this.invokeOnThread(()=>
                                                {
                                                    clearChangedRulesList();
                                                    return null;
                                                });
                        
                        var newCallbackSignature = "O2.AutoMapping";
                        DI.log.info("adding {0} cirFunctions as rules", cirFunctionsToProcess.Count);

                        // get rules that we will keep (if there are rules loaded from Db and keepRulesLoadedFromDatabase is set)
                        var newO2Rules = (keepRulesLoadedFromDatabase)
                                             ? O2RulePackUtils.getRulesThatAreFromDB(currentO2RulePack)
                                             : new List<IO2Rule>();

                        //update index
                        indexedCurrentO2Rules = IndexedO2Rules.indexAll(newO2Rules);

                        if (keepRulesLoadedFromDatabase)
                            foreach (var o2Rule in newO2Rules)
                                o2Rule.Tagged = false;

                        var currentDatabaseID = MiscUtils_OunceV6.getIdForSuportedLanguage(currentLanguage).ToString();

                        var listOfChangedRules = new List<IO2Rule>();
                        var functionsToProcess = cirFunctionsToProcess.Count;
                        var functionsProcessed = 0;
                        foreach (var cirFunction in cirFunctionsToProcess)
                        {
                            var functionSignature = new FilteredSignature(cirFunction).sSignature;                            
                            // first check if there are any callers or callees on this function
                            //bDontAddIfThereAreNoCallersAndCallees
                            if (bDontAddIfThereAreNoCallersAndCallees && cirFunction.FunctionIsCalledBy.Count == 0 &&
                                cirFunction.FunctionsCalledUniqueList.Count == 0)
                            {
                                // don't add
                            }
                            else 
                                // then check if this already exists on the database
                                if (bdontAddIfRuleSignatureAlreadyExists &&
                                     indexedCurrentO2Rules.ContainsKey(functionSignature))
                                {
                                    foreach (var o2Rule in indexedCurrentO2Rules[functionSignature])
                                        o2Rule.Tagged = true;
                                }
                                // if not, then we will need ot create a new rule for this function
                                else
                                {                                    
                                    bool addAsNotMappedRule = false;
                                    //var functionSignature = new FilteredSignature(cirFunction).sSignature;

                                    // handle special cases 


                                    //bAddInternalMethodsWithNoCallersAsCallbacks (or the function is explicitly marked with cirFunction.IsTainted
                                    if (cirFunction.IsTainted || 
                                        (bAddInternalMethodsWithNoCallersAsCallbacks && cirFunction.HasControlFlowGraph && cirFunction.FunctionIsCalledBy.Count == 0))
                                    {
                                        //bDontMarkAsCallbackMethodsWithNoParameters
                                        if (false == bDontMarkAsCallbackOrSinksMethodsWithNoParameters ||
                                            cirFunction.FunctionSignature.IndexOf("()") == - 1)
                                            //cirFunction.FunctionParameters.Count > 0)  // can't use this since it is not 100% reliable
                                        {
                                            var newCallback = new O2Rule(O2RuleType.Callback,
                                                                         newCallbackSignature + ".Callback",
                                                                         functionSignature, currentDatabaseID, true);
                                            listOfChangedRules.Add(newCallback);
                                            newO2Rules.Add(newCallback);
                                        }
                                        else
                                            addAsNotMappedRule = true;
                                    }
                                    //bAddExternalMethodsAsSourcesAndSinks  - function calls nobody but it is called by others
                                    else if (bAddExternalMethodsAsSourcesAndSinks &&
                                             cirFunction.FunctionsCalledUniqueList.Count == 0 &&
                                             cirFunction.FunctionIsCalledBy.Count > 0)
                                    {
                                        // when importing CirData created by Core on Java, there is a bug that causes the ReturnType NOT to be populated 
                                        // this is why we use the cirFunction.FunctionSignature.IndexOf(":void") > -1 below instead of the more correct if (string.IsNullOrEmpty(cirFunction.ReturnType))
                                        //if (string.IsNullOrEmpty(cirFunction.ReturnType))
                                        //    DI.log.info("Method had empty cirFunction.ReturnType: {0}", cirFunction.FunctionSignature);
                                        // Only add source if the return parameter is not void
                                        if (!(cirFunction.FunctionSignature.IndexOf(":void") > -1 || cirFunction.ReturnType == "void" || cirFunction.ReturnType == "System.Void"))
                                        {
                                            var newSource = new O2Rule(O2RuleType.Source,
                                                                       newCallbackSignature + ".Source",
                                                                       functionSignature, currentDatabaseID, true);
                                            listOfChangedRules.Add(newSource);
                                            newO2Rules.Add(newSource);
                                        }
                                        else
                                            DI.log.info("Method Not marked as Source: {0}", cirFunction.FunctionSignature);
                                        // for sinks check for bDontMarkAsCallbackOrSinksMethodsWithNoParameters
                                        if (false == bDontMarkAsCallbackOrSinksMethodsWithNoParameters ||
                                            cirFunction.FunctionSignature.IndexOf("()") == -1)
                                            //cirFunction.FunctionParameters.Count > 0)
                                        {

                                            var newSink = new O2Rule(O2RuleType.Sink, newCallbackSignature + ".Sink",
                                                                     functionSignature, currentDatabaseID, true);
                                            listOfChangedRules.Add(newSink);
                                            newO2Rules.Add(newSink);
                                        }
                                        //else                                            
                                        //    DI.log.info("Method Not marked as Sink: ", cirFunction.FunctionSignature);
                                    }
                                    else
                                    {
                                        addAsNotMappedRule = true;
                                    }

                                    if (addAsNotMappedRule)
                                    {
                                        // add as NotMapped
                                        var newO2Rule = new O2Rule(newRulesVulnType, functionSignature, currentDatabaseID) { Tagged = true };
                                        newO2Rules.Add(newO2Rule);
                                    }
                                }
                            // Counter
                            if ((functionsProcessed++)%200 == 0)
                                DI.log.info("In addCirFunctionsAsRules: {0} / {1} cir Functions processed",
                                            functionsProcessed, functionsToProcess);
                        }

                        // make the current rule pack the one with the rules we have just loaded
                            DI.log.info("{0} rules created", newO2Rules.Count);
                            var newRulePack = new O2RulePack("Rule Pack", newO2Rules);
                        setCurrentRulePack(newRulePack);

                        // we need to back to the GUI thread for the updates
                        this.invokeOnThread(
                            () =>
                                {
                                    // hide this ListView for performance reasons
                                    lvChangedRules.Visible = false;
                                    dgvRules.Visible = false;
                                    // add rules
                                    addRulesToChangedRulesList_BatchMode(listOfChangedRules);

                                  //  foreach (var changedO2Rule in listOfChangedRules)
                                  //      addRuleToChangedRulesList(changedO2Rule, false /*checkIfRuleIsAlreadyInList*/);
                                    
                                    // if we are in view all mode changed it to OnlyTaggedRules
                                    if (rbViewMode_AllRules.Checked)
                                        rbViewMode_OnlyTaggedRules.Checked = true;
                                    else
                                        setRulesViewMode(); // trigger refresh

                                    // now that all rules have been added make it visible again
                                    lvChangedRules.Visible = true;
                                    dgvRules.Visible = true;
                                });                                                                        
                    });
        }
 private void filterByFilteredSignature(FilteredSignature filteredSignature)
 {
     setFilter1TextValue(filteredSignature.sSignature, true);
 }
Ejemplo n.º 26
0
        public static void remapIsCalledByXrefs(ICirDataAnalysis cirDataAnalysis)
        {
            try
            {
                remapSuperClassesXrefs(cirDataAnalysis);
                var timer = new O2Timer("remapIsCalledByXrefs").start();

                // first clear all Xref 

                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    cirFunction.FunctionIsCalledBy = new List<ICirFunctionCall>();

                // make sure all FunctionsCalledUniqueList and FunctionsCalled are syncronized with dCirFunction_bySignature 
                var functionsToMap = cirDataAnalysis.dCirFunction_bySignature.Values.ToList().Count;
                var functionsProcessed = 0;
                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values.ToList())
                {
                    for (int i = 0; i < cirFunction.FunctionsCalledUniqueList.Count; i++)
                        cirFunction.FunctionsCalledUniqueList[i] = syncFunctions(cirDataAnalysis, cirFunction.FunctionsCalledUniqueList[i]);
                    for (int i = 0; i < cirFunction.FunctionsCalled.Count; i++)
                        cirFunction.FunctionsCalled[i].cirFunction = syncFunctions(cirDataAnalysis, cirFunction.FunctionsCalled[i].cirFunction);
                    if ((functionsProcessed++) % 500 == 0)
                        DI.log.info("  processed {0} / {1}", functionsProcessed, functionsToMap);
                }

                // check the FunctionsCalledUniqueList is calledby mappngs
                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    foreach (var functionCalled in cirFunction.FunctionsCalled)
                    {
                        var functionCalledXref = getFunctionRef(cirDataAnalysis, functionCalled.cirFunction);
                        /*if (false == cirDataAnalysis.dCirFunction_bySignature.ContainsValue(functionCalled))                    
                            DI.log.error("in remapIsCalledByXrefs something is wrong because the called fucntions does not have a cirFunction mapping: {0}", functionCalled.FunctionSignature);
                        else
                        //{*/
                        bool found = false;
                        foreach (var functionCall in functionCalled.cirFunction.FunctionIsCalledBy)
                            if (functionCall.cirFunction == functionCalledXref)
                                found = true;
                        if (found == false)
                            functionCalled.cirFunction.FunctionIsCalledBy.Add(new CirFunctionCall(cirFunction, functionCalled.fileName, functionCalled.lineNumber));
                        //if (false == functionCalledXref.FunctionIsCalledBy.Contains(cirFunction))
                        //    functionCalledXref.FunctionIsCalledBy.Add(cirFunction);
                    }

                // make sure all functions are syncronized with dCirFunction_bySignature 
                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    for (int i = 0; i < cirFunction.FunctionsCalledUniqueList.Count; i++)
                        cirFunction.FunctionsCalledUniqueList[i] = syncFunctions(cirDataAnalysis, cirFunction.FunctionsCalledUniqueList[i]);

                // endure all iscalledby are correcly mapped
                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    for (int i = 0; i < cirFunction.FunctionIsCalledBy.Count; i++)
                        cirFunction.FunctionIsCalledBy[i].cirFunction = syncFunctions(cirDataAnalysis, cirFunction.FunctionIsCalledBy[i].cirFunction);

                // make sure there is a reference to this function on the Classes Dictionanry
                foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
                    foreach (var functionCalled in cirFunction.FunctionsCalled)
                        if (functionCalled.cirFunction.ParentClass == null)
                        {
                            var functionSignature = new FilteredSignature(functionCalled.cirFunction.FunctionSignature);
                            var parentClassName = functionSignature.sFunctionClass;                            
                            if (false == cirDataAnalysis.dCirClass_bySignature.ContainsKey(parentClassName))
                                cirDataAnalysis.dCirClass_bySignature.Add(parentClassName, new CirClass(parentClassName));
                            var parentCirClass = cirDataAnalysis.dCirClass_bySignature[parentClassName];
                            var functionAlreadyMappedToClass = false;
                            foreach (var cirFunctionMappedToClass in parentCirClass.dFunctions.Values)
                                if (cirFunctionMappedToClass.FunctionSignature == functionCalled.cirFunction.FunctionSignature)
                                    functionAlreadyMappedToClass = true;
                            if (false == functionAlreadyMappedToClass)
                                parentCirClass.dFunctions.Add(functionCalled.cirFunction.FunctionSignature, functionCalled.cirFunction);
                            functionCalled.cirFunction.ParentClass = parentCirClass;
                            functionCalled.cirFunction.ParentClassName = parentCirClass.Name;
                            functionCalled.cirFunction.ParentClassFullName = parentCirClass.FullName;
                        }

                timer.stop();
            }
            catch (Exception ex)
            {
                DI.log.error("in remapIsCalledByXrefs: {0}", ex.Message);
            }

        }
Ejemplo n.º 27
0
            public static void findSpringAttributes(TreeView tvRawData)
            {
                String sFunctionSignature = "ModelMap.addAttribute";
                O2Timer tTimer = new O2Timer("Resolving attribute based function: {0} ").start();

                Dictionary<AssessmentAssessmentFileFinding, O2AssessmentData_OunceV6> dMatches =
                    analyzer.getSinksFindingsThatMatchRegEx(tvRawData, sFunctionSignature);
                foreach (AssessmentAssessmentFileFinding fFinding in dMatches.Keys)
                {
                    // resolve addAddtibute name
                    String sSinkContext = AnalysisUtils.getSinkContext(fFinding, dMatches[fFinding]);
                    var fsFilteredSignature = new FilteredSignature(sSinkContext);
                    String sParameters = fsFilteredSignature.sParameters.Replace("\"", "");
                    String sSpringParameter = sParameters.Substring(0, sParameters.IndexOf(',')).Trim();

                    // create a unique name for it:
                    String sSink = AnalysisUtils.getSink(fFinding, dMatches[fFinding]);
                    String sSinkWithAttributeName = sSink.Replace("(", "_" + sSpringParameter + "(");
                    // make sure we have not added this already
                    if (sSink.IndexOf(sSpringParameter) == -1)
                    {
                        //     String sSinkWithAttributeName = sSink.Replace("(", "_" + sSpringParameter + "(");
                        //      String sSinkWithAttributeName = sSpringParameter;
                        String sUniqueSignature = analyzer.getUniqueSignature(fFinding, TraceType.Known_Sink,
                                                                              dMatches[fFinding], true);
                        var otbO2TraceBlockOfThisFinding = (O2TraceBlock_OunceV6) tvRawData.Nodes[sUniqueSignature].Tag;

                        CallInvocation ciCallInvocation =
                            AnalysisSearch.findTraceTypeInSmartTrace_Recursive_returnCallInvocation(
                                fFinding.Trace, TraceType.Known_Sink);
                        UInt32 uNewId = OzasmtUtils_OunceV6.addTextToStringIndexes(sSinkWithAttributeName,
                                                                                   dMatches[fFinding].arAssessmentRun);
                        ;
                        ciCallInvocation.sig_id = uNewId;
                        DI.log.debug(" Found spring attribute '{0}' on sinks and modified to {1}", sSpringParameter,
                                     sSinkWithAttributeName);
                        //o2.analysis.Analysis.getSink(fFinding, dMatches[fFinding]));
                        otbO2TraceBlockOfThisFinding.sSignature = sSinkWithAttributeName;
                        otbO2TraceBlockOfThisFinding.sUniqueName = analyzer.getUniqueSignature(fFinding,
                                                                                               TraceType.
                                                                                                   Known_Sink,
                                                                                               dMatches[fFinding], true);

                        List<O2TraceBlock_OunceV6> lotbO2TraceBlockWithVelocityMappings =
                            analyzer.getO2TraceBlocksThatMatchSignature(sSinkWithAttributeName, tvRawData);


/*                        String sVelocityMapping = String.Format("{0}            0", sSinkWithAttributeName);
                        TreeNode tnVelocityNode = tvRawData.Nodes[sVelocityMapping];
                        if (tnVelocityNode != null)
 */
                        foreach (
                            O2TraceBlock_OunceV6 otbO2TraceBlockWithVelocityMappings in lotbO2TraceBlockWithVelocityMappings)
                        {
                            if (otbO2TraceBlockWithVelocityMappings.sFile.IndexOf(".vm") > -1)

                                //O2TraceBlock_OunceV6 otbO2TraceBlockWithVelocityMappings = (O2TraceBlock_OunceV6)tnVelocityNode.Tag;
                                foreach (
                                    AssessmentAssessmentFileFinding fVelocityFinding in
                                        otbO2TraceBlockWithVelocityMappings.dSinks.Keys)
                                {
                                    if (false == otbO2TraceBlockOfThisFinding.dGluedSinks.ContainsKey(fVelocityFinding))
                                        otbO2TraceBlockOfThisFinding.dGluedSinks.Add(fVelocityFinding,
                                                                                     otbO2TraceBlockWithVelocityMappings
                                                                                         .dSinks[fVelocityFinding]);
                                    if (false == otbO2TraceBlockOfThisFinding.dSinks.ContainsKey(fVelocityFinding))
                                        otbO2TraceBlockOfThisFinding.dSinks.Add(fVelocityFinding,
                                                                                otbO2TraceBlockWithVelocityMappings.
                                                                                    dSinks[fVelocityFinding]);
                                }
                        }
                    }
                }
                tTimer.stop();
            }
Ejemplo n.º 28
0
 public static List<String> getListWithWordsFromSignature(string signature)
 {
     var filteredSignature = new FilteredSignature(signature);
     List<string> wordsFromSignature = filteredSignature.lsFunctionClass_Parsed; // words in namespace & class
     wordsFromSignature.Add(filteredSignature.sFunctionName); // also add the method name
     return wordsFromSignature;
 }
Ejemplo n.º 29
0
        public void test_PopulateCirWithTraces()
        {
            // get Assessment Data
            var o2Assessment = new O2Assessment(new O2AssessmentLoad_OunceV6(), findingsFile);
            Assert.That(o2Assessment.o2Findings.Count > 0, "There were no findings in o2Assessment");
            DI.log.info("There are {0} findings in the assessment loaded", o2Assessment.o2Findings.Count);
            var uniqueListOfSignatures = OzasmtUtils.getUniqueListOfSignatures(o2Assessment.o2Findings);
            Assert.That(uniqueListOfSignatures.Count() > 0, "uniqueListOfSignatures.Count ==0 ");
            DI.log.info("There are {0} unique signatures ", uniqueListOfSignatures.Count());
            
            // get cir data
            var cirDataAnalysis = new CirDataAnalysis();
            CirDataAnalysisUtils.loadFileIntoCirDataAnalysisObject(fileToCreateCirFrom,cirDataAnalysis);
            CirDataAnalysisUtils.remapIsCalledByXrefs(cirDataAnalysis);

            Assert.That(cirDataAnalysis.dCirFunction_bySignature.Count > 0, "cirDataAnalysis.dCirFunction_bySignature.Count == 0");

            // need to convert to Ozasmt signature format
            var cirMappedFunctions = new Dictionary<string, ICirFunction>();
            foreach (var cirFunction in cirDataAnalysis.dCirFunction_bySignature.Values)
            {              
                if (cirFunction.FunctionSignature.IndexOf("O2AppDomainFactory>") > -1)
                {
                }
                var filteredSignature = new FilteredSignature(cirFunction);
                cirMappedFunctions.Add(filteredSignature.sSignature, cirFunction);
            }
            var matches = new List<String>();
            foreach (var sig in cirMappedFunctions.Keys)
                if (sig.IndexOf("IndexOf") > -1)
                    matches.Add(sig);

            //var matches = new List<String>();
       /*     foreach (var cirFunction in cirMappedFunctions.Values)
                foreach (var called in cirFunction.FunctionsCalledUniqueList)
                    if (called.FunctionSignature.IndexOf("System.Object::.ctor") > -1)
                    {
                        matches.Add(called.FunctionSignature);
                        var asd = cirDataAnalysis.dCirFunction_bySignature.ContainsKey(called.FunctionSignature);
                    }*/


            foreach (var signature in uniqueListOfSignatures)            
                if (false == cirMappedFunctions.ContainsKey(signature))
                    DI.log.info("NO MATCH:" + signature);
                
            foreach(O2Finding o2Finding in o2Assessment.o2Findings)
            {
                var source = o2Finding.Sink;
                if (source != "" && false == cirMappedFunctions.ContainsKey(source))
                    DI.log.info("NO MATCH for Source:" + source);

                var sink = o2Finding.Sink;
                if (sink != "" && false == cirMappedFunctions.ContainsKey(sink))
                    DI.log.info("NO MATCH for Sink:" + sink);
            }

            /*foreach (var signature in uniqueListOfSignatures)
                DI.log.info(signature);
            return;*/
            
            
        }
 void TextArea_DragDrop(object sender, DragEventArgs e)
 {
     var fileOrFolder = Dnd.tryToGetFileOrDirectoryFromDroppedObject(e);
     if (fileOrFolder.fileExists())
     {
         loadSourceCodeFile(fileOrFolder);
         return;
     }
     var data = Dnd.tryToGetObjectFromDroppedObject(e);
     if (data != null)
     {
         var dsa = data.GetType().FullName;
         if (data is List<MethodInfo>)
         {
             var methods = (List<MethodInfo>)data;
             if (methods.Count > 0)
             {
                 var filteredSignature = new FilteredSignature(methods[0]);
                 tecSourceCode.ActiveTextAreaControl.TextArea.InsertString(filteredSignature.sFunctionNameAndParams);
                 //  var functionSignature = new FilteredSignature
             }
         }
         else
             tecSourceCode.ActiveTextAreaControl.TextArea.InsertString(data.ToString());
     }
 }
Ejemplo n.º 31
0
        public static String createFindingsFromVMFiles(ConsolidatedProcessedVelocityFiles cpvfVelocityFiles,
                                                       ascx_TraceViewer ascxTraceViewer)
        {
            String sTemplateSpringModeMapName =
                "org.springframework.ui.ModelMap.addAttribute_{0}(java.lang.String;java.lang.Object):org.springframework.ui.ModelMap";
            var lfrFindingsResult = new List<AnalysisSearch.FindingsResult>();
            foreach (ProcessedVelocityFile pvFile in cpvfVelocityFiles.getListWithProcessedLoadedFilesObjects())
            {
                foreach (String sMethod in pvFile.getFunctions())
                {
                    var fsFilteredSignature = new FilteredSignature(sMethod, ',');
                    if (fsFilteredSignature.sParameters == "")
                        // if there are no parameters just add them method as both source and sink
                    {
                        lfrFindingsResult.Add(createFindingsResultForSourceAndSink(sMethod, sMethod,
                                                                                   "Velocity.Finding.Function_noParam",
                                                                                   pvFile.getNormalizedFileName(),
                                                                                   "Velocity.Finding.Function_noParam",
                                                                                   pvFile.getNormalizedFileName(),
                                                                                   pvFile.sFullPathToOriginalFile
                                                  ));
                    }
                    else
                    {
                        foreach (String sParameter in fsFilteredSignature.lsParameters_Parsed)
                        {
                            String sVelocityVariableName =
                                sParameter.Replace("$", "").Replace("!", "").Replace("{", "").Replace("}", "");

                            String sSourceSignature = String.Format(sTemplateSpringModeMapName, sVelocityVariableName);
                            String sSinkSignature = sMethod;
                            lfrFindingsResult.Add(createFindingsResultForSourceAndSink(sSourceSignature, sSinkSignature,
                                                                                       "Velocity.Finding.Function_withParam",
                                                                                       pvFile.getNormalizedFileName(),
                                                                                       "Velocity.Finding.Function_withParam",
                                                                                       pvFile.getNormalizedFileName(),
                                                                                       pvFile.sFullPathToOriginalFile
                                                      ));
                        }
                    }
                }

                foreach (String sVar in pvFile.getVars())
                {
                    String sVelocityVariableName = sVar.Replace("$", "").Replace("!", "").Replace("{", "").Replace("}",
                                                                                                                   "");
                    String sSourceSignature = String.Format(sTemplateSpringModeMapName, sVelocityVariableName);
                    String sSinkSignature = sVar;
                    lfrFindingsResult.Add(createFindingsResultForSourceAndSink(sSourceSignature, sSinkSignature,
                                                                               "Velocity.Finding.Variable",
                                                                               pvFile.getNormalizedFileName(),
                                                                               "Velocity.Finding.Variable",
                                                                               pvFile.getNormalizedFileName(),
                                                                               pvFile.sFullPathToOriginalFile
                                              ));
                    //FindingViewItem fviFindingViewItem = new FindingViewItem(nfNewFinding.fFinding, nfNewFinding.oadNewO2AssessmentData);            
                    //ascxTraceViewer.setTraceDataAndRefresh(fviFindingViewItem);
                }
            }
            String sNewAssessmentFile = DI.config.TempFileNameInTempDirectory;

            CustomAssessmentFile.create_CustomSavedAssessmentRunFile_From_FindingsResult_List(lfrFindingsResult,
                                                                                              sNewAssessmentFile);
            return sNewAssessmentFile;
        }
Ejemplo n.º 32
0
        public void addBindableFieldsIntoTreeView_Recursive(TreeNodeCollection tncTreeNodes, String sClassToFind,
                                                            bool bHideGetAndSetStrings, ICirData fadCirData)
        {
            String sFixedClassToFind = sClassToFind[0].ToString().ToUpper() + sClassToFind.Substring(1);
            foreach (ICirClass ccCirClass in fadCirData.dClasses_bySignature.Values)
            {
                if (ccCirClass.Name == sFixedClassToFind)
                {
                    var tnClass = new TreeNode(ccCirClass.Signature);

                    foreach (ICirFunction cfCirFunction in ccCirClass.dFunctions.Values)
                    {
                        String sFunctionName = new FilteredSignature(cfCirFunction.FunctionSignature).sFunctionName;
                        switch (sFunctionName.Substring(0, 3))
                        {
                            case "get":
                                var tnSubObject = new TreeNode(sFunctionName);
                                String sFixedSubObjectName = sFunctionName.Replace("get", "");
                                if (bHideGetAndSetStrings)
                                    tnSubObject.Text = sFixedSubObjectName;

                                // tnSubObject = tnClass;
                                addBindableFieldsIntoTreeView_Recursive(tnSubObject.Nodes, sFixedSubObjectName,
                                                                        bHideGetAndSetStrings, fadCirData);
                                if (tnSubObject.Nodes.Count > 0)
                                    tnClass.Nodes.Add(tnSubObject);
                                break;
                            case "set":
                                String sSetNodeText = new FilteredSignature(cfCirFunction.FunctionSignature).sFunctionName;
                                if (bHideGetAndSetStrings)
                                    sSetNodeText = sSetNodeText.Replace("set", "");
                                tnClass.Nodes.Add(sSetNodeText);
                                break;
                            default:
                                break;
                        }
                    }

                    tncTreeNodes.Add(tnClass);
                }
                //    String sClassName = 
            }
        }