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