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