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