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