Coverage Report - org.owasp.dependencycheck.Engine
 
Classes in this File Line Coverage Branch Coverage Complexity
Engine
53%
111/208
55%
39/70
3.348
 
 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;
 19  
 
 20  
 import java.io.File;
 21  
 import java.util.ArrayList;
 22  
 import java.util.EnumMap;
 23  
 import java.util.HashSet;
 24  
 import java.util.Iterator;
 25  
 import java.util.List;
 26  
 import java.util.Set;
 27  
 import java.util.logging.Level;
 28  
 import java.util.logging.Logger;
 29  
 import org.owasp.dependencycheck.analyzer.AnalysisPhase;
 30  
 import org.owasp.dependencycheck.analyzer.Analyzer;
 31  
 import org.owasp.dependencycheck.analyzer.AnalyzerService;
 32  
 import org.owasp.dependencycheck.analyzer.FileTypeAnalyzer;
 33  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 34  
 import org.owasp.dependencycheck.data.nvdcve.ConnectionFactory;
 35  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 36  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 37  
 import org.owasp.dependencycheck.data.update.CachedWebDataSource;
 38  
 import org.owasp.dependencycheck.data.update.UpdateService;
 39  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 40  
 import org.owasp.dependencycheck.dependency.Dependency;
 41  
 import org.owasp.dependencycheck.exception.NoDataException;
 42  
 import org.owasp.dependencycheck.utils.FileUtils;
 43  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 44  
 import org.owasp.dependencycheck.utils.Settings;
 45  
 
 46  
 /**
 47  
  * Scans files, directories, etc. for Dependencies. Analyzers are loaded and used to process the files found by the
 48  
  * scan, if a file is encountered and an Analyzer is associated with the file type then the file is turned into a
 49  
  * dependency.
 50  
  *
 51  
  * @author Jeremy Long <jeremy.long@owasp.org>
 52  
  */
 53  
 public class Engine {
 54  
 
 55  
     /**
 56  
      * The list of dependencies.
 57  
      */
 58  1
     private List<Dependency> dependencies = new ArrayList<Dependency>();
 59  
     /**
 60  
      * A Map of analyzers grouped by Analysis phase.
 61  
      */
 62  1
     private EnumMap<AnalysisPhase, List<Analyzer>> analyzers = new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
 63  
 
 64  
     /**
 65  
      * A Map of analyzers grouped by Analysis phase.
 66  
      */
 67  1
     private Set<FileTypeAnalyzer> fileTypeAnalyzers = new HashSet<FileTypeAnalyzer>();
 68  
 
 69  
     /**
 70  
      * The ClassLoader to use when dynamically loading Analyzer and Update services.
 71  
      */
 72  1
     private ClassLoader serviceClassLoader = Thread.currentThread().getContextClassLoader();
 73  
     /**
 74  
      * The Logger for use throughout the class.
 75  
      */
 76  1
     private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
 77  
 
 78  
     /**
 79  
      * Creates a new Engine.
 80  
      *
 81  
      * @throws DatabaseException thrown if there is an error connecting to the database
 82  
      */
 83  1
     public Engine() throws DatabaseException {
 84  1
         initializeEngine();
 85  1
     }
 86  
 
 87  
     /**
 88  
      * Creates a new Engine.
 89  
      *
 90  
      * @param serviceClassLoader a reference the class loader being used
 91  
      * @throws DatabaseException thrown if there is an error connecting to the database
 92  
      */
 93  0
     public Engine(ClassLoader serviceClassLoader) throws DatabaseException {
 94  0
         this.serviceClassLoader = serviceClassLoader;
 95  0
         initializeEngine();
 96  0
     }
 97  
 
 98  
     /**
 99  
      * Creates a new Engine using the specified classloader to dynamically load Analyzer and Update services.
 100  
      *
 101  
      * @throws DatabaseException thrown if there is an error connecting to the database
 102  
      */
 103  
     protected final void initializeEngine() throws DatabaseException {
 104  1
         ConnectionFactory.initialize();
 105  1
         loadAnalyzers();
 106  1
     }
 107  
 
 108  
     /**
 109  
      * Properly cleans up resources allocated during analysis.
 110  
      */
 111  
     public void cleanup() {
 112  0
         ConnectionFactory.cleanup();
 113  0
     }
 114  
 
 115  
     /**
 116  
      * Loads the analyzers specified in the configuration file (or system properties).
 117  
      */
 118  
     private void loadAnalyzers() {
 119  1
         if (analyzers.size() > 0) {
 120  0
             return;
 121  
         }
 122  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 123  9
             analyzers.put(phase, new ArrayList<Analyzer>());
 124  
         }
 125  
 
 126  1
         final AnalyzerService service = new AnalyzerService(serviceClassLoader);
 127  1
         final Iterator<Analyzer> iterator = service.getAnalyzers();
 128  15
         while (iterator.hasNext()) {
 129  14
             final Analyzer a = iterator.next();
 130  14
             analyzers.get(a.getAnalysisPhase()).add(a);
 131  14
             if (a instanceof FileTypeAnalyzer) {
 132  6
                 this.fileTypeAnalyzers.add((FileTypeAnalyzer) a);
 133  
             }
 134  14
         }
 135  1
     }
 136  
 
 137  
     /**
 138  
      * Get the List of the analyzers for a specific phase of analysis.
 139  
      *
 140  
      * @param phase the phase to get the configured analyzers.
 141  
      * @return the analyzers loaded
 142  
      */
 143  
     public List<Analyzer> getAnalyzers(AnalysisPhase phase) {
 144  0
         return analyzers.get(phase);
 145  
     }
 146  
 
 147  
     /**
 148  
      * Get the dependencies identified.
 149  
      *
 150  
      * @return the dependencies identified
 151  
      */
 152  
     public List<Dependency> getDependencies() {
 153  
         return dependencies;
 154  
     }
 155  
 
 156  
     public void setDependencies(List<Dependency> dependencies) {
 157  
         this.dependencies = dependencies;
 158  
     }
 159  
 
 160  
     /**
 161  
      * Scans an array of files or directories. If a directory is specified, it will be scanned recursively. Any
 162  
      * dependencies identified are added to the dependency collection.
 163  
      *
 164  
      * @param paths an array of paths to files or directories to be analyzed
 165  
      * @return the list of dependencies scanned
 166  
      *
 167  
      * @since v0.3.2.5
 168  
      */
 169  
     public List<Dependency> scan(String[] paths) {
 170  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 171  0
         for (String path : paths) {
 172  0
             final File file = new File(path);
 173  0
             final List<Dependency> d = scan(file);
 174  0
             if (d != null) {
 175  0
                 deps.addAll(d);
 176  
             }
 177  
         }
 178  0
         return deps;
 179  
     }
 180  
 
 181  
     /**
 182  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 183  
      * identified are added to the dependency collection.
 184  
      *
 185  
      * @param path the path to a file or directory to be analyzed
 186  
      * @return the list of dependencies scanned
 187  
      */
 188  
     public List<Dependency> scan(String path) {
 189  0
         final File file = new File(path);
 190  0
         return scan(file);
 191  
     }
 192  
 
 193  
     /**
 194  
      * Scans an array of files or directories. If a directory is specified, it will be scanned recursively. Any
 195  
      * dependencies identified are added to the dependency collection.
 196  
      *
 197  
      * @param files an array of paths to files or directories to be analyzed.
 198  
      * @return the list of dependencies
 199  
      *
 200  
      * @since v0.3.2.5
 201  
      */
 202  
     public List<Dependency> scan(File[] files) {
 203  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 204  0
         for (File file : files) {
 205  0
             final List<Dependency> d = scan(file);
 206  0
             if (d != null) {
 207  0
                 deps.addAll(d);
 208  
             }
 209  
         }
 210  0
         return deps;
 211  
     }
 212  
 
 213  
     /**
 214  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 215  
      * dependencies identified are added to the dependency collection.
 216  
      *
 217  
      * @param files a set of paths to files or directories to be analyzed
 218  
      * @return the list of dependencies scanned
 219  
      *
 220  
      * @since v0.3.2.5
 221  
      */
 222  
     public List<Dependency> scan(Set<File> files) {
 223  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 224  0
         for (File file : files) {
 225  0
             final List<Dependency> d = scan(file);
 226  0
             if (d != null) {
 227  0
                 deps.addAll(d);
 228  
             }
 229  0
         }
 230  0
         return deps;
 231  
     }
 232  
 
 233  
     /**
 234  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 235  
      * dependencies identified are added to the dependency collection.
 236  
      *
 237  
      * @param files a set of paths to files or directories to be analyzed
 238  
      * @return the list of dependencies scanned
 239  
      *
 240  
      * @since v0.3.2.5
 241  
      */
 242  
     public List<Dependency> scan(List<File> files) {
 243  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 244  0
         for (File file : files) {
 245  0
             final List<Dependency> d = scan(file);
 246  0
             if (d != null) {
 247  0
                 deps.addAll(d);
 248  
             }
 249  0
         }
 250  0
         return deps;
 251  
     }
 252  
 
 253  
     /**
 254  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 255  
      * identified are added to the dependency collection.
 256  
      *
 257  
      * @param file the path to a file or directory to be analyzed
 258  
      * @return the list of dependencies scanned
 259  
      *
 260  
      * @since v0.3.2.4
 261  
      *
 262  
      */
 263  
     public List<Dependency> scan(File file) {
 264  4
         if (file.exists()) {
 265  4
             if (file.isDirectory()) {
 266  2
                 return scanDirectory(file);
 267  
             } else {
 268  2
                 final Dependency d = scanFile(file);
 269  2
                 if (d != null) {
 270  2
                     final List<Dependency> deps = new ArrayList<Dependency>();
 271  2
                     deps.add(d);
 272  2
                     return deps;
 273  
                 }
 274  
             }
 275  
         }
 276  0
         return null;
 277  
     }
 278  
 
 279  
     /**
 280  
      * Recursively scans files and directories. Any dependencies identified are added to the dependency collection.
 281  
      *
 282  
      * @param dir the directory to scan
 283  
      * @return the list of Dependency objects scanned
 284  
      */
 285  
     protected List<Dependency> scanDirectory(File dir) {
 286  38
         final File[] files = dir.listFiles();
 287  38
         final List<Dependency> deps = new ArrayList<Dependency>();
 288  38
         if (files != null) {
 289  74
             for (File f : files) {
 290  36
                 if (f.isDirectory()) {
 291  36
                     final List<Dependency> d = scanDirectory(f);
 292  36
                     if (d != null) {
 293  36
                         deps.addAll(d);
 294  
                     }
 295  36
                 } else {
 296  0
                     final Dependency d = scanFile(f);
 297  0
                     deps.add(d);
 298  
                 }
 299  
             }
 300  
         }
 301  38
         return deps;
 302  
     }
 303  
 
 304  
     /**
 305  
      * Scans a specified file. If a dependency is identified it is added to the dependency collection.
 306  
      *
 307  
      * @param file The file to scan
 308  
      * @return the scanned dependency
 309  
      */
 310  
     protected Dependency scanFile(File file) {
 311  2
         if (!file.isFile()) {
 312  0
             final String msg = String.format("Path passed to scanFile(File) is not a file: %s. Skipping the file.", file.toString());
 313  0
             LOGGER.log(Level.FINE, msg);
 314  0
             return null;
 315  
         }
 316  2
         final String fileName = file.getName();
 317  2
         final String extension = FileUtils.getFileExtension(fileName);
 318  2
         Dependency dependency = null;
 319  2
         if (extension != null) {
 320  2
             if (supportsExtension(extension)) {
 321  2
                 dependency = new Dependency(file);
 322  2
                 dependencies.add(dependency);
 323  
             }
 324  
         } else {
 325  0
             final String msg = String.format("No file extension found on file '%s'. The file was not analyzed.", file.toString());
 326  0
             LOGGER.log(Level.FINEST, msg);
 327  
         }
 328  2
         return dependency;
 329  
     }
 330  
 
 331  
     /**
 332  
      * Runs the analyzers against all of the dependencies.
 333  
      */
 334  
     public void analyzeDependencies() {
 335  1
         boolean autoUpdate = true;
 336  
         try {
 337  1
             autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
 338  0
         } catch (InvalidSettingException ex) {
 339  0
             LOGGER.log(Level.FINE, "Invalid setting for auto-update; using true.");
 340  1
         }
 341  1
         if (autoUpdate) {
 342  0
             doUpdates();
 343  
         }
 344  
 
 345  
         //need to ensure that data exists
 346  
         try {
 347  1
             ensureDataExists();
 348  0
         } catch (NoDataException ex) {
 349  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 350  0
             LOGGER.log(Level.SEVERE, msg);
 351  0
             LOGGER.log(Level.FINE, null, ex);
 352  0
             return;
 353  0
         } catch (DatabaseException ex) {
 354  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 355  0
             LOGGER.log(Level.SEVERE, msg);
 356  0
             LOGGER.log(Level.FINE, null, ex);
 357  0
             return;
 358  
 
 359  1
         }
 360  
 
 361  1
         final String logHeader = String.format("%n"
 362  
                 + "----------------------------------------------------%n"
 363  
                 + "BEGIN ANALYSIS%n"
 364  
                 + "----------------------------------------------------");
 365  1
         LOGGER.log(Level.FINE, logHeader);
 366  1
         LOGGER.log(Level.INFO, "Analysis Starting");
 367  
 
 368  
         // analysis phases
 369  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 370  9
             final List<Analyzer> analyzerList = analyzers.get(phase);
 371  
 
 372  9
             for (Analyzer a : analyzerList) {
 373  14
                 a = initializeAnalyzer(a);
 374  
 
 375  
                 /* need to create a copy of the collection because some of the
 376  
                  * analyzers may modify it. This prevents ConcurrentModificationExceptions.
 377  
                  * This is okay for adds/deletes because it happens per analyzer.
 378  
                  */
 379  14
                 final String msg = String.format("Begin Analyzer '%s'", a.getName());
 380  14
                 LOGGER.log(Level.FINE, msg);
 381  14
                 final Set<Dependency> dependencySet = new HashSet<Dependency>();
 382  14
                 dependencySet.addAll(dependencies);
 383  14
                 for (Dependency d : dependencySet) {
 384  28
                     boolean shouldAnalyze = true;
 385  28
                     if (a instanceof FileTypeAnalyzer) {
 386  12
                         final FileTypeAnalyzer fAnalyzer = (FileTypeAnalyzer) a;
 387  12
                         shouldAnalyze = fAnalyzer.supportsExtension(d.getFileExtension());
 388  
                     }
 389  28
                     if (shouldAnalyze) {
 390  22
                         final String msgFile = String.format("Begin Analysis of '%s'", d.getActualFilePath());
 391  22
                         LOGGER.log(Level.FINE, msgFile);
 392  
                         try {
 393  22
                             a.analyze(d, this);
 394  0
                         } catch (AnalysisException ex) {
 395  0
                             final String exMsg = String.format("An error occurred while analyzing '%s'.", d.getActualFilePath());
 396  0
                             LOGGER.log(Level.WARNING, exMsg);
 397  0
                             LOGGER.log(Level.FINE, "", ex);
 398  0
                         } catch (Throwable ex) {
 399  0
                             final String axMsg = String.format("An unexpected error occurred during analysis of '%s'", d.getActualFilePath());
 400  
                             //final AnalysisException ax = new AnalysisException(axMsg, ex);
 401  0
                             LOGGER.log(Level.WARNING, axMsg);
 402  0
                             LOGGER.log(Level.FINE, "", ex);
 403  22
                         }
 404  
                     }
 405  28
                 }
 406  14
             }
 407  
         }
 408  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 409  9
             final List<Analyzer> analyzerList = analyzers.get(phase);
 410  
 
 411  9
             for (Analyzer a : analyzerList) {
 412  14
                 closeAnalyzer(a);
 413  14
             }
 414  
         }
 415  
 
 416  1
         final String logFooter = String.format("%n"
 417  
                 + "----------------------------------------------------%n"
 418  
                 + "END ANALYSIS%n"
 419  
                 + "----------------------------------------------------");
 420  1
         LOGGER.log(Level.FINE, logFooter);
 421  1
         LOGGER.log(Level.INFO, "Analysis Complete");
 422  1
     }
 423  
 
 424  
     /**
 425  
      * Initializes the given analyzer.
 426  
      *
 427  
      * @param analyzer the analyzer to initialize
 428  
      * @return the initialized analyzer
 429  
      */
 430  
     protected Analyzer initializeAnalyzer(Analyzer analyzer) {
 431  
         try {
 432  14
             final String msg = String.format("Initializing %s", analyzer.getName());
 433  14
             LOGGER.log(Level.FINE, msg);
 434  14
             analyzer.initialize();
 435  0
         } catch (Throwable ex) {
 436  0
             final String msg = String.format("Exception occurred initializing %s.", analyzer.getName());
 437  0
             LOGGER.log(Level.SEVERE, msg);
 438  0
             LOGGER.log(Level.FINE, null, ex);
 439  
             try {
 440  0
                 analyzer.close();
 441  0
             } catch (Throwable ex1) {
 442  0
                 LOGGER.log(Level.FINEST, null, ex1);
 443  0
             }
 444  14
         }
 445  14
         return analyzer;
 446  
     }
 447  
 
 448  
     /**
 449  
      * Closes the given analyzer.
 450  
      *
 451  
      * @param analyzer the analyzer to close
 452  
      */
 453  
     protected void closeAnalyzer(Analyzer analyzer) {
 454  14
         final String msg = String.format("Closing Analyzer '%s'", analyzer.getName());
 455  14
         LOGGER.log(Level.FINE, msg);
 456  
         try {
 457  14
             analyzer.close();
 458  0
         } catch (Throwable ex) {
 459  0
             LOGGER.log(Level.FINEST, null, ex);
 460  14
         }
 461  14
     }
 462  
 
 463  
     /**
 464  
      * Cycles through the cached web data sources and calls update on all of them.
 465  
      */
 466  
     private void doUpdates() {
 467  0
         LOGGER.info("Checking for updates");
 468  0
         final UpdateService service = new UpdateService(serviceClassLoader);
 469  0
         final Iterator<CachedWebDataSource> iterator = service.getDataSources();
 470  0
         while (iterator.hasNext()) {
 471  0
             final CachedWebDataSource source = iterator.next();
 472  
             try {
 473  0
                 source.update();
 474  0
             } catch (UpdateException ex) {
 475  0
                 LOGGER.log(Level.WARNING,
 476  
                         "Unable to update Cached Web DataSource, using local data instead. Results may not include recent vulnerabilities.");
 477  0
                 LOGGER.log(Level.FINE, String.format("Unable to update details for %s", source.getClass().getName()), ex);
 478  0
             }
 479  0
         }
 480  0
         LOGGER.info("Check for updates complete");
 481  0
     }
 482  
 
 483  
     /**
 484  
      * Returns a full list of all of the analyzers. This is useful for reporting which analyzers where used.
 485  
      *
 486  
      * @return a list of Analyzers
 487  
      */
 488  
     public List<Analyzer> getAnalyzers() {
 489  0
         final List<Analyzer> ret = new ArrayList<Analyzer>();
 490  0
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 491  0
             final List<Analyzer> analyzerList = analyzers.get(phase);
 492  0
             ret.addAll(analyzerList);
 493  
         }
 494  0
         return ret;
 495  
     }
 496  
 
 497  
     /**
 498  
      * Checks all analyzers to see if an extension is supported.
 499  
      *
 500  
      * @param ext a file extension
 501  
      * @return true or false depending on whether or not the file extension is supported
 502  
      */
 503  
     public boolean supportsExtension(String ext) {
 504  851
         if (ext == null) {
 505  3
             return false;
 506  
         }
 507  848
         boolean scan = false;
 508  848
         for (FileTypeAnalyzer a : this.fileTypeAnalyzers) {
 509  
             /* note, we can't break early on this loop as the analyzers need to know if
 510  
              they have files to work on prior to initialization */
 511  5088
             scan |= a.supportsExtension(ext);
 512  5088
         }
 513  848
         return scan;
 514  
     }
 515  
 
 516  
     /**
 517  
      * Checks the CPE Index to ensure documents exists. If none exist a NoDataException is thrown.
 518  
      *
 519  
      * @throws NoDataException thrown if no data exists in the CPE Index
 520  
      * @throws DatabaseException thrown if there is an exception opening the database
 521  
      */
 522  
     private void ensureDataExists() throws NoDataException, DatabaseException {
 523  1
         final CveDB cve = new CveDB();
 524  
         try {
 525  1
             cve.open();
 526  1
             if (!cve.dataExists()) {
 527  0
                 throw new NoDataException("No documents exist");
 528  
             }
 529  0
         } catch (DatabaseException ex) {
 530  0
             throw new NoDataException(ex.getMessage(), ex);
 531  
         } finally {
 532  1
             cve.close();
 533  1
         }
 534  1
     }
 535  
 }