Coverage Report - org.owasp.dependencycheck.analyzer.DependencyBundlingAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
DependencyBundlingAnalyzer
41%
63/151
33%
53/158
7.923
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.analyzer;
 19  
 
 20  
 import java.io.File;
 21  
 import java.util.HashSet;
 22  
 import java.util.Iterator;
 23  
 import java.util.ListIterator;
 24  
 import java.util.Set;
 25  
 import java.util.logging.Level;
 26  
 import java.util.logging.Logger;
 27  
 import java.util.regex.Matcher;
 28  
 import java.util.regex.Pattern;
 29  
 import org.owasp.dependencycheck.Engine;
 30  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 31  
 import org.owasp.dependencycheck.dependency.Dependency;
 32  
 import org.owasp.dependencycheck.dependency.Identifier;
 33  
 import org.owasp.dependencycheck.utils.DependencyVersion;
 34  
 import org.owasp.dependencycheck.utils.DependencyVersionUtil;
 35  
 import org.owasp.dependencycheck.utils.LogUtils;
 36  
 
 37  
 /**
 38  
  * <p>
 39  
  * This analyzer ensures dependencies that should be grouped together, to remove excess noise from the report, are grouped. An
 40  
  * example would be Spring, Spring Beans, Spring MVC, etc. If they are all for the same version and have the same relative path
 41  
  * then these should be grouped into a single dependency under the core/main library.</p>
 42  
  * <p>
 43  
  * Note, this grouping only works on dependencies with identified CVE entries</p>
 44  
  *
 45  
  * @author Jeremy Long
 46  
  */
 47  6
 public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Analyzer {
 48  
 
 49  
     /**
 50  
      * The Logger.
 51  
      */
 52  1
     private static final Logger LOGGER = Logger.getLogger(DependencyBundlingAnalyzer.class.getName());
 53  
 
 54  
     //<editor-fold defaultstate="collapsed" desc="Constants and Member Variables">
 55  
     /**
 56  
      * A pattern for obtaining the first part of a filename.
 57  
      */
 58  1
     private static final Pattern STARTING_TEXT_PATTERN = Pattern.compile("^[a-zA-Z0-9]*");
 59  
     /**
 60  
      * a flag indicating if this analyzer has run. This analyzer only runs once.
 61  
      */
 62  6
     private boolean analyzed = false;
 63  
     //</editor-fold>
 64  
     //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
 65  
     /**
 66  
      * The name of the analyzer.
 67  
      */
 68  
     private static final String ANALYZER_NAME = "Dependency Bundling Analyzer";
 69  
     /**
 70  
      * The phase that this analyzer is intended to run in.
 71  
      */
 72  1
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.PRE_FINDING_ANALYSIS;
 73  
 
 74  
     /**
 75  
      * Returns the name of the analyzer.
 76  
      *
 77  
      * @return the name of the analyzer.
 78  
      */
 79  
     public String getName() {
 80  5
         return ANALYZER_NAME;
 81  
     }
 82  
 
 83  
     /**
 84  
      * Returns the phase that the analyzer is intended to run in.
 85  
      *
 86  
      * @return the phase that the analyzer is intended to run in.
 87  
      */
 88  
     public AnalysisPhase getAnalysisPhase() {
 89  2
         return ANALYSIS_PHASE;
 90  
     }
 91  
     //</editor-fold>
 92  
 
 93  
     /**
 94  
      * Analyzes a set of dependencies. If they have been found to have the same base path and the same set of identifiers they are
 95  
      * likely related. The related dependencies are bundled into a single reportable item.
 96  
      *
 97  
      * @param ignore this analyzer ignores the dependency being analyzed
 98  
      * @param engine the engine that is scanning the dependencies
 99  
      * @throws AnalysisException is thrown if there is an error reading the JAR file.
 100  
      */
 101  
     @Override
 102  
     public void analyze(Dependency ignore, Engine engine) throws AnalysisException {
 103  2
         if (!analyzed) {
 104  1
             analyzed = true;
 105  1
             final Set<Dependency> dependenciesToRemove = new HashSet<Dependency>();
 106  1
             final ListIterator<Dependency> mainIterator = engine.getDependencies().listIterator();
 107  
             //for (Dependency nextDependency : engine.getDependencies()) {
 108  3
             while (mainIterator.hasNext()) {
 109  2
                 final Dependency dependency = mainIterator.next();
 110  2
                 if (mainIterator.hasNext() && !dependenciesToRemove.contains(dependency)) {
 111  1
                     final ListIterator<Dependency> subIterator = engine.getDependencies().listIterator(mainIterator.nextIndex());
 112  2
                     while (subIterator.hasNext()) {
 113  1
                         final Dependency nextDependency = subIterator.next();
 114  1
                         if (hashesMatch(dependency, nextDependency)) {
 115  0
                             if (firstPathIsShortest(dependency.getFilePath(), nextDependency.getFilePath())) {
 116  0
                                 mergeDependencies(dependency, nextDependency, dependenciesToRemove);
 117  
                             } else {
 118  0
                                 mergeDependencies(nextDependency, dependency, dependenciesToRemove);
 119  0
                                 break; //since we merged into the next dependency - skip forward to the next in mainIterator
 120  
                             }
 121  1
                         } else if (isShadedJar(dependency, nextDependency)) {
 122  0
                             if (dependency.getFileName().toLowerCase().endsWith("pom.xml")) {
 123  0
                                 mergeDependencies(nextDependency, dependency, dependenciesToRemove);
 124  0
                                 nextDependency.getRelatedDependencies().remove(dependency);
 125  0
                                 break;
 126  
                             } else {
 127  0
                                 mergeDependencies(dependency, nextDependency, dependenciesToRemove);
 128  0
                                 nextDependency.getRelatedDependencies().remove(nextDependency);
 129  
                             }
 130  1
                         } else if (cpeIdentifiersMatch(dependency, nextDependency)
 131  
                                 && hasSameBasePath(dependency, nextDependency)
 132  
                                 && fileNameMatch(dependency, nextDependency)) {
 133  0
                             if (isCore(dependency, nextDependency)) {
 134  0
                                 mergeDependencies(dependency, nextDependency, dependenciesToRemove);
 135  
                             } else {
 136  0
                                 mergeDependencies(nextDependency, dependency, dependenciesToRemove);
 137  0
                                 break; //since we merged into the next dependency - skip forward to the next in mainIterator
 138  
                             }
 139  
                         }
 140  1
                     }
 141  
                 }
 142  2
             }
 143  
             //removing dependencies here as ensuring correctness and avoiding ConcurrentUpdateExceptions
 144  
             // was difficult because of the inner iterator.
 145  1
             engine.getDependencies().removeAll(dependenciesToRemove);
 146  
         }
 147  2
     }
 148  
 
 149  
     /**
 150  
      * Adds the relatedDependency to the dependency's related dependencies.
 151  
      *
 152  
      * @param dependency the main dependency
 153  
      * @param relatedDependency a collection of dependencies to be removed from the main analysis loop, this is the source of
 154  
      * dependencies to remove
 155  
      * @param dependenciesToRemove a collection of dependencies that will be removed from the main analysis loop, this function
 156  
      * adds to this collection
 157  
      */
 158  
     private void mergeDependencies(final Dependency dependency, final Dependency relatedDependency, final Set<Dependency> dependenciesToRemove) {
 159  0
         dependency.addRelatedDependency(relatedDependency);
 160  0
         final Iterator<Dependency> i = relatedDependency.getRelatedDependencies().iterator();
 161  0
         while (i.hasNext()) {
 162  0
             dependency.addRelatedDependency(i.next());
 163  0
             i.remove();
 164  
         }
 165  0
         if (dependency.getSha1sum().equals(relatedDependency.getSha1sum())) {
 166  0
             dependency.addAllProjectReferences(relatedDependency.getProjectReferences());
 167  
         }
 168  0
         dependenciesToRemove.add(relatedDependency);
 169  0
     }
 170  
 
 171  
     /**
 172  
      * Attempts to trim a maven repo to a common base path. This is typically [drive]\[repo_location]\repository\[path1]\[path2].
 173  
      *
 174  
      * @param path the path to trim
 175  
      * @return a string representing the base path.
 176  
      */
 177  
     private String getBaseRepoPath(final String path) {
 178  0
         int pos = path.indexOf("repository" + File.separator) + 11;
 179  0
         if (pos < 0) {
 180  0
             return path;
 181  
         }
 182  0
         int tmp = path.indexOf(File.separator, pos);
 183  0
         if (tmp <= 0) {
 184  0
             return path;
 185  
         }
 186  0
         if (tmp > 0) {
 187  0
             pos = tmp + 1;
 188  
         }
 189  0
         tmp = path.indexOf(File.separator, pos);
 190  0
         if (tmp > 0) {
 191  0
             pos = tmp + 1;
 192  
         }
 193  0
         return path.substring(0, pos);
 194  
     }
 195  
 
 196  
     /**
 197  
      * Returns true if the file names (and version if it exists) of the two dependencies are sufficiently similar.
 198  
      *
 199  
      * @param dependency1 a dependency2 to compare
 200  
      * @param dependency2 a dependency2 to compare
 201  
      * @return true if the identifiers in the two supplied dependencies are equal
 202  
      */
 203  
     private boolean fileNameMatch(Dependency dependency1, Dependency dependency2) {
 204  0
         if (dependency1 == null || dependency1.getFileName() == null
 205  
                 || dependency2 == null || dependency2.getFileName() == null) {
 206  0
             return false;
 207  
         }
 208  0
         final String fileName1 = dependency1.getActualFile().getName();
 209  0
         final String fileName2 = dependency2.getActualFile().getName();
 210  
 
 211  
         //version check
 212  0
         final DependencyVersion version1 = DependencyVersionUtil.parseVersion(fileName1);
 213  0
         final DependencyVersion version2 = DependencyVersionUtil.parseVersion(fileName2);
 214  0
         if (version1 != null && version2 != null) {
 215  0
             if (!version1.equals(version2)) {
 216  0
                 return false;
 217  
             }
 218  
         }
 219  
 
 220  
         //filename check
 221  0
         final Matcher match1 = STARTING_TEXT_PATTERN.matcher(fileName1);
 222  0
         final Matcher match2 = STARTING_TEXT_PATTERN.matcher(fileName2);
 223  0
         if (match1.find() && match2.find()) {
 224  0
             return match1.group().equals(match2.group());
 225  
         }
 226  
 
 227  0
         return false;
 228  
     }
 229  
 
 230  
     /**
 231  
      * Returns true if the CPE identifiers in the two supplied dependencies are equal.
 232  
      *
 233  
      * @param dependency1 a dependency2 to compare
 234  
      * @param dependency2 a dependency2 to compare
 235  
      * @return true if the identifiers in the two supplied dependencies are equal
 236  
      */
 237  
     private boolean cpeIdentifiersMatch(Dependency dependency1, Dependency dependency2) {
 238  1
         if (dependency1 == null || dependency1.getIdentifiers() == null
 239  
                 || dependency2 == null || dependency2.getIdentifiers() == null) {
 240  0
             return false;
 241  
         }
 242  1
         boolean matches = false;
 243  1
         int cpeCount1 = 0;
 244  1
         int cpeCount2 = 0;
 245  1
         for (Identifier i : dependency1.getIdentifiers()) {
 246  0
             if ("cpe".equals(i.getType())) {
 247  0
                 cpeCount1 += 1;
 248  
             }
 249  0
         }
 250  1
         for (Identifier i : dependency2.getIdentifiers()) {
 251  2
             if ("cpe".equals(i.getType())) {
 252  2
                 cpeCount2 += 1;
 253  
             }
 254  2
         }
 255  1
         if (cpeCount1 > 0 && cpeCount1 == cpeCount2) {
 256  0
             for (Identifier i : dependency1.getIdentifiers()) {
 257  0
                 if ("cpe".equals(i.getType())) {
 258  0
                     matches |= dependency2.getIdentifiers().contains(i);
 259  0
                     if (!matches) {
 260  0
                         break;
 261  
                     }
 262  
                 }
 263  0
             }
 264  
         }
 265  1
         if (LogUtils.isVerboseLoggingEnabled()) {
 266  0
             final String msg = String.format("IdentifiersMatch=%s (%s, %s)", matches, dependency1.getFileName(), dependency2.getFileName());
 267  0
             LOGGER.log(Level.FINE, msg);
 268  
         }
 269  1
         return matches;
 270  
     }
 271  
 
 272  
     /**
 273  
      * Determines if the two dependencies have the same base path.
 274  
      *
 275  
      * @param dependency1 a Dependency object
 276  
      * @param dependency2 a Dependency object
 277  
      * @return true if the base paths of the dependencies are identical
 278  
      */
 279  
     private boolean hasSameBasePath(Dependency dependency1, Dependency dependency2) {
 280  0
         if (dependency1 == null || dependency2 == null) {
 281  0
             return false;
 282  
         }
 283  0
         final File lFile = new File(dependency1.getFilePath());
 284  0
         String left = lFile.getParent();
 285  0
         final File rFile = new File(dependency2.getFilePath());
 286  0
         String right = rFile.getParent();
 287  0
         if (left == null) {
 288  0
             return right == null;
 289  
         }
 290  0
         if (left.equalsIgnoreCase(right)) {
 291  0
             return true;
 292  
         }
 293  0
         if (left.matches(".*[/\\\\]repository[/\\\\].*") && right.matches(".*[/\\\\]repository[/\\\\].*")) {
 294  0
             left = getBaseRepoPath(left);
 295  0
             right = getBaseRepoPath(right);
 296  
         }
 297  0
         if (left.equalsIgnoreCase(right)) {
 298  0
             return true;
 299  
         }
 300  
         //new code
 301  0
         for (Dependency child : dependency2.getRelatedDependencies()) {
 302  0
             if (hasSameBasePath(dependency1, child)) {
 303  0
                 return true;
 304  
             }
 305  0
         }
 306  0
         return false;
 307  
     }
 308  
 
 309  
     /**
 310  
      * This is likely a very broken attempt at determining if the 'left' dependency is the 'core' library in comparison to the
 311  
      * 'right' library.
 312  
      *
 313  
      * @param left the dependency to test
 314  
      * @param right the dependency to test against
 315  
      * @return a boolean indicating whether or not the left dependency should be considered the "core" version.
 316  
      */
 317  
     boolean isCore(Dependency left, Dependency right) {
 318  2
         final String leftName = left.getFileName().toLowerCase();
 319  2
         final String rightName = right.getFileName().toLowerCase();
 320  
 
 321  
         final boolean returnVal;
 322  2
         if (!rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+")
 323  
                 || rightName.contains("core") && !leftName.contains("core")
 324  
                 || rightName.contains("kernel") && !leftName.contains("kernel")) {
 325  0
             returnVal = false;
 326  2
         } else if (rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && !leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+")
 327  
                 || !rightName.contains("core") && leftName.contains("core")
 328  
                 || !rightName.contains("kernel") && leftName.contains("kernel")) {
 329  2
             returnVal = true;
 330  
 //        } else if (leftName.matches(".*struts2\\-core.*") && rightName.matches(".*xwork\\-core.*")) {
 331  
 //            returnVal = true;
 332  
 //        } else if (rightName.matches(".*struts2\\-core.*") && leftName.matches(".*xwork\\-core.*")) {
 333  
 //            returnVal = false;
 334  
         } else {
 335  
             /*
 336  
              * considered splitting the names up and comparing the components,
 337  
              * but decided that the file name length should be sufficient as the
 338  
              * "core" component, if this follows a normal naming protocol should
 339  
              * be shorter:
 340  
              * axis2-saaj-1.4.1.jar
 341  
              * axis2-1.4.1.jar       <-----
 342  
              * axis2-kernel-1.4.1.jar
 343  
              */
 344  0
             returnVal = leftName.length() <= rightName.length();
 345  
         }
 346  2
         if (LogUtils.isVerboseLoggingEnabled()) {
 347  0
             final String msg = String.format("IsCore=%s (%s, %s)", returnVal, left.getFileName(), right.getFileName());
 348  0
             LOGGER.log(Level.FINE, msg);
 349  
         }
 350  2
         return returnVal;
 351  
     }
 352  
 
 353  
     /**
 354  
      * Compares the SHA1 hashes of two dependencies to determine if they are equal.
 355  
      *
 356  
      * @param dependency1 a dependency object to compare
 357  
      * @param dependency2 a dependency object to compare
 358  
      * @return true if the sha1 hashes of the two dependencies match; otherwise false
 359  
      */
 360  
     private boolean hashesMatch(Dependency dependency1, Dependency dependency2) {
 361  1
         if (dependency1 == null || dependency2 == null || dependency1.getSha1sum() == null || dependency2.getSha1sum() == null) {
 362  0
             return false;
 363  
         }
 364  1
         return dependency1.getSha1sum().equals(dependency2.getSha1sum());
 365  
     }
 366  
 
 367  
     /**
 368  
      * Determines if the jar is shaded and the created pom.xml identified the same CPE as the jar - if so, the pom.xml dependency
 369  
      * should be removed.
 370  
      *
 371  
      * @param dependency a dependency to check
 372  
      * @param nextDependency another dependency to check
 373  
      * @return true if on of the dependencies is a pom.xml and the identifiers between the two collections match; otherwise false
 374  
      */
 375  
     private boolean isShadedJar(Dependency dependency, Dependency nextDependency) {
 376  1
         final String mainName = dependency.getFileName().toLowerCase();
 377  1
         final String nextName = nextDependency.getFileName().toLowerCase();
 378  1
         if (mainName.endsWith(".jar") && nextName.endsWith("pom.xml")) {
 379  0
             return dependency.getIdentifiers().containsAll(nextDependency.getIdentifiers());
 380  1
         } else if (nextName.endsWith(".jar") && mainName.endsWith("pom.xml")) {
 381  0
             return nextDependency.getIdentifiers().containsAll(dependency.getIdentifiers());
 382  
         }
 383  1
         return false;
 384  
     }
 385  
 
 386  
     /**
 387  
      * Determines which path is shortest; if path lengths are equal then we use compareTo of the string method to determine if the
 388  
      * first path is smaller.
 389  
      *
 390  
      * @param left the first path to compare
 391  
      * @param right the second path to compare
 392  
      * @return <code>true</code> if the leftPath is the shortest; otherwise <code>false</code>
 393  
      */
 394  
     protected boolean firstPathIsShortest(String left, String right) {
 395  5
         final String leftPath = left.replace('\\', '/');
 396  5
         final String rightPath = right.replace('\\', '/');
 397  
 
 398  5
         final int leftCount = countChar(leftPath, '/');
 399  5
         final int rightCount = countChar(rightPath, '/');
 400  5
         if (leftCount == rightCount) {
 401  3
             return leftPath.compareTo(rightPath) <= 0;
 402  
         } else {
 403  2
             return leftCount < rightCount;
 404  
         }
 405  
     }
 406  
 
 407  
     /**
 408  
      * Counts the number of times the character is present in the string.
 409  
      *
 410  
      * @param string the string to count the characters in
 411  
      * @param c the character to count
 412  
      * @return the number of times the character is present in the string
 413  
      */
 414  
     private int countChar(String string, char c) {
 415  10
         int count = 0;
 416  10
         final int max = string.length();
 417  116
         for (int i = 0; i < max; i++) {
 418  106
             if (c == string.charAt(i)) {
 419  28
                 count++;
 420  
             }
 421  
         }
 422  10
         return count;
 423  
     }
 424  
 }