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