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