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