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