Coverage Report - org.owasp.dependencycheck.analyzer.JarAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
JarAnalyzer
0%
0/580
0%
0/352
7.486
JarAnalyzer$ClassNameInformation
0%
0/17
0%
0/10
7.486
 
 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.BufferedOutputStream;
 21  
 import java.io.File;
 22  
 import java.io.FileInputStream;
 23  
 import java.io.FileNotFoundException;
 24  
 import java.io.FileOutputStream;
 25  
 import java.io.IOException;
 26  
 import java.io.InputStream;
 27  
 import java.io.InputStreamReader;
 28  
 import java.io.OutputStream;
 29  
 import java.io.Reader;
 30  
 import java.io.UnsupportedEncodingException;
 31  
 import java.util.ArrayList;
 32  
 import java.util.Collections;
 33  
 import java.util.Enumeration;
 34  
 import java.util.HashMap;
 35  
 import java.util.List;
 36  
 import java.util.Map;
 37  
 import java.util.Map.Entry;
 38  
 import java.util.Properties;
 39  
 import java.util.Set;
 40  
 import java.util.StringTokenizer;
 41  
 import java.util.jar.Attributes;
 42  
 import java.util.jar.JarEntry;
 43  
 import java.util.jar.JarFile;
 44  
 import java.util.jar.Manifest;
 45  
 import java.util.logging.Level;
 46  
 import java.util.logging.Logger;
 47  
 import java.util.regex.Pattern;
 48  
 import java.util.zip.ZipEntry;
 49  
 import javax.xml.bind.JAXBContext;
 50  
 import javax.xml.bind.JAXBElement;
 51  
 import javax.xml.bind.JAXBException;
 52  
 import javax.xml.bind.Unmarshaller;
 53  
 import javax.xml.parsers.ParserConfigurationException;
 54  
 import javax.xml.parsers.SAXParser;
 55  
 import javax.xml.parsers.SAXParserFactory;
 56  
 import javax.xml.transform.sax.SAXSource;
 57  
 import org.jsoup.Jsoup;
 58  
 import org.owasp.dependencycheck.Engine;
 59  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 60  
 import org.owasp.dependencycheck.dependency.Confidence;
 61  
 import org.owasp.dependencycheck.dependency.Dependency;
 62  
 import org.owasp.dependencycheck.dependency.EvidenceCollection;
 63  
 import org.owasp.dependencycheck.jaxb.pom.MavenNamespaceFilter;
 64  
 import org.owasp.dependencycheck.jaxb.pom.generated.License;
 65  
 import org.owasp.dependencycheck.jaxb.pom.generated.Model;
 66  
 import org.owasp.dependencycheck.jaxb.pom.generated.Organization;
 67  
 import org.owasp.dependencycheck.jaxb.pom.generated.Parent;
 68  
 import org.owasp.dependencycheck.utils.FileUtils;
 69  
 import org.owasp.dependencycheck.utils.NonClosingStream;
 70  
 import org.owasp.dependencycheck.utils.Settings;
 71  
 import org.xml.sax.InputSource;
 72  
 import org.xml.sax.SAXException;
 73  
 import org.xml.sax.XMLFilter;
 74  
 import org.xml.sax.XMLReader;
 75  
 
 76  
 /**
 77  
  *
 78  
  * Used to load a JAR file and collect information that can be used to determine the associated CPE.
 79  
  *
 80  
  * @author Jeremy Long <jeremy.long@owasp.org>
 81  
  */
 82  
 public class JarAnalyzer extends AbstractFileTypeAnalyzer {
 83  
 
 84  
     //<editor-fold defaultstate="collapsed" desc="Constants and Member Variables">
 85  
     /**
 86  
      * The logger.
 87  
      */
 88  0
     private static final Logger LOGGER = Logger.getLogger(JarAnalyzer.class.getName());
 89  
     /**
 90  
      * The buffer size to use when extracting files from the archive.
 91  
      */
 92  
     private static final int BUFFER_SIZE = 4096;
 93  
     /**
 94  
      * The count of directories created during analysis. This is used for creating temporary directories.
 95  
      */
 96  0
     private static int dirCount = 0;
 97  
     /**
 98  
      * The system independent newline character.
 99  
      */
 100  0
     private static final String NEWLINE = System.getProperty("line.separator");
 101  
     /**
 102  
      * A list of values in the manifest to ignore as they only result in false positives.
 103  
      */
 104  0
     private static final Set<String> IGNORE_VALUES = newHashSet(
 105  
             "Sun Java System Application Server");
 106  
     /**
 107  
      * A list of elements in the manifest to ignore.
 108  
      */
 109  0
     private static final Set<String> IGNORE_KEYS = newHashSet(
 110  
             "built-by",
 111  
             "created-by",
 112  
             "builtby",
 113  
             "createdby",
 114  
             "build-jdk",
 115  
             "buildjdk",
 116  
             "ant-version",
 117  
             "antversion",
 118  
             "dynamicimportpackage",
 119  
             "dynamicimport-package",
 120  
             "dynamic-importpackage",
 121  
             "dynamic-import-package",
 122  
             "import-package",
 123  
             "ignore-package",
 124  
             "export-package",
 125  
             "importpackage",
 126  
             "ignorepackage",
 127  
             "exportpackage",
 128  
             "sealed",
 129  
             "manifest-version",
 130  
             "archiver-version",
 131  
             "manifestversion",
 132  
             "archiverversion",
 133  
             "classpath",
 134  
             "class-path",
 135  
             "tool",
 136  
             "bundle-manifestversion",
 137  
             "bundlemanifestversion",
 138  
             "include-resource",
 139  
             "embed-dependency",
 140  
             "ipojo-components",
 141  
             "ipojo-extension");
 142  
     /**
 143  
      * item in some manifest, should be considered medium confidence.
 144  
      */
 145  
     private static final String BUNDLE_VERSION = "Bundle-Version"; //: 2.1.2
 146  
     /**
 147  
      * item in some manifest, should be considered medium confidence.
 148  
      */
 149  
     private static final String BUNDLE_DESCRIPTION = "Bundle-Description"; //: Apache Struts 2
 150  
     /**
 151  
      * item in some manifest, should be considered medium confidence.
 152  
      */
 153  
     private static final String BUNDLE_NAME = "Bundle-Name"; //: Struts 2 Core
 154  
     /**
 155  
      * item in some manifest, should be considered medium confidence.
 156  
      */
 157  
     private static final String BUNDLE_VENDOR = "Bundle-Vendor"; //: Apache Software Foundation
 158  
     /**
 159  
      * A pattern to detect HTML within text.
 160  
      */
 161  0
     private static final Pattern HTML_DETECTION_PATTERN = Pattern.compile("\\<[a-z]+.*/?\\>", Pattern.CASE_INSENSITIVE);
 162  
     /**
 163  
      * The unmarshaller used to parse the pom.xml from a JAR file.
 164  
      */
 165  
     private Unmarshaller pomUnmarshaller;
 166  
     //</editor-fold>
 167  
 
 168  
     /**
 169  
      * Constructs a new JarAnalyzer.
 170  
      */
 171  0
     public JarAnalyzer() {
 172  
         try {
 173  0
             final JAXBContext jaxbContext = JAXBContext.newInstance("org.owasp.dependencycheck.jaxb.pom.generated");
 174  0
             pomUnmarshaller = jaxbContext.createUnmarshaller();
 175  0
         } catch (JAXBException ex) { //guess we will just have a null pointer exception later...
 176  0
             LOGGER.log(Level.SEVERE, "Unable to load parser. See the log for more details.");
 177  0
             LOGGER.log(Level.FINE, null, ex);
 178  0
         }
 179  0
     }
 180  
 
 181  
     //<editor-fold defaultstate="collapsed" desc="All standard implmentation details of Analyzer">
 182  
     /**
 183  
      * The name of the analyzer.
 184  
      */
 185  
     private static final String ANALYZER_NAME = "Jar Analyzer";
 186  
     /**
 187  
      * The phase that this analyzer is intended to run in.
 188  
      */
 189  0
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION;
 190  
     /**
 191  
      * The set of file extensions supported by this analyzer.
 192  
      */
 193  0
     private static final Set<String> EXTENSIONS = newHashSet("jar", "war");
 194  
 
 195  
     /**
 196  
      * Returns a list of file EXTENSIONS supported by this analyzer.
 197  
      *
 198  
      * @return a list of file EXTENSIONS supported by this analyzer.
 199  
      */
 200  
     @Override
 201  
     public Set<String> getSupportedExtensions() {
 202  0
         return EXTENSIONS;
 203  
     }
 204  
 
 205  
     /**
 206  
      * Returns the name of the analyzer.
 207  
      *
 208  
      * @return the name of the analyzer.
 209  
      */
 210  
     @Override
 211  
     public String getName() {
 212  0
         return ANALYZER_NAME;
 213  
     }
 214  
 
 215  
     /**
 216  
      * Returns the phase that the analyzer is intended to run in.
 217  
      *
 218  
      * @return the phase that the analyzer is intended to run in.
 219  
      */
 220  
     public AnalysisPhase getAnalysisPhase() {
 221  0
         return ANALYSIS_PHASE;
 222  
     }
 223  
     //</editor-fold>
 224  
 
 225  
     /**
 226  
      * Returns the key used in the properties file to reference the analyzer's enabled property.
 227  
      *
 228  
      * @return the analyzer's enabled property setting key
 229  
      */
 230  
     @Override
 231  
     protected String getAnalyzerEnabledSettingKey() {
 232  0
         return Settings.KEYS.ANALYZER_JAR_ENABLED;
 233  
     }
 234  
 
 235  
     /**
 236  
      * Loads a specified JAR file and collects information from the manifest and checksums to identify the correct CPE
 237  
      * information.
 238  
      *
 239  
      * @param dependency the dependency to analyze.
 240  
      * @param engine the engine that is scanning the dependencies
 241  
      * @throws AnalysisException is thrown if there is an error reading the JAR file.
 242  
      */
 243  
     @Override
 244  
     public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
 245  
         try {
 246  0
             final ArrayList<ClassNameInformation> classNames = collectClassNames(dependency);
 247  0
             final String fileName = dependency.getFileName().toLowerCase();
 248  0
             if (classNames.isEmpty()
 249  
                     && (fileName.endsWith("-sources.jar")
 250  
                     || fileName.endsWith("-javadoc.jar")
 251  
                     || fileName.endsWith("-src.jar")
 252  
                     || fileName.endsWith("-doc.jar"))) {
 253  0
                 engine.getDependencies().remove(dependency);
 254  
             }
 255  0
             final boolean hasManifest = parseManifest(dependency, classNames);
 256  0
             final boolean hasPOM = analyzePOM(dependency, classNames, engine);
 257  0
             final boolean addPackagesAsEvidence = !(hasManifest && hasPOM);
 258  0
             analyzePackageNames(classNames, dependency, addPackagesAsEvidence);
 259  0
         } catch (IOException ex) {
 260  0
             throw new AnalysisException("Exception occurred reading the JAR file.", ex);
 261  0
         }
 262  0
     }
 263  
 
 264  
     /**
 265  
      * Attempts to find a pom.xml within the JAR file. If found it extracts information and adds it to the evidence.
 266  
      * This will attempt to interpolate the strings contained within the pom.properties if one exists.
 267  
      *
 268  
      * @param dependency the dependency being analyzed
 269  
      * @param classes a collection of class name information
 270  
      * @param engine the analysis engine, used to add additional dependencies
 271  
      * @throws AnalysisException is thrown if there is an exception parsing the pom
 272  
      * @return whether or not evidence was added to the dependency
 273  
      */
 274  
     protected boolean analyzePOM(Dependency dependency, ArrayList<ClassNameInformation> classes, Engine engine) throws AnalysisException {
 275  0
         boolean foundSomething = false;
 276  
         final JarFile jar;
 277  
         try {
 278  0
             jar = new JarFile(dependency.getActualFilePath());
 279  0
         } catch (IOException ex) {
 280  0
             final String msg = String.format("Unable to read JarFile '%s'.", dependency.getActualFilePath());
 281  
             //final AnalysisException ax = new AnalysisException(msg, ex);
 282  0
             LOGGER.log(Level.WARNING, msg);
 283  0
             LOGGER.log(Level.FINE, "", ex);
 284  0
             return false;
 285  0
         }
 286  
         List<String> pomEntries;
 287  
         try {
 288  0
             pomEntries = retrievePomListing(jar);
 289  0
         } catch (IOException ex) {
 290  0
             final String msg = String.format("Unable to read Jar file entries in '%s'.", dependency.getActualFilePath());
 291  
             //final AnalysisException ax = new AnalysisException(msg, ex);
 292  0
             LOGGER.log(Level.WARNING, msg);
 293  0
             LOGGER.log(Level.FINE, msg, ex);
 294  0
             return false;
 295  0
         }
 296  0
         if (pomEntries.isEmpty()) {
 297  0
             return false;
 298  
         }
 299  0
         for (String path : pomEntries) {
 300  0
             Properties pomProperties = null;
 301  
             try {
 302  0
                 pomProperties = retrievePomProperties(path, jar);
 303  0
             } catch (IOException ex) {
 304  0
                 LOGGER.log(Level.FINEST, "ignore this, failed reading a non-existent pom.properties", ex);
 305  0
             }
 306  0
             Model pom = null;
 307  
             try {
 308  0
                 if (pomEntries.size() > 1) {
 309  
                     //extract POM to its own directory and add it as its own dependency
 310  0
                     final Dependency newDependency = new Dependency();
 311  0
                     pom = extractPom(path, jar, newDependency);
 312  
 
 313  0
                     final String displayPath = String.format("%s%s%s",
 314  
                             dependency.getFilePath(),
 315  
                             File.separator,
 316  
                             path); //.replaceAll("[\\/]", File.separator));
 317  0
                     final String displayName = String.format("%s%s%s",
 318  
                             dependency.getFileName(),
 319  
                             File.separator,
 320  
                             path); //.replaceAll("[\\/]", File.separator));
 321  
 
 322  0
                     newDependency.setFileName(displayName);
 323  0
                     newDependency.setFilePath(displayPath);
 324  0
                     addPomEvidence(newDependency, pom, pomProperties);
 325  0
                     engine.getDependencies().add(newDependency);
 326  0
                     Collections.sort(engine.getDependencies());
 327  0
                 } else {
 328  0
                     pom = retrievePom(path, jar);
 329  0
                     foundSomething |= setPomEvidence(dependency, pom, pomProperties, classes);
 330  
                 }
 331  0
             } catch (AnalysisException ex) {
 332  0
                 final String msg = String.format("An error occured while analyzing '%s'.", dependency.getActualFilePath());
 333  0
                 LOGGER.log(Level.WARNING, msg);
 334  0
                 LOGGER.log(Level.FINE, "", ex);
 335  0
             }
 336  0
         }
 337  0
         return foundSomething;
 338  
     }
 339  
 
 340  
     /**
 341  
      * Given a path to a pom.xml within a JarFile, this method attempts to load a sibling pom.properties if one exists.
 342  
      *
 343  
      * @param path the path to the pom.xml within the JarFile
 344  
      * @param jar the JarFile to load the pom.properties from
 345  
      * @return a Properties object or null if no pom.properties was found
 346  
      * @throws IOException thrown if there is an exception reading the pom.properties
 347  
      */
 348  
     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "OS_OPEN_STREAM",
 349  
             justification = "The reader is closed by closing the zipEntry")
 350  
     private Properties retrievePomProperties(String path, final JarFile jar) throws IOException {
 351  0
         Properties pomProperties = null;
 352  0
         final String propPath = path.substring(0, path.length() - 7) + "pom.properies";
 353  0
         final ZipEntry propEntry = jar.getEntry(propPath);
 354  0
         if (propEntry != null) {
 355  0
             final Reader reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8");
 356  0
             pomProperties = new Properties();
 357  0
             pomProperties.load(reader);
 358  
         }
 359  0
         return pomProperties;
 360  
     }
 361  
 
 362  
     /**
 363  
      * Searches a JarFile for pom.xml entries and returns a listing of these entries.
 364  
      *
 365  
      * @param jar the JarFile to search
 366  
      * @return a list of pom.xml entries
 367  
      * @throws IOException thrown if there is an exception reading a JarEntryf
 368  
      */
 369  
     private List<String> retrievePomListing(final JarFile jar) throws IOException {
 370  0
         final List<String> pomEntries = new ArrayList<String>();
 371  0
         final Enumeration<JarEntry> entries = jar.entries();
 372  0
         while (entries.hasMoreElements()) {
 373  0
             final JarEntry entry = entries.nextElement();
 374  0
             final String entryName = (new File(entry.getName())).getName().toLowerCase();
 375  0
             if (!entry.isDirectory() && "pom.xml".equals(entryName)) {
 376  0
                 pomEntries.add(entry.getName());
 377  
             }
 378  0
         }
 379  0
         return pomEntries;
 380  
     }
 381  
 
 382  
     /**
 383  
      * Retrieves the specified POM from a jar file and converts it to a Model.
 384  
      *
 385  
      * @param path the path to the pom.xml file within the jar file
 386  
      * @param jar the jar file to extract the pom from
 387  
      * @param dependency the dependency being analyzed
 388  
      * @return returns the POM object
 389  
      * @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
 390  
      * {@link org.owasp.dependencycheck.jaxb.pom.generated.Model} object
 391  
      */
 392  
     private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException {
 393  0
         InputStream input = null;
 394  0
         FileOutputStream fos = null;
 395  0
         BufferedOutputStream bos = null;
 396  0
         final File tmpDir = getNextTempDirectory();
 397  0
         final File file = new File(tmpDir, "pom.xml");
 398  
         try {
 399  0
             final ZipEntry entry = jar.getEntry(path);
 400  0
             input = jar.getInputStream(entry);
 401  0
             fos = new FileOutputStream(file);
 402  0
             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 403  
             int count;
 404  0
             final byte data[] = new byte[BUFFER_SIZE];
 405  0
             while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
 406  0
                 bos.write(data, 0, count);
 407  
             }
 408  0
             bos.flush();
 409  0
             dependency.setActualFilePath(file.getAbsolutePath());
 410  0
         } catch (IOException ex) {
 411  0
             final String msg = String.format("An error occured reading '%s' from '%s'.", path, dependency.getFilePath());
 412  0
             LOGGER.warning(msg);
 413  0
             LOGGER.log(Level.SEVERE, "", ex);
 414  
         } finally {
 415  0
             closeStream(bos);
 416  0
             closeStream(fos);
 417  0
             closeStream(input);
 418  0
         }
 419  0
         Model model = null;
 420  0
         FileInputStream fis = null;
 421  
         try {
 422  0
             fis = new FileInputStream(file);
 423  0
             final InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
 424  0
             final InputSource xml = new InputSource(reader);
 425  0
             final SAXSource source = new SAXSource(xml);
 426  0
             model = readPom(source);
 427  0
         } catch (FileNotFoundException ex) {
 428  0
             final String msg = String.format("Unable to parse pom '%s' in jar '%s' (File Not Found)", path, jar.getName());
 429  0
             LOGGER.log(Level.WARNING, msg);
 430  0
             LOGGER.log(Level.FINE, "", ex);
 431  0
             throw new AnalysisException(ex);
 432  0
         } catch (UnsupportedEncodingException ex) {
 433  0
             final String msg = String.format("Unable to parse pom '%s' in jar '%s' (IO Exception)", path, jar.getName());
 434  0
             LOGGER.log(Level.WARNING, msg);
 435  0
             LOGGER.log(Level.FINE, "", ex);
 436  0
             throw new AnalysisException(ex);
 437  0
         } catch (AnalysisException ex) {
 438  0
             final String msg = String.format("Unable to parse pom '%s' in jar '%s'", path, jar.getName());
 439  0
             LOGGER.log(Level.WARNING, msg);
 440  0
             LOGGER.log(Level.FINE, "", ex);
 441  0
             throw ex;
 442  
         } finally {
 443  0
             closeStream(fis);
 444  0
         }
 445  0
         return model;
 446  
     }
 447  
 
 448  
     /**
 449  
      * Silently closes an input stream ignoring errors.
 450  
      *
 451  
      * @param stream an input stream to close
 452  
      */
 453  
     private void closeStream(InputStream stream) {
 454  0
         if (stream != null) {
 455  
             try {
 456  0
                 stream.close();
 457  0
             } catch (IOException ex) {
 458  0
                 LOGGER.log(Level.FINEST, null, ex);
 459  0
             }
 460  
         }
 461  0
     }
 462  
 
 463  
     /**
 464  
      * Silently closes an output stream ignoring errors.
 465  
      *
 466  
      * @param stream an output stream to close
 467  
      */
 468  
     private void closeStream(OutputStream stream) {
 469  0
         if (stream != null) {
 470  
             try {
 471  0
                 stream.close();
 472  0
             } catch (IOException ex) {
 473  0
                 LOGGER.log(Level.FINEST, null, ex);
 474  0
             }
 475  
         }
 476  0
     }
 477  
 
 478  
     /**
 479  
      * Retrieves the specified POM from a jar file and converts it to a Model.
 480  
      *
 481  
      * @param path the path to the pom.xml file within the jar file
 482  
      * @param jar the jar file to extract the pom from
 483  
      * @return returns a
 484  
      * @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
 485  
      * {@link org.owasp.dependencycheck.jaxb.pom.generated.Model} object
 486  
      */
 487  
     private Model retrievePom(String path, JarFile jar) throws AnalysisException {
 488  0
         final ZipEntry entry = jar.getEntry(path);
 489  0
         Model model = null;
 490  0
         if (entry != null) { //should never be null
 491  
             try {
 492  0
                 final NonClosingStream stream = new NonClosingStream(jar.getInputStream(entry));
 493  0
                 final InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
 494  0
                 final InputSource xml = new InputSource(reader);
 495  0
                 final SAXSource source = new SAXSource(xml);
 496  0
                 model = readPom(source);
 497  0
             } catch (SecurityException ex) {
 498  0
                 final String msg = String.format("Unable to parse pom '%s' in jar '%s'; invalid signature", path, jar.getName());
 499  0
                 Logger
 500  
                         .getLogger(JarAnalyzer.class
 501  
                                 .getName()).log(Level.WARNING, msg);
 502  0
                 Logger.getLogger(JarAnalyzer.class
 503  
                         .getName()).log(Level.FINE, null, ex);
 504  0
                 throw new AnalysisException(ex);
 505  0
             } catch (IOException ex) {
 506  0
                 final String msg = String.format("Unable to parse pom '%s' in jar '%s' (IO Exception)", path, jar.getName());
 507  0
                 LOGGER.log(Level.WARNING, msg);
 508  0
                 LOGGER.log(Level.FINE, "", ex);
 509  0
                 throw new AnalysisException(ex);
 510  0
             } catch (Throwable ex) {
 511  0
                 final String msg = String.format("Unexpected error during parsing of the pom '%s' in jar '%s'", path, jar.getName());
 512  0
                 LOGGER.log(Level.WARNING, msg);
 513  0
                 LOGGER.log(Level.FINE, "", ex);
 514  0
                 throw new AnalysisException(ex);
 515  0
             }
 516  
         }
 517  0
         return model;
 518  
     }
 519  
 
 520  
     /**
 521  
      * Retrieves the specified POM from a jar file and converts it to a Model.
 522  
      *
 523  
      * @param source the SAXSource input stream to read the POM from
 524  
      * @return returns the POM object
 525  
      * @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
 526  
      * {@link org.owasp.dependencycheck.jaxb.pom.generated.Model} object
 527  
      */
 528  
     private Model readPom(SAXSource source) throws AnalysisException {
 529  0
         Model model = null;
 530  
         try {
 531  0
             final XMLFilter filter = new MavenNamespaceFilter();
 532  0
             final SAXParserFactory spf = SAXParserFactory.newInstance();
 533  0
             final SAXParser sp = spf.newSAXParser();
 534  0
             final XMLReader xr = sp.getXMLReader();
 535  0
             filter.setParent(xr);
 536  0
             final JAXBElement<Model> el = pomUnmarshaller.unmarshal(source, Model.class);
 537  0
             model = el.getValue();
 538  0
         } catch (SecurityException ex) {
 539  0
             throw new AnalysisException(ex);
 540  0
         } catch (ParserConfigurationException ex) {
 541  0
             throw new AnalysisException(ex);
 542  0
         } catch (SAXException ex) {
 543  0
             throw new AnalysisException(ex);
 544  0
         } catch (JAXBException ex) {
 545  0
             throw new AnalysisException(ex);
 546  0
         } catch (Throwable ex) {
 547  0
             throw new AnalysisException(ex);
 548  0
         }
 549  0
         return model;
 550  
     }
 551  
 
 552  
     /**
 553  
      * Sets evidence from the pom on the supplied dependency.
 554  
      *
 555  
      * @param dependency the dependency to set data on
 556  
      * @param pom the information from the pom
 557  
      * @param pomProperties the pom properties file (null if none exists)
 558  
      * @param classes a collection of ClassNameInformation - containing data about the fully qualified class names
 559  
      * within the JAR file being analyzed
 560  
      * @return true if there was evidence within the pom that we could use; otherwise false
 561  
      */
 562  
     private boolean setPomEvidence(Dependency dependency, Model pom, Properties pomProperties, ArrayList<ClassNameInformation> classes) {
 563  0
         boolean foundSomething = false;
 564  0
         if (pom == null) {
 565  0
             return foundSomething;
 566  
         }
 567  0
         String groupid = interpolateString(pom.getGroupId(), pomProperties);
 568  0
         if (groupid != null && !groupid.isEmpty()) {
 569  0
             if (groupid.startsWith("org.") || groupid.startsWith("com.")) {
 570  0
                 groupid = groupid.substring(4);
 571  
             }
 572  0
             foundSomething = true;
 573  0
             dependency.getVendorEvidence().addEvidence("pom", "groupid", groupid, Confidence.HIGH);
 574  0
             dependency.getProductEvidence().addEvidence("pom", "groupid", groupid, Confidence.LOW);
 575  0
             addMatchingValues(classes, groupid, dependency.getVendorEvidence());
 576  0
             addMatchingValues(classes, groupid, dependency.getProductEvidence());
 577  
         }
 578  0
         String artifactid = interpolateString(pom.getArtifactId(), pomProperties);
 579  0
         if (artifactid != null && !artifactid.isEmpty()) {
 580  0
             if (artifactid.startsWith("org.") || artifactid.startsWith("com.")) {
 581  0
                 artifactid = artifactid.substring(4);
 582  
             }
 583  0
             foundSomething = true;
 584  0
             dependency.getProductEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.HIGH);
 585  0
             dependency.getVendorEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.LOW);
 586  0
             addMatchingValues(classes, artifactid, dependency.getVendorEvidence());
 587  0
             addMatchingValues(classes, artifactid, dependency.getProductEvidence());
 588  
         }
 589  
         //version
 590  0
         final String version = interpolateString(pom.getVersion(), pomProperties);
 591  0
         if (version != null && !version.isEmpty()) {
 592  0
             foundSomething = true;
 593  0
             dependency.getVersionEvidence().addEvidence("pom", "version", version, Confidence.HIGHEST);
 594  
         }
 595  
         // org name
 596  0
         final Organization org = pom.getOrganization();
 597  0
         if (org != null && org.getName() != null) {
 598  0
             foundSomething = true;
 599  0
             final String orgName = interpolateString(org.getName(), pomProperties);
 600  0
             if (orgName != null && !orgName.isEmpty()) {
 601  0
                 dependency.getVendorEvidence().addEvidence("pom", "organization name", orgName, Confidence.HIGH);
 602  0
                 addMatchingValues(classes, orgName, dependency.getVendorEvidence());
 603  
             }
 604  
         }
 605  
         //pom name
 606  0
         final String pomName = interpolateString(pom.getName(), pomProperties);
 607  0
         if (pomName != null && !pomName.isEmpty()) {
 608  0
             foundSomething = true;
 609  0
             dependency.getProductEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
 610  0
             dependency.getVendorEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
 611  0
             addMatchingValues(classes, pomName, dependency.getVendorEvidence());
 612  0
             addMatchingValues(classes, pomName, dependency.getProductEvidence());
 613  
         }
 614  
 
 615  
         //Description
 616  0
         if (pom.getDescription() != null) {
 617  0
             foundSomething = true;
 618  0
             final String description = interpolateString(pom.getDescription(), pomProperties);
 619  0
             if (description != null && !description.isEmpty()) {
 620  0
                 final String trimmedDescription = addDescription(dependency, description, "pom", "description");
 621  0
                 addMatchingValues(classes, trimmedDescription, dependency.getVendorEvidence());
 622  0
                 addMatchingValues(classes, trimmedDescription, dependency.getProductEvidence());
 623  
             }
 624  
         }
 625  0
         extractLicense(pom, pomProperties, dependency);
 626  0
         return foundSomething;
 627  
     }
 628  
 
 629  
     /**
 630  
      * Analyzes the path information of the classes contained within the JarAnalyzer to try and determine possible
 631  
      * vendor or product names. If any are found they are stored in the packageVendor and packageProduct hashSets.
 632  
      *
 633  
      * @param classNames a list of class names
 634  
      * @param dependency a dependency to analyze
 635  
      * @param addPackagesAsEvidence a flag indicating whether or not package names should be added as evidence.
 636  
      */
 637  
     protected void analyzePackageNames(ArrayList<ClassNameInformation> classNames,
 638  
             Dependency dependency, boolean addPackagesAsEvidence) {
 639  0
         final HashMap<String, Integer> vendorIdentifiers = new HashMap<String, Integer>();
 640  0
         final HashMap<String, Integer> productIdentifiers = new HashMap<String, Integer>();
 641  0
         analyzeFullyQualifiedClassNames(classNames, vendorIdentifiers, productIdentifiers);
 642  
 
 643  0
         final int classCount = classNames.size();
 644  0
         final EvidenceCollection vendor = dependency.getVendorEvidence();
 645  0
         final EvidenceCollection product = dependency.getProductEvidence();
 646  
 
 647  0
         for (Map.Entry<String, Integer> entry : vendorIdentifiers.entrySet()) {
 648  0
             final float ratio = entry.getValue() / (float) classCount;
 649  0
             if (ratio > 0.5) {
 650  
                 //TODO remove weighting
 651  0
                 vendor.addWeighting(entry.getKey());
 652  0
                 if (addPackagesAsEvidence && entry.getKey().length() > 1) {
 653  0
                     vendor.addEvidence("jar", "package", entry.getKey(), Confidence.LOW);
 654  
                 }
 655  
             }
 656  0
         }
 657  0
         for (Map.Entry<String, Integer> entry : productIdentifiers.entrySet()) {
 658  0
             final float ratio = entry.getValue() / (float) classCount;
 659  0
             if (ratio > 0.5) {
 660  0
                 product.addWeighting(entry.getKey());
 661  0
                 if (addPackagesAsEvidence && entry.getKey().length() > 1) {
 662  0
                     product.addEvidence("jar", "package", entry.getKey(), Confidence.LOW);
 663  
                 }
 664  
             }
 665  0
         }
 666  0
     }
 667  
 
 668  
     /**
 669  
      * <p>
 670  
      * Reads the manifest from the JAR file and collects the entries. Some vendorKey entries are:</p>
 671  
      * <ul><li>Implementation Title</li>
 672  
      * <li>Implementation Version</li> <li>Implementation Vendor</li>
 673  
      * <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle Version</li> <li>Bundle Vendor</li> <li>Bundle
 674  
      * Description</li> <li>Main Class</li> </ul>
 675  
      * However, all but a handful of specific entries are read in.
 676  
      *
 677  
      * @param dependency A reference to the dependency
 678  
      * @param classInformation a collection of class information
 679  
      * @return whether evidence was identified parsing the manifest
 680  
      * @throws IOException if there is an issue reading the JAR file
 681  
      */
 682  
     protected boolean parseManifest(Dependency dependency, ArrayList<ClassNameInformation> classInformation) throws IOException {
 683  0
         boolean foundSomething = false;
 684  0
         JarFile jar = null;
 685  
         try {
 686  0
             jar = new JarFile(dependency.getActualFilePath());
 687  
 
 688  0
             final Manifest manifest = jar.getManifest();
 689  
 
 690  0
             if (manifest == null) {
 691  
                 //don't log this for javadoc or sources jar files
 692  0
                 if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
 693  
                         && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
 694  
                         && !dependency.getFileName().toLowerCase().endsWith("-src.jar")
 695  
                         && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
 696  0
                     Logger.getLogger(JarAnalyzer.class
 697  
                             .getName()).log(Level.INFO,
 698  
                                     String.format("Jar file '%s' does not contain a manifest.",
 699  
                                             dependency.getFileName()));
 700  
                 }
 701  0
                 return false;
 702  
             }
 703  0
             final Attributes atts = manifest.getMainAttributes();
 704  
 
 705  0
             final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
 706  0
             final EvidenceCollection productEvidence = dependency.getProductEvidence();
 707  0
             final EvidenceCollection versionEvidence = dependency.getVersionEvidence();
 708  
 
 709  0
             final String source = "Manifest";
 710  
 
 711  0
             for (Entry<Object, Object> entry : atts.entrySet()) {
 712  0
                 String key = entry.getKey().toString();
 713  0
                 String value = atts.getValue(key);
 714  0
                 if (HTML_DETECTION_PATTERN.matcher(value).find()) {
 715  0
                     value = Jsoup.parse(value).text();
 716  
                 }
 717  0
                 if (IGNORE_VALUES.contains(value)) {
 718  0
                     continue;
 719  0
                 } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
 720  0
                     foundSomething = true;
 721  0
                     productEvidence.addEvidence(source, key, value, Confidence.HIGH);
 722  0
                     addMatchingValues(classInformation, value, productEvidence);
 723  0
                 } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
 724  0
                     foundSomething = true;
 725  0
                     versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
 726  0
                 } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
 727  0
                     foundSomething = true;
 728  0
                     vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
 729  0
                     addMatchingValues(classInformation, value, vendorEvidence);
 730  0
                 } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR_ID.toString())) {
 731  0
                     foundSomething = true;
 732  0
                     vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 733  0
                     addMatchingValues(classInformation, value, vendorEvidence);
 734  0
                 } else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
 735  0
                     foundSomething = true;
 736  0
                     addDescription(dependency, value, "manifest", key);
 737  
                     //productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 738  0
                     addMatchingValues(classInformation, value, productEvidence);
 739  0
                 } else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
 740  0
                     foundSomething = true;
 741  0
                     productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 742  0
                     addMatchingValues(classInformation, value, productEvidence);
 743  0
                 } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
 744  0
                     foundSomething = true;
 745  0
                     vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
 746  0
                     addMatchingValues(classInformation, value, vendorEvidence);
 747  0
                 } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
 748  0
                     foundSomething = true;
 749  0
                     versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
 750  0
                 } else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) {
 751  0
                     continue;
 752  
                     //skipping main class as if this has important information to add
 753  
                     // it will be added during class name analysis...  if other fields
 754  
                     // have the information from the class name then they will get added...
 755  
 //                    foundSomething = true;
 756  
 //                    productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 757  
 //                    vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 758  
 //                    addMatchingValues(classInformation, value, vendorEvidence);
 759  
 //                    addMatchingValues(classInformation, value, productEvidence);
 760  
                 } else {
 761  0
                     key = key.toLowerCase();
 762  
 
 763  0
                     if (!IGNORE_KEYS.contains(key)
 764  
                             && !key.endsWith("jdk")
 765  
                             && !key.contains("lastmodified")
 766  
                             && !key.endsWith("package")
 767  
                             && !key.endsWith("classpath")
 768  
                             && !key.endsWith("class-path")
 769  
                             && !key.endsWith("-scm") //todo change this to a regex?
 770  
                             && !key.startsWith("scm-")
 771  
                             && !isImportPackage(key, value)
 772  
                             && !isPackage(key, value)) {
 773  
 
 774  0
                         foundSomething = true;
 775  0
                         if (key.contains("version")) {
 776  0
                             if (key.contains("specification")) {
 777  0
                                 versionEvidence.addEvidence(source, key, value, Confidence.LOW);
 778  
                             } else {
 779  0
                                 versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 780  
                             }
 781  0
                         } else if ("build-id".equals(key)) {
 782  0
                             int pos = value.indexOf('(');
 783  0
                             if (pos >= 0) {
 784  0
                                 value = value.substring(0, pos - 1);
 785  
                             }
 786  0
                             pos = value.indexOf('[');
 787  0
                             if (pos >= 0) {
 788  0
                                 value = value.substring(0, pos - 1);
 789  
                             }
 790  0
                             versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 791  0
                         } else if (key.contains("title")) {
 792  0
                             productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 793  0
                             addMatchingValues(classInformation, value, productEvidence);
 794  0
                         } else if (key.contains("vendor")) {
 795  0
                             if (key.contains("specification")) {
 796  0
                                 vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
 797  
                             } else {
 798  0
                                 vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 799  0
                                 addMatchingValues(classInformation, value, vendorEvidence);
 800  
                             }
 801  0
                         } else if (key.contains("name")) {
 802  0
                             productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 803  0
                             vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
 804  0
                             addMatchingValues(classInformation, value, vendorEvidence);
 805  0
                             addMatchingValues(classInformation, value, productEvidence);
 806  0
                         } else if (key.contains("license")) {
 807  0
                             addLicense(dependency, value);
 808  
                         } else {
 809  0
                             if (key.contains("description")) {
 810  0
                                 addDescription(dependency, value, "manifest", key);
 811  
                             } else {
 812  0
                                 productEvidence.addEvidence(source, key, value, Confidence.LOW);
 813  0
                                 vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
 814  0
                                 addMatchingValues(classInformation, value, vendorEvidence);
 815  0
                                 addMatchingValues(classInformation, value, productEvidence);
 816  0
                                 if (value.matches(".*\\d.*")) {
 817  0
                                     final StringTokenizer tokenizer = new StringTokenizer(value, " ");
 818  0
                                     while (tokenizer.hasMoreElements()) {
 819  0
                                         final String s = tokenizer.nextToken();
 820  0
                                         if (s.matches("^[0-9.]+$")) {
 821  0
                                             versionEvidence.addEvidence(source, key, s, Confidence.LOW);
 822  
                                         }
 823  0
                                     }
 824  
                                 }
 825  
                             }
 826  
                         }
 827  
                     }
 828  
                 }
 829  0
             }
 830  
         } finally {
 831  0
             if (jar != null) {
 832  0
                 jar.close();
 833  
             }
 834  
         }
 835  0
         return foundSomething;
 836  
     }
 837  
 
 838  
     /**
 839  
      * Adds a description to the given dependency. If the description contains one of the following strings beyond 100
 840  
      * characters, then the description used will be trimmed to that position:
 841  
      * <ul><li>"such as"</li><li>"like "</li><li>"will use "</li><li>"* uses "</li></ul>
 842  
      *
 843  
      * @param dependency a dependency
 844  
      * @param description the description
 845  
      * @param source the source of the evidence
 846  
      * @param key the "name" of the evidence
 847  
      * @return if the description is trimmed, the trimmed version is returned; otherwise the original description is
 848  
      * returned
 849  
      */
 850  
     private String addDescription(Dependency dependency, String description, String source, String key) {
 851  0
         if (dependency.getDescription() == null) {
 852  0
             dependency.setDescription(description);
 853  
         }
 854  
         String desc;
 855  0
         if (HTML_DETECTION_PATTERN.matcher(description).find()) {
 856  0
             desc = Jsoup.parse(description).text();
 857  
         } else {
 858  0
             desc = description;
 859  
         }
 860  0
         dependency.setDescription(desc);
 861  0
         if (desc.length() > 100) {
 862  0
             desc = desc.replaceAll("\\s\\s+", " ");
 863  0
             final int posSuchAs = desc.toLowerCase().indexOf("such as ", 100);
 864  0
             final int posLike = desc.toLowerCase().indexOf("like ", 100);
 865  0
             final int posWillUse = desc.toLowerCase().indexOf("will use ", 100);
 866  0
             final int posUses = desc.toLowerCase().indexOf(" uses ", 100);
 867  0
             int pos = -1;
 868  0
             pos = Math.max(pos, posSuchAs);
 869  0
             if (pos >= 0 && posLike >= 0) {
 870  0
                 pos = Math.min(pos, posLike);
 871  
             } else {
 872  0
                 pos = Math.max(pos, posLike);
 873  
             }
 874  0
             if (pos >= 0 && posWillUse >= 0) {
 875  0
                 pos = Math.min(pos, posWillUse);
 876  
             } else {
 877  0
                 pos = Math.max(pos, posWillUse);
 878  
             }
 879  0
             if (pos >= 0 && posUses >= 0) {
 880  0
                 pos = Math.min(pos, posUses);
 881  
             } else {
 882  0
                 pos = Math.max(pos, posUses);
 883  
             }
 884  
 
 885  0
             if (pos > 0) {
 886  0
                 final StringBuilder sb = new StringBuilder(pos + 3);
 887  0
                 sb.append(desc.substring(0, pos));
 888  0
                 sb.append("...");
 889  0
                 desc = sb.toString();
 890  
             }
 891  0
             dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.LOW);
 892  0
             dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.LOW);
 893  0
         } else {
 894  0
             dependency.getProductEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
 895  0
             dependency.getVendorEvidence().addEvidence(source, key, desc, Confidence.MEDIUM);
 896  
         }
 897  0
         return desc;
 898  
     }
 899  
 
 900  
     /**
 901  
      * Adds a license to the given dependency.
 902  
      *
 903  
      * @param d a dependency
 904  
      * @param license the license
 905  
      */
 906  
     private void addLicense(Dependency d, String license) {
 907  0
         if (d.getLicense() == null) {
 908  0
             d.setLicense(license);
 909  0
         } else if (!d.getLicense().contains(license)) {
 910  0
             d.setLicense(d.getLicense() + NEWLINE + license);
 911  
         }
 912  0
     }
 913  
 
 914  
     /**
 915  
      * The parent directory for the individual directories per archive.
 916  
      */
 917  0
     private File tempFileLocation = null;
 918  
 
 919  
     /**
 920  
      * Initializes the JarAnalyzer.
 921  
      *
 922  
      * @throws Exception is thrown if there is an exception creating a temporary directory
 923  
      */
 924  
     @Override
 925  
     public void initializeFileTypeAnalyzer() throws Exception {
 926  0
         final File baseDir = Settings.getTempDirectory();
 927  0
         if (!baseDir.exists()) {
 928  0
             if (!baseDir.mkdirs()) {
 929  0
                 final String msg = String.format("Unable to make a temporary folder '%s'", baseDir.getPath());
 930  0
                 throw new AnalysisException(msg);
 931  
             }
 932  
         }
 933  0
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 934  0
         if (!tempFileLocation.delete()) {
 935  0
             final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
 936  0
             throw new AnalysisException(msg);
 937  
         }
 938  0
         if (!tempFileLocation.mkdirs()) {
 939  0
             final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
 940  0
             throw new AnalysisException(msg);
 941  
         }
 942  0
     }
 943  
 
 944  
     /**
 945  
      * Deletes any files extracted from the JAR during analysis.
 946  
      */
 947  
     @Override
 948  
     public void close() {
 949  0
         if (tempFileLocation != null && tempFileLocation.exists()) {
 950  0
             LOGGER.log(Level.FINE, "Attempting to delete temporary files");
 951  0
             final boolean success = FileUtils.delete(tempFileLocation);
 952  0
             if (!success) {
 953  0
                 LOGGER.log(Level.WARNING,
 954  
                         "Failed to delete some temporary files, see the log for more details");
 955  
             }
 956  
         }
 957  0
     }
 958  
 
 959  
     /**
 960  
      * <p>
 961  
      * A utility function that will interpolate strings based on values given in the properties file. It will also
 962  
      * interpolate the strings contained within the properties file so that properties can reference other
 963  
      * properties.</p>
 964  
      * <p>
 965  
      * <b>Note:</b> if there is no property found the reference will be removed. In other words, if the interpolated
 966  
      * string will be replaced with an empty string.
 967  
      * </p>
 968  
      * <p>
 969  
      * Example:</p>
 970  
      * <code>
 971  
      * Properties p = new Properties();
 972  
      * p.setProperty("key", "value");
 973  
      * String s = interpolateString("'${key}' and '${nothing}'", p);
 974  
      * System.out.println(s);
 975  
      * </code>
 976  
      * <p>
 977  
      * Will result in:</p>
 978  
      * <code>
 979  
      * 'value' and ''
 980  
      * </code>
 981  
      *
 982  
      * @param text the string that contains references to properties.
 983  
      * @param properties a collection of properties that may be referenced within the text.
 984  
      * @return the interpolated text.
 985  
      */
 986  
     protected String interpolateString(String text, Properties properties) {
 987  0
         Properties props = properties;
 988  0
         if (text == null) {
 989  0
             return text;
 990  
         }
 991  0
         if (props == null) {
 992  0
             props = new Properties();
 993  
         }
 994  
 
 995  0
         final int pos = text.indexOf("${");
 996  0
         if (pos < 0) {
 997  0
             return text;
 998  
         }
 999  0
         final int end = text.indexOf("}");
 1000  0
         if (end < pos) {
 1001  0
             return text;
 1002  
         }
 1003  
 
 1004  0
         final String propName = text.substring(pos + 2, end);
 1005  0
         String propValue = interpolateString(props.getProperty(propName), props);
 1006  0
         if (propValue == null) {
 1007  0
             propValue = "";
 1008  
         }
 1009  0
         final StringBuilder sb = new StringBuilder(propValue.length() + text.length());
 1010  0
         sb.append(text.subSequence(0, pos));
 1011  0
         sb.append(propValue);
 1012  0
         sb.append(text.substring(end + 1));
 1013  0
         return interpolateString(sb.toString(), props); //yes yes, this should be a loop...
 1014  
     }
 1015  
 
 1016  
     /**
 1017  
      * Determines if the key value pair from the manifest is for an "import" type entry for package names.
 1018  
      *
 1019  
      * @param key the key from the manifest
 1020  
      * @param value the value from the manifest
 1021  
      * @return true or false depending on if it is believed the entry is an "import" entry
 1022  
      */
 1023  
     private boolean isImportPackage(String key, String value) {
 1024  0
         final Pattern packageRx = Pattern.compile("^([a-zA-Z0-9_#\\$\\*\\.]+\\s*[,;]\\s*)+([a-zA-Z0-9_#\\$\\*\\.]+\\s*)?$");
 1025  0
         final boolean matches = packageRx.matcher(value).matches();
 1026  0
         return matches && (key.contains("import") || key.contains("include") || value.length() > 10);
 1027  
     }
 1028  
 
 1029  
     /**
 1030  
      * Cycles through an enumeration of JarEntries, contained within the dependency, and returns a list of the class
 1031  
      * names. This does not include core Java package names (i.e. java.* or javax.*).
 1032  
      *
 1033  
      * @param dependency the dependency being analyzed
 1034  
      * @return an list of fully qualified class names
 1035  
      */
 1036  
     private ArrayList<ClassNameInformation> collectClassNames(Dependency dependency) {
 1037  0
         final ArrayList<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>();
 1038  0
         JarFile jar = null;
 1039  
         try {
 1040  0
             jar = new JarFile(dependency.getActualFilePath());
 1041  0
             final Enumeration entries = jar.entries();
 1042  0
             while (entries.hasMoreElements()) {
 1043  0
                 final JarEntry entry = (JarEntry) entries.nextElement();
 1044  0
                 final String name = entry.getName().toLowerCase();
 1045  
                 //no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs.
 1046  0
                 if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) {
 1047  0
                     final ClassNameInformation className = new ClassNameInformation(name.substring(0, name.length() - 6));
 1048  0
                     classNames.add(className);
 1049  
                 }
 1050  0
             }
 1051  0
         } catch (IOException ex) {
 1052  0
             final String msg = String.format("Unable to open jar file '%s'.", dependency.getFileName());
 1053  0
             Logger
 1054  
                     .getLogger(JarAnalyzer.class
 1055  
                             .getName()).log(Level.WARNING, msg);
 1056  0
             Logger.getLogger(JarAnalyzer.class
 1057  
                     .getName()).log(Level.FINE, null, ex);
 1058  
         } finally {
 1059  0
             if (jar != null) {
 1060  
                 try {
 1061  0
                     jar.close();
 1062  0
                 } catch (IOException ex) {
 1063  0
                     LOGGER.log(Level.FINEST, null, ex);
 1064  0
                 }
 1065  
             }
 1066  
         }
 1067  0
         return classNames;
 1068  
     }
 1069  
 
 1070  
     /**
 1071  
      * Cycles through the list of class names and places the package levels 0-3 into the provided maps for vendor and
 1072  
      * product. This is helpful when analyzing vendor/product as many times this is included in the package name.
 1073  
      *
 1074  
      * @param classNames a list of class names
 1075  
      * @param vendor HashMap of possible vendor names from package names (e.g. owasp)
 1076  
      * @param product HashMap of possible product names from package names (e.g. dependencycheck)
 1077  
      */
 1078  
     private void analyzeFullyQualifiedClassNames(ArrayList<ClassNameInformation> classNames,
 1079  
             HashMap<String, Integer> vendor, HashMap<String, Integer> product) {
 1080  0
         for (ClassNameInformation entry : classNames) {
 1081  0
             final ArrayList<String> list = entry.getPackageStructure();
 1082  0
             addEntry(vendor, list.get(0));
 1083  
 
 1084  0
             if (list.size() == 2) {
 1085  0
                 addEntry(product, list.get(1));
 1086  
             }
 1087  0
             if (list.size() == 3) {
 1088  0
                 addEntry(vendor, list.get(1));
 1089  0
                 addEntry(product, list.get(1));
 1090  0
                 addEntry(product, list.get(2));
 1091  
             }
 1092  0
             if (list.size() >= 4) {
 1093  0
                 addEntry(vendor, list.get(1));
 1094  0
                 addEntry(vendor, list.get(2));
 1095  0
                 addEntry(product, list.get(1));
 1096  0
                 addEntry(product, list.get(2));
 1097  0
                 addEntry(product, list.get(3));
 1098  
             }
 1099  0
         }
 1100  0
     }
 1101  
 
 1102  
     /**
 1103  
      * Adds an entry to the specified collection and sets the Integer (e.g. the count) to 1. If the entry already exists
 1104  
      * in the collection then the Integer is incremented by 1.
 1105  
      *
 1106  
      * @param collection a collection of strings and their occurrence count
 1107  
      * @param key the key to add to the collection
 1108  
      */
 1109  
     private void addEntry(HashMap<String, Integer> collection, String key) {
 1110  0
         if (collection.containsKey(key)) {
 1111  0
             collection.put(key, collection.get(key) + 1);
 1112  
         } else {
 1113  0
             collection.put(key, 1);
 1114  
         }
 1115  0
     }
 1116  
 
 1117  
     /**
 1118  
      * Cycles through the collection of class name information to see if parts of the package names are contained in the
 1119  
      * provided value. If found, it will be added as the HIGHEST confidence evidence because we have more then one
 1120  
      * source corroborating the value.
 1121  
      *
 1122  
      * @param classes a collection of class name information
 1123  
      * @param value the value to check to see if it contains a package name
 1124  
      * @param evidence the evidence collection to add new entries too
 1125  
      */
 1126  
     private void addMatchingValues(ArrayList<ClassNameInformation> classes, String value, EvidenceCollection evidence) {
 1127  0
         if (value == null || value.isEmpty()) {
 1128  0
             return;
 1129  
         }
 1130  0
         final String text = value.toLowerCase();
 1131  0
         for (ClassNameInformation cni : classes) {
 1132  0
             for (String key : cni.getPackageStructure()) {
 1133  0
                 if (text.contains(key)) { //note, package structure elements are already lowercase.
 1134  0
                     evidence.addEvidence("jar", "package name", key, Confidence.HIGHEST);
 1135  
                 }
 1136  0
             }
 1137  0
         }
 1138  0
     }
 1139  
 
 1140  
     /**
 1141  
      * Simple check to see if the attribute from a manifest is just a package name.
 1142  
      *
 1143  
      * @param key the key of the value to check
 1144  
      * @param value the value to check
 1145  
      * @return true if the value looks like a java package name, otherwise false
 1146  
      */
 1147  
     private boolean isPackage(String key, String value) {
 1148  
 
 1149  0
         return !key.matches(".*(version|title|vendor|name|license|description).*")
 1150  
                 && value.matches("^([a-zA-Z_][a-zA-Z0-9_\\$]*(\\.[a-zA-Z_][a-zA-Z0-9_\\$]*)*)?$");
 1151  
 
 1152  
     }
 1153  
 
 1154  
     /**
 1155  
      * Adds evidence from the POM to the dependency. This includes the GAV and in some situations the parent GAV if
 1156  
      * specified.
 1157  
      *
 1158  
      * @param dependency the dependency being analyzed
 1159  
      * @param pom the POM data
 1160  
      * @param pomProperties the properties file associated with the pom
 1161  
      */
 1162  
     private void addPomEvidence(Dependency dependency, Model pom, Properties pomProperties) {
 1163  0
         if (pom == null) {
 1164  0
             return;
 1165  
         }
 1166  0
         String groupid = interpolateString(pom.getGroupId(), pomProperties);
 1167  0
         if (groupid != null && !groupid.isEmpty()) {
 1168  0
             if (groupid.startsWith("org.") || groupid.startsWith("com.")) {
 1169  0
                 groupid = groupid.substring(4);
 1170  
             }
 1171  0
             dependency.getVendorEvidence().addEvidence("pom", "groupid", groupid, Confidence.HIGH);
 1172  0
             dependency.getProductEvidence().addEvidence("pom", "groupid", groupid, Confidence.LOW);
 1173  
         }
 1174  0
         String artifactid = interpolateString(pom.getArtifactId(), pomProperties);
 1175  0
         if (artifactid != null && !artifactid.isEmpty()) {
 1176  0
             if (artifactid.startsWith("org.") || artifactid.startsWith("com.")) {
 1177  0
                 artifactid = artifactid.substring(4);
 1178  
             }
 1179  0
             dependency.getProductEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.HIGH);
 1180  0
             dependency.getVendorEvidence().addEvidence("pom", "artifactid", artifactid, Confidence.LOW);
 1181  
         }
 1182  0
         final String version = interpolateString(pom.getVersion(), pomProperties);
 1183  0
         if (version != null && !version.isEmpty()) {
 1184  0
             dependency.getVersionEvidence().addEvidence("pom", "version", version, Confidence.HIGHEST);
 1185  
         }
 1186  
 
 1187  0
         final Parent parent = pom.getParent(); //grab parent GAV
 1188  0
         if (parent != null) {
 1189  0
             final String parentGroupId = interpolateString(parent.getGroupId(), pomProperties);
 1190  0
             if (parentGroupId != null && !parentGroupId.isEmpty()) {
 1191  0
                 if (groupid == null || groupid.isEmpty()) {
 1192  0
                     dependency.getVendorEvidence().addEvidence("pom", "parent.groupid", parentGroupId, Confidence.HIGH);
 1193  
                 } else {
 1194  0
                     dependency.getVendorEvidence().addEvidence("pom", "parent.groupid", parentGroupId, Confidence.MEDIUM);
 1195  
                 }
 1196  0
                 dependency.getProductEvidence().addEvidence("pom", "parent.groupid", parentGroupId, Confidence.LOW);
 1197  
             }
 1198  0
             final String parentArtifactId = interpolateString(parent.getArtifactId(), pomProperties);
 1199  0
             if (parentArtifactId != null && !parentArtifactId.isEmpty()) {
 1200  0
                 if (artifactid == null || artifactid.isEmpty()) {
 1201  0
                     dependency.getProductEvidence().addEvidence("pom", "parent.artifactid", parentArtifactId, Confidence.HIGH);
 1202  
                 } else {
 1203  0
                     dependency.getProductEvidence().addEvidence("pom", "parent.artifactid", parentArtifactId, Confidence.MEDIUM);
 1204  
                 }
 1205  0
                 dependency.getVendorEvidence().addEvidence("pom", "parent.artifactid", parentArtifactId, Confidence.LOW);
 1206  
             }
 1207  0
             final String parentVersion = interpolateString(parent.getVersion(), pomProperties);
 1208  0
             if (parentVersion != null && !parentVersion.isEmpty()) {
 1209  0
                 if (version == null || version.isEmpty()) {
 1210  0
                     dependency.getVersionEvidence().addEvidence("pom", "parent.version", parentVersion, Confidence.HIGH);
 1211  
                 } else {
 1212  0
                     dependency.getVersionEvidence().addEvidence("pom", "parent.version", parentVersion, Confidence.LOW);
 1213  
                 }
 1214  
             }
 1215  
         }
 1216  
         // org name
 1217  0
         final Organization org = pom.getOrganization();
 1218  0
         if (org != null && org.getName() != null) {
 1219  0
             final String orgName = interpolateString(org.getName(), pomProperties);
 1220  0
             if (orgName != null && !orgName.isEmpty()) {
 1221  0
                 dependency.getVendorEvidence().addEvidence("pom", "organization name", orgName, Confidence.HIGH);
 1222  
             }
 1223  
         }
 1224  
         //pom name
 1225  0
         final String pomName = interpolateString(pom.getName(), pomProperties);
 1226  0
         if (pomName != null && !pomName.isEmpty()) {
 1227  0
             dependency.getProductEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
 1228  0
             dependency.getVendorEvidence().addEvidence("pom", "name", pomName, Confidence.HIGH);
 1229  
         }
 1230  
 
 1231  
         //Description
 1232  0
         if (pom.getDescription() != null) {
 1233  0
             final String description = interpolateString(pom.getDescription(), pomProperties);
 1234  0
             if (description != null && !description.isEmpty()) {
 1235  0
                 addDescription(dependency, description, "pom", "description");
 1236  
             }
 1237  
         }
 1238  0
         extractLicense(pom, pomProperties, dependency);
 1239  0
     }
 1240  
 
 1241  
     /**
 1242  
      * Extracts the license information from the pom and adds it to the dependency.
 1243  
      *
 1244  
      * @param pom the pom object
 1245  
      * @param pomProperties the properties, used for string interpolation
 1246  
      * @param dependency the dependency to add license information too
 1247  
      */
 1248  
     private void extractLicense(Model pom, Properties pomProperties, Dependency dependency) {
 1249  
         //license
 1250  0
         if (pom.getLicenses() != null) {
 1251  0
             String license = null;
 1252  0
             for (License lic : pom.getLicenses().getLicense()) {
 1253  0
                 String tmp = null;
 1254  0
                 if (lic.getName() != null) {
 1255  0
                     tmp = interpolateString(lic.getName(), pomProperties);
 1256  
                 }
 1257  0
                 if (lic.getUrl() != null) {
 1258  0
                     if (tmp == null) {
 1259  0
                         tmp = interpolateString(lic.getUrl(), pomProperties);
 1260  
                     } else {
 1261  0
                         tmp += ": " + interpolateString(lic.getUrl(), pomProperties);
 1262  
                     }
 1263  
                 }
 1264  0
                 if (tmp == null) {
 1265  0
                     continue;
 1266  
                 }
 1267  0
                 if (HTML_DETECTION_PATTERN.matcher(tmp).find()) {
 1268  0
                     tmp = Jsoup.parse(tmp).text();
 1269  
                 }
 1270  0
                 if (license == null) {
 1271  0
                     license = tmp;
 1272  
                 } else {
 1273  0
                     license += "\n" + tmp;
 1274  
                 }
 1275  0
             }
 1276  0
             if (license != null) {
 1277  0
                 dependency.setLicense(license);
 1278  
             }
 1279  
         }
 1280  0
     }
 1281  
 
 1282  
     /**
 1283  
      * Stores information about a class name.
 1284  
      */
 1285  
     protected static class ClassNameInformation {
 1286  
 
 1287  
         /**
 1288  
          * <p>
 1289  
          * Stores information about a given class name. This class will keep the fully qualified class name and a list
 1290  
          * of the important parts of the package structure. Up to the first four levels of the package structure are
 1291  
          * stored, excluding a leading "org" or "com". Example:</p>
 1292  
          * <code>ClassNameInformation obj = new ClassNameInformation("org.owasp.dependencycheck.analyzer.JarAnalyzer");
 1293  
          * System.out.println(obj.getName());
 1294  
          * for (String p : obj.getPackageStructure())
 1295  
          *     System.out.println(p);
 1296  
          * </code>
 1297  
          * <p>
 1298  
          * Would result in:</p>
 1299  
          * <code>org.owasp.dependencycheck.analyzer.JarAnalyzer
 1300  
          * owasp
 1301  
          * dependencycheck
 1302  
          * analyzer
 1303  
          * jaranalyzer</code>
 1304  
          *
 1305  
          * @param className a fully qualified class name
 1306  
          */
 1307  0
         ClassNameInformation(String className) {
 1308  0
             name = className;
 1309  0
             if (name.contains("/")) {
 1310  0
                 final String[] tmp = className.toLowerCase().split("/");
 1311  0
                 int start = 0;
 1312  0
                 int end = 3;
 1313  0
                 if ("com".equals(tmp[0]) || "org".equals(tmp[0])) {
 1314  0
                     start = 1;
 1315  0
                     end = 4;
 1316  
                 }
 1317  0
                 if (tmp.length <= end) {
 1318  0
                     end = tmp.length - 1;
 1319  
                 }
 1320  0
                 for (int i = start; i <= end; i++) {
 1321  0
                     packageStructure.add(tmp[i]);
 1322  
                 }
 1323  0
             } else {
 1324  0
                 packageStructure.add(name);
 1325  
             }
 1326  0
         }
 1327  
         /**
 1328  
          * The fully qualified class name.
 1329  
          */
 1330  
         private String name;
 1331  
 
 1332  
         /**
 1333  
          * Get the value of name
 1334  
          *
 1335  
          * @return the value of name
 1336  
          */
 1337  
         public String getName() {
 1338  
             return name;
 1339  
         }
 1340  
 
 1341  
         /**
 1342  
          * Set the value of name
 1343  
          *
 1344  
          * @param name new value of name
 1345  
          */
 1346  
         public void setName(String name) {
 1347  
             this.name = name;
 1348  
         }
 1349  
         /**
 1350  
          * Up to the first four levels of the package structure, excluding a leading "org" or "com".
 1351  
          */
 1352  0
         private final ArrayList<String> packageStructure = new ArrayList<String>();
 1353  
 
 1354  
         /**
 1355  
          * Get the value of packageStructure
 1356  
          *
 1357  
          * @return the value of packageStructure
 1358  
          */
 1359  
         public ArrayList<String> getPackageStructure() {
 1360  
             return packageStructure;
 1361  
         }
 1362  
     }
 1363  
 
 1364  
     /**
 1365  
      * Retrieves the next temporary directory to extract an archive too.
 1366  
      *
 1367  
      * @return a directory
 1368  
      * @throws AnalysisException thrown if unable to create temporary directory
 1369  
      */
 1370  
     private File getNextTempDirectory() throws AnalysisException {
 1371  0
         dirCount += 1;
 1372  0
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 1373  
         //getting an exception for some directories not being able to be created; might be because the directory already exists?
 1374  0
         if (directory.exists()) {
 1375  0
             return getNextTempDirectory();
 1376  
         }
 1377  0
         if (!directory.mkdirs()) {
 1378  0
             final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
 1379  0
             throw new AnalysisException(msg);
 1380  
         }
 1381  0
         return directory;
 1382  
     }
 1383  
 }