Coverage Report - org.owasp.dependencycheck.Engine
 
Classes in this File Line Coverage Branch Coverage Complexity
Engine
57%
104/181
71%
47/66
3.889
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 3  
  *
 4  
  * Dependency-check-core is free software: you can redistribute it and/or modify it
 5  
  * under the terms of the GNU General Public License as published by the Free
 6  
  * Software Foundation, either version 3 of the License, or (at your option) any
 7  
  * later version.
 8  
  *
 9  
  * Dependency-check-core is distributed in the hope that it will be useful, but
 10  
  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  
  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 12  
  * details.
 13  
  *
 14  
  * You should have received a copy of the GNU General Public License along with
 15  
  * dependency-check-core. If not, see http://www.gnu.org/licenses/.
 16  
  *
 17  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 18  
  */
 19  
 package org.owasp.dependencycheck;
 20  
 
 21  
 import java.io.File;
 22  
 import java.util.ArrayList;
 23  
 import java.util.EnumMap;
 24  
 import java.util.HashSet;
 25  
 import java.util.Iterator;
 26  
 import java.util.List;
 27  
 import java.util.Set;
 28  
 import java.util.logging.Level;
 29  
 import java.util.logging.Logger;
 30  
 import org.owasp.dependencycheck.analyzer.AnalysisException;
 31  
 import org.owasp.dependencycheck.analyzer.AnalysisPhase;
 32  
 import org.owasp.dependencycheck.analyzer.Analyzer;
 33  
 import org.owasp.dependencycheck.analyzer.AnalyzerService;
 34  
 import org.owasp.dependencycheck.data.cpe.CpeMemoryIndex;
 35  
 import org.owasp.dependencycheck.data.cpe.IndexException;
 36  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 37  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 38  
 import org.owasp.dependencycheck.data.update.CachedWebDataSource;
 39  
 import org.owasp.dependencycheck.data.update.UpdateService;
 40  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 41  
 import org.owasp.dependencycheck.dependency.Dependency;
 42  
 import org.owasp.dependencycheck.exception.NoDataException;
 43  
 import org.owasp.dependencycheck.utils.FileUtils;
 44  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 45  
 import org.owasp.dependencycheck.utils.Settings;
 46  
 
 47  
 /**
 48  
  * Scans files, directories, etc. for Dependencies. Analyzers are loaded and used to process the files found by the
 49  
  * scan, if a file is encountered and an Analyzer is associated with the file type then the file is turned into a
 50  
  * dependency.
 51  
  *
 52  
  * @author Jeremy Long <jeremy.long@owasp.org>
 53  
  */
 54  
 public class Engine {
 55  
 
 56  
     /**
 57  
      * The list of dependencies.
 58  
      */
 59  6
     private final List<Dependency> dependencies = new ArrayList<Dependency>();
 60  
     /**
 61  
      * A Map of analyzers grouped by Analysis phase.
 62  
      */
 63  6
     private final EnumMap<AnalysisPhase, List<Analyzer>> analyzers
 64  
             = new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
 65  
     /**
 66  
      * A set of extensions supported by the analyzers.
 67  
      */
 68  6
     private final Set<String> extensions = new HashSet<String>();
 69  
 
 70  
     /**
 71  
      * Creates a new Engine.
 72  
      */
 73  6
     public Engine() {
 74  6
         boolean autoUpdate = true;
 75  
         try {
 76  6
             autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
 77  0
         } catch (InvalidSettingException ex) {
 78  0
             Logger.getLogger(Engine.class.getName()).log(Level.FINE, "Invalid setting for auto-update; using true.");
 79  6
         }
 80  6
         if (autoUpdate) {
 81  0
             doUpdates();
 82  
         }
 83  6
         loadAnalyzers();
 84  6
     }
 85  
 
 86  
     /**
 87  
      * Creates a new Engine.
 88  
      *
 89  
      * @param autoUpdate indicates whether or not data should be updated from the Internet
 90  
      * @deprecated This function should no longer be used; the autoupdate flag should be set using:
 91  
      * <code>Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, value);</code>
 92  
      */
 93  
     @Deprecated
 94  0
     public Engine(boolean autoUpdate) {
 95  0
         if (autoUpdate) {
 96  0
             doUpdates();
 97  
         }
 98  0
         loadAnalyzers();
 99  0
     }
 100  
 
 101  
     /**
 102  
      * Loads the analyzers specified in the configuration file (or system properties).
 103  
      */
 104  
     private void loadAnalyzers() {
 105  
 
 106  60
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 107  54
             analyzers.put(phase, new ArrayList<Analyzer>());
 108  
         }
 109  
 
 110  6
         final AnalyzerService service = AnalyzerService.getInstance();
 111  6
         final Iterator<Analyzer> iterator = service.getAnalyzers();
 112  72
         while (iterator.hasNext()) {
 113  66
             final Analyzer a = iterator.next();
 114  66
             analyzers.get(a.getAnalysisPhase()).add(a);
 115  66
             if (a.getSupportedExtensions() != null) {
 116  18
                 extensions.addAll(a.getSupportedExtensions());
 117  
             }
 118  66
         }
 119  6
     }
 120  
 
 121  
     /**
 122  
      * Get the List of the analyzers for a specific phase of analysis.
 123  
      *
 124  
      * @param phase the phase to get the configured analyzers.
 125  
      * @return the analyzers loaded
 126  
      */
 127  
     public List<Analyzer> getAnalyzers(AnalysisPhase phase) {
 128  0
         return analyzers.get(phase);
 129  
     }
 130  
 
 131  
     /**
 132  
      * Get the dependencies identified.
 133  
      *
 134  
      * @return the dependencies identified
 135  
      */
 136  
     public List<Dependency> getDependencies() {
 137  38
         return dependencies;
 138  
     }
 139  
 
 140  
     /**
 141  
      * Scans an array of files or directories. If a directory is specified, it will be scanned recursively. Any
 142  
      * dependencies identified are added to the dependency collection.
 143  
      *
 144  
      * @since v0.3.2.5
 145  
      *
 146  
      * @param paths an array of paths to files or directories to be analyzed.
 147  
      */
 148  
     public void scan(String[] paths) {
 149  0
         for (String path : paths) {
 150  0
             final File file = new File(path);
 151  0
             scan(file);
 152  
         }
 153  0
     }
 154  
 
 155  
     /**
 156  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 157  
      * identified are added to the dependency collection.
 158  
      *
 159  
      * @param path the path to a file or directory to be analyzed.
 160  
      */
 161  
     public void scan(String path) {
 162  0
         final File file = new File(path);
 163  0
         scan(file);
 164  0
     }
 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 files an array of paths to files or directories to be analyzed.
 173  
      */
 174  
     public void scan(File[] files) {
 175  0
         for (File file : files) {
 176  0
             scan(file);
 177  
         }
 178  0
     }
 179  
 
 180  
     /**
 181  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 182  
      * dependencies identified are added to the dependency collection.
 183  
      *
 184  
      * @since v0.3.2.5
 185  
      *
 186  
      * @param files a set of paths to files or directories to be analyzed.
 187  
      */
 188  
     public void scan(Set<File> files) {
 189  0
         for (File file : files) {
 190  0
             scan(file);
 191  0
         }
 192  0
     }
 193  
 
 194  
     /**
 195  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 196  
      * dependencies identified are added to the dependency collection.
 197  
      *
 198  
      * @since v0.3.2.5
 199  
      *
 200  
      * @param files a set of paths to files or directories to be analyzed.
 201  
      */
 202  
     public void scan(List<File> files) {
 203  0
         for (File file : files) {
 204  0
             scan(file);
 205  0
         }
 206  0
     }
 207  
 
 208  
     /**
 209  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 210  
      * identified are added to the dependency collection.
 211  
      *
 212  
      * @since v0.3.2.4
 213  
      *
 214  
      * @param file the path to a file or directory to be analyzed.
 215  
      */
 216  
     public void scan(File file) {
 217  13
         if (file.exists()) {
 218  13
             if (file.isDirectory()) {
 219  8
                 scanDirectory(file);
 220  
             } else {
 221  5
                 scanFile(file);
 222  
             }
 223  
         }
 224  13
     }
 225  
 
 226  
     /**
 227  
      * Recursively scans files and directories. Any dependencies identified are added to the dependency collection.
 228  
      *
 229  
      * @param dir the directory to scan.
 230  
      */
 231  
     protected void scanDirectory(File dir) {
 232  33
         final File[] files = dir.listFiles();
 233  33
         if (files != null) {
 234  68
             for (File f : files) {
 235  35
                 if (f.isDirectory()) {
 236  25
                     scanDirectory(f);
 237  
                 } else {
 238  10
                     scanFile(f);
 239  
                 }
 240  
             }
 241  
         }
 242  33
     }
 243  
 
 244  
     /**
 245  
      * Scans a specified file. If a dependency is identified it is added to the dependency collection.
 246  
      *
 247  
      * @param file The file to scan.
 248  
      */
 249  
     protected void scanFile(File file) {
 250  15
         if (!file.isFile()) {
 251  0
             final String msg = String.format("Path passed to scanFile(File) is not a file: %s. Skipping the file.", file.toString());
 252  0
             Logger.getLogger(Engine.class.getName()).log(Level.FINE, msg);
 253  0
             return;
 254  
         }
 255  15
         final String fileName = file.getName();
 256  15
         final String extension = FileUtils.getFileExtension(fileName);
 257  15
         if (extension != null) {
 258  15
             if (extensions.contains(extension)) {
 259  15
                 final Dependency dependency = new Dependency(file);
 260  15
                 dependencies.add(dependency);
 261  15
             }
 262  
         } else {
 263  0
             final String msg = String.format("No file extension found on file '%s'. The file was not analyzed.",
 264  
                     file.toString());
 265  0
             Logger.getLogger(Engine.class.getName()).log(Level.FINEST, msg);
 266  
         }
 267  15
     }
 268  
 
 269  
     /**
 270  
      * Runs the analyzers against all of the dependencies.
 271  
      */
 272  
     public void analyzeDependencies() {
 273  
         //need to ensure that data exists
 274  
         try {
 275  3
             ensureDataExists();
 276  0
         } catch (NoDataException ex) {
 277  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 278  0
             Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, msg);
 279  0
             Logger.getLogger(Engine.class.getName()).log(Level.FINE, null, ex);
 280  0
             return;
 281  0
         } catch (DatabaseException ex) {
 282  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 283  0
             Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, msg);
 284  0
             Logger.getLogger(Engine.class.getName()).log(Level.FINE, null, ex);
 285  0
             return;
 286  
 
 287  3
         }
 288  
 
 289  3
         final String logHeader = String.format("%n"
 290  
                 + "----------------------------------------------------%n"
 291  
                 + "BEGIN ANALYSIS%n"
 292  
                 + "----------------------------------------------------");
 293  3
         Logger.getLogger(Engine.class.getName()).log(Level.FINE, logHeader);
 294  3
         Logger.getLogger(Engine.class.getName()).log(Level.INFO, "Analysis Starting");
 295  
 
 296  
         //phase one initialize
 297  30
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 298  27
             final List<Analyzer> analyzerList = analyzers.get(phase);
 299  27
             for (Analyzer a : analyzerList) {
 300  
                 try {
 301  33
                     final String msg = String.format("Initializing %s", a.getName());
 302  33
                     Logger.getLogger(Engine.class.getName()).log(Level.FINE, msg);
 303  33
                     a.initialize();
 304  0
                 } catch (Exception ex) {
 305  0
                     final String msg = String.format("Exception occurred initializing %s.", a.getName());
 306  0
                     Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, msg);
 307  0
                     Logger.getLogger(Engine.class.getName()).log(Level.INFO, null, ex);
 308  
                     try {
 309  0
                         a.close();
 310  0
                     } catch (Exception ex1) {
 311  0
                         Logger.getLogger(Engine.class.getName()).log(Level.FINEST, null, ex1);
 312  0
                     }
 313  33
                 }
 314  33
             }
 315  
         }
 316  
 
 317  
         // analysis phases
 318  30
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 319  27
             final List<Analyzer> analyzerList = analyzers.get(phase);
 320  
 
 321  27
             for (Analyzer a : analyzerList) {
 322  
                 /* need to create a copy of the collection because some of the
 323  
                  * analyzers may modify it. This prevents ConcurrentModificationExceptions.
 324  
                  * This is okay for adds/deletes because it happens per analyzer.
 325  
                  */
 326  33
                 final String msg = String.format("Begin Analyzer '%s'", a.getName());
 327  33
                 Logger.getLogger(Engine.class.getName()).log(Level.FINE, msg);
 328  33
                 final Set<Dependency> dependencySet = new HashSet<Dependency>();
 329  33
                 dependencySet.addAll(dependencies);
 330  33
                 for (Dependency d : dependencySet) {
 331  95
                     if (a.supportsExtension(d.getFileExtension())) {
 332  84
                         final String msgFile = String.format("Begin Analysis of '%s'", d.getActualFilePath());
 333  84
                         Logger.getLogger(Engine.class.getName()).log(Level.FINE, msgFile);
 334  
                         try {
 335  84
                             a.analyze(d, this);
 336  0
                         } catch (AnalysisException ex) {
 337  0
                             d.addAnalysisException(ex);
 338  0
                         } catch (Throwable ex) {
 339  0
                             final String axMsg = String.format("An unexpected error occurred during analysis of '%s'", d.getActualFilePath());
 340  0
                             final AnalysisException ax = new AnalysisException(axMsg, ex);
 341  0
                             d.addAnalysisException(ax);
 342  0
                             Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, axMsg);
 343  0
                             Logger.getLogger(Engine.class.getName()).log(Level.FINE, axMsg, ex);
 344  84
                         }
 345  
                     }
 346  95
                 }
 347  33
             }
 348  
         }
 349  
 
 350  
         //close/cleanup
 351  30
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 352  27
             final List<Analyzer> analyzerList = analyzers.get(phase);
 353  27
             for (Analyzer a : analyzerList) {
 354  33
                 final String msg = String.format("Closing Analyzer '%s'", a.getName());
 355  33
                 Logger.getLogger(Engine.class.getName()).log(Level.FINE, msg);
 356  
                 try {
 357  33
                     a.close();
 358  0
                 } catch (Exception ex) {
 359  0
                     Logger.getLogger(Engine.class.getName()).log(Level.FINEST, null, ex);
 360  33
                 }
 361  33
             }
 362  
         }
 363  
 
 364  3
         final String logFooter = String.format("%n"
 365  
                 + "----------------------------------------------------%n"
 366  
                 + "END ANALYSIS%n"
 367  
                 + "----------------------------------------------------");
 368  3
         Logger.getLogger(Engine.class.getName()).log(Level.FINE, logFooter);
 369  3
     }
 370  
 
 371  
     /**
 372  
      * Cycles through the cached web data sources and calls update on all of them.
 373  
      */
 374  
     private void doUpdates() {
 375  0
         final UpdateService service = UpdateService.getInstance();
 376  0
         final Iterator<CachedWebDataSource> iterator = service.getDataSources();
 377  0
         while (iterator.hasNext()) {
 378  0
             final CachedWebDataSource source = iterator.next();
 379  
             try {
 380  0
                 source.update();
 381  0
             } catch (UpdateException ex) {
 382  0
                 Logger.getLogger(Engine.class.getName()).log(Level.WARNING,
 383  
                         "Unable to update Cached Web DataSource, using local data instead. Results may not include recent vulnerabilities.");
 384  0
                 Logger.getLogger(Engine.class.getName()).log(Level.FINE,
 385  
                         String.format("Unable to update details for %s", source.getClass().getName()), ex);
 386  0
             }
 387  0
         }
 388  0
     }
 389  
 
 390  
     /**
 391  
      * Returns a full list of all of the analyzers. This is useful for reporting which analyzers where used.
 392  
      *
 393  
      * @return a list of Analyzers
 394  
      */
 395  
     public List<Analyzer> getAnalyzers() {
 396  1
         final List<Analyzer> ret = new ArrayList<Analyzer>();
 397  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 398  9
             final List<Analyzer> analyzerList = analyzers.get(phase);
 399  9
             ret.addAll(analyzerList);
 400  
         }
 401  1
         return ret;
 402  
     }
 403  
 
 404  
     /**
 405  
      * Checks all analyzers to see if an extension is supported.
 406  
      *
 407  
      * @param ext a file extension
 408  
      * @return true or false depending on whether or not the file extension is supported
 409  
      */
 410  
     public boolean supportsExtension(String ext) {
 411  143
         if (ext == null) {
 412  8
             return false;
 413  
         }
 414  1267
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 415  1142
             final List<Analyzer> analyzerList = analyzers.get(phase);
 416  1142
             for (Analyzer a : analyzerList) {
 417  1399
                 if (a.getSupportedExtensions() != null && a.supportsExtension(ext)) {
 418  10
                     return true;
 419  
                 }
 420  1389
             }
 421  
         }
 422  125
         return false;
 423  
     }
 424  
 
 425  
     /**
 426  
      * Checks the CPE Index to ensure documents exists. If none exist a NoDataException is thrown.
 427  
      *
 428  
      * @throws NoDataException thrown if no data exists in the CPE Index
 429  
      * @throws DatabaseException thrown if there is an exception opening the database
 430  
      */
 431  
     private void ensureDataExists() throws NoDataException, DatabaseException {
 432  3
         final CpeMemoryIndex cpe = CpeMemoryIndex.getInstance();
 433  3
         final CveDB cve = new CveDB();
 434  
 
 435  
         try {
 436  3
             cve.open();
 437  3
             cpe.open(cve);
 438  0
         } catch (IndexException ex) {
 439  0
             throw new NoDataException(ex.getMessage(), ex);
 440  0
         } catch (DatabaseException ex) {
 441  0
             throw new NoDataException(ex.getMessage(), ex);
 442  
         } finally {
 443  3
             cve.close();
 444  3
         }
 445  3
         if (cpe.numDocs() <= 0) {
 446  0
             cpe.close();
 447  0
             throw new NoDataException("No documents exist");
 448  
         }
 449  3
     }
 450  
 }