Coverage Report - org.owasp.dependencycheck.analyzer.ArchiveAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
ArchiveAnalyzer
0%
0/163
0%
0/70
6.455
 
 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  0
     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  0
     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  0
     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  0
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL;
 92  
     /**
 93  
      * The set of things we can handle with Zip methods
 94  
      */
 95  0
     private static final Set<String> ZIPPABLES = newHashSet("zip", "ear", "war", "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  0
     private static final Set<String> EXTENSIONS = newHashSet("tar", "gz", "tgz");
 101  
 
 102  
     static {
 103  0
         final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS);
 104  0
         if (additionalZipExt != null) {
 105  0
             final HashSet ext = new HashSet<String>(Arrays.asList(additionalZipExt));
 106  0
             ZIPPABLES.addAll(ext);
 107  
         }
 108  0
         EXTENSIONS.addAll(ZIPPABLES);
 109  0
     }
 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  0
         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  0
         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  0
         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  0
         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  0
         final File baseDir = Settings.getTempDirectory();
 160  0
         if (!baseDir.exists()) {
 161  0
             if (!baseDir.mkdirs()) {
 162  0
                 final String msg = String.format("Unable to make a temporary folder '%s'", baseDir.getPath());
 163  0
                 throw new AnalysisException(msg);
 164  
             }
 165  
         }
 166  0
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 167  0
         if (!tempFileLocation.delete()) {
 168  0
             final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
 169  0
             throw new AnalysisException(msg);
 170  
         }
 171  0
         if (!tempFileLocation.mkdirs()) {
 172  0
             final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
 173  0
             throw new AnalysisException(msg);
 174  
         }
 175  0
     }
 176  
 
 177  
     /**
 178  
      * The close method deletes any temporary files and directories created during analysis.
 179  
      *
 180  
      * @throws Exception thrown if there is an exception deleting temporary files
 181  
      */
 182  
     @Override
 183  
     public void close() throws Exception {
 184  0
         if (tempFileLocation != null && tempFileLocation.exists()) {
 185  0
             LOGGER.log(Level.FINE, "Attempting to delete temporary files");
 186  0
             final boolean success = FileUtils.delete(tempFileLocation);
 187  0
             if (!success) {
 188  0
                 LOGGER.log(Level.WARNING, "Failed to delete some temporary files, see the log for more details");
 189  
             }
 190  
         }
 191  0
     }
 192  
 
 193  
     /**
 194  
      * Analyzes a given dependency. If the dependency is an archive, such as a WAR or EAR, the contents are extracted,
 195  
      * scanned, and added to the list of dependencies within the engine.
 196  
      *
 197  
      * @param dependency the dependency to analyze
 198  
      * @param engine the engine scanning
 199  
      * @throws AnalysisException thrown if there is an analysis exception
 200  
      */
 201  
     @Override
 202  
     public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
 203  0
         final File f = new File(dependency.getActualFilePath());
 204  0
         final File tmpDir = getNextTempDirectory();
 205  0
         extractFiles(f, tmpDir, engine);
 206  
 
 207  
         //make a copy
 208  0
         final List<Dependency> dependencies = new ArrayList<Dependency>(engine.getDependencies());
 209  0
         engine.scan(tmpDir);
 210  0
         final List<Dependency> newDependencies = engine.getDependencies();
 211  0
         if (dependencies.size() != newDependencies.size()) {
 212  
             //get the new dependencies
 213  0
             final Set<Dependency> dependencySet = new HashSet<Dependency>();
 214  0
             dependencySet.addAll(newDependencies);
 215  0
             dependencySet.removeAll(dependencies);
 216  
 
 217  0
             for (Dependency d : dependencySet) {
 218  
                 //fix the dependency's display name and path
 219  0
                 final String displayPath = String.format("%s%s",
 220  
                         dependency.getFilePath(),
 221  
                         d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
 222  0
                 final String displayName = String.format("%s%s%s",
 223  
                         dependency.getFileName(),
 224  
                         File.separator,
 225  
                         d.getFileName());
 226  0
                 d.setFilePath(displayPath);
 227  0
                 d.setFileName(displayName);
 228  
 
 229  
                 //TODO - can we get more evidence from the parent? EAR contains module name, etc.
 230  
                 //analyze the dependency (i.e. extract files) if it is a supported type.
 231  0
                 if (this.supportsExtension(d.getFileExtension()) && scanDepth < MAX_SCAN_DEPTH) {
 232  0
                     scanDepth += 1;
 233  0
                     analyze(d, engine);
 234  0
                     scanDepth -= 1;
 235  
                 }
 236  0
             }
 237  
         }
 238  0
         Collections.sort(engine.getDependencies());
 239  0
     }
 240  
 
 241  
     /**
 242  
      * Retrieves the next temporary directory to extract an archive too.
 243  
      *
 244  
      * @return a directory
 245  
      * @throws AnalysisException thrown if unable to create temporary directory
 246  
      */
 247  
     private File getNextTempDirectory() throws AnalysisException {
 248  0
         dirCount += 1;
 249  0
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 250  
         //getting an exception for some directories not being able to be created; might be because the directory already exists?
 251  0
         if (directory.exists()) {
 252  0
             return getNextTempDirectory();
 253  
         }
 254  0
         if (!directory.mkdirs()) {
 255  0
             final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
 256  0
             throw new AnalysisException(msg);
 257  
         }
 258  0
         return directory;
 259  
     }
 260  
 
 261  
     /**
 262  
      * Extracts the contents of an archive into the specified directory.
 263  
      *
 264  
      * @param archive an archive file such as a WAR or EAR
 265  
      * @param destination a directory to extract the contents to
 266  
      * @param engine the scanning engine
 267  
      * @throws AnalysisException thrown if the archive is not found
 268  
      */
 269  
     private void extractFiles(File archive, File destination, Engine engine) throws AnalysisException {
 270  0
         if (archive == null || destination == null) {
 271  0
             return;
 272  
         }
 273  
 
 274  0
         FileInputStream fis = null;
 275  
         try {
 276  0
             fis = new FileInputStream(archive);
 277  0
         } catch (FileNotFoundException ex) {
 278  0
             LOGGER.log(Level.FINE, null, ex);
 279  0
             throw new AnalysisException("Archive file was not found.", ex);
 280  0
         }
 281  0
         final String archiveExt = FileUtils.getFileExtension(archive.getName()).toLowerCase();
 282  
         try {
 283  0
             if (ZIPPABLES.contains(archiveExt)) {
 284  0
                 extractArchive(new ZipArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 285  0
             } else if ("tar".equals(archiveExt)) {
 286  0
                 extractArchive(new TarArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 287  0
             } else if ("gz".equals(archiveExt) || "tgz".equals(archiveExt)) {
 288  0
                 final String uncompressedName = GzipUtils.getUncompressedFilename(archive.getName());
 289  0
                 final String uncompressedExt = FileUtils.getFileExtension(uncompressedName).toLowerCase();
 290  0
                 if (engine.supportsExtension(uncompressedExt)) {
 291  0
                     decompressFile(new GzipCompressorInputStream(new BufferedInputStream(fis)), new File(destination, uncompressedName));
 292  
                 }
 293  
             }
 294  0
         } catch (ArchiveExtractionException ex) {
 295  0
             final String msg = String.format("Exception extracting archive '%s'.", archive.getName());
 296  0
             LOGGER.log(Level.WARNING, msg);
 297  0
             LOGGER.log(Level.FINE, null, ex);
 298  0
         } catch (IOException ex) {
 299  0
             final String msg = String.format("Exception reading archive '%s'.", archive.getName());
 300  0
             LOGGER.log(Level.WARNING, msg);
 301  0
             LOGGER.log(Level.FINE, null, ex);
 302  
         } finally {
 303  0
             try {
 304  0
                 fis.close();
 305  0
             } catch (IOException ex) {
 306  0
                 LOGGER.log(Level.FINEST, null, ex);
 307  0
             }
 308  0
         }
 309  0
     }
 310  
 
 311  
     /**
 312  
      * Extracts files from an archive.
 313  
      *
 314  
      * @param input the archive to extract files from
 315  
      * @param destination the location to write the files too
 316  
      * @param engine the dependency-check engine
 317  
      * @throws ArchiveExtractionException thrown if there is an exception extracting files from the archive
 318  
      */
 319  
     private void extractArchive(ArchiveInputStream input, File destination, Engine engine) throws ArchiveExtractionException {
 320  
         ArchiveEntry entry;
 321  
         try {
 322  0
             while ((entry = input.getNextEntry()) != null) {
 323  0
                 if (entry.isDirectory()) {
 324  0
                     final File d = new File(destination, entry.getName());
 325  0
                     if (!d.exists()) {
 326  0
                         if (!d.mkdirs()) {
 327  0
                             final String msg = String.format("Unable to create directory '%s'.", d.getAbsolutePath());
 328  0
                             throw new AnalysisException(msg);
 329  
                         }
 330  
                     }
 331  0
                 } else {
 332  0
                     final File file = new File(destination, entry.getName());
 333  0
                     final String ext = FileUtils.getFileExtension(file.getName());
 334  0
                     if (engine.supportsExtension(ext)) {
 335  0
                         BufferedOutputStream bos = null;
 336  
                         FileOutputStream fos;
 337  
                         try {
 338  0
                             final File parent = file.getParentFile();
 339  0
                             if (!parent.isDirectory()) {
 340  0
                                 if (!parent.mkdirs()) {
 341  0
                                     final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath());
 342  0
                                     throw new AnalysisException(msg);
 343  
                                 }
 344  
                             }
 345  0
                             fos = new FileOutputStream(file);
 346  0
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 347  
                             int count;
 348  0
                             final byte data[] = new byte[BUFFER_SIZE];
 349  0
                             while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
 350  0
                                 bos.write(data, 0, count);
 351  
                             }
 352  0
                             bos.flush();
 353  0
                         } catch (FileNotFoundException ex) {
 354  0
                             Logger.getLogger(ArchiveAnalyzer.class
 355  
                                     .getName()).log(Level.FINE, null, ex);
 356  0
                             final String msg = String.format("Unable to find file '%s'.", file.getName());
 357  0
                             throw new AnalysisException(msg, ex);
 358  0
                         } catch (IOException ex) {
 359  0
                             Logger.getLogger(ArchiveAnalyzer.class
 360  
                                     .getName()).log(Level.FINE, null, ex);
 361  0
                             final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
 362  0
                             throw new AnalysisException(msg, ex);
 363  
                         } finally {
 364  0
                             if (bos != null) {
 365  
                                 try {
 366  0
                                     bos.close();
 367  0
                                 } catch (IOException ex) {
 368  0
                                     Logger.getLogger(ArchiveAnalyzer.class
 369  
                                             .getName()).log(Level.FINEST, null, ex);
 370  0
                                 }
 371  
                             }
 372  
                         }
 373  
                     }
 374  0
                 }
 375  
             }
 376  0
         } catch (IOException ex) {
 377  0
             throw new ArchiveExtractionException(ex);
 378  0
         } catch (Throwable ex) {
 379  0
             throw new ArchiveExtractionException(ex);
 380  
         } finally {
 381  0
             if (input != null) {
 382  
                 try {
 383  0
                     input.close();
 384  0
                 } catch (IOException ex) {
 385  0
                     LOGGER.log(Level.FINEST, null, ex);
 386  0
                 }
 387  
             }
 388  
         }
 389  0
     }
 390  
 
 391  
     /**
 392  
      * Decompresses a file.
 393  
      *
 394  
      * @param inputStream the compressed file
 395  
      * @param outputFile the location to write the decompressed file
 396  
      * @throws ArchiveExtractionException thrown if there is an exception decompressing the file
 397  
      */
 398  
     private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException {
 399  0
         FileOutputStream out = null;
 400  
         try {
 401  0
             out = new FileOutputStream(outputFile);
 402  0
             final byte[] buffer = new byte[BUFFER_SIZE];
 403  0
             int n = 0;
 404  0
             while (-1 != (n = inputStream.read(buffer))) {
 405  0
                 out.write(buffer, 0, n);
 406  
             }
 407  0
         } catch (FileNotFoundException ex) {
 408  0
             LOGGER.log(Level.FINE, null, ex);
 409  0
             throw new ArchiveExtractionException(ex);
 410  0
         } catch (IOException ex) {
 411  0
             LOGGER.log(Level.FINE, null, ex);
 412  0
             throw new ArchiveExtractionException(ex);
 413  
         } finally {
 414  0
             if (out != null) {
 415  
                 try {
 416  0
                     out.close();
 417  0
                 } catch (IOException ex) {
 418  0
                     LOGGER.log(Level.FINEST, null, ex);
 419  0
                 }
 420  
             }
 421  
         }
 422  0
     }
 423  
 }