Coverage Report - org.owasp.dependencycheck.analyzer.ArchiveAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
ArchiveAnalyzer
72%
71/98
61%
21/34
4.556
 
 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) 2013 Jeremy Long. All Rights Reserved.
 18  
  */
 19  
 package org.owasp.dependencycheck.analyzer;
 20  
 
 21  
 import java.io.BufferedInputStream;
 22  
 import java.io.BufferedOutputStream;
 23  
 import java.io.File;
 24  
 import java.io.FileInputStream;
 25  
 import java.io.FileNotFoundException;
 26  
 import java.io.FileOutputStream;
 27  
 import java.io.IOException;
 28  
 import java.util.ArrayList;
 29  
 import java.util.Collections;
 30  
 import java.util.HashSet;
 31  
 import java.util.List;
 32  
 import java.util.Set;
 33  
 import java.util.logging.Level;
 34  
 import java.util.logging.Logger;
 35  
 import java.util.zip.ZipEntry;
 36  
 import java.util.zip.ZipInputStream;
 37  
 import org.h2.store.fs.FileUtils;
 38  
 import org.owasp.dependencycheck.Engine;
 39  
 import org.owasp.dependencycheck.dependency.Dependency;
 40  
 import org.owasp.dependencycheck.utils.Settings;
 41  
 
 42  
 /**
 43  
  * <p>An analyzer that works on archive files:
 44  
  * <ul>
 45  
  * <li><b>ZIP</b> - if it is determined to be a JAR, WAR or EAR a copy is made
 46  
  * and the copy is given the correct extension so that it will be correctly
 47  
  * analyzed.</li>
 48  
  * <li><b>WAR</b> - the WAR contents are extracted and added as dependencies to
 49  
  * the scan. The displayed path is relative to the WAR.</li>
 50  
  * <li><b>EAR</b> - the WAR contents are extracted and added as dependencies to
 51  
  * the scan. Any WAR files are also processed so that the contained JAR files
 52  
  * are added to the list of dependencies. The displayed path is relative to the
 53  
  * EAR.</li>
 54  
  * </ul></p>
 55  
  *
 56  
  * @author Jeremy Long (jeremy.long@owasp.org)
 57  
  */
 58  21
 public class ArchiveAnalyzer extends AbstractAnalyzer implements Analyzer {
 59  
 
 60  
     /**
 61  
      * The buffer size to use when extracting files from the archive.
 62  
      */
 63  
     private static final int BUFFER_SIZE = 4096;
 64  
     /**
 65  
      * The count of directories created during analysis. This is used for
 66  
      * creating temporary directories.
 67  
      */
 68  3
     private static int dirCount = 0;
 69  
     /**
 70  
      * The parent directory for the individual directories per archive.
 71  
      */
 72  21
     private File tempFileLocation = null;
 73  
     /**
 74  
      * The max scan depth that the analyzer will recursively extract nested
 75  
      * archives.
 76  
      */
 77  3
     private static final int MAX_SCAN_DEPTH = Settings.getInt("archive.scan.depth", 3);
 78  
     /**
 79  
      * Tracks the current scan/extraction depth for nested archives.
 80  
      */
 81  21
     private int scanDepth = 0;
 82  
     //<editor-fold defaultstate="collapsed" desc="All standard implmentation details of Analyzer">
 83  
     /**
 84  
      * The name of the analyzer.
 85  
      */
 86  
     private static final String ANALYZER_NAME = "Archive Analyzer";
 87  
     /**
 88  
      * The phase that this analyzer is intended to run in.
 89  
      */
 90  3
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL;
 91  
     /**
 92  
      * The set of file extensions supported by this analyzer.
 93  
      */
 94  3
     private static final Set<String> EXTENSIONS = newHashSet("zip", "ear", "war");
 95  
 
 96  
     /**
 97  
      * Returns a list of file EXTENSIONS supported by this analyzer.
 98  
      *
 99  
      * @return a list of file EXTENSIONS supported by this analyzer.
 100  
      */
 101  
     public Set<String> getSupportedExtensions() {
 102  17472
         return EXTENSIONS;
 103  
     }
 104  
 
 105  
     /**
 106  
      * Returns the name of the analyzer.
 107  
      *
 108  
      * @return the name of the analyzer.
 109  
      */
 110  
     public String getName() {
 111  3
         return ANALYZER_NAME;
 112  
     }
 113  
 
 114  
     /**
 115  
      * Returns whether or not this analyzer can process the given extension.
 116  
      *
 117  
      * @param extension the file extension to test for support.
 118  
      * @return whether or not the specified file extension is supported by this
 119  
      * analyzer.
 120  
      */
 121  
     public boolean supportsExtension(String extension) {
 122  17649
         return EXTENSIONS.contains(extension);
 123  
     }
 124  
 
 125  
     /**
 126  
      * Returns the phase that the analyzer is intended to run in.
 127  
      *
 128  
      * @return the phase that the analyzer is intended to run in.
 129  
      */
 130  
     public AnalysisPhase getAnalysisPhase() {
 131  6
         return ANALYSIS_PHASE;
 132  
     }
 133  
     //</editor-fold>
 134  
 
 135  
     /**
 136  
      * The initialize method does nothing for this Analyzer.
 137  
      *
 138  
      * @throws Exception is thrown if there is an exception deleting or creating
 139  
      * temporary files
 140  
      */
 141  
     @Override
 142  
     public void initialize() throws Exception {
 143  6
         final String tmpDir = Settings.getString(Settings.KEYS.TEMP_DIRECTORY, System.getProperty("java.io.tmpdir"));
 144  6
         final File baseDir = new File(tmpDir);
 145  6
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 146  6
         if (!tempFileLocation.delete()) {
 147  0
             throw new AnalysisException("Unable to delete temporary file '" + tempFileLocation.getAbsolutePath() + "'.");
 148  
         }
 149  6
         if (!tempFileLocation.mkdirs()) {
 150  0
             throw new AnalysisException("Unable to create directory '" + tempFileLocation.getAbsolutePath() + "'.");
 151  
         }
 152  6
     }
 153  
 
 154  
     /**
 155  
      * The close method does nothing for this Analyzer.
 156  
      *
 157  
      * @throws Exception thrown if there is an exception deleting temporary
 158  
      * files
 159  
      */
 160  
     @Override
 161  
     public void close() throws Exception {
 162  6
         if (tempFileLocation != null && tempFileLocation.exists()) {
 163  6
             FileUtils.deleteRecursive(tempFileLocation.getAbsolutePath(), true);
 164  
         }
 165  6
     }
 166  
 
 167  
     /**
 168  
      * Analyzes a given dependency. If the dependency is an archive, such as a
 169  
      * WAR or EAR, the contents are extracted, scanned, and added to the list of
 170  
      * dependencies within the engine.
 171  
      *
 172  
      * @param dependency the dependency to analyze
 173  
      * @param engine the engine scanning
 174  
      * @throws AnalysisException thrown if there is an analysis exception
 175  
      */
 176  
     @Override
 177  
     public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
 178  3
         final File f = new File(dependency.getActualFilePath());
 179  3
         final File tmpDir = getNextTempDirectory();
 180  3
         extractFiles(f, tmpDir, engine);
 181  
 
 182  
         //make a copy
 183  3
         final List<Dependency> dependencies = new ArrayList<Dependency>(engine.getDependencies());
 184  3
         engine.scan(tmpDir);
 185  3
         final List<Dependency> newDependencies = engine.getDependencies();
 186  3
         if (dependencies.size() != newDependencies.size()) {
 187  
             //get the new dependencies
 188  3
             final Set<Dependency> dependencySet = new HashSet<Dependency>();
 189  3
             dependencySet.addAll(newDependencies);
 190  3
             dependencySet.removeAll(dependencies);
 191  
 
 192  3
             for (Dependency d : dependencySet) {
 193  
                 //fix the dependency's display name and path
 194  177
                 final String displayPath = String.format("%s%s",
 195  
                         dependency.getFilePath(),
 196  
                         d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
 197  177
                 final String displayName = String.format("%s%s%s",
 198  
                         dependency.getFileName(),
 199  
                         File.separator,
 200  
                         d.getFileName());
 201  177
                 d.setFilePath(displayPath);
 202  177
                 d.setFileName(displayName);
 203  
 
 204  
                 //TODO - can we get more evidence from the parent? EAR contains module name, etc.
 205  
 
 206  
                 //analyze the dependency (i.e. extract files) if it is a supported type.
 207  177
                 if (this.supportsExtension(d.getFileExtension()) && scanDepth < MAX_SCAN_DEPTH) {
 208  0
                     scanDepth += 1;
 209  0
                     analyze(d, engine);
 210  0
                     scanDepth -= 1;
 211  
                 }
 212  177
             }
 213  
         }
 214  3
         Collections.sort(engine.getDependencies());
 215  3
     }
 216  
 
 217  
     /**
 218  
      * Retrieves the next temporary directory to extract an archive too.
 219  
      *
 220  
      * @return a directory
 221  
      * @throws AnalysisException thrown if unable to create temporary directory
 222  
      */
 223  
     private File getNextTempDirectory() throws AnalysisException {
 224  3
         dirCount += 1;
 225  3
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 226  3
         if (!directory.mkdirs()) {
 227  0
             throw new AnalysisException("Unable to create temp directory '" + directory.getAbsolutePath() + "'.");
 228  
         }
 229  3
         return directory;
 230  
     }
 231  
 
 232  
     /**
 233  
      * Extracts the contents of an archive into the specified directory.
 234  
      *
 235  
      * @param archive an archive file such as a WAR or EAR
 236  
      * @param extractTo a directory to extract the contents to
 237  
      * @param engine the scanning engine
 238  
      * @throws AnalysisException thrown if the archive is not found
 239  
      */
 240  
     private void extractFiles(File archive, File extractTo, Engine engine) throws AnalysisException {
 241  3
         if (archive == null || extractTo == null) {
 242  0
             return;
 243  
         }
 244  
 
 245  3
         FileInputStream fis = null;
 246  3
         ZipInputStream zis = null;
 247  
 
 248  
         try {
 249  3
             fis = new FileInputStream(archive);
 250  0
         } catch (FileNotFoundException ex) {
 251  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.INFO, null, ex);
 252  0
             throw new AnalysisException("Archive file was not found.", ex);
 253  3
         }
 254  3
         zis = new ZipInputStream(new BufferedInputStream(fis));
 255  
         ZipEntry entry;
 256  
         try {
 257  18567
             while ((entry = zis.getNextEntry()) != null) {
 258  18564
                 if (entry.isDirectory()) {
 259  873
                     final File d = new File(extractTo, entry.getName());
 260  873
                     if (!d.mkdirs()) {
 261  0
                         throw new AnalysisException("Unable to create '" + d.getAbsolutePath() + "'.");
 262  
                     }
 263  873
                 } else {
 264  17691
                     final File file = new File(extractTo, entry.getName());
 265  17691
                     final String ext = org.owasp.dependencycheck.utils.FileUtils.getFileExtension(file.getName());
 266  17691
                     if (engine.supportsExtension(ext)) {
 267  177
                         BufferedOutputStream bos = null;
 268  
                         FileOutputStream fos;
 269  
                         try {
 270  177
                             fos = new FileOutputStream(file);
 271  177
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 272  
                             int count;
 273  177
                             final byte data[] = new byte[BUFFER_SIZE];
 274  354765
                             while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
 275  354588
                                 bos.write(data, 0, count);
 276  
                             }
 277  177
                             bos.flush();
 278  0
                         } catch (FileNotFoundException ex) {
 279  0
                             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 280  0
                             throw new AnalysisException("Unable to find file '" + file.getName() + "'.", ex);
 281  0
                         } catch (IOException ex) {
 282  0
                             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 283  0
                             throw new AnalysisException("IO Exception while parsing file '" + file.getName() + "'.", ex);
 284  
                         } finally {
 285  177
                             if (bos != null) {
 286  
                                 try {
 287  177
                                     bos.close();
 288  0
                                 } catch (IOException ex) {
 289  0
                                     Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 290  177
                                 }
 291  
                             }
 292  
                         }
 293  
                     }
 294  17691
                 }
 295  
             }
 296  0
         } catch (IOException ex) {
 297  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 298  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, msg, ex);
 299  0
             throw new AnalysisException(msg, ex);
 300  
         } finally {
 301  0
             try {
 302  3
                 zis.close();
 303  0
             } catch (IOException ex) {
 304  0
                 Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 305  3
             }
 306  0
         }
 307  3
     }
 308  
 }