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