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