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