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