Exemple #1
0
        public static IO2Finding createCopy(IO2Finding o2Finding, bool processChildTraces)
        {
            var newO2Finding = new O2Finding
                                   {
                                       actionObject = o2Finding.actionObject,
                                       callerName = o2Finding.callerName,
                                       context = o2Finding.context,
                                       columnNumber = o2Finding.actionObject,
                                       confidence = o2Finding.confidence,
                                       exclude = o2Finding.exclude,
                                       file = o2Finding.file,
                                       lineNumber = o2Finding.lineNumber,
                                       ordinal = o2Finding.ordinal,
                                       projectName = o2Finding.projectName,
                                       propertyIds = o2Finding.propertyIds,
                                       recordId = o2Finding.recordId,
                                       severity = o2Finding.severity,
                                       text = createCopy(o2Finding.text),
                                       vulnName = o2Finding.vulnName,
                                       vulnType = o2Finding.vulnType
                                   };
            if (processChildTraces)
                newO2Finding.o2Traces = createCopy(o2Finding.o2Traces);

            return newO2Finding;
        }
Exemple #2
0
        public static List<IO2Finding> findParameterStaticValueInMethodX(CirData cirData)
        {
            string functionToFind = "System.Web.UI.WebControls.Button.add_Click(System.EventHandler):void";
            var createdO2Findings = new List<IO2Finding>();
            try
            {
                if (cirData.dFunctions_bySignature.ContainsKey(functionToFind))
                {
                    var function = cirData.dFunctions_bySignature[functionToFind];
                    foreach (CirFunction functionXRef in function.FunctionIsCalledBy)
                    {
                        //var functionXRef = cirData.dFunctions_bySignature[functionXRefName];
                        foreach (var basicBlock in functionXRef.lcfgBasicBlocks)
                        {
                            if (basicBlock != null && basicBlock.Items != null)
                                for (var i = 0; i < basicBlock.Items.Length; i++)
                                {
                                    var item = basicBlock.Items[i];
                                    if (item.GetType().Name == "ControlFlowGraphBasicBlockEvalExprStmt")
                                    {
                                        var evalExprStmt = (ControlFlowGraphBasicBlockEvalExprStmt)item;
                                        if (evalExprStmt.NaryCallVirtual != null && evalExprStmt.NaryCallVirtual.FunctionName == functionToFind)
                                        {
                                            // go to the previous block
                                            var evalExprStmtWithStaticParameterValue = (ControlFlowGraphBasicBlockEvalExprStmt)basicBlock.Items[i - 1];
                                            if (evalExprStmtWithStaticParameterValue.NaryCall != null && evalExprStmtWithStaticParameterValue.NaryCall.UnaryOprCast != null && evalExprStmtWithStaticParameterValue.NaryCall.UnaryOprCast.Length == 2)
                                            {

                                                string staticParameterValue =
                                                    evalExprStmtWithStaticParameterValue.NaryCall.UnaryOprCast[1].
                                                        ConstFunctionAddress.FunctionName;
                                                var o2Finding = new O2Finding(staticParameterValue, "Asp.NET Event Mapping") { o2Traces = new List<IO2Trace>{ new O2Trace(functionXRef.FunctionSignature, TraceType.Root_Call)} };
                                                var sourceTrace = new O2Trace(functionXRef.ParentClass.Signature, functionXRef.FunctionSignature, TraceType.Source);
                                                var sinkTrace = new O2Trace(staticParameterValue, TraceType.Known_Sink)
                                                                    {
                                                                        context =
                                                                            "this . HacmeBank_v2_Website.ascx.PostMessageForm.btnPostMessage_Click ( sender, e )"
                                                                    };
                                                sourceTrace.childTraces.Add(sinkTrace);
                                                o2Finding.o2Traces[0].childTraces.Add(sourceTrace);
                                                createdO2Findings.Add(o2Finding);
                                                DI.log.debug("{0} -- > {1}", functionXRef.FunctionSignature, staticParameterValue);
                                            }
                                        }
                                    }
                                }
                        }

                    }                  
                    return createdO2Findings;
                }
            }
            catch (Exception ex)
            {
                DI.log.debug("in findParameterStaticValueInMethodX :{0}:", ex.Message);
            }


            return null;
        }
 public static List<IO2Finding> createFindingsFromConversation(List<IWebscarabConversation> webScarabConversations)
 {
     List<IO2Finding> o2Findings = new List<IO2Finding>();
     foreach (IWebscarabConversation conversation in webScarabConversations)
     {
         O2Finding o2Finding = new O2Finding();
         if ((conversation.TAG != null) && (conversation.TAG != ""))
         {
             o2Finding.vulnType = conversation.TAG;
         }
         else
         {
             o2Finding.vulnType = "Tag not defined";
         }
         o2Finding.vulnName = conversation.METHOD + ": " + conversation.URL;
         addTrace(o2Finding, conversation.COOKIE, "COOKIE");
         addTrace(o2Finding, conversation.STATUS, "STATUS");
         addTrace(o2Finding, conversation.ORIGIN, "ORIGIN");
         addTrace(o2Finding, conversation.URL, "URL");
         addTrace(o2Finding, conversation.XSS_GET, "XSS_GET");
         addTrace(o2Finding, conversation.CRLF_GET, "CRLF_GET");
         addTrace(o2Finding, conversation.SET_COOKIE, "SET_COOKIE");
         addTrace(o2Finding, conversation.XSS_POST, "XSS_POST");
         var traceRequest = new O2Trace("request: " + conversation.request);
         traceRequest.file = conversation.request;                
         var traceResponse = new O2Trace("response: " + conversation.response);
         traceResponse.file = conversation.response;
         o2Finding.file =  conversation.response;
         o2Finding.o2Traces.Add(traceRequest);
         o2Finding.o2Traces.Add(traceResponse);
         o2Findings.Add(o2Finding);
     }
     return o2Findings;
 }
        public static IO2Finding createCopy(IO2Finding o2Finding, bool processChildTraces)
        {
            var newO2Finding = new O2Finding
            {
                actionObject = o2Finding.actionObject,
                callerName   = o2Finding.callerName,
                context      = o2Finding.context,
                columnNumber = o2Finding.actionObject,
                confidence   = o2Finding.confidence,
                exclude      = o2Finding.exclude,
                file         = o2Finding.file,
                lineNumber   = o2Finding.lineNumber,
                ordinal      = o2Finding.ordinal,
                projectName  = o2Finding.projectName,
                propertyIds  = o2Finding.propertyIds,
                recordId     = o2Finding.recordId,
                severity     = o2Finding.severity,
                text         = createCopy(o2Finding.text),
                vulnName     = o2Finding.vulnName,
                vulnType     = o2Finding.vulnType
            };

            if (processChildTraces)
            {
                newO2Finding.o2Traces = createCopy(o2Finding.o2Traces);
            }

            return(newO2Finding);
        }
        public static List<IO2Finding> createFindingsFromConversation(List<IWebscarabConversation> webScarabConversations)
        {
            var o2Findings = new List<IO2Finding>();
            foreach (var conversation in webScarabConversations)
            {
                var o2Finding = new O2Finding();
                if (conversation.TAG != null && conversation.TAG != "")
                    o2Finding.vulnType = conversation.TAG;
                else
                    o2Finding.vulnType = "Tag not defined";
                o2Finding.vulnName = conversation.METHOD + ": " + conversation.URL;

                addTrace(o2Finding, conversation.COOKIE, "COOKIE");
                addTrace(o2Finding, conversation.STATUS, "STATUS");
                addTrace(o2Finding, conversation.ORIGIN, "ORIGIN");
                addTrace(o2Finding, conversation.URL, "URL");
                addTrace(o2Finding, conversation.XSS_GET, "XSS_GET");
                addTrace(o2Finding, conversation.CRLF_GET, "CRLF_GET");
                addTrace(o2Finding, conversation.SET_COOKIE, "SET_COOKIE");
                addTrace(o2Finding, conversation.XSS_POST, "XSS_POST");

                // add request and response
                var requestTrace = new O2Trace("request: " + conversation.request) {file = conversation.request};
                // requestTrace.context = Files.getFileContents(requestTrace.file);

                var responseTrace = new O2Trace("response: " + conversation.response) {file = conversation.response};
                // responseTrace.context = Files.getFileContents(responseTrace.file);

                o2Finding.o2Traces.Add(requestTrace);
                o2Finding.o2Traces.Add(responseTrace);
                o2Findings.Add(o2Finding);

            }
            return o2Findings;
        }
 private static IO2Finding getO2Finding(AssessmentAsmntFileFinding finding, AssessmentRun assessmentRunToImport)
 {
     var o2Finding = new O2Finding();
     addFindingDataToO2Finding(finding, o2Finding, assessmentRunToImport);
     addTraceToO2Finding(finding.trace, o2Finding, assessmentRunToImport);
     OzasmtUtils.fixExternalSourceSourceMappingProblem(o2Finding);           // fix the 'ExternalSource Source' problem
     return o2Finding;
 }
Exemple #7
0
        public static O2Finding CreateFinding_WithTrace()
        {
            const uint line_number = 2;
            const uint column_number = 3;
            const uint ordinal = 1;
            const string context = "TraceContext";
            const string signature = "TraceSignature";
            const string clazz = "class.this.trace.is.in";
            const string file = @"c:\o2\temp\file\trace\is\in.cs";
            const string method = "methodExectuted";
            const uint taintPropagation = 0;
            var text = new List<string> {"this is a text inside a trace"};



            var o2Finding = new O2Finding("Vulnerability.Name", "Vulnerability.Type");

            o2Finding.o2Traces.Add(new O2Trace
                                        {
                                            clazz = clazz,
                                            columnNumber = column_number,
                                            context = context,
                                            file = file,
                                            lineNumber = line_number,
                                            method = method,
                                            ordinal = ordinal,
                                            signature = signature,
                                            taintPropagation = taintPropagation,
                                            text = text,
                                        });

            
            const string sinkText = "this is a sink";
            const string methodOnSinkPath = "method call on sink path";
            const string methodOnSourcePath = "method call on source path";
            const string sourceText = "this is a source";

            
            var o2Trace = new O2Trace("Class.Signature", "Method executed");

            var o2TraceOnSinkPath = new O2Trace(methodOnSinkPath, TraceType.Type_0);
            o2TraceOnSinkPath.childTraces.Add(new O2Trace(sinkText, TraceType.Known_Sink));

            var o2TraceOnSourcePath = new O2Trace(methodOnSourcePath, TraceType.Type_0);
            o2TraceOnSourcePath.childTraces.Add(new O2Trace(sourceText, TraceType.Source));

            o2Trace.childTraces.Add(o2TraceOnSourcePath);

            o2Trace.childTraces.Add(o2TraceOnSinkPath);

            o2Finding.o2Traces = new List<IO2Trace> {o2Trace};

            return o2Finding;

        }
        public static List <IO2Trace> getListWithAllTraces(O2Finding o2Finding)
        {
            var allTraces = new List <IO2Trace>();

            try
            {
                getListWithAllTraces(o2Finding.o2Traces, allTraces);
            }
            catch (Exception ex)
            {
                DI.log.error("in getListWithAllTraces: {0}", ex.Message);
            }
            return(allTraces);
        }
 public static void fixExternalSourceSourceMappingProblem(O2Finding o2Finding)
 {
     try
     {
         // fix the external_source callback generated finding problem since the source should be the callback back methods and not the <external_source>(...) rule
         if (o2Finding.Source.IndexOf("<external_source>") > -1)
         {
             o2Finding.getSource().traceType = TraceType.Root_Call;
             o2Finding.o2Traces[0].childTraces[1].traceType = TraceType.Source;
         }
     }
     catch (Exception ex)
     {
         DI.log.ex(ex, "in getO2Finding, while trying to fix the external_source callback generated finding problem");
     }
 }
 public static IO2Finding createO2FindingFromTrace(IO2Trace o2Trace)
 {
     var o2Finding = new O2Finding
                         {
                             callerName = o2Trace.signature,
                             context = o2Trace.context,
                             columnNumber = o2Trace.columnNumber,
                             file = o2Trace.file,
                             lineNumber = o2Trace.lineNumber,
                             o2Traces = new List<IO2Trace> {OzasmtCopy.createCopy(o2Trace)},
                             ordinal = o2Trace.ordinal,
                             text = OzasmtCopy.createCopy(o2Trace.text),
                             vulnName = o2Trace.signature,
                             vulnType = "FindingFromTrace"
                         };
     return o2Finding;
 }
        public static List<IO2Finding> loadWebInspectResultsAndReturnO2FindingsFor_SqlInjection_PoC1(
            string webInspectResultsFile)
        {
            var results = new List<IO2Finding>();
            var webInspectResults = new XmlDocument();
            webInspectResults.Load(webInspectResultsFile);
            List<XmlNode> sessionsCheckFoundWithEngineId = getSessionsCheckFoundWithEngineId(webInspectResults,
                                                                                             sqlInjectionEngineId);
            foreach (XmlNode sessionCheckFound in sessionsCheckFoundWithEngineId)
            {
                // ReSharper disable PossibleNullReferenceException
                string sessionId = sessionCheckFound["VulnerableSessionID"].InnerText;

                List<XmlNode> sessionsFoundWithSessionId = getSessionsWithSessionID(webInspectResults, sessionId);
                foreach (XmlNode session in sessionsFoundWithSessionId)
                {
                    string fullURL = session["FullURL"].InnerText;
                    string attackParamDescriptor = session["AttackParamDescriptor"].InnerText;
                    if (attackParamDescriptor.IndexOf(':') > -1)
                        attackParamDescriptor = attackParamDescriptor.Split(new[] {':'})[1];
                    string attackDescriptor = session["AttackDescriptor"].InnerText;
                    var o2Finding = new O2Finding
                                        {
                                            o2Traces = new List<IO2Trace> { new O2Trace("WebInspect -> Ounce Mapping")},
                                            context = attackDescriptor,
                                            vulnName = fullURL,
                                            vulnType = "WebInspect Vulnerability"
                                        };
                    var source = new O2Trace(fullURL, TraceType.Source);
                    source.childTraces.Add(new O2Trace(attackDescriptor));

                    var Sink = new O2Trace(attackParamDescriptor)
                                   {
                                       traceType = TraceType.Known_Sink,
                                   };

                    source.childTraces.Add(Sink);

                    o2Finding.o2Traces[0].childTraces.Add(source);

                    results.Add(o2Finding);
                }
                // ReSharper restore PossibleNullReferenceException
            }
            return results;
        }
        public static List<IO2Finding> createFindingsFromStrutsMappings(IStrutsMappings iStrutsMappings)
        {
            var newO2Findings = new List<IO2Finding>();


            foreach (var actionServlet in iStrutsMappings.actionServlets)
                foreach (var controler in actionServlet.controllers.Values)
                {
                    var o2Finding = new O2Finding
                    {
                        vulnType = "Struts.Finding : " + controler.type,
                        vulnName = controler.type ?? ""
                    };


                    var o2RootTrace = (O2Trace)o2Finding.addTrace("Struts Mapping", TraceType.O2JoinSource);
                    o2RootTrace.addTrace("Controller Type: " + controler.type, TraceType.O2JoinSink);

                    // add formbean
                    if (controler.formBean != null)
                    {
                        var beanTrace = (O2Trace)o2RootTrace.addTrace("Form Bean : " + controler.formBean.name, TraceType.O2Info);
                        beanTrace.addTrace("has validation mapping" + controler.formBean.hasValidationMapping);
                        foreach (var field in controler.formBean.fields)
                            beanTrace.addTrace(field.Value.name);
                    }


                    var pathsTrace = (O2Trace)o2RootTrace.addTrace("paths:", TraceType.O2Info);

                    foreach (var path in controler.paths)
                    {
                        var pathTrace = (O2Trace)pathsTrace.addTrace("url: " + path.path);
                        pathTrace.addTrace("controller: " + controler.type + " <- ");
                        pathTrace.addTraces("view: ", TraceType.O2JoinSink, path.resolvedViews.ToArray());
                    }

                    //o2Finding.o2Traces.Add(o2RootTrace);
                    newO2Findings.Add(o2Finding);
                }
            return newO2Findings;
        }
Exemple #13
0
        public static IO2Finding createO2FindingFromTrace(IO2Trace o2Trace)
        {
            var o2Finding = new O2Finding
            {
                callerName   = o2Trace.signature,
                context      = o2Trace.context,
                columnNumber = o2Trace.columnNumber,
                file         = o2Trace.file,
                lineNumber   = o2Trace.lineNumber,
                o2Traces     = new List <IO2Trace> {
                    OzasmtCopy.createCopy(o2Trace)
                },
                ordinal  = o2Trace.ordinal,
                text     = OzasmtCopy.createCopy(o2Trace.text),
                vulnName = o2Trace.signature,
                vulnType = "FindingFromTrace"
            };

            return(o2Finding);
        }
 private IO2Assessment createO2AssessmentFromCodeCrawlerObject(Xsd.DocumentElement codeCrawlerObject, String fileName)
 {
     var o2Assessment = new O2Assessment();
     o2Assessment.name = "CodeCrawler Import of: " + fileName;
     foreach(var threat in codeCrawlerObject.ThreatList)
     {
         var o2Finding = new O2Finding
                             {
                                 vulnName = threat.Threat,
                                 vulnType = threat.Threat,
                                 context = threat.Description,
                                 severity = threat.Level,
                                 confidence = 2,
                                 lineNumber = threat.Line,
                                 file = fileName
                             };
         o2Finding.text.Add(threat.Description);
         o2Assessment.o2Findings.Add(o2Finding);
     }
     return o2Assessment;
 }
        public void calculateResults()
        /*ascx_StrutsMappings strutsMappingsControl,
        ascx_FilteredFindings filteredFindings_TaintSources,
        ascx_FilteredFindings filteredFindings_FinalSinks,
        ascx_FindingsViewer findingsViewer_FinalFindings
        )*/
        {
            //const string controlTypePrefixString = "Controller Type: ";
            //const string viewPrefixString = "view: ";

            var results = new List<IO2Finding>();

            // need to build 4 dictionaries
            PublicDI.log.debug("building 4 dictionaries with sources,sinks and Join points");
            // JoinSink in taintSources
            var taintSourcesJoinSinks = new Dictionary<string, List<IO2Finding>>();
            //foreach (O2Finding o2Finding in filteredFindings_TaintSources.getResults())
            foreach (O2Finding o2Finding in findingsWith_FindingsFromTaintSources)
            {
                var joinSinks = o2Finding.JoinSinks();
                if (joinSinks.Count == 1)
                {
                    var joinSink = joinSinks[0]; // we currenty only support the case where there is one JoinSink
                    if (false == taintSourcesJoinSinks.ContainsKey(joinSink))
                        taintSourcesJoinSinks.Add(joinSink, new List<IO2Finding>());
                    taintSourcesJoinSinks[joinSink].Add(o2Finding);
                }
            }

            // var taintSourcesJoinLocations
            var taintSourcesJoinLocations = new Dictionary<string, List<IO2Finding>>();
            //foreach (O2Finding o2Finding in filteredFindings_TaintSources.getResults())
            foreach (O2Finding o2Finding in findingsWith_FindingsFromTaintSources)
            {
                var joinLocations = o2Finding.getJoinLocations();
                if (joinLocations.Count == 1)
                {
                    var joinLocation = joinLocations[0].signature; // we currenty only support the case where there is one JoinLocation
                    if (false == taintSourcesJoinLocations.ContainsKey(joinLocation))
                        taintSourcesJoinLocations.Add(joinLocation, new List<IO2Finding>());
                    taintSourcesJoinLocations[joinLocation].Add(o2Finding);
                }
            }

            // JoinSources in final Sinks
            var finalSinksTaintSources = new Dictionary<string, List<IO2Finding>>();
            //foreach (O2Finding o2Finding in filteredFindings_FinalSinks.getResults())
            foreach (O2Finding o2Finding in findingsWith_FindingsToFinalSinks)
            {
                var joinSources = o2Finding.JoinSources();
                if (joinSources.Count == 1)
                {
                    var joinSource = joinSources[0]; // we currenty only support the case where there is one JoinSource
                    if (false == finalSinksTaintSources.ContainsKey(joinSource))
                        finalSinksTaintSources.Add(joinSource, new List<IO2Finding>());
                    finalSinksTaintSources[joinSource].Add(o2Finding);
                }
            }

            // var finalSinksJoinLocations
            var finalSinksJoinLocations = new Dictionary<string, List<IO2Finding>>();
            //foreach (O2Finding o2Finding in filteredFindings_FinalSinks.getResults())
            foreach (O2Finding o2Finding in findingsWith_FindingsToFinalSinks)
            {
                var joinLocations = o2Finding.getJoinLocations();
                if (joinLocations.Count == 1)
                {
                    var joinLocation = joinLocations[0].signature; // we currenty only support the case where there is one JoinLocation
                    if (false == finalSinksJoinLocations.ContainsKey(joinLocation))
                        finalSinksJoinLocations.Add(joinLocation, new List<IO2Finding>());
                    finalSinksJoinLocations[joinLocation].Add(o2Finding);
                }
            }

            PublicDI.log.debug("mapping all data");
            //foreach (var actionServlet in strutsMappingsControl.getStrutsMappingObject().actionServlets)            
            foreach (var actionServlet in StrutsMappings.actionServlets)
            {
                var controllersToAdd = actionServlet.controllers.Values.Count;
                var controllersAdded = 0;
                foreach (var controler in actionServlet.controllers.Values)
                {
                    if (controllersAdded++ % 10 == 0)
                        PublicDI.log.debug("   Added [{0}/{1}] controllers ({2} findings so far)", controllersAdded, controllersToAdd , results.Count );
                    foreach (var path in controler.paths)
                        foreach (var view in path.resolvedViews)
                        {
                            //DI.log.info("{0} - {1}", controler.type, view);
                            // now search on the Join Locations
                            foreach (var taintSourcesJoinLocation in taintSourcesJoinLocations)
                                foreach (var finalSinksJoinLocation in finalSinksJoinLocations)
                                {
                                    var filteredController = controler.type ?? "";
                                    var filteredView = JoinPointFilter(view); //.Replace("\\", ".").Replace('/', '.');
                                    var filteredTaintSource = JoinPointFilter(taintSourcesJoinLocation.Key);
                                        //.Replace('\\', '.').Replace('/', '.');
                                    var filteredFinalSink = JoinPointFilter(finalSinksJoinLocation.Key);
                                        //.Replace('\\', '.').Replace('/', '.'); ;

                                    if (filteredTaintSource.Contains(filteredController) &&
                                        filteredFinalSink.Contains(filteredView))
                                    {
                                        foreach (O2Finding taintSourceFinding in taintSourcesJoinLocation.Value)
                                            foreach (O2Finding finalSinkFinding in finalSinksJoinLocation.Value)
                                            {
                                                if (taintSourceFinding.JoinSinks().Count == 1 &&
                                                    finalSinkFinding.JoinSources().Count == 1)
                                                {
                                                    if (taintSourceFinding.JoinSinks()[0] ==
                                                        finalSinkFinding.JoinSources()[0])
                                                    {

                                                        // if we have a match , create the finding
                                                        var o2Finding = new O2Finding
                                                                            {
                                                                                vulnType =
                                                                                    "Struts.Finding : " + controler.type,
                                                                                vulnName = controler.type ?? ""
                                                                            };


                                                        var o2RootTrace =
                                                            (O2Trace)
                                                            o2Finding.addTrace("Struts Mapping", TraceType.Root_Call);
                                                        var controllerTrace =
                                                            o2RootTrace.addTrace("Controller: " + controler.type,
                                                                                 TraceType.O2JoinSink);                                                        
                                                        if (controler.formBean != null)
                                                        {
                                                            var beanTrace =
                                                                (O2Trace)
                                                                o2RootTrace.addTrace(
                                                                    "Form Bean : " + controler.formBean.name,
                                                                    TraceType.O2Info);
                                                            beanTrace.addTrace("has validation mapping" +
                                                                               controler.formBean.hasValidationMapping);

                                                            // only add the field that matches the current join
                                                            var currentJoinPoint = JoinOnAttributes.extractNameFromContext(taintSourceFinding.SourceContext, "\"", "\"");                                                                
                                                            foreach (var field in controler.formBean.fields)
                                                                if (field.Key == currentJoinPoint)
                                                                {

                                                                    var joinPoint =
                                                                        (O2Trace) beanTrace.addTrace(field.Value.name);
                                                                    joinPoint.addTrace("hasValidationMapping: " +
                                                                                       field.Value.hasValidationMapping);
                                                                    joinPoint.addTrace_IfNotEmpty("depends: ",
                                                                                                  field.Value.depends);
                                                                    joinPoint.addTrace_IfNotEmpty("initial",
                                                                                                  field.Value.initial);
                                                                    joinPoint.addTrace_IfNotEmpty("type",
                                                                                                  field.Value.type);
                                                                    foreach (var validator in field.Value.validators)
                                                                        joinPoint.addTrace(
                                                                            string.Format("validator: {0}={1}",
                                                                                          validator.Key, validator.Value));
                                                                }

                                                            //var formBeanTrace = o2RootTrace.addTrace( "Form Bean: " + controler.formBean.type ?? "",TraceType.O2Info);
                                                        }
                                                        controllerTrace.childTraces.AddRange(taintSourceFinding.o2Traces);

                                                        var pathsTrace =
                                                            (O2Trace) o2RootTrace.addTrace("paths:", TraceType.O2Info);
                                                        var pathTrace =
                                                            (O2Trace) pathsTrace.addTrace("url: " + path.path);
                                                        pathTrace.addTrace("controller: " + controler.type + " <- ");
                                                        var viewTrace = pathTrace.addTrace("view: " + filteredView,
                                                                                           TraceType.O2JoinSink);

                                                        viewTrace.childTraces.AddRange(finalSinkFinding.o2Traces);
                                                        results.Add(o2Finding);
                                                    }
                                                }

                                            }


                                        /* o2Finding.addTraces(new[]
                                                                {
                                                                    filteredController, filteredView, filteredTaintSource,
                                                                    filteredFinalSink
                                                                });*/

                                    }
                                    //DI.log.info(" {0} = {1}", filteredController, filteredTaintSource);
                                    //DI.log.info("   {0} = {1}", filteredView, filteredFinalSink);
                                }
                        }
                }
            }
            findingsWith_Results = results;
            PublicDI.log.debug("mapping complete");
            //findingsViewer_FinalFindings.loadO2Findings(results, true);

        }
Exemple #16
0
        public void CreateFinding_WithTrace()
        {
            string sFileToCreate = DI.config.TempFileNameInTempDirectory;
            const uint line_number = 2;
            const uint column_number = 3;
            const uint ordinal = 1;
            const string context = "TraceContext";
            const string signature = "TraceSignature";
            const string clazz = "class.this.trace.is.in";
            const string file = @"c:\o2\temp\file\trace\is\in.cs";
            const string method = "methodExectuted";
            const uint taintPropagation = 0;
            var text = new List<string> {"this is a text inside a trace"};

            var o2Assessment = new O2Assessment();
            // Finding #1
            var o2Finding1 = new O2Finding("vulnName.Testing.TraceCreation", "vulnType.CustomType",
                                           "This is the Context",
                                           "This is the caller");
            o2Finding1.o2Traces.Add(new O2Trace
                                        {
                                            clazz = clazz,
                                            columnNumber = column_number,
                                            context = context,
                                            file = file,
                                            lineNumber = line_number,
                                            method = method,
                                            ordinal = ordinal,
                                            signature = signature,
                                            taintPropagation = taintPropagation,
                                            text = text,
                                        });
            o2Assessment.o2Findings.Add(o2Finding1);

            // Finding #1
            const string sinkText = "this is a sink";
            const string methodOnSinkPath = "method call on sink path";
            const string methodOnSourcePath = "method call on source path";
            const string sourceText = "this is a source";
            var o2Finding2 = new O2Finding("Vulnerability.Name", "Vulnerability.Type");

            var o2Trace = new O2Trace("Class.Signature", "Method executed");

            var o2TraceOnSinkPath = new O2Trace(methodOnSinkPath, TraceType.Type_0);
            o2TraceOnSinkPath.childTraces.Add(new O2Trace(sinkText, TraceType.Known_Sink));

            var o2TraceOnSourcePath = new O2Trace(methodOnSourcePath, TraceType.Type_0);
            o2TraceOnSourcePath.childTraces.Add(new O2Trace(sourceText, TraceType.Source));

            o2Trace.childTraces.Add(o2TraceOnSourcePath);

            o2Trace.childTraces.Add(o2TraceOnSinkPath);

            o2Finding2.o2Traces = new List<IO2Trace> {o2Trace};

            o2Assessment.o2Findings.Add(o2Finding2);

            // save assessment file
            o2Assessment.save(o2AssessmentSave, sFileToCreate);

            // check if data was saved correctly 
            var loadedO2Assessment = new O2Assessment(o2AssessmentLoad, sFileToCreate);

            List<IO2Finding> loadedO2Findings = loadedO2Assessment.o2Findings;
            Assert.IsTrue(loadedO2Assessment.o2Findings.Count == 2, "There should be 2 findings in the Assessment File");

            // in o2Findings1
            Assert.IsTrue(loadedO2Assessment.o2Findings[0].o2Traces.Count == 1,
                          "There should be 1 Trace in the Finding #1");

            IO2Trace loadedO2Trace = loadedO2Findings[0].o2Traces[0];
            Assert.IsTrue(loadedO2Trace.clazz == clazz, "clazz");
            Assert.IsTrue(loadedO2Trace.columnNumber == column_number, "columnNumber");
            Assert.IsTrue(loadedO2Trace.context == context, "context");
            Assert.IsTrue(loadedO2Trace.file == file, "file");
            Assert.IsTrue(loadedO2Trace.lineNumber == line_number, "lineNumber");
            Assert.IsTrue(loadedO2Trace.method == method, "method");
            Assert.IsTrue(loadedO2Trace.ordinal == ordinal, "ordinal");
            Assert.IsTrue(loadedO2Trace.signature == signature, "signature");
            Assert.IsTrue(loadedO2Trace.taintPropagation == taintPropagation, "taintPropagation");
            Assert.IsTrue(loadedO2Trace.text[0] == text[0], "text");

            // in o2Findings2
            Assert.IsTrue(loadedO2Assessment.o2Findings[1].o2Traces.Count == 1,
                          "There should be 1 Trace in the Finding #2");
            Assert.IsTrue(loadedO2Assessment.o2Findings[1].o2Traces[0].childTraces.Count == 2,
                          "There should be 2 child traces in this trace");

            Assert.IsNotNull(OzasmtUtils.getKnownSink(loadedO2Assessment.o2Findings[1].o2Traces), "Could not find Sink");
            Assert.IsTrue(OzasmtUtils.getKnownSink(loadedO2Assessment.o2Findings[1].o2Traces).clazz == sinkText,
                          "Sink text didn't match");

            Assert.IsTrue(OzasmtUtils.getSource(loadedO2Assessment.o2Findings[1].o2Traces).clazz == sourceText,
                          "Source text didn't match");
        }
Exemple #17
0
 public void FindingConstructors()
 {
     var o2Finding1 = new O2Finding();
     Assert.That(o2Finding1.vulnName == "", "vulnName was not empty");
     Assert.That(o2Finding1.vulnType == "", "vulnType was not empty");
     Assert.That(o2Finding1.context == "", "context was not empty");
     Assert.That(o2Finding1.callerName == "", "callerName was not empty");
     Assert.That(o2Finding1.exclude == false, "exclude was not false");
     var vulnName2 = "test vulnName2";
     var vulnType2 = "test vulnType2";
     var o2Finding2 = new O2Finding(vulnName2, vulnType2);
     Assert.That(o2Finding2.vulnName == vulnName2, "vulnName2 was not assigned value");
     Assert.That(o2Finding2.vulnType == vulnType2, "vulnType2 was not assigned value");
     Assert.That(o2Finding1.callerName == "", "callerName was not empty");
     Assert.That(o2Finding2.context == "", "context was not empty");
     Assert.That(o2Finding2.exclude == false, "exclude was not false");
     var vulnName3 = "test vulnName3";
     var vulnType3 = "test vulnType3";
     var context3 = "test context3";
     var callerName3 = "test vulnType3";
     var o2Finding3 = new O2Finding(vulnName3, vulnType3, context3, callerName3);
     Assert.That(o2Finding3.vulnName == vulnName3, "vulnName3 was not assigned value");
     Assert.That(o2Finding3.vulnType == vulnType3, "vulnType3 was not assigned value");
     Assert.That(o2Finding3.context == context3, "context3 was not assigned value");
     Assert.That(o2Finding3.callerName == callerName3, "callerName3 was not assigned value");
     Assert.That(o2Finding3.exclude == false, "exclude was not false");
 }
Exemple #18
0
        public void CreateFinding()
        {
            string sFileToCreate = DI.config.TempFileNameInTempDirectory;
            const string file = @"c:\O2\Temp\testFile.cs";
            const uint record_id = 1;
            const uint line_number = 2;
            const uint column_number = 3;
            const uint actionobject_id = 4;
            const byte severity = 3;
            const byte confidence = 2;
            const bool exclude = false;
            const uint ordinal = 1;
            const string context = "context";
            const string vuln_name = "vuln_name";
            const string caller_name = "caller_name";
            const string vuln_type = "vuln_type";
            const string project_name = "project_name";
            const string property_ids = "property_ids";
            var o2Assessment = new O2Assessment();
            // create test O2Finding objects
            var o2Finding1 = new O2Finding
                                 {
                                     actionObject = actionobject_id,
                                     confidence = confidence,
                                     file = file,
                                     columnNumber = column_number,
                                     exclude = exclude,
                                     lineNumber = line_number,
                                     ordinal = ordinal,
                                     recordId = record_id,
                                     severity = severity,
                                     context = context,
                                     vulnName = vuln_name,
                                     callerName = caller_name,
                                     vulnType = vuln_type,
                                     projectName = project_name,
                                     propertyIds = property_ids
                                 };
            var o2Finding2 = new O2Finding(vuln_name, vuln_type, context, caller_name);

            // add O2Findings and saved assessment run
            o2Assessment.o2Findings.Add(o2Finding1);
            o2Assessment.o2Findings.Add(o2Finding2);
            o2Assessment.save(o2AssessmentSave, sFileToCreate);

            // check that file created is ok
            var loadedO2Assessment = new O2Assessment(o2AssessmentLoad, sFileToCreate);
            Assert.IsTrue(loadedO2Assessment.o2Findings.Count == 2, "There should be 2 findings saved");
            IO2Finding loadedO2Fiding = loadedO2Assessment.o2Findings[0];
            Assert.IsTrue(loadedO2Fiding.actionObject == actionobject_id, "actionobject_id");
            Assert.IsTrue(loadedO2Fiding.confidence == confidence, "confidence");
            Assert.IsTrue(loadedO2Fiding.file == file, "file");
            Assert.IsTrue(loadedO2Fiding.columnNumber == column_number, "column_number");
            Assert.IsTrue(loadedO2Fiding.exclude == exclude, "exclude");
            Assert.IsTrue(loadedO2Fiding.lineNumber == line_number, "line_number");
            Assert.IsTrue(loadedO2Fiding.ordinal == ordinal, "ordinal");
            Assert.IsTrue(loadedO2Fiding.recordId == record_id, "record_id");
            Assert.IsTrue(loadedO2Fiding.severity == severity, "severity");
            Assert.IsTrue(loadedO2Fiding.context == context, "context");
            Assert.IsTrue(loadedO2Fiding.vulnName == vuln_name, "vuln_name");
            Assert.IsTrue(loadedO2Fiding.callerName == caller_name, "caller_name");
            Assert.IsTrue(loadedO2Fiding.vulnType == vuln_type, "vuln_type");
            Assert.IsTrue(loadedO2Fiding.projectName == project_name, "project_name");
            Assert.IsTrue(loadedO2Fiding.propertyIds == property_ids, "property_ids");
        }
Exemple #19
0
 public static void addClassAttributesToFinding(XElement xClassElement, O2Finding o2Finding)
 {
     //var pathToSource = o2Finding.getPathToSource();
     //var numberOfTraces = pathToSource.Count;
     //if (pathToSource.Count >1)
     //{
     //	var rootTrace = pathToSource[numberOfTraces-1];				
     var classAnnotations = from xelement in xClassElement.Elements("attribute").Elements("annotation") select xelement;
     if (classAnnotations.Count() > 0)
     {
         var annotationsTrace = new O2Trace("Annotations for class: " + xClassElement.Attribute("name").Value);
         o2Finding.o2Traces.Insert(0, annotationsTrace);
         foreach (var annotation in classAnnotations)
             annotationsTrace.childTraces.Add(new O2Trace(annotation.Attribute("toString").Value, TraceType.Type_4));
     }
     //}
 }
Exemple #20
0
        public static void fixExternalSourceSourceMappingProblem(O2Finding o2Finding)
        {
            try
            {
                // fix the external_source callback generated finding problem since the source should be the callback back methods and not the <external_source>(...) rule
                if (o2Finding.Source.IndexOf("<external_source>") > -1)
                {
                    o2Finding.getSource().traceType = TraceType.Root_Call;
                    o2Finding.o2Traces[0].childTraces[1].traceType = TraceType.Source;
                }

            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "in getO2Finding, while trying to fix the external_source callback generated finding problem");
            }
        }
Exemple #21
0
        public static void addCatNetResultsAsFindings(O2Assessment o2Assessment, XmlDocument catNetXml)
        {
            //var results = catNetXml.GetElementsByTagName("Resultsss");
            DI.log.info(" -------------------- ");

            foreach (XmlElement rule in catNetXml.GetElementsByTagName("Rule"))
            {
                try
                {
                    XmlElement ruleNameXmlElement = rule["Name"];
                    string ruleName = (ruleNameXmlElement == null) ? "Unknown Rule Name" : ruleNameXmlElement.InnerText;

                    foreach (XmlNode result in rule.GetElementsByTagName("Result"))
                    {
                        // ReSharper disable PossibleNullReferenceException
                        string signature = getSignatureFromEntryPoint(result["EntryPoint"].InnerText);

                        var o2Finding = new O2Finding();

                        o2Finding.context = (result["EntryPoint"] == null) ? "" : result["EntryPoint"].InnerText;
                        o2Finding.confidence = (result["ConfidenceLevel"] == null)
                                                   ? (byte) 0
                                                   : getConfidence(result["ConfidenceLevel"].InnerText);
                        o2Finding.callerName = getMethodNameFromSignature(signature);
                        o2Finding.lineNumber = (result["Transformations"] == null &&
                                                result["Transformations"]["Origin"] != null)
                                                   ? 0
                                                   : uint.Parse(
                                                         result["Transformations"]["Origin"].GetAttribute("line"));


                        o2Finding.file = (result["Transformations"] == null &&
                                          result["Transformations"]["Origin"] != null)
                                             ? ""
                                             : result["Transformations"]["Origin"].GetAttribute("file");
                        o2Finding.severity = 2;
                        o2Finding.vulnName = signature;
                        o2Finding.vulnType = ruleName;

                        //                        };

                        o2Finding.text.Add(result["Resolution"].InnerText);
                        o2Finding.text.Add(result["ProblemDescription"].InnerText);


                        addCatNetTransformationsAsO2Traces(o2Finding, result["Transformations"]);

                        // ReSharper restore PossibleNullReferenceException
                        o2Assessment.o2Findings.Add(o2Finding);
                    }
                }
                catch (Exception ex)
                {
                    DI.log.ex(ex, "in addCatNetResultsAsFindings, while processing rule: " + rule.InnerXml);
                }
            }
        }
Exemple #22
0
        public static void addMethodAttributesToFinding(XElement xMethodElement, O2Finding o2Finding)
        {
            var pathToSource = o2Finding.getPathToSource();
            var numberOfTraces = pathToSource.Count;
            if (pathToSource.Count > 1)
            {
                var rootTrace = pathToSource[numberOfTraces - 1];
                // add annotations in Method's Parameters
                var methodParametersAnnotations = from xelement in xMethodElement.Elements("methodParameterAnnotation") select xelement;
                if (methodParametersAnnotations.Count() > 0)
                {
                    var methodParametersAttributes = new O2Trace("Spring MVC - Method Parameters Attributes");
                    foreach (var annotation in methodParametersAnnotations)
                    {
                        if (annotation.Attribute("toString") == null)
                            methodParametersAttributes.childTraces.Add(new O2Trace("no attribute"));
                        else
                        {
                            //var annotationTrace1 = new O2Trace(annotation.Attribute("toString").Value, TraceType.Type_4);
                            var annotationTrace = new O2Trace(annotation.Attribute("typeName").Value, TraceType.Type_4);
                            foreach (var member in annotation.Elements("member"))
                            {
                                //annotationTrace.childTraces.Add(new O2Trace(annotation.Attribute("typeName").Value, TraceType.Type_6));
                                var memberTraceText = string.Format("{0}={1}", member.Attribute("memberName").Value, member.Attribute("memberValue").Value);
                                annotationTrace.childTraces.Add(new O2Trace(memberTraceText, TraceType.Type_6));
                            }
                            methodParametersAttributes.childTraces.Add(annotationTrace);
                        }
                    }
                    rootTrace.childTraces.Insert(0, methodParametersAttributes);
                }

                // add annotations in Method 				
                var methodAnnotations = from xelement in xMethodElement.Elements("methodAttribute").Elements("methodAnnotation") select xelement;
                if (methodAnnotations.Count() > 0)
                {
                    var methodAttributes = new O2Trace("Spring MVC - Method Attributes");
                    foreach (var annotation in methodAnnotations)
                    {
                        var annotationTrace = new O2Trace(annotation.Attribute("typeName").Value, TraceType.Type_4);
                        foreach (var member in annotation.Elements("member"))
                        {
                            var memberTraceText = string.Format("{0}={1}", member.Attribute("memberName").Value, member.Attribute("memberValue").Value);
                            annotationTrace.childTraces.Add(new O2Trace(memberTraceText, TraceType.Type_6));
                        }
                        methodAttributes.childTraces.Insert(0, annotationTrace);

                        // handle special case of org.springframework.web.bind.annotation.RequestMapping (which we want to make the source)
                        if (annotation.Attribute("typeName").Value == "org.springframework.web.bind.annotation.RequestMapping")
                        {
                            //annotationTrace.traceType = TraceType.Source;
                            o2Finding.vulnType = "O2.SpringMvc.Controller";
                            o2Finding.vulnName = o2Finding.Sink;
                        }
                    }
                    rootTrace.childTraces.Insert(0, methodAttributes);
                }

                //else
                //	log.error("There are no method Attributes for method: " + xMethodElement.ToString());

            }
        }       
        public static IO2Finding createO2FindingForXElement(XElement xElement, string currentFile)
        {

            var createFinding = false;
            var xElementSignature = xElement.Name.LocalName;
            var sourceTrace1 = new O2Trace();
            var sourceTrace2 = new O2Trace();
            foreach (var attribute in xElement.Attributes())
            {
                if (attribute.Name == "value" && attribute.Value.IndexOf("#{") > -1)
                {
                    createFinding = true;
                    sourceTrace1.signature = attribute.Value;
                    sourceTrace2.signature = getFilteredValue(attribute.Value);
                    sourceTrace2.traceType = TraceType.Source;
                    // set source file and line number
                    var attributeLineInfo = (IXmlLineInfo)attribute;
                    sourceTrace2.file = currentFile;
                    sourceTrace2.lineNumber = (uint)attributeLineInfo.LineNumber;

                }
                //
                xElementSignature += String.Format(" {0}=\"{1}\" ", attribute.Name, attribute.Value);
            }
            if (createFinding == false)
                return null;

            var newFinding = new O2Finding();
            newFinding.vulnType = "JSF.AutoMapping";
            newFinding.vulnName = xElementSignature;

            // add traces

            // root trace
            var rootTrace = new O2Trace(currentFile);
            newFinding.o2Traces.Add(rootTrace);
            // traceWithFileName
            var traceWithFileName = new O2Trace(Path.GetFileName(currentFile));
            rootTrace.childTraces.Add(traceWithFileName);
            // sourceTrace
            traceWithFileName.childTraces.Add(sourceTrace1);
            sourceTrace1.childTraces.Add(sourceTrace2);
            // traceWithNamespaceAndElementName
            var traceWithNamespaceAndElementName = new O2Trace(xElement.Name.ToString());
            sourceTrace2.childTraces.Add(traceWithNamespaceAndElementName);
            // Sink trace (with xElementSignature contents)
            var sinkTrace = new O2Trace(xElementSignature);
            sinkTrace.traceType = TraceType.Known_Sink;
            traceWithNamespaceAndElementName.childTraces.Add(sinkTrace);

            // set file and line number for sink & finding
            var elementLineInfo = (IXmlLineInfo)xElement;
            newFinding.file = sourceTrace2.file = currentFile;
            newFinding.lineNumber = sourceTrace2.lineNumber = (uint)elementLineInfo.LineNumber;
            return newFinding;
        }
 public static void showO2FindingInDataGridView(O2Finding o2Finding, DataGridView dataGridView)
 {
 }
Exemple #25
0
 public static List<IO2Trace> getListWithAllTraces(O2Finding o2Finding)
 {
     var allTraces = new List<IO2Trace>();
     try
     {
         getListWithAllTraces(o2Finding.o2Traces, allTraces);
     }
     catch (Exception ex)
     {
         DI.log.error("in getListWithAllTraces: {0}", ex.Message);
     }            
     return allTraces;
 }
        public static IO2Finding getO2Finding(AssessmentAssessmentFileFinding finding,
                                              AssessmentAssessmentFile assessmentFile, AssessmentRun assessmentRun)
        {
            var o2Finding = new O2Finding
                                {
                                    actionObject = finding.actionobject_id,
                                    columnNumber = finding.column_number,
                                    confidence = finding.confidence,
                                    exclude = finding.exclude,
                                    file = assessmentFile.filename,
                                    lineNumber = finding.line_number,
                                    ordinal = finding.ordinal,
                                    propertyIds = finding.property_ids,
                                    recordId = finding.record_id,
                                    severity = finding.severity,
                                    o2Traces = getO2TraceFromCallInvocation(finding.Trace, assessmentRun),
                                };

            if (finding.cxt_id != null)
                o2Finding.context = getStringIndexValue(UInt32.Parse(finding.cxt_id), assessmentRun);

            o2Finding.callerName = finding.caller_name;
            if (o2Finding.callerName == null && finding.caller_name_id != null)
                o2Finding.callerName = getStringIndexValue(UInt32.Parse(finding.caller_name_id), assessmentRun);

            o2Finding.projectName = finding.project_name;
            if (o2Finding.projectName == null && finding.project_name_id != null)
                o2Finding.projectName = getStringIndexValue(UInt32.Parse(finding.project_name_id), assessmentRun);

            o2Finding.vulnName = finding.vuln_name;
            if (o2Finding.vulnName == null && finding.vuln_name_id != null)
                o2Finding.vulnName = getStringIndexValue(UInt32.Parse(finding.vuln_name_id), assessmentRun);

            o2Finding.vulnType = finding.vuln_type;
            if (o2Finding.vulnType == null && finding.vuln_type_id != null)
                o2Finding.vulnType = getStringIndexValue(UInt32.Parse(finding.vuln_type_id), assessmentRun);

            if (finding.Text != null)
                o2Finding.text = new List<string>(finding.Text);

            OzasmtUtils.fixExternalSourceSourceMappingProblem(o2Finding);
            return o2Finding;
        }
        public static List<IO2Finding> loadWebInspectResultsAndReturnO2FindingsFor_SqlInjection_PoC2(
            string webInspectResultsFile)
        {
            var results = new List<IO2Finding>();
            var webInspectResults = new XmlDocument();
            webInspectResults.Load(webInspectResultsFile);
            List<XmlNode> sessionsCheckFoundWithEngineId = getSessionsCheckFoundWithEngineId(webInspectResults,
                                                                                             sqlInjectionEngineId);
            foreach (XmlNode sessionCheckFound in sessionsCheckFoundWithEngineId)
            {
                // ReSharper disable PossibleNullReferenceException
                string sessionId = sessionCheckFound["VulnerableSessionID"].InnerText;

                List<XmlNode> sessionsFoundWithSessionId = getSessionsWithSessionID(webInspectResults, sessionId);
                foreach (XmlNode session in sessionsFoundWithSessionId)
                {
                    string attackParam = session["AttackParamDescriptor"].InnerText;
                    // Hack to handle crl#: form parameter names in ASP.NET
                    if (attackParam.IndexOf(':') > -1)
                        attackParam = attackParam.Split(new[] {':'})[1];
                    string attackPayload = session["AttackDescriptor"].InnerText;

                    var filteredUrl = new FilteredUrl(session["FullURL"].InnerText);
                    foreach (var word in filteredUrl.words)
                    {
                        var sink = new O2Trace("WebInspect:   " + filteredUrl.pathAndPageAndParameters,
                                               TraceType.Known_Sink)
                                       {
                                           context = attackPayload,
                                           method = attackParam
                                       };
                        //var sink = new O2Trace("WebInspect:   " + attackParam, TraceType.Known_Sink);
                        //source.childTraces.Add(sink);
                        var o2Trace = new O2Trace("WebInspect -> Ounce Mapping (Sql Injection)");
                        //o2Trace.childTraces.Add(source);
                        o2Trace.childTraces.Add(sink);
                        //source.context = "This is the context of the Source";
                        //sink.context = attackPayload;
                        var o2Finding = new O2Finding
                                            {
                                                o2Traces = new List<IO2Trace> { o2Trace},
                                                context = attackPayload,
                                                vulnName = word + "_" + attackParam,
                                                vulnType = "Sql Injection (from WebInspect)"
                                            };
                        results.Add(o2Finding);
                    }


/*                   
                   
                   
                   
                   var o2Finding = new O2Finding
                   {
                       o2Trace = new O2Trace("WebInspect -> Ounce Mapping"),
                       context = attackDescriptor,
                       vulnName = fullURL,
                       vulnType = "WebInspect Vulnerability"
                   };
                   var source = new O2Trace(fullURL, TraceType.Source);
                   source.childTraces.Add(new O2Trace(attackDescriptor));

                   var Sink = new O2Trace(attackParamDescriptor)
                   {
                       traceType = TraceType.Known_Sink
                   };

                   source.childTraces.Add(Sink);

                   o2Finding.o2Trace.childTraces.Add(source);

                   results.Add(o2Finding);*/
                }
                // ReSharper restore PossibleNullReferenceException
            }
            return results;
        }
        public static void createFindingsFromSpringMvcMappings(bool createFindingForUsesOfModelAttribute,
                                                         bool createFindingForUsesOfGetParameter,
                                                         ascx_FindingsViewer findingsViewer,
                                                         Dictionary<SpringMvcController, TreeNode> treeNodesForloadedSpringMvcControllers, ICirData cirData) //IEnumerable<SpringMvcController> springMvcControllers)
        {
            var findingsCreated = new List<IO2Finding>();

            if (createFindingForUsesOfModelAttribute)
            {
                foreach (SpringMvcController springMvcController in treeNodesForloadedSpringMvcControllers.Keys)
                {
                    var modelAttributeParameter = SpringMvcUtils.getMethodUsedInController(springMvcController, "ModelAttribute");
                    if (modelAttributeParameter != null)
                    {
                        var findingType = "SpringMvc.Use of ModelAttribute";
                        var findingText = string.Format("{0} {1} {2}", springMvcController.HttpRequestMethod,
                                                        springMvcController.HttpRequestUrl,
                                                        springMvcController.HttpMappingParameter);
                        var o2Finding = new O2Finding(findingText, findingType)
                        {
                            file = springMvcController.FileName,
                            lineNumber = springMvcController.LineNumber
                        };
                        var rootTrace = new O2Trace(findingType);
                        var sourceTrace = new O2Trace(springMvcController.HttpRequestUrl) { traceType = TraceType.Source };
                        var modelAttribute = new O2Trace("ModelAttribute Class: " + modelAttributeParameter.className);
                        var sinkTrace = new O2Trace(springMvcController.JavaClass) { traceType = TraceType.Known_Sink };
                        var postTrace = new O2Trace(springMvcController.JavaClassAndFunction);
                        rootTrace.childTraces.Add(sourceTrace);
                        sourceTrace.childTraces.Add(modelAttribute);
                        modelAttribute.childTraces.Add(sinkTrace);
                        sinkTrace.childTraces.Add(postTrace);
                        o2Finding.o2Traces.Add(rootTrace);

                        rootTrace.file = sourceTrace.file = sinkTrace.file = o2Finding.file;
                        rootTrace.lineNumber = sourceTrace.lineNumber = sinkTrace.lineNumber = o2Finding.lineNumber;

                        findingsCreated.Add(o2Finding);
                        //tvControllers.Nodes.Add(
                        //    O2Forms.cloneTreeNode(treeNodesForloadedSpingMvcControllers[springMcvController]));
                    }
                }
            }

            if (createFindingForUsesOfGetParameter)
            {
                try
                {
                    var nodesWithGetParameter = getNodes_ThatUseGetParameter_RecursiveSearch(cirData, treeNodesForloadedSpringMvcControllers);
                    foreach (var treeNode in nodesWithGetParameter)
                    {
                        var springMvcController = (SpringMvcController)treeNode.Tag;
                        /*var o2Finding = new O2Finding(springMvcController.JavaFunction, "SpringMvc.Use of GetParameter")
                                            {
                                                file = springMvcController.FileName,
                                                lineNumber = springMvcController.LineNumber
                                            };
                        findingsCreated.Add(o2Finding);*/
                        var findingType = "SpringMvc.Use of GetParameter";
                        var findingText = string.Format("{0} {1} {2}", springMvcController.HttpRequestMethod,
                                                        springMvcController.HttpRequestUrl,
                                                        springMvcController.HttpMappingParameter);
                        var o2Finding = new O2Finding(findingText, findingType)
                        {
                            file = springMvcController.FileName,
                            lineNumber = springMvcController.LineNumber
                        };
                        var rootTrace = new O2Trace(findingType);
                        var sourceTrace = new O2Trace(springMvcController.HttpRequestUrl) { traceType = TraceType.Source };
                        var sinkTrace = new O2Trace(springMvcController.JavaClass) { traceType = TraceType.Known_Sink };
                        var postTrace = new O2Trace(springMvcController.JavaClassAndFunction);
                        rootTrace.childTraces.Add(sourceTrace);
                        sourceTrace.childTraces.Add(sinkTrace);
                        sinkTrace.childTraces.Add(postTrace);
                        o2Finding.o2Traces.Add(rootTrace);

                        rootTrace.file = sourceTrace.file = sinkTrace.file = o2Finding.file;
                        rootTrace.lineNumber = sourceTrace.lineNumber = sinkTrace.lineNumber = o2Finding.lineNumber;

                        findingsCreated.Add(o2Finding);
                    }
                }
                catch (Exception ex)
                {
                    DI.log.ex(ex, "in createFindingForUsesOfGetParameter");
                }

            }


            //            findingsCreated.Add(o2Finding);

            findingsViewer.clearO2Findings();
            findingsViewer.loadO2Findings(findingsCreated);
        }
Exemple #29
0
        public static void addCatNetTransformationsAsO2Traces(O2Finding o2Finding, XmlElement transformations)
        {
            // ReSharper disable PossibleNullReferenceException
            //var o2Trace = new O2Trace();
            //o2Finding.o2Traces.Add(o2Trace);
            foreach (XmlNode transformation in transformations.ChildNodes)
            {
                var o2Trace = new O2Trace
                                  {
                                      context =
                                          (transformation["Statement"] == null)
                                              ? ""
                                              : transformation["Statement"].InnerText,
                                      lineNumber =
                                          (transformation.Attributes["line"] == null)
                                              ? 0
                                              : uint.Parse(transformation.Attributes["line"].Value),
                                      file =
                                          (transformation.Attributes["file"] == null)
                                              ? ""
                                              : transformation.Attributes["file"].Value
                                  };

                switch (transformation.Name)
                {
                    case "Origin":
                        o2Finding.o2Traces.Add(new O2Trace
                                                   {
                                                       clazz = "Origin",
                                                       traceType = TraceType.Source,
                                                       method = transformation["StatementMethod"].InnerText,
                                                       signature = transformation["StatementMethod"].InnerText,
                                                       context = o2Trace.context,
                                                       lineNumber = o2Trace.lineNumber,
                                                       file = o2Trace.file
                                                   });
                        o2Finding.o2Traces.Add(o2Trace);
                        break;
                    case "MethodBoundary":
                    case "CallResult":
                        o2Trace.clazz = transformation.Name;
                        o2Trace.method = transformation["Method"].InnerText;
                        o2Trace.signature = o2Trace.method;
                        if (o2Finding.o2Traces.Count > 0)
                        {
                            o2Finding.o2Traces[0].childTraces.Add(o2Trace);
                            o2Trace.traceType = o2Finding.o2Traces[0].childTraces.Count ==
                                                (transformations.ChildNodes.Count - 1)
                                                    ? TraceType.Known_Sink
                                                    : TraceType.Root_Call;
                        }
                        else
                            o2Finding.o2Traces.Add(o2Trace);
                        break;
                    default:
                        break;
                }
            }
            // ReSharper restore PossibleNullReferenceException
        }
 public static void showO2FindingInDataGridView(O2Finding o2Finding, DataGridView dataGridView)
 {
 }
Exemple #31
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);
        }
        private IO2Assessment createO2AssessmentFromFindBugsObject(Xsd.BugCollection findBugsObject, String fileName)
        {
            var o2Assessment = new O2Assessment();
            o2Assessment.name = "FindBugs Import of: " + fileName;
            foreach (var bug in findBugsObject.BugInstance)
            {
                var o2Finding = new O2Finding
                                    {
                                        vulnName = bug.type,
                                        vulnType = bug.category + "." + bug.abbrev,
                                        severity = bug.priority,
                                        confidence = 2
                                    };
             //   o2Finding.text.Add(threat.Description);

                foreach (var item in bug.Items)
                {
                    var o2Trace = new O2Trace();
                    switch (item.GetType().Name)
                    {
                        case "BugCollectionBugInstanceClass":
                            var clazz = (BugCollectionBugInstanceClass) item;

                            o2Trace.signature = "Class: " + clazz.classname;
                            o2Trace.context = "Class: " + clazz.role;

                            o2Trace.file = tryToResolveFullFilePath(clazz.SourceLine.sourcepath, findBugsObject);
                            o2Trace.lineNumber = 0;
                            break;

                        case "BugCollectionBugInstanceSourceLine":
                            var sourceLine = (BugCollectionBugInstanceSourceLine)item;
                            o2Trace.signature = "SourceLine: " + sourceLine.sourcefile + "  on line " + sourceLine.start;
                            o2Trace.file = tryToResolveFullFilePath(sourceLine.sourcepath , findBugsObject);
                            o2Trace.lineNumber = sourceLine.start;
                            break;

                        case "BugCollectionBugInstanceMethod":
                            var method = (BugCollectionBugInstanceMethod)item;
                            o2Trace.signature = "Method:  + " + method.signature;
                            o2Trace.file = tryToResolveFullFilePath(method.SourceLine.sourcepath, findBugsObject);
                            o2Trace.lineNumber = method.SourceLine.start;
                            break;

                        case "BugCollectionBugInstanceClassSourceLine":
                            o2Trace.signature = "ClassSourceLine";
                            break;
                        case "BugCollectionBugInstanceField":
                            o2Trace.signature = "Field";
                            break;
                        case "BugCollectionBugInstanceFieldSourceLine":
                            o2Trace.signature = "FieldSourceLine";
                            break;
                        case "BugCollectionBugInstanceMethodSourceLine":
                            o2Trace.signature = "MethodSourceLine";
                            break;
                        case "BugCollectionBugInstanceInt":
                            o2Trace.signature = "Int";
                            break;
                        case "BugCollectionBugInstanceLocalVariable":
                            o2Trace.signature = "LocalVariable";
                            break;
                        case "BugCollectionBugInstanceString":
                            o2Trace.signature = "String";
                            break;
                        case "BugCollectionBugInstanceProperty":
                            o2Trace.signature = "Property";
                            break;
                        case "BugCollectionBugInstanceType":
                            o2Trace.signature = "Type";
                            break;
                        case "BugCollectionBugInstanceTypeSourceLine":
                            o2Trace.signature = "TypeSourceLine";
                            break;
                        case "Object":          // ignore it
                            break;
                        default:
                            o2Trace.signature = item.GetType().Name;

                            break;
                    }
                    o2Finding.o2Traces.Add(o2Trace);
                }
                o2Assessment.o2Findings.Add(o2Finding);
            }
            return o2Assessment;
        }
Exemple #33
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;
 }
        private IO2Assessment createO2AssessmentFromCodeCrawlerObject(taintResultSet appScanDEResultsFile, String fileName)
        {
            var o2Assessment = new O2Assessment();
            o2Assessment.name = "AppScan Import of: " + fileName;
            var o2Findings = new List<IO2Finding>();
            foreach (taintResultSetTaintResult resultSet in appScanDEResultsFile.TaintResult)
            {
                //log.info(" id: {0} {1} {2}", resultSet.id, resultSet.issueID, resultSet.userSeverity);
                var o2Finding = new O2Finding();
                o2Finding.vulnName = resultSet.issueID;
                o2Finding.vulnType = resultSet.issueID;
                //o2Finding.severity = resultSet.userSeverity;
                var sourceNode = new O2Trace(resultSet.taintSource.className + "." + resultSet.taintSource.methodName + resultSet.taintSource.methodSignature);
                sourceNode.traceType = TraceType.Source;
                //sourceNode.file = resultSet.taintSource.fileName;
                var lastNode = sourceNode;
                foreach (var taintStep in resultSet.taintStep)
                {
                    var stepNode = new O2Trace(taintStep.className + "." + taintStep.methodName + taintStep.methodSignature);

                    // set filename and line number for step trace:
                    stepNode.file = taintStep.fileName;
                    stepNode.lineNumber = taintStep.highlight.lineNumber;
                    if (taintStep.snippetText != null)
                    {
                        var splittedText = taintStep.snippetText.Split(new[] { '\n' });
                        var lineIndex = taintStep.highlight.lineNumber - taintStep.snippetStartLine;
                        if (taintStep.snippetText != "")
                        {
                            stepNode.context = (lineIndex > -1) ? splittedText[lineIndex - 1] : taintStep.snippetText;
                            stepNode.context = "> " + stepNode.context.Replace("\t", " ").Trim() + "                                                      \n\n  --------  \n\n" + taintStep.snippetText;
                        }
                    }
                    // make the finding have the values of the last taitstep
                    o2Finding.file = taintStep.fileName;
                    o2Finding.lineNumber = taintStep.highlight.lineNumber;

                    // set childnodes
                    lastNode.childTraces.Add(stepNode);
                    lastNode = stepNode;
                }

                var sinkNode = new O2Trace(resultSet.taintSink.className + "." + resultSet.taintSink.methodName + resultSet.taintSink.methodSignature);
                sinkNode.traceType = TraceType.Known_Sink;
                //sinkNode.file = resultSet.taintSink.fileName;

                lastNode.childTraces.Add(sinkNode);

                o2Finding.o2Traces.Add(sourceNode);
                o2Findings.Add(o2Finding);

                o2Assessment.o2Findings.Add(o2Finding);
            }
            return o2Assessment;
        }
Exemple #35
0
    	public static List<IO2Finding> calculate_Url_to_EntryMethod_Mappings(string pathWithSourceFiles, string urlBase, string port, ProgressBar progressBar)
    	{
    		var o2Findings = new List<IO2Finding>();
			var filesToAnalyze = pathWithSourceFiles.files("*.cs",true);
			progressBar.maximum(filesToAnalyze.size());
			foreach(var file in filesToAnalyze)
			{	
					"Processing file:{0}".info(file);
				var url = urlBase.format(port, file.replace(pathWithSourceFiles,"").replace(".ascx.cs",""));
				
				foreach(var type in file.csharpAst().types(true))
					foreach(var baseType in type.BaseTypes)			
						if (baseType.str() == "System.Web.UI.UserControl")				
						{
							var astData = new O2MappedAstData();
							astData.loadFile(file);
							foreach(var iMethod in astData.iMethods())
							{
								var o2Finding = new O2Finding();
								o2Finding.vulnName = url;
								o2Finding.vulnType = "Web EntryPoint";
								var source = new O2Trace(url);
								var sink = new O2Trace(iMethod.fullName());
								source.traceType = TraceType.Source;
								sink.traceType = TraceType.Known_Sink;					
								source.childTraces.Add(sink);
								o2Finding.o2Traces.Add(source);					
								o2Findings.Add(o2Finding);
							}									
						}	
				progressBar.increment(1);				
			}		
			return o2Findings;
    	}