Exemplo n.º 1
0
        /// <summary>
        /// Parses a "location" node from the supplied instance of <see cref="XmlReader"/>.
        /// </summary>
        /// <exception cref="XmlException">Thrown if <paramref name="reader"/> points to XML of an
        /// incorrect format.</exception>
        /// <param name="reader">The reader from which XML will be parsed. Upon entry to this method, this
        /// XML reader must be positioned on the location node to parse. Upon completion of this method,
        /// the reader will be positioned on the node following the location node.</param>
        /// <param name="strings">Strings used to parse the CppCheck log.</param>
        /// <returns>
        /// A <see cref="CppCheckLocation"/> instance containing data from the current node of
        /// <paramref name="reader"/>.
        /// </returns>
        public static CppCheckLocation Parse(XmlReader reader, CppCheckStrings strings)
        {
            if (!reader.IsStartElement(strings.Location))
            {
                throw reader.CreateException(ConverterResources.CppCheckLocationElementNameIncorrect);
            }

            string file     = null;
            string lineText = null;

            while (reader.MoveToNextAttribute())
            {
                string name = reader.LocalName;
                if (StringReference.AreEqual(name, strings.File))
                {
                    file = reader.Value;
                }
                else if (StringReference.AreEqual(name, strings.Line))
                {
                    lineText = reader.Value;
                }
            }

            if (file == null)
            {
                throw reader.CreateException(ConverterResources.CppCheckLocationMissingName);
            }

            if (lineText == null)
            {
                throw reader.CreateException(ConverterResources.CppCheckLocationMissingLine);
            }

            int line = XmlConvert.ToInt32(lineText);

            reader.MoveToElement();
            reader.Skip();

            return(new CppCheckLocation(file, line));
        }
Exemplo n.º 2
0
 private bool AtEndOf(string elementName)
 {
     return(_reader.EOF ||
            (_reader.NodeType == XmlNodeType.EndElement && StringReference.AreEqual(_reader.LocalName, elementName)));
 }
Exemplo n.º 3
0
 private bool AtStartOf(string elementName)
 {
     return(!_reader.EOF &&
            (_reader.NodeType == XmlNodeType.Element && StringReference.AreEqual(_reader.LocalName, elementName)));
 }
Exemplo n.º 4
0
 // Same as XmlReader.IsStartElement except does not call MoveToContent first.
 private static bool IsOnElement(XmlReader xmlReader, string elementName)
 {
     return(xmlReader.NodeType == XmlNodeType.Element && StringReference.AreEqual(xmlReader.LocalName, elementName));
 }
Exemplo n.º 5
0
        private void ProcessCppCheckLog(XmlReader reader, IResultLogWriter output, OptionallyEmittedData dataToInsert)
        {
            reader.ReadStartElement(_strings.Results);

            if (!StringReference.AreEqual(reader.LocalName, _strings.CppCheck))
            {
                throw reader.CreateException(ConverterResources.CppCheckCppCheckElementMissing);
            }

            string version = reader.GetAttribute(_strings.Version);

            if (version != null && !version.IsSemanticVersioningCompatible())
            {
                // This logic only fixes up simple cases, such as being passed
                // 1.66, where Semantic Versioning 2.0 requires 1.66.0. Also
                // strips Revision member if passed a complete .NET version.
                Version dotNetVersion;
                if (Version.TryParse(version, out dotNetVersion))
                {
                    version =
                        Math.Max(0, dotNetVersion.Major) + "." +
                        Math.Max(0, dotNetVersion.Minor) + "." +
                        Math.Max(0, dotNetVersion.Build);
                }
            }

            if (String.IsNullOrWhiteSpace(version))
            {
                throw reader.CreateException(ConverterResources.CppCheckCppCheckElementMissing);
            }

            reader.Skip(); // <cppcheck />

            if (!StringReference.AreEqual(reader.LocalName, _strings.Errors))
            {
                throw reader.CreateException(ConverterResources.CppCheckErrorsElementMissing);
            }

            var results = new List <Result>();

            if (reader.IsEmptyElement)
            {
                reader.Skip(); // <errors />
            }
            else
            {
                int errorsDepth = reader.Depth;
                reader.Read(); // <errors>

                while (reader.Depth > errorsDepth)
                {
                    var parsedError = CppCheckError.Parse(reader, _strings);
                    results.Add(parsedError.ToSarifIssue());
                }

                reader.ReadEndElement(); // </errors>
            }

            reader.ReadEndElement(); // </results>

            var tool = new Tool
            {
                Name    = "CppCheck",
                Version = version,
            };

            var fileInfoFactory = new FileInfoFactory(uri => MimeType.Cpp, dataToInsert);
            Dictionary <string, FileData> fileDictionary = fileInfoFactory.Create(results);

            var run = new Run()
            {
                Tool = tool
            };

            output.Initialize(run);

            if (fileDictionary != null && fileDictionary.Count > 0)
            {
                output.WriteFiles(fileDictionary);
            }

            output.OpenResults();
            output.WriteResults(results);
            output.CloseResults();
        }
Exemplo n.º 6
0
        private void ProcessCppCheckLog(XmlReader reader, IResultLogWriter output, OptionallyEmittedData dataToInsert)
        {
            reader.ReadStartElement(_strings.Results);

            if (!StringReference.AreEqual(reader.LocalName, _strings.CppCheck))
            {
                throw reader.CreateException(ConverterResources.CppCheckCppCheckElementMissing);
            }

            string version = reader.GetAttribute(_strings.Version);

            if (version != null && !version.IsSemanticVersioningCompatible())
            {
                // This logic only fixes up simple cases, such as being passed
                // 1.66, where Semantic Versioning 2.0 requires 1.66.0. Also
                // strips Revision member if passed a complete .NET version.
                Version dotNetVersion;
                if (Version.TryParse(version, out dotNetVersion))
                {
                    version =
                        Math.Max(0, dotNetVersion.Major) + "." +
                        Math.Max(0, dotNetVersion.Minor) + "." +
                        Math.Max(0, dotNetVersion.Build);
                }
            }

            if (string.IsNullOrWhiteSpace(version))
            {
                throw reader.CreateException(ConverterResources.CppCheckCppCheckElementMissing);
            }

            reader.Skip(); // <cppcheck />

            if (!StringReference.AreEqual(reader.LocalName, _strings.Errors))
            {
                throw reader.CreateException(ConverterResources.CppCheckErrorsElementMissing);
            }

            var results = new List <Result>();

            if (reader.IsEmptyElement)
            {
                reader.Skip(); // <errors />
            }
            else
            {
                int errorsDepth = reader.Depth;
                reader.Read(); // <errors>

                while (reader.Depth > errorsDepth)
                {
                    var parsedError = CppCheckError.Parse(reader, _strings);
                    results.Add(parsedError.ToSarifIssue());
                }

                reader.ReadEndElement(); // </errors>
            }

            reader.ReadEndElement(); // </results>

            var run = new Run()
            {
                Tool = new Tool {
                    Driver = new ToolComponent {
                        Name = ToolName, Version = version
                    }
                },
            };

            PersistResults(output, results, run);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Parses a Fortify Result element from an <see cref="XmlReader"/>.
        /// </summary>
        /// <param name="xmlReader">The <see cref="XmlReader"/> from which an element containing a Fortify result shall be
        /// consumed. When this method returns, this <see cref="XmlReader"/> is positioned on the following element.</param>
        /// <param name="strings">Strings used in processing a Fortify report.</param>
        /// <returns>A <see cref="FortifyIssue"/> containing data from the node on which <paramref name="xmlReader"/> was
        /// placed when this method was called.</returns>
        public static FortifyIssue Parse(XmlReader xmlReader, FortifyStrings strings)
        {
            //<xs:element name="Result">
            //    <xs:complexType>
            //        <xs:sequence>
            //            <!-- Result Description -->
            //            <xs:element name="Category" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //            <xs:element name="Folder" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //            <xs:element name="Kingdom" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //            <xs:element name="Abstract" type="xs:string" minOccurs="0" maxOccurs="1"/>
            //            <xs:element name="AbstractCustom" type="xs:string" minOccurs="0" maxOccurs="1"/>
            //            <xs:element name="Friority" type="xs:string" minOccurs="0" maxOccurs="1"/>
            //            <!-- custom tags including Analysis -->
            //            <xs:element name="Tag" minOccurs="0" maxOccurs="unbounded">
            //                <xs:complexType>
            //                    <xs:sequence>
            //                        <xs:element name="Name" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //                        <xs:element name="Value" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //                    </xs:sequence>
            //                </xs:complexType>
            //            </xs:element>
            //            <xs:element name="Comment" minOccurs="0" maxOccurs="unbounded">
            //                <xs:complexType>
            //                    <xs:sequence>
            //                        <xs:element name="UserInfo" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //                        <xs:element name="Comment" type="xs:string" minOccurs="1" maxOccurs="1"/>
            //                    </xs:sequence>
            //                </xs:complexType>
            //            </xs:element>
            //            <!-- primary or sink -->
            //            <xs:element name="Primary" type="PathElement" minOccurs="1" maxOccurs="1"/>
            //            <!-- source -->
            //            <xs:element name="Source" type="PathElement" minOccurs="0" maxOccurs="1"/>
            //            <xs:element name="TraceDiagramPath" type="xs:string" minOccurs="0" maxOccurs="1"/>
            //            <!-- optional external category (i.e. STIG) -->
            //            <xs:element name="ExternalCategory" minOccurs="0" maxOccurs="1">
            //                <xs:complexType>
            //                    <xs:simpleContent>
            //                        <xs:extension base="xs:string">
            //                            <xs:attribute name="type" type="xs:string" use="required"/>
            //                        </xs:extension>
            //                    </xs:simpleContent>
            //                </xs:complexType>
            //            </xs:element>
            //        </xs:sequence>
            //        <xs:attribute name="iid" type="xs:string" use="optional"/>
            //        <xs:attribute name="ruleID" type="xs:string" use="optional"/>
            //    </xs:complexType>
            //</xs:element>
            if (!xmlReader.IsStartElement(strings.Issue))
            {
                throw xmlReader.CreateException(ConverterResources.FortifyNotValidResult);
            }

            string iid    = null;
            string ruleId = null;

            while (xmlReader.MoveToNextAttribute())
            {
                string name = xmlReader.LocalName;
                if (StringReference.AreEqual(name, strings.Iid))
                {
                    iid = xmlReader.Value;
                }
                else if (StringReference.AreEqual(name, strings.RuleId))
                {
                    ruleId = xmlReader.Value;
                }
            }

            xmlReader.MoveToElement();
            xmlReader.Read(); // reads start element

            string category = xmlReader.ReadElementContentAsString(strings.Category, String.Empty);

            xmlReader.IgnoreElement(strings.Folder, IgnoreOptions.Required);
            string kingdom        = xmlReader.ReadElementContentAsString(strings.Kingdom, String.Empty);
            string abstract_      = xmlReader.ReadOptionalElementContentAsString(strings.Abstract);
            string abstractCustom = xmlReader.ReadOptionalElementContentAsString(strings.AbstractCustom);
            string friority       = xmlReader.ReadOptionalElementContentAsString(strings.Friority);

            xmlReader.IgnoreElement(strings.Tag, IgnoreOptions.Optional | IgnoreOptions.Multiple);
            xmlReader.IgnoreElement(strings.Comment, IgnoreOptions.Optional | IgnoreOptions.Multiple);
            FortifyPathElement primary = FortifyPathElement.Parse(xmlReader, strings);
            FortifyPathElement source;

            if (xmlReader.NodeType == XmlNodeType.Element && StringReference.AreEqual(xmlReader.LocalName, strings.Source))
            {
                source = FortifyPathElement.Parse(xmlReader, strings);
            }
            else
            {
                source = null;
            }

            xmlReader.IgnoreElement(strings.TraceDiagramPath, IgnoreOptions.Optional);
            ImmutableArray <int> cweIds = ImmutableArray <int> .Empty;

            if (xmlReader.NodeType == XmlNodeType.Element && StringReference.AreEqual(xmlReader.LocalName, strings.ExternalCategory))
            {
                if (xmlReader.GetAttribute(strings.Type) == "CWE")
                {
                    cweIds = ParseCweIds(xmlReader.ReadElementContentAsString());
                }
                else
                {
                    xmlReader.Skip();
                }
            }

            xmlReader.ReadEndElement(); // </Result>

            return(new FortifyIssue(ruleId, iid, category, kingdom, abstract_, abstractCustom, friority, primary, source, cweIds));
        }
Exemplo n.º 8
0
        /// <summary>Parses a "problem" node from an Android Studio log and consumes that node.</summary>
        /// <exception cref="XmlException">Thrown when the Android Studio file is incorrect.</exception>
        /// <param name="reader">The reader from which the problem shall be parsed.</param>
        /// <param name="strings">NameTable strings used to parse Android Studio files.</param>
        /// <returns>
        /// If the problem node is not empty, an instance of <see cref="AndroidStudioProblem" />;
        /// otherwise, null.
        /// </returns>
        public static AndroidStudioProblem Parse(XmlReader reader, AndroidStudioStrings strings)
        {
            if (!reader.IsStartElement(strings.Problem))
            {
                throw reader.CreateException(ConverterResources.AndroidStudioNotProblemElement);
            }

            Builder b = new Builder();

            if (!reader.IsEmptyElement)
            {
                int problemDepth = reader.Depth;
                reader.Read(); // Get to children
                while (reader.Depth > problemDepth)
                {
                    string nodeName = reader.LocalName;
                    if (StringReference.AreEqual(nodeName, strings.File))
                    {
                        b.File = reader.ReadElementContentAsString();
                    }
                    else if (StringReference.AreEqual(nodeName, strings.Line))
                    {
                        b.Line = Math.Max(1, reader.ReadElementContentAsInt());
                    }
                    else if (StringReference.AreEqual(nodeName, strings.Module))
                    {
                        b.Module = reader.ReadElementContentAsString();
                    }
                    else if (StringReference.AreEqual(nodeName, strings.Package))
                    {
                        b.Package = reader.ReadElementContentAsString();
                    }
                    else if (StringReference.AreEqual(nodeName, strings.EntryPoint))
                    {
                        ReadEntryPointElement(ref b, reader, strings);
                    }
                    else if (StringReference.AreEqual(nodeName, strings.ProblemClass))
                    {
                        ReadProblemClassElement(ref b, reader, strings);
                    }
                    else if (StringReference.AreEqual(nodeName, strings.Hints))
                    {
                        b.Hints = ReadHints(reader, strings);
                    }
                    else if (StringReference.AreEqual(nodeName, strings.Description))
                    {
                        b.Description = reader.ReadElementContentAsString();
                    }
                    else
                    {
                        reader.Skip();
                    }
                }
            }

            reader.Read(); // Consume the empty / end element

            if (b.IsEmpty)
            {
                return(null);
            }

            try
            {
                return(new AndroidStudioProblem(b));
            }
            catch (ArgumentException invalidData)
            {
                throw reader.CreateException(invalidData.Message);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Interface implementation for converting a stream of Fortify report in XML format to a
        /// SARIF json format stream.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <param name="input">Stream of the Fortify report.</param>
        /// <param name="output">Stream of SARIF json.</param>
        /// <param name="dataToInsert">Optionally emitted properties that should be written to log.</param>
        public override void Convert(Stream input, IResultLogWriter output, OptionallyEmittedData dataToInsert)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

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

            var settings = new XmlReaderSettings
            {
                DtdProcessing    = DtdProcessing.Ignore,
                IgnoreWhitespace = true,
                NameTable        = _nameTable,
                XmlResolver      = null
            };

            string runDescription = null;
            var    results        = new List <Result>();

            using (XmlReader reader = XmlReader.Create(input, settings))
            {
                while (reader.Read())
                {
                    if (runDescription == null)
                    {
                        // Find the executive summary <ReportSection> element
                        if (StringReference.AreEqual(reader.LocalName, _strings.ReportSection) && reader.IsStartElement())
                        {
                            reader.Read(); // Move to Title element

                            if (reader.ReadElementContentAsString(_strings.Title, String.Empty) == "Executive Summary")
                            {
                                reader.Read(); // Move to SubSection element
                                reader.IgnoreElement(_strings.Title, IgnoreOptions.Required);
                                reader.IgnoreElement(_strings.Description, IgnoreOptions.Required);
                                runDescription = reader.ReadElementContentAsString(_strings.Text, String.Empty);
                            }
                        }
                    }
                    else
                    {
                        while (StringReference.AreEqual(reader.LocalName, _strings.Issue))
                        {
                            FortifyIssue fortify = FortifyIssue.Parse(reader, _strings);
                            results.Add(ConvertFortifyIssueToSarifIssue(fortify));
                        }
                    }
                }
            }

            var tool = new Tool
            {
                Name = "Fortify"
            };

            var fileInfoFactory = new FileInfoFactory(MimeType.DetermineFromFileExtension, dataToInsert);
            Dictionary <string, FileData> fileDictionary = fileInfoFactory.Create(results);

            var run = new Run()
            {
                Description = new Message
                {
                    Text = runDescription
                },
                Tool = tool
            };

            output.Initialize(run);

            if (fileDictionary != null && fileDictionary.Count > 0)
            {
                output.WriteFiles(fileDictionary);
            }

            output.OpenResults();
            output.WriteResults(results);
            output.CloseResults();
        }
Exemplo n.º 10
0
        /// <summary>
        /// Interface implementation for converting a stream of Fortify report in XML format to a
        /// SARIF json format stream.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception>
        /// <param name="input">Stream of the Fortify report.</param>
        /// <param name="output">Stream of SARIF json.</param>
        /// <param name="dataToInsert">Optionally emitted properties that should be written to log.</param>
        public override void Convert(Stream input, IResultLogWriter output, OptionallyEmittedData dataToInsert)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

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

            var settings = new XmlReaderSettings
            {
                DtdProcessing    = DtdProcessing.Ignore,
                IgnoreWhitespace = true,
                NameTable        = _nameTable,
                XmlResolver      = null
            };

            string runDescription = null;
            var    results        = new List <Result>();

            using (XmlReader reader = XmlReader.Create(input, settings))
            {
                while (reader.Read())
                {
                    if (runDescription == null)
                    {
                        // Find the executive summary <ReportSection> element
                        if (StringReference.AreEqual(reader.LocalName, _strings.ReportSection) && reader.IsStartElement())
                        {
                            reader.Read(); // Move to Title element

                            if (reader.ReadElementContentAsString(_strings.Title, String.Empty) == "Executive Summary")
                            {
                                reader.Read(); // Move to SubSection element
                                reader.IgnoreElement(_strings.Title, IgnoreOptions.Required);
                                reader.IgnoreElement(_strings.Description, IgnoreOptions.Required);
                                runDescription = reader.ReadElementContentAsString(_strings.Text, String.Empty);
                            }
                        }
                    }
                    else
                    {
                        while (StringReference.AreEqual(reader.LocalName, _strings.Issue))
                        {
                            FortifyIssue fortify = FortifyIssue.Parse(reader, _strings);
                            results.Add(ConvertFortifyIssueToSarifIssue(fortify));
                        }
                    }
                }
            }

            var run = new Run()
            {
                AutomationDetails = new RunAutomationDetails
                {
                    Description = new Message
                    {
                        Text = runDescription
                    }
                },
                Tool = new Tool {
                    Driver = new ToolComponent {
                        Name = ToolName
                    }
                }
            };

            PersistResults(output, results, run);
        }