Coverage Report - org.owasp.dependencycheck.analyzer.ArchiveAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
ArchiveAnalyzer
70%
74/105
69%
25/36
4.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) 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  1
         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
             baseDir.mkdirs();
 149  
         }
 150  4
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 151  4
         if (!tempFileLocation.delete()) {
 152  0
             throw new AnalysisException("Unable to delete temporary file '" + tempFileLocation.getAbsolutePath() + "'.");
 153  
         }
 154  4
         if (!tempFileLocation.mkdirs()) {
 155  0
             throw new AnalysisException("Unable to create directory '" + tempFileLocation.getAbsolutePath() + "'.");
 156  
         }
 157  4
     }
 158  
 
 159  
     /**
 160  
      * The close method does nothing for this Analyzer.
 161  
      *
 162  
      * @throws Exception thrown if there is an exception deleting temporary
 163  
      * files
 164  
      */
 165  
     @Override
 166  
     public void close() throws Exception {
 167  4
         if (tempFileLocation != null && tempFileLocation.exists()) {
 168  4
             FileUtils.deleteRecursive(tempFileLocation.getAbsolutePath(), true);
 169  
         }
 170  4
     }
 171  
 
 172  
     /**
 173  
      * Analyzes a given dependency. If the dependency is an archive, such as a
 174  
      * WAR or EAR, the contents are extracted, scanned, and added to the list of
 175  
      * dependencies within the engine.
 176  
      *
 177  
      * @param dependency the dependency to analyze
 178  
      * @param engine the engine scanning
 179  
      * @throws AnalysisException thrown if there is an analysis exception
 180  
      */
 181  
     @Override
 182  
     public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
 183  3
         final File f = new File(dependency.getActualFilePath());
 184  3
         final File tmpDir = getNextTempDirectory();
 185  3
         extractFiles(f, tmpDir, engine);
 186  
 
 187  
         //make a copy
 188  3
         final List<Dependency> dependencies = new ArrayList<Dependency>(engine.getDependencies());
 189  3
         engine.scan(tmpDir);
 190  3
         final List<Dependency> newDependencies = engine.getDependencies();
 191  3
         if (dependencies.size() != newDependencies.size()) {
 192  
             //get the new dependencies
 193  1
             final Set<Dependency> dependencySet = new HashSet<Dependency>();
 194  1
             dependencySet.addAll(newDependencies);
 195  1
             dependencySet.removeAll(dependencies);
 196  
 
 197  1
             for (Dependency d : dependencySet) {
 198  
                 //fix the dependency's display name and path
 199  5
                 final String displayPath = String.format("%s%s",
 200  
                         dependency.getFilePath(),
 201  
                         d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
 202  5
                 final String displayName = String.format("%s%s%s",
 203  
                         dependency.getFileName(),
 204  
                         File.separator,
 205  
                         d.getFileName());
 206  5
                 d.setFilePath(displayPath);
 207  5
                 d.setFileName(displayName);
 208  
 
 209  
                 //TODO - can we get more evidence from the parent? EAR contains module name, etc.
 210  
 
 211  
                 //analyze the dependency (i.e. extract files) if it is a supported type.
 212  5
                 if (this.supportsExtension(d.getFileExtension()) && scanDepth < MAX_SCAN_DEPTH) {
 213  1
                     scanDepth += 1;
 214  1
                     analyze(d, engine);
 215  1
                     scanDepth -= 1;
 216  
                 }
 217  5
             }
 218  
         }
 219  3
         Collections.sort(engine.getDependencies());
 220  3
     }
 221  
 
 222  
     /**
 223  
      * Retrieves the next temporary directory to extract an archive too.
 224  
      *
 225  
      * @return a directory
 226  
      * @throws AnalysisException thrown if unable to create temporary directory
 227  
      */
 228  
     private File getNextTempDirectory() throws AnalysisException {
 229  3
         dirCount += 1;
 230  3
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 231  3
         if (!directory.mkdirs()) {
 232  0
             throw new AnalysisException("Unable to create temp directory '" + directory.getAbsolutePath() + "'.");
 233  
         }
 234  3
         return directory;
 235  
     }
 236  
 
 237  
     /**
 238  
      * Extracts the contents of an archive into the specified directory.
 239  
      *
 240  
      * @param archive an archive file such as a WAR or EAR
 241  
      * @param extractTo a directory to extract the contents to
 242  
      * @param engine the scanning engine
 243  
      * @throws AnalysisException thrown if the archive is not found
 244  
      */
 245  
     private void extractFiles(File archive, File extractTo, Engine engine) throws AnalysisException {
 246  3
         if (archive == null || extractTo == null) {
 247  0
             return;
 248  
         }
 249  
 
 250  3
         FileInputStream fis = null;
 251  
         //ZipInputStream zis = null;
 252  3
         ZipArchiveInputStream zis = null;
 253  
 
 254  
         try {
 255  3
             fis = new FileInputStream(archive);
 256  0
         } catch (FileNotFoundException ex) {
 257  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.INFO, null, ex);
 258  0
             throw new AnalysisException("Archive file was not found.", ex);
 259  3
         }
 260  3
         zis = new ZipArchiveInputStream(new BufferedInputStream(fis));
 261  
         ZipArchiveEntry entry;
 262  
 
 263  
         try {
 264  166
             while ((entry = zis.getNextZipEntry()) != null) {
 265  163
                 if (entry.isDirectory()) {
 266  25
                     final File d = new File(extractTo, entry.getName());
 267  25
                     if (!d.mkdirs()) {
 268  0
                         throw new AnalysisException("Unable to create '" + d.getAbsolutePath() + "'.");
 269  
                     }
 270  25
                 } else {
 271  138
                     final File file = new File(extractTo, entry.getName());
 272  138
                     final String ext = org.owasp.dependencycheck.utils.FileUtils.getFileExtension(file.getName());
 273  138
                     if (engine.supportsExtension(ext)) {
 274  5
                         BufferedOutputStream bos = null;
 275  
                         FileOutputStream fos;
 276  
                         try {
 277  5
                             fos = new FileOutputStream(file);
 278  5
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 279  
                             int count;
 280  5
                             final byte data[] = new byte[BUFFER_SIZE];
 281  1307
                             while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
 282  1302
                                 bos.write(data, 0, count);
 283  
                             }
 284  5
                             bos.flush();
 285  0
                         } catch (FileNotFoundException ex) {
 286  0
                             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 287  0
                             throw new AnalysisException("Unable to find file '" + file.getName() + "'.", ex);
 288  0
                         } catch (IOException ex) {
 289  0
                             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 290  0
                             throw new AnalysisException("IO Exception while parsing file '" + file.getName() + "'.", ex);
 291  
                         } finally {
 292  5
                             if (bos != null) {
 293  
                                 try {
 294  5
                                     bos.close();
 295  0
                                 } catch (IOException ex) {
 296  0
                                     Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 297  5
                                 }
 298  
                             }
 299  
                         }
 300  
                     }
 301  138
                 }
 302  
             }
 303  0
         } catch (IOException ex) {
 304  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 305  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.WARNING, msg);
 306  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 307  0
             throw new AnalysisException(msg, ex);
 308  0
         } catch (Throwable ex) {
 309  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 310  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.WARNING, msg);
 311  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.WARNING, null, ex);
 312  0
             throw new AnalysisException(msg, ex);
 313  
         } finally {
 314  0
             try {
 315  3
                 zis.close();
 316  0
             } catch (IOException ex) {
 317  0
                 Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 318  3
             }
 319  0
         }
 320  3
     }
 321  
 }