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