Coverage Report - org.owasp.dependencycheck.analyzer.ArchiveAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
ArchiveAnalyzer
65%
101/155
69%
46/66
6.545
 
 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) 2013 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.analyzer;
 19  
 
 20  
 import java.io.BufferedInputStream;
 21  
 import java.io.BufferedOutputStream;
 22  
 import java.io.File;
 23  
 import java.io.FileInputStream;
 24  
 import java.io.FileNotFoundException;
 25  
 import java.io.FileOutputStream;
 26  
 import java.io.IOException;
 27  
 import java.util.ArrayList;
 28  
 import java.util.Collections;
 29  
 import java.util.HashSet;
 30  
 import java.util.List;
 31  
 import java.util.Set;
 32  
 import java.util.logging.Level;
 33  
 import java.util.logging.Logger;
 34  
 import org.apache.commons.compress.archivers.ArchiveEntry;
 35  
 import org.apache.commons.compress.archivers.ArchiveInputStream;
 36  
 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
 37  
 import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
 38  
 import org.apache.commons.compress.compressors.CompressorInputStream;
 39  
 import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
 40  
 import org.apache.commons.compress.compressors.gzip.GzipUtils;
 41  
 import org.h2.store.fs.FileUtils;
 42  
 import org.owasp.dependencycheck.Engine;
 43  
 import org.owasp.dependencycheck.dependency.Dependency;
 44  
 import org.owasp.dependencycheck.utils.Settings;
 45  
 
 46  
 /**
 47  
  * <p>
 48  
  * An analyzer that extracts files from archives and ensures any supported files contained within the archive are added
 49  
  * to the dependency list.</p>
 50  
  *
 51  
  * @author Jeremy Long <jeremy.long@owasp.org>
 52  
  */
 53  22
 public class ArchiveAnalyzer extends AbstractAnalyzer implements Analyzer {
 54  
 
 55  
     /**
 56  
      * The buffer size to use when extracting files from the archive.
 57  
      */
 58  
     private static final int BUFFER_SIZE = 4096;
 59  
     /**
 60  
      * The count of directories created during analysis. This is used for creating temporary directories.
 61  
      */
 62  2
     private static int dirCount = 0;
 63  
     /**
 64  
      * The parent directory for the individual directories per archive.
 65  
      */
 66  22
     private File tempFileLocation = null;
 67  
     /**
 68  
      * The max scan depth that the analyzer will recursively extract nested archives.
 69  
      */
 70  2
     private static final int MAX_SCAN_DEPTH = Settings.getInt("archive.scan.depth", 3);
 71  
     /**
 72  
      * Tracks the current scan/extraction depth for nested archives.
 73  
      */
 74  22
     private int scanDepth = 0;
 75  
     //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
 76  
     /**
 77  
      * The name of the analyzer.
 78  
      */
 79  
     private static final String ANALYZER_NAME = "Archive Analyzer";
 80  
     /**
 81  
      * The phase that this analyzer is intended to run in.
 82  
      */
 83  2
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL;
 84  
     /**
 85  
      * The set of file extensions supported by this analyzer.
 86  
      */
 87  2
     private static final Set<String> EXTENSIONS = newHashSet("zip", "ear", "war", "tar", "gz", "tgz");
 88  
 
 89  
     /**
 90  
      * Returns a list of file EXTENSIONS supported by this analyzer.
 91  
      *
 92  
      * @return a list of file EXTENSIONS supported by this analyzer.
 93  
      */
 94  
     public Set<String> getSupportedExtensions() {
 95  316
         return EXTENSIONS;
 96  
     }
 97  
 
 98  
     /**
 99  
      * Returns the name of the analyzer.
 100  
      *
 101  
      * @return the name of the analyzer.
 102  
      */
 103  
     public String getName() {
 104  20
         return ANALYZER_NAME;
 105  
     }
 106  
 
 107  
     /**
 108  
      * Returns whether or not this analyzer can process the given extension.
 109  
      *
 110  
      * @param extension the file extension to test for support.
 111  
      * @return whether or not the specified file extension is supported by this analyzer.
 112  
      */
 113  
     public boolean supportsExtension(String extension) {
 114  344
         return EXTENSIONS.contains(extension);
 115  
     }
 116  
 
 117  
     /**
 118  
      * Returns the phase that the analyzer is intended to run in.
 119  
      *
 120  
      * @return the phase that the analyzer is intended to run in.
 121  
      */
 122  
     public AnalysisPhase getAnalysisPhase() {
 123  14
         return ANALYSIS_PHASE;
 124  
     }
 125  
     //</editor-fold>
 126  
 
 127  
     /**
 128  
      * The initialize method does nothing for this Analyzer.
 129  
      *
 130  
      * @throws Exception is thrown if there is an exception deleting or creating temporary files
 131  
      */
 132  
     @Override
 133  
     public void initialize() throws Exception {
 134  18
         final File baseDir = Settings.getTempDirectory();
 135  18
         if (!baseDir.exists()) {
 136  0
             if (!baseDir.mkdirs()) {
 137  0
                 final String msg = String.format("Unable to make a temporary folder '%s'", baseDir.getPath());
 138  0
                 throw new AnalysisException(msg);
 139  
             }
 140  
         }
 141  18
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 142  18
         if (!tempFileLocation.delete()) {
 143  0
             final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
 144  0
             throw new AnalysisException(msg);
 145  
         }
 146  18
         if (!tempFileLocation.mkdirs()) {
 147  0
             final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
 148  0
             throw new AnalysisException(msg);
 149  
         }
 150  18
     }
 151  
 
 152  
     /**
 153  
      * The close method does nothing for this Analyzer.
 154  
      *
 155  
      * @throws Exception thrown if there is an exception deleting temporary files
 156  
      */
 157  
     @Override
 158  
     public void close() throws Exception {
 159  18
         if (tempFileLocation != null && tempFileLocation.exists()) {
 160  18
             FileUtils.deleteRecursive(tempFileLocation.getAbsolutePath(), true);
 161  
         }
 162  18
     }
 163  
 
 164  
     /**
 165  
      * Analyzes a given dependency. If the dependency is an archive, such as a WAR or EAR, the contents are extracted,
 166  
      * scanned, and added to the list of dependencies within the engine.
 167  
      *
 168  
      * @param dependency the dependency to analyze
 169  
      * @param engine the engine scanning
 170  
      * @throws AnalysisException thrown if there is an analysis exception
 171  
      */
 172  
     @Override
 173  
     public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
 174  16
         final File f = new File(dependency.getActualFilePath());
 175  16
         final File tmpDir = getNextTempDirectory();
 176  16
         extractFiles(f, tmpDir, engine);
 177  
 
 178  
         //make a copy
 179  16
         final List<Dependency> dependencies = new ArrayList<Dependency>(engine.getDependencies());
 180  16
         engine.scan(tmpDir);
 181  16
         final List<Dependency> newDependencies = engine.getDependencies();
 182  16
         if (dependencies.size() != newDependencies.size()) {
 183  
             //get the new dependencies
 184  12
             final Set<Dependency> dependencySet = new HashSet<Dependency>();
 185  12
             dependencySet.addAll(newDependencies);
 186  12
             dependencySet.removeAll(dependencies);
 187  
 
 188  12
             for (Dependency d : dependencySet) {
 189  
                 //fix the dependency's display name and path
 190  38
                 final String displayPath = String.format("%s%s",
 191  
                         dependency.getFilePath(),
 192  
                         d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
 193  38
                 final String displayName = String.format("%s%s%s",
 194  
                         dependency.getFileName(),
 195  
                         File.separator,
 196  
                         d.getFileName());
 197  38
                 d.setFilePath(displayPath);
 198  38
                 d.setFileName(displayName);
 199  
 
 200  
                 //TODO - can we get more evidence from the parent? EAR contains module name, etc.
 201  
                 //analyze the dependency (i.e. extract files) if it is a supported type.
 202  38
                 if (this.supportsExtension(d.getFileExtension()) && scanDepth < MAX_SCAN_DEPTH) {
 203  6
                     scanDepth += 1;
 204  6
                     analyze(d, engine);
 205  6
                     scanDepth -= 1;
 206  
                 }
 207  38
             }
 208  
         }
 209  16
         Collections.sort(engine.getDependencies());
 210  16
     }
 211  
 
 212  
     /**
 213  
      * Retrieves the next temporary directory to extract an archive too.
 214  
      *
 215  
      * @return a directory
 216  
      * @throws AnalysisException thrown if unable to create temporary directory
 217  
      */
 218  
     private File getNextTempDirectory() throws AnalysisException {
 219  16
         dirCount += 1;
 220  16
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 221  
         //getting an exception for some directories not being able to be created; might be because the directory already exists?
 222  16
         if (directory.exists()) {
 223  0
             return getNextTempDirectory();
 224  
         }
 225  16
         if (!directory.mkdirs()) {
 226  0
             final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
 227  0
             throw new AnalysisException(msg);
 228  
         }
 229  16
         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 destination 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 destination, Engine engine) throws AnalysisException {
 241  16
         if (archive == null || destination == null) {
 242  0
             return;
 243  
         }
 244  
 
 245  16
         FileInputStream fis = null;
 246  
         try {
 247  16
             fis = new FileInputStream(archive);
 248  0
         } catch (FileNotFoundException ex) {
 249  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.INFO, null, ex);
 250  0
             throw new AnalysisException("Archive file was not found.", ex);
 251  16
         }
 252  16
         final String archiveExt = org.owasp.dependencycheck.utils.FileUtils.getFileExtension(archive.getName()).toLowerCase();
 253  
         try {
 254  16
             if ("zip".equals(archiveExt) || "war".equals(archiveExt) || "ear".equals(archiveExt)) {
 255  6
                 extractArchive(new ZipArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 256  10
             } else if ("tar".equals(archiveExt)) {
 257  6
                 extractArchive(new TarArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 258  4
             } else if ("gz".equals(archiveExt) || "tgz".equals(archiveExt)) {
 259  4
                 final String uncompressedName = GzipUtils.getUncompressedFilename(archive.getName());
 260  4
                 final String uncompressedExt = org.owasp.dependencycheck.utils.FileUtils.getFileExtension(uncompressedName).toLowerCase();
 261  4
                 if (engine.supportsExtension(uncompressedExt)) {
 262  4
                     decompressFile(new GzipCompressorInputStream(new BufferedInputStream(fis)), new File(destination, uncompressedName));
 263  
                 }
 264  
             }
 265  0
         } catch (ArchiveExtractionException ex) {
 266  0
             final String msg = String.format("Exception extracting archive '%s'.", archive.getName());
 267  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.WARNING, msg);
 268  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 269  0
         } catch (IOException ex) {
 270  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 271  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.WARNING, msg);
 272  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 273  
         } finally {
 274  0
             try {
 275  16
                 fis.close();
 276  0
             } catch (IOException ex) {
 277  0
                 Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 278  16
             }
 279  0
         }
 280  16
     }
 281  
 
 282  
     /**
 283  
      * Extracts files from an archive.
 284  
      *
 285  
      * @param input the archive to extract files from
 286  
      * @param destination the location to write the files too
 287  
      * @param engine the dependency-check engine
 288  
      * @throws ArchiveExtractionException thrown if there is an exception extracting files from the archive
 289  
      */
 290  
     private void extractArchive(ArchiveInputStream input, File destination, Engine engine) throws ArchiveExtractionException {
 291  
         ArchiveEntry entry;
 292  
         try {
 293  362
             while ((entry = input.getNextEntry()) != null) {
 294  350
                 if (entry.isDirectory()) {
 295  50
                     final File d = new File(destination, entry.getName());
 296  50
                     if (!d.exists()) {
 297  50
                         if (!d.mkdirs()) {
 298  0
                             final String msg = String.format("Unable to create directory '%s'.", d.getAbsolutePath());
 299  0
                             throw new AnalysisException(msg);
 300  
                         }
 301  
                     }
 302  50
                 } else {
 303  300
                     final File file = new File(destination, entry.getName());
 304  300
                     final String ext = org.owasp.dependencycheck.utils.FileUtils.getFileExtension(file.getName());
 305  300
                     if (engine.supportsExtension(ext)) {
 306  34
                         BufferedOutputStream bos = null;
 307  
                         FileOutputStream fos;
 308  
                         try {
 309  34
                             final File parent = file.getParentFile();
 310  34
                             if (!parent.isDirectory()) {
 311  2
                                 if (!parent.mkdirs()) {
 312  0
                                     final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath());
 313  0
                                     throw new AnalysisException(msg);
 314  
                                 }
 315  
                             }
 316  34
                             fos = new FileOutputStream(file);
 317  34
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 318  
                             int count;
 319  34
                             final byte data[] = new byte[BUFFER_SIZE];
 320  6734
                             while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
 321  6700
                                 bos.write(data, 0, count);
 322  
                             }
 323  34
                             bos.flush();
 324  0
                         } catch (FileNotFoundException ex) {
 325  0
                             Logger.getLogger(ArchiveAnalyzer.class
 326  
                                     .getName()).log(Level.FINE, null, ex);
 327  0
                             final String msg = String.format("Unable to find file '%s'.", file.getName());
 328  0
                             throw new AnalysisException(msg, ex);
 329  0
                         } catch (IOException ex) {
 330  0
                             Logger.getLogger(ArchiveAnalyzer.class
 331  
                                     .getName()).log(Level.FINE, null, ex);
 332  0
                             final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
 333  0
                             throw new AnalysisException(msg, ex);
 334  
                         } finally {
 335  34
                             if (bos != null) {
 336  
                                 try {
 337  34
                                     bos.close();
 338  0
                                 } catch (IOException ex) {
 339  0
                                     Logger.getLogger(ArchiveAnalyzer.class
 340  
                                             .getName()).log(Level.FINEST, null, ex);
 341  34
                                 }
 342  
                             }
 343  
                         }
 344  
                     }
 345  300
                 }
 346  
             }
 347  0
         } catch (IOException ex) {
 348  0
             throw new ArchiveExtractionException(ex);
 349  0
         } catch (Throwable ex) {
 350  0
             throw new ArchiveExtractionException(ex);
 351  
         } finally {
 352  12
             if (input != null) {
 353  
                 try {
 354  12
                     input.close();
 355  0
                 } catch (IOException ex) {
 356  0
                     Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 357  12
                 }
 358  
             }
 359  
         }
 360  12
     }
 361  
 
 362  
     /**
 363  
      * Decompresses a file.
 364  
      *
 365  
      * @param inputStream the compressed file
 366  
      * @param outputFile the location to write the decompressed file
 367  
      * @throws ArchiveExtractionException thrown if there is an exception decompressing the file
 368  
      */
 369  
     private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException {
 370  4
         FileOutputStream out = null;
 371  
         try {
 372  4
             out = new FileOutputStream(outputFile);
 373  4
             final byte[] buffer = new byte[BUFFER_SIZE];
 374  4
             int n = 0;
 375  544
             while (-1 != (n = inputStream.read(buffer))) {
 376  540
                 out.write(buffer, 0, n);
 377  
             }
 378  0
         } catch (FileNotFoundException ex) {
 379  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 380  0
             throw new ArchiveExtractionException(ex);
 381  0
         } catch (IOException ex) {
 382  0
             Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINE, null, ex);
 383  0
             throw new ArchiveExtractionException(ex);
 384  
         } finally {
 385  4
             if (out != null) {
 386  
                 try {
 387  4
                     out.close();
 388  0
                 } catch (IOException ex) {
 389  0
                     Logger.getLogger(ArchiveAnalyzer.class.getName()).log(Level.FINEST, null, ex);
 390  4
                 }
 391  
             }
 392  
         }
 393  4
     }
 394  
 }