Coverage Report - org.owasp.dependencycheck.analyzer.DependencyBundlingAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
DependencyBundlingAnalyzer
42%
63/147
35%
56/156
7.846
 
 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
 40  
  * grouped. An example would be Spring, Spring Beans, Spring MVC, etc. If they are all for the same version and have the
 41  
  * same relative path 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 <jeremy.long@owasp.org>
 46  
  */
 47  
 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  
     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
 95  
      * identifiers they are 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  
 
 134  0
                             if (isCore(dependency, nextDependency)) {
 135  0
                                 mergeDependencies(dependency, nextDependency, dependenciesToRemove);
 136  
                             } else {
 137  0
                                 mergeDependencies(nextDependency, dependency, dependenciesToRemove);
 138  0
                                 break; //since we merged into the next dependency - skip forward to the next in mainIterator
 139  
                             }
 140  
                         }
 141  1
                     }
 142  
                 }
 143  2
             }
 144  
             //removing dependencies here as ensuring correctness and avoiding ConcurrentUpdateExceptions
 145  
             // was difficult because of the inner iterator.
 146  1
             engine.getDependencies().removeAll(dependenciesToRemove);
 147  
         }
 148  2
     }
 149  
 
 150  
     /**
 151  
      * Adds the relatedDependency to the dependency's related dependencies.
 152  
      *
 153  
      * @param dependency the main dependency
 154  
      * @param relatedDependency a collection of dependencies to be removed from the main analysis loop, this is the
 155  
      * source of dependencies to remove
 156  
      * @param dependenciesToRemove a collection of dependencies that will be removed from the main analysis loop, this
 157  
      * function adds to this collection
 158  
      */
 159  
     private void mergeDependencies(final Dependency dependency, final Dependency relatedDependency, final Set<Dependency> dependenciesToRemove) {
 160  0
         dependency.addRelatedDependency(relatedDependency);
 161  0
         final Iterator<Dependency> i = relatedDependency.getRelatedDependencies().iterator();
 162  0
         while (i.hasNext()) {
 163  0
             dependency.addRelatedDependency(i.next());
 164  0
             i.remove();
 165  
         }
 166  0
         dependenciesToRemove.add(relatedDependency);
 167  0
     }
 168  
 
 169  
     /**
 170  
      * Attempts to trim a maven repo to a common base path. This is typically
 171  
      * [drive]\[repo_location]\repository\[path1]\[path2].
 172  
      *
 173  
      * @param path the path to trim
 174  
      * @return a string representing the base path.
 175  
      */
 176  
     private String getBaseRepoPath(final String path) {
 177  0
         int pos = path.indexOf("repository" + File.separator) + 11;
 178  0
         if (pos < 0) {
 179  0
             return path;
 180  
         }
 181  0
         int tmp = path.indexOf(File.separator, pos);
 182  0
         if (tmp <= 0) {
 183  0
             return path;
 184  
         }
 185  0
         if (tmp > 0) {
 186  0
             pos = tmp + 1;
 187  
         }
 188  0
         tmp = path.indexOf(File.separator, pos);
 189  0
         if (tmp > 0) {
 190  0
             pos = tmp + 1;
 191  
         }
 192  0
         return path.substring(0, pos);
 193  
     }
 194  
 
 195  
     /**
 196  
      * Returns true if the file names (and version if it exists) of the two dependencies are sufficiently similar.
 197  
      *
 198  
      * @param dependency1 a dependency2 to compare
 199  
      * @param dependency2 a dependency2 to compare
 200  
      * @return true if the identifiers in the two supplied dependencies are equal
 201  
      */
 202  
     private boolean fileNameMatch(Dependency dependency1, Dependency dependency2) {
 203  0
         if (dependency1 == null || dependency1.getFileName() == null
 204  
                 || dependency2 == null || dependency2.getFileName() == null) {
 205  0
             return false;
 206  
         }
 207  0
         final String fileName1 = dependency1.getActualFile().getName();
 208  0
         final String fileName2 = dependency2.getActualFile().getName();
 209  
 
 210  
 //        //REMOVED because this is attempting to duplicate what is in the hasSameBasePath function.
 211  
 //        final File one = new File(fileName1);
 212  
 //        final File two = new File(fileName2);
 213  
 //        final String oneParent = one.getParent();
 214  
 //        final String twoParent = two.getParent();
 215  
 //        if (oneParent != null) {
 216  
 //            if (oneParent.equals(twoParent)) {
 217  
 //                fileName1 = one.getName();
 218  
 //                fileName2 = two.getName();
 219  
 //            } else {
 220  
 //                return false;
 221  
 //            }
 222  
 //        } else if (twoParent != null) {
 223  
 //            return false;
 224  
 //        }
 225  
         //version check
 226  0
         final DependencyVersion version1 = DependencyVersionUtil.parseVersion(fileName1);
 227  0
         final DependencyVersion version2 = DependencyVersionUtil.parseVersion(fileName2);
 228  0
         if (version1 != null && version2 != null) {
 229  0
             if (!version1.equals(version2)) {
 230  0
                 return false;
 231  
             }
 232  
         }
 233  
 
 234  
         //filename check
 235  0
         final Matcher match1 = STARTING_TEXT_PATTERN.matcher(fileName1);
 236  0
         final Matcher match2 = STARTING_TEXT_PATTERN.matcher(fileName2);
 237  0
         if (match1.find() && match2.find()) {
 238  0
             return match1.group().equals(match2.group());
 239  
         }
 240  
 
 241  0
         return false;
 242  
     }
 243  
 
 244  
     /**
 245  
      * Returns true if the CPE identifiers in the two supplied dependencies are equal.
 246  
      *
 247  
      * @param dependency1 a dependency2 to compare
 248  
      * @param dependency2 a dependency2 to compare
 249  
      * @return true if the identifiers in the two supplied dependencies are equal
 250  
      */
 251  
     private boolean cpeIdentifiersMatch(Dependency dependency1, Dependency dependency2) {
 252  1
         if (dependency1 == null || dependency1.getIdentifiers() == null
 253  
                 || dependency2 == null || dependency2.getIdentifiers() == null) {
 254  0
             return false;
 255  
         }
 256  1
         boolean matches = false;
 257  1
         int cpeCount1 = 0;
 258  1
         int cpeCount2 = 0;
 259  1
         for (Identifier i : dependency1.getIdentifiers()) {
 260  1
             if ("cpe".equals(i.getType())) {
 261  0
                 cpeCount1 += 1;
 262  
             }
 263  1
         }
 264  1
         for (Identifier i : dependency2.getIdentifiers()) {
 265  3
             if ("cpe".equals(i.getType())) {
 266  2
                 cpeCount2 += 1;
 267  
             }
 268  3
         }
 269  1
         if (cpeCount1 > 0 && cpeCount1 == cpeCount2) {
 270  0
             for (Identifier i : dependency1.getIdentifiers()) {
 271  0
                 if ("cpe".equals(i.getType())) {
 272  0
                     matches |= dependency2.getIdentifiers().contains(i);
 273  0
                     if (!matches) {
 274  0
                         break;
 275  
                     }
 276  
                 }
 277  0
             }
 278  
         }
 279  1
         if (LogUtils.isVerboseLoggingEnabled()) {
 280  0
             final String msg = String.format("IdentifiersMatch=%s (%s, %s)", matches, dependency1.getFileName(), dependency2.getFileName());
 281  0
             LOGGER.log(Level.FINE, msg);
 282  
         }
 283  1
         return matches;
 284  
     }
 285  
 
 286  
     /**
 287  
      * Determines if the two dependencies have the same base path.
 288  
      *
 289  
      * @param dependency1 a Dependency object
 290  
      * @param dependency2 a Dependency object
 291  
      * @return true if the base paths of the dependencies are identical
 292  
      */
 293  
     private boolean hasSameBasePath(Dependency dependency1, Dependency dependency2) {
 294  0
         if (dependency1 == null || dependency2 == null) {
 295  0
             return false;
 296  
         }
 297  0
         final File lFile = new File(dependency1.getFilePath());
 298  0
         String left = lFile.getParent();
 299  0
         final File rFile = new File(dependency2.getFilePath());
 300  0
         String right = rFile.getParent();
 301  0
         if (left == null) {
 302  0
             return right == null;
 303  
         }
 304  0
         if (left.equalsIgnoreCase(right)) {
 305  0
             return true;
 306  
         }
 307  0
         if (left.matches(".*[/\\\\]repository[/\\\\].*") && right.matches(".*[/\\\\]repository[/\\\\].*")) {
 308  0
             left = getBaseRepoPath(left);
 309  0
             right = getBaseRepoPath(right);
 310  
         }
 311  0
         if (left.equalsIgnoreCase(right)) {
 312  0
             return true;
 313  
         }
 314  
         //new code
 315  0
         for (Dependency child : dependency2.getRelatedDependencies()) {
 316  0
             if (hasSameBasePath(dependency1, child)) {
 317  0
                 return true;
 318  
             }
 319  0
         }
 320  0
         return false;
 321  
     }
 322  
 
 323  
     /**
 324  
      * This is likely a very broken attempt at determining if the 'left' dependency is the 'core' library in comparison
 325  
      * to the 'right' library.
 326  
      *
 327  
      * @param left the dependency to test
 328  
      * @param right the dependency to test against
 329  
      * @return a boolean indicating whether or not the left dependency should be considered the "core" version.
 330  
      */
 331  
     boolean isCore(Dependency left, Dependency right) {
 332  2
         final String leftName = left.getFileName().toLowerCase();
 333  2
         final String rightName = right.getFileName().toLowerCase();
 334  
 
 335  
         final boolean returnVal;
 336  2
         if (!rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+")
 337  
                 || rightName.contains("core") && !leftName.contains("core")
 338  
                 || rightName.contains("kernel") && !leftName.contains("kernel")) {
 339  0
             returnVal = false;
 340  2
         } else if (rightName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+") && !leftName.matches(".*\\.(tar|tgz|gz|zip|ear|war).+")
 341  
                 || !rightName.contains("core") && leftName.contains("core")
 342  
                 || !rightName.contains("kernel") && leftName.contains("kernel")) {
 343  2
             returnVal = true;
 344  
 //        } else if (leftName.matches(".*struts2\\-core.*") && rightName.matches(".*xwork\\-core.*")) {
 345  
 //            returnVal = true;
 346  
 //        } else if (rightName.matches(".*struts2\\-core.*") && leftName.matches(".*xwork\\-core.*")) {
 347  
 //            returnVal = false;
 348  
         } else {
 349  
             /*
 350  
              * considered splitting the names up and comparing the components,
 351  
              * but decided that the file name length should be sufficient as the
 352  
              * "core" component, if this follows a normal naming protocol should
 353  
              * be shorter:
 354  
              * axis2-saaj-1.4.1.jar
 355  
              * axis2-1.4.1.jar       <-----
 356  
              * axis2-kernel-1.4.1.jar
 357  
              */
 358  0
             returnVal = leftName.length() <= rightName.length();
 359  
         }
 360  2
         if (LogUtils.isVerboseLoggingEnabled()) {
 361  0
             final String msg = String.format("IsCore=%s (%s, %s)", returnVal, left.getFileName(), right.getFileName());
 362  0
             LOGGER.log(Level.FINE, msg);
 363  
         }
 364  2
         return returnVal;
 365  
     }
 366  
 
 367  
     /**
 368  
      * Compares the SHA1 hashes of two dependencies to determine if they are equal.
 369  
      *
 370  
      * @param dependency1 a dependency object to compare
 371  
      * @param dependency2 a dependency object to compare
 372  
      * @return true if the sha1 hashes of the two dependencies match; otherwise false
 373  
      */
 374  
     private boolean hashesMatch(Dependency dependency1, Dependency dependency2) {
 375  1
         if (dependency1 == null || dependency2 == null || dependency1.getSha1sum() == null || dependency2.getSha1sum() == null) {
 376  0
             return false;
 377  
         }
 378  1
         return dependency1.getSha1sum().equals(dependency2.getSha1sum());
 379  
     }
 380  
 
 381  
     /**
 382  
      * Determines if the jar is shaded and the created pom.xml identified the same CPE as the jar - if so, the pom.xml
 383  
      * dependency should be removed.
 384  
      *
 385  
      * @param dependency a dependency to check
 386  
      * @param nextDependency another dependency to check
 387  
      * @return true if on of the dependencies is a pom.xml and the identifiers between the two collections match;
 388  
      * otherwise false
 389  
      */
 390  
     private boolean isShadedJar(Dependency dependency, Dependency nextDependency) {
 391  1
         final String mainName = dependency.getFileName().toLowerCase();
 392  1
         final String nextName = nextDependency.getFileName().toLowerCase();
 393  1
         if (mainName.endsWith(".jar") && nextName.endsWith("pom.xml")) {
 394  0
             return dependency.getIdentifiers().containsAll(nextDependency.getIdentifiers());
 395  1
         } else if (nextName.endsWith(".jar") && mainName.endsWith("pom.xml")) {
 396  0
             return nextDependency.getIdentifiers().containsAll(dependency.getIdentifiers());
 397  
         }
 398  1
         return false;
 399  
     }
 400  
 
 401  
     /**
 402  
      * Determines which path is shortest; if path lengths are equal then we use compareTo of the string method to
 403  
      * determine if the first path is smaller.
 404  
      *
 405  
      * @param left the first path to compare
 406  
      * @param right the second path to compare
 407  
      * @return <code>true</code> if the leftPath is the shortest; otherwise <code>false</code>
 408  
      */
 409  
     protected boolean firstPathIsShortest(String left, String right) {
 410  5
         final String leftPath = left.replace('\\', '/');
 411  5
         final String rightPath = right.replace('\\', '/');
 412  
 
 413  5
         final int leftCount = countChar(leftPath, '/');
 414  5
         final int rightCount = countChar(rightPath, '/');
 415  5
         if (leftCount == rightCount) {
 416  3
             return leftPath.compareTo(rightPath) <= 0;
 417  
         } else {
 418  2
             return leftCount < rightCount;
 419  
         }
 420  
     }
 421  
 
 422  
     /**
 423  
      * Counts the number of times the character is present in the string.
 424  
      *
 425  
      * @param string the string to count the characters in
 426  
      * @param c the character to count
 427  
      * @return the number of times the character is present in the string
 428  
      */
 429  
     private int countChar(String string, char c) {
 430  10
         int count = 0;
 431  10
         final int max = string.length();
 432  116
         for (int i = 0; i < max; i++) {
 433  106
             if (c == string.charAt(i)) {
 434  28
                 count++;
 435  
             }
 436  
         }
 437  10
         return count;
 438  
     }
 439  
 }