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