Coverage Report - org.owasp.dependencycheck.analyzer.AssemblyAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
AssemblyAnalyzer
67%
85/126
50%
25/50
6.875
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.analyzer;
 19  
 
 20  
 import java.io.BufferedReader;
 21  
 import java.io.File;
 22  
 import java.io.FileFilter;
 23  
 import java.io.FileOutputStream;
 24  
 import java.io.IOException;
 25  
 import java.io.InputStream;
 26  
 import java.io.InputStreamReader;
 27  
 import org.owasp.dependencycheck.Engine;
 28  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 29  
 import org.owasp.dependencycheck.dependency.Confidence;
 30  
 import org.owasp.dependencycheck.dependency.Dependency;
 31  
 import org.owasp.dependencycheck.dependency.Evidence;
 32  
 import org.owasp.dependencycheck.utils.FileFilterBuilder;
 33  
 import org.owasp.dependencycheck.utils.Settings;
 34  
 import org.slf4j.Logger;
 35  
 import org.slf4j.LoggerFactory;
 36  
 import org.w3c.dom.Document;
 37  
 import org.xml.sax.SAXException;
 38  
 
 39  
 import javax.xml.parsers.DocumentBuilder;
 40  
 import javax.xml.parsers.DocumentBuilderFactory;
 41  
 import javax.xml.xpath.XPath;
 42  
 import javax.xml.xpath.XPathExpressionException;
 43  
 import javax.xml.xpath.XPathFactory;
 44  
 import java.util.ArrayList;
 45  
 import java.util.List;
 46  
 
 47  
 /**
 48  
  * Analyzer for getting company, product, and version information from a .NET assembly.
 49  
  *
 50  
  * @author colezlaw
 51  
  *
 52  
  */
 53  9
 public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
 54  
 
 55  
     /**
 56  
      * The analyzer name
 57  
      */
 58  
     private static final String ANALYZER_NAME = "Assembly Analyzer";
 59  
     /**
 60  
      * The analysis phase
 61  
      */
 62  1
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION;
 63  
     /**
 64  
      * The list of supported extensions
 65  
      */
 66  1
     private static final String[] SUPPORTED_EXTENSIONS = {"dll", "exe"};
 67  
     /**
 68  
      * The temp value for GrokAssembly.exe
 69  
      */
 70  9
     private File grokAssemblyExe = null;
 71  
     /**
 72  
      * The DocumentBuilder for parsing the XML
 73  
      */
 74  
     private DocumentBuilder builder;
 75  
     /**
 76  
      * Logger
 77  
      */
 78  1
     private static final Logger LOGGER = LoggerFactory.getLogger(AssemblyAnalyzer.class);
 79  
 
 80  
     /**
 81  
      * Builds the beginnings of a List for ProcessBuilder
 82  
      *
 83  
      * @return the list of arguments to begin populating the ProcessBuilder
 84  
      */
 85  
     private List<String> buildArgumentList() {
 86  
         // Use file.separator as a wild guess as to whether this is Windows
 87  8
         final List<String> args = new ArrayList<String>();
 88  8
         if (!"\\".equals(System.getProperty("file.separator"))) {
 89  0
             if (Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) {
 90  0
                 args.add(Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH));
 91  
             } else {
 92  0
                 args.add("mono");
 93  
             }
 94  
         }
 95  8
         args.add(grokAssemblyExe.getPath());
 96  
 
 97  8
         return args;
 98  
     }
 99  
 
 100  
     /**
 101  
      * Performs the analysis on a single Dependency.
 102  
      *
 103  
      * @param dependency the dependency to analyze
 104  
      * @param engine the engine to perform the analysis under
 105  
      * @throws AnalysisException if anything goes sideways
 106  
      */
 107  
     @Override
 108  
     public void analyzeFileType(Dependency dependency, Engine engine)
 109  
             throws AnalysisException {
 110  3
         if (grokAssemblyExe == null) {
 111  0
             LOGGER.warn("GrokAssembly didn't get deployed");
 112  0
             return;
 113  
         }
 114  
 
 115  3
         final List<String> args = buildArgumentList();
 116  3
         args.add(dependency.getActualFilePath());
 117  3
         final ProcessBuilder pb = new ProcessBuilder(args);
 118  3
         BufferedReader rdr = null;
 119  3
         Document doc = null;
 120  
         try {
 121  3
             final Process proc = pb.start();
 122  
             // Try evacuating the error stream
 123  3
             rdr = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "UTF-8"));
 124  3
             String line = null;
 125  
             // CHECKSTYLE:OFF
 126  3
             while (rdr.ready() && (line = rdr.readLine()) != null) {
 127  0
                 LOGGER.warn("Error from GrokAssembly: {}", line);
 128  
             }
 129  
             // CHECKSTYLE:ON
 130  3
             int rc = 0;
 131  3
             doc = builder.parse(proc.getInputStream());
 132  
 
 133  
             try {
 134  3
                 rc = proc.waitFor();
 135  0
             } catch (InterruptedException ie) {
 136  
                 return;
 137  3
             }
 138  3
             if (rc == 3) {
 139  0
                 LOGGER.debug("{} is not a .NET assembly or executable and as such cannot be analyzed by dependency-check",
 140  
                         dependency.getActualFilePath());
 141  
                 return;
 142  3
             } else if (rc != 0) {
 143  1
                 LOGGER.warn("Return code {} from GrokAssembly", rc);
 144  
             }
 145  
 
 146  3
             final XPath xpath = XPathFactory.newInstance().newXPath();
 147  
 
 148  
             // First, see if there was an error
 149  3
             final String error = xpath.evaluate("/assembly/error", doc);
 150  3
             if (error != null && !error.isEmpty()) {
 151  1
                 throw new AnalysisException(error);
 152  
             }
 153  
 
 154  2
             final String version = xpath.evaluate("/assembly/version", doc);
 155  2
             if (version != null) {
 156  2
                 dependency.getVersionEvidence().addEvidence(new Evidence("grokassembly", "version",
 157  
                         version, Confidence.HIGHEST));
 158  
             }
 159  
 
 160  2
             final String vendor = xpath.evaluate("/assembly/company", doc);
 161  2
             if (vendor != null) {
 162  2
                 dependency.getVendorEvidence().addEvidence(new Evidence("grokassembly", "vendor",
 163  
                         vendor, Confidence.HIGH));
 164  
             }
 165  
 
 166  2
             final String product = xpath.evaluate("/assembly/product", doc);
 167  2
             if (product != null) {
 168  2
                 dependency.getProductEvidence().addEvidence(new Evidence("grokassembly", "product",
 169  
                         product, Confidence.HIGH));
 170  
             }
 171  
 
 172  0
         } catch (IOException ioe) {
 173  0
             throw new AnalysisException(ioe);
 174  0
         } catch (SAXException saxe) {
 175  0
             throw new AnalysisException("Couldn't parse GrokAssembly result", saxe);
 176  0
         } catch (XPathExpressionException xpe) {
 177  
             // This shouldn't happen
 178  0
             throw new AnalysisException(xpe);
 179  
         } finally {
 180  3
             if (rdr != null) {
 181  
                 try {
 182  3
                     rdr.close();
 183  0
                 } catch (IOException ex) {
 184  0
                     LOGGER.debug("ignore", ex);
 185  4
                 }
 186  
             }
 187  
         }
 188  2
     }
 189  
 
 190  
     /**
 191  
      * Initialize the analyzer. In this case, extract GrokAssembly.exe to a temporary location.
 192  
      *
 193  
      * @throws Exception if anything goes wrong
 194  
      */
 195  
     @Override
 196  
     public void initializeFileTypeAnalyzer() throws Exception {
 197  5
         final File tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory());
 198  5
         FileOutputStream fos = null;
 199  5
         InputStream is = null;
 200  
         try {
 201  5
             fos = new FileOutputStream(tempFile);
 202  5
             is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe");
 203  5
             final byte[] buff = new byte[4096];
 204  5
             int bread = -1;
 205  15
             while ((bread = is.read(buff)) >= 0) {
 206  10
                 fos.write(buff, 0, bread);
 207  
             }
 208  5
             grokAssemblyExe = tempFile;
 209  
             // Set the temp file to get deleted when we're done
 210  5
             grokAssemblyExe.deleteOnExit();
 211  5
             LOGGER.debug("Extracted GrokAssembly.exe to {}", grokAssemblyExe.getPath());
 212  0
         } catch (IOException ioe) {
 213  0
             this.setEnabled(false);
 214  0
             LOGGER.warn("Could not extract GrokAssembly.exe: {}", ioe.getMessage());
 215  0
             throw new AnalysisException("Could not extract GrokAssembly.exe", ioe);
 216  
         } finally {
 217  5
             if (fos != null) {
 218  
                 try {
 219  5
                     fos.close();
 220  0
                 } catch (Throwable e) {
 221  0
                     LOGGER.debug("Error closing output stream");
 222  5
                 }
 223  
             }
 224  5
             if (is != null) {
 225  
                 try {
 226  5
                     is.close();
 227  0
                 } catch (Throwable e) {
 228  0
                     LOGGER.debug("Error closing input stream");
 229  5
                 }
 230  
             }
 231  
         }
 232  
 
 233  
         // Now, need to see if GrokAssembly actually runs from this location.
 234  5
         final List<String> args = buildArgumentList();
 235  5
         BufferedReader rdr = null;
 236  
         try {
 237  5
             final ProcessBuilder pb = new ProcessBuilder(args);
 238  5
             final Process p = pb.start();
 239  
             // Try evacuating the error stream
 240  5
             rdr = new BufferedReader(new InputStreamReader(p.getErrorStream(), "UTF-8"));
 241  
             // CHECKSTYLE:OFF
 242  5
             while (rdr.ready() && rdr.readLine() != null) {
 243  
                 // We expect this to complain
 244  
             }
 245  
             // CHECKSTYLE:ON
 246  5
             final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(p.getInputStream());
 247  5
             final XPath xpath = XPathFactory.newInstance().newXPath();
 248  5
             final String error = xpath.evaluate("/assembly/error", doc);
 249  5
             if (p.waitFor() != 1 || error == null || error.isEmpty()) {
 250  0
                 LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
 251  0
                 LOGGER.debug("GrokAssembly.exe is not working properly");
 252  0
                 grokAssemblyExe = null;
 253  0
                 this.setEnabled(false);
 254  0
                 throw new AnalysisException("Could not execute .NET AssemblyAnalyzer");
 255  
             }
 256  0
         } catch (Throwable e) {
 257  0
             if (e instanceof AnalysisException) {
 258  0
                 throw (AnalysisException) e;
 259  
             } else {
 260  0
                 LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n"
 261  
                         + "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.");
 262  0
                 LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
 263  0
                 this.setEnabled(false);
 264  0
                 throw new AnalysisException("An error occured with the .NET AssemblyAnalyzer", e);
 265  
             }
 266  
         } finally {
 267  5
             if (rdr != null) {
 268  
                 try {
 269  5
                     rdr.close();
 270  0
                 } catch (IOException ex) {
 271  0
                     LOGGER.trace("ignore", ex);
 272  5
                 }
 273  
             }
 274  
         }
 275  5
         builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
 276  5
     }
 277  
 
 278  
     /**
 279  
      * Removes resources used from the local file system.
 280  
      *
 281  
      * @throws Exception thrown if there is a problem closing the analyzer
 282  
      */
 283  
     @Override
 284  
     public void close() throws Exception {
 285  6
         super.close();
 286  
         try {
 287  6
             if (grokAssemblyExe != null && !grokAssemblyExe.delete()) {
 288  0
                 grokAssemblyExe.deleteOnExit();
 289  
             }
 290  0
         } catch (SecurityException se) {
 291  0
             LOGGER.debug("Can't delete temporary GrokAssembly.exe");
 292  6
         }
 293  6
     }
 294  
 
 295  
     /**
 296  
      * The File Filter used to filter supported extensions.
 297  
      */
 298  1
     private static final FileFilter FILTER = FileFilterBuilder.newInstance().addExtensions(
 299  
             SUPPORTED_EXTENSIONS).build();
 300  
 
 301  
     @Override
 302  
     protected FileFilter getFileFilter() {
 303  858
         return FILTER;
 304  
     }
 305  
 
 306  
     /**
 307  
      * Gets this analyzer's name.
 308  
      *
 309  
      * @return the analyzer name
 310  
      */
 311  
     @Override
 312  
     public String getName() {
 313  5
         return ANALYZER_NAME;
 314  
     }
 315  
 
 316  
     /**
 317  
      * Returns the phase this analyzer runs under.
 318  
      *
 319  
      * @return the phase this runs under
 320  
      */
 321  
     @Override
 322  
     public AnalysisPhase getAnalysisPhase() {
 323  3
         return ANALYSIS_PHASE;
 324  
     }
 325  
 
 326  
     /**
 327  
      * Returns the key used in the properties file to reference the analyzer's enabled property.
 328  
      *
 329  
      * @return the analyzer's enabled property setting key
 330  
      */
 331  
     @Override
 332  
     protected String getAnalyzerEnabledSettingKey() {
 333  9
         return Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED;
 334  
     }
 335  
 }