Coverage Report - org.owasp.dependencycheck.analyzer.ArchiveAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
ArchiveAnalyzer
31%
67/211
22%
20/90
7.25
 
 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.FileFilter;
 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.Arrays;
 30  
 import java.util.Collections;
 31  
 import java.util.Enumeration;
 32  
 import java.util.HashSet;
 33  
 import java.util.List;
 34  
 import java.util.Set;
 35  
 
 36  
 import org.apache.commons.compress.archivers.ArchiveEntry;
 37  
 import org.apache.commons.compress.archivers.ArchiveInputStream;
 38  
 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
 39  
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 40  
 import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
 41  
 import org.apache.commons.compress.archivers.zip.ZipFile;
 42  
 import org.apache.commons.compress.compressors.CompressorInputStream;
 43  
 import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
 44  
 import org.apache.commons.compress.compressors.gzip.GzipUtils;
 45  
 import org.owasp.dependencycheck.Engine;
 46  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 47  
 import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException;
 48  
 import org.owasp.dependencycheck.dependency.Dependency;
 49  
 import org.owasp.dependencycheck.utils.FileFilterBuilder;
 50  
 import org.owasp.dependencycheck.utils.FileUtils;
 51  
 import org.owasp.dependencycheck.utils.Settings;
 52  
 import org.slf4j.Logger;
 53  
 import org.slf4j.LoggerFactory;
 54  
 
 55  
 /**
 56  
  * <p>
 57  
  * An analyzer that extracts files from archives and ensures any supported files contained within the archive are added to the
 58  
  * dependency list.</p>
 59  
  *
 60  
  * @author Jeremy Long
 61  
  */
 62  24
 public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
 63  
 
 64  
     /**
 65  
      * The logger.
 66  
      */
 67  8
     private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveAnalyzer.class);
 68  
     /**
 69  
      * The buffer size to use when extracting files from the archive.
 70  
      */
 71  
     private static final int BUFFER_SIZE = 4096;
 72  
     /**
 73  
      * The count of directories created during analysis. This is used for creating temporary directories.
 74  
      */
 75  8
     private static int dirCount = 0;
 76  
     /**
 77  
      * The parent directory for the individual directories per archive.
 78  
      */
 79  24
     private File tempFileLocation = null;
 80  
     /**
 81  
      * The max scan depth that the analyzer will recursively extract nested archives.
 82  
      */
 83  8
     private static final int MAX_SCAN_DEPTH = Settings.getInt("archive.scan.depth", 3);
 84  
     /**
 85  
      * Tracks the current scan/extraction depth for nested archives.
 86  
      */
 87  24
     private int scanDepth = 0;
 88  
 
 89  
     //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
 90  
     /**
 91  
      * The name of the analyzer.
 92  
      */
 93  
     private static final String ANALYZER_NAME = "Archive Analyzer";
 94  
     /**
 95  
      * The phase that this analyzer is intended to run in.
 96  
      */
 97  8
     private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INITIAL;
 98  
     /**
 99  
      * The set of things we can handle with Zip methods
 100  
      */
 101  8
     private static final Set<String> ZIPPABLES = newHashSet("zip", "ear", "war", "jar", "sar", "apk", "nupkg");
 102  
     /**
 103  
      * The set of file extensions supported by this analyzer. Note for developers, any additions to this list will need to be
 104  
      * explicitly handled in extractFiles().
 105  
      */
 106  8
     private static final Set<String> EXTENSIONS = newHashSet("tar", "gz", "tgz");
 107  
 
 108  
     /**
 109  
      * Detects files with extensions to remove from the engine's collection of dependencies.
 110  
      */
 111  8
     private static final FileFilter REMOVE_FROM_ANALYSIS = FileFilterBuilder.newInstance().addExtensions("zip", "tar", "gz", "tgz").build();
 112  
 
 113  
     static {
 114  8
         final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS);
 115  8
         if (additionalZipExt != null) {
 116  0
             final Set<String> ext = new HashSet<String>(Arrays.asList(additionalZipExt));
 117  0
             ZIPPABLES.addAll(ext);
 118  
         }
 119  8
         EXTENSIONS.addAll(ZIPPABLES);
 120  
     }
 121  
 
 122  
     /**
 123  
      * The file filter used to filter supported files.
 124  
      */
 125  8
     private static final FileFilter FILTER = FileFilterBuilder.newInstance().addExtensions(EXTENSIONS).build();
 126  
 
 127  
     @Override
 128  
     protected FileFilter getFileFilter() {
 129  6824
         return FILTER;
 130  
     }
 131  
 
 132  
     /**
 133  
      * Detects files with .zip extension.
 134  
      */
 135  8
     private static final FileFilter ZIP_FILTER = FileFilterBuilder.newInstance().addExtensions("zip").build();
 136  
 
 137  
     /**
 138  
      * Returns the name of the analyzer.
 139  
      *
 140  
      * @return the name of the analyzer.
 141  
      */
 142  
     @Override
 143  
     public String getName() {
 144  32
         return ANALYZER_NAME;
 145  
     }
 146  
 
 147  
     /**
 148  
      * Returns the phase that the analyzer is intended to run in.
 149  
      *
 150  
      * @return the phase that the analyzer is intended to run in.
 151  
      */
 152  
     @Override
 153  
     public AnalysisPhase getAnalysisPhase() {
 154  16
         return ANALYSIS_PHASE;
 155  
     }
 156  
     //</editor-fold>
 157  
 
 158  
     /**
 159  
      * Returns the key used in the properties file to reference the analyzer's enabled property.
 160  
      *
 161  
      * @return the analyzer's enabled property setting key
 162  
      */
 163  
     @Override
 164  
     protected String getAnalyzerEnabledSettingKey() {
 165  24
         return Settings.KEYS.ANALYZER_ARCHIVE_ENABLED;
 166  
     }
 167  
 
 168  
     /**
 169  
      * The initialize method does nothing for this Analyzer.
 170  
      *
 171  
      * @throws Exception is thrown if there is an exception deleting or creating temporary files
 172  
      */
 173  
     @Override
 174  
     public void initializeFileTypeAnalyzer() throws Exception {
 175  8
         final File baseDir = Settings.getTempDirectory();
 176  8
         tempFileLocation = File.createTempFile("check", "tmp", baseDir);
 177  8
         if (!tempFileLocation.delete()) {
 178  0
             final String msg = String.format("Unable to delete temporary file '%s'.", tempFileLocation.getAbsolutePath());
 179  0
             throw new AnalysisException(msg);
 180  
         }
 181  8
         if (!tempFileLocation.mkdirs()) {
 182  0
             final String msg = String.format("Unable to create directory '%s'.", tempFileLocation.getAbsolutePath());
 183  0
             throw new AnalysisException(msg);
 184  
         }
 185  8
     }
 186  
 
 187  
     /**
 188  
      * The close method deletes any temporary files and directories created during analysis.
 189  
      *
 190  
      * @throws Exception thrown if there is an exception deleting temporary files
 191  
      */
 192  
     @Override
 193  
     public void close() throws Exception {
 194  8
         if (tempFileLocation != null && tempFileLocation.exists()) {
 195  8
             LOGGER.debug("Attempting to delete temporary files");
 196  8
             final boolean success = FileUtils.delete(tempFileLocation);
 197  8
             if (!success && tempFileLocation != null && tempFileLocation.exists() && tempFileLocation.list().length > 0) {
 198  0
                 LOGGER.warn("Failed to delete some temporary files, see the log for more details");
 199  
             }
 200  
         }
 201  8
     }
 202  
 
 203  
     /**
 204  
      * Analyzes a given dependency. If the dependency is an archive, such as a WAR or EAR, the contents are extracted, scanned,
 205  
      * and added to the list of dependencies within the engine.
 206  
      *
 207  
      * @param dependency the dependency to analyze
 208  
      * @param engine the engine scanning
 209  
      * @throws AnalysisException thrown if there is an analysis exception
 210  
      */
 211  
     @Override
 212  
     public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
 213  16
         final File f = new File(dependency.getActualFilePath());
 214  16
         final File tmpDir = getNextTempDirectory();
 215  16
         extractFiles(f, tmpDir, engine);
 216  
 
 217  
         //make a copy
 218  16
         List<Dependency> dependencies = new ArrayList<Dependency>(engine.getDependencies());
 219  16
         engine.scan(tmpDir);
 220  16
         List<Dependency> newDependencies = engine.getDependencies();
 221  16
         if (dependencies.size() != newDependencies.size()) {
 222  
             //get the new dependencies
 223  0
             final Set<Dependency> dependencySet = new HashSet<Dependency>();
 224  0
             dependencySet.addAll(newDependencies);
 225  0
             dependencySet.removeAll(dependencies);
 226  
 
 227  0
             for (Dependency d : dependencySet) {
 228  
                 //fix the dependency's display name and path
 229  0
                 final String displayPath = String.format("%s%s",
 230  
                         dependency.getFilePath(),
 231  
                         d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
 232  0
                 final String displayName = String.format("%s: %s",
 233  
                         dependency.getFileName(),
 234  
                         d.getFileName());
 235  0
                 d.setFilePath(displayPath);
 236  0
                 d.setFileName(displayName);
 237  
 
 238  
                 //TODO - can we get more evidence from the parent? EAR contains module name, etc.
 239  
                 //analyze the dependency (i.e. extract files) if it is a supported type.
 240  0
                 if (this.accept(d.getActualFile()) && scanDepth < MAX_SCAN_DEPTH) {
 241  0
                     scanDepth += 1;
 242  0
                     analyze(d, engine);
 243  0
                     scanDepth -= 1;
 244  
                 }
 245  0
             }
 246  
         }
 247  16
         if (REMOVE_FROM_ANALYSIS.accept(dependency.getActualFile())) {
 248  0
             if (ZIP_FILTER.accept(dependency.getActualFile()) && isZipFileActuallyJarFile(dependency)) {
 249  0
                 final File tdir = getNextTempDirectory();
 250  0
                 final String fileName = dependency.getFileName();
 251  
 
 252  0
                 LOGGER.info(String.format("The zip file '%s' appears to be a JAR file, making a copy and analyzing it as a JAR.", fileName));
 253  
 
 254  0
                 final File tmpLoc = new File(tdir, fileName.substring(0, fileName.length() - 3) + "jar");
 255  
                 try {
 256  0
                     org.apache.commons.io.FileUtils.copyFile(tdir, tmpLoc);
 257  0
                     dependencies = new ArrayList<Dependency>(engine.getDependencies());
 258  0
                     engine.scan(tmpLoc);
 259  0
                     newDependencies = engine.getDependencies();
 260  0
                     if (dependencies.size() != newDependencies.size()) {
 261  
                         //get the new dependencies
 262  0
                         final Set<Dependency> dependencySet = new HashSet<Dependency>();
 263  0
                         dependencySet.addAll(newDependencies);
 264  0
                         dependencySet.removeAll(dependencies);
 265  0
                         if (dependencySet.size() != 1) {
 266  0
                             LOGGER.info("Deep copy of ZIP to JAR file resulted in more then one dependency?");
 267  
                         }
 268  0
                         for (Dependency d : dependencySet) {
 269  
                             //fix the dependency's display name and path
 270  0
                             d.setFilePath(dependency.getFilePath());
 271  0
                             d.setDisplayFileName(dependency.getFileName());
 272  0
                         }
 273  
                     }
 274  0
                 } catch (IOException ex) {
 275  0
                     LOGGER.debug("Unable to perform deep copy on '{}'", dependency.getActualFile().getPath(), ex);
 276  0
                 }
 277  
             }
 278  0
             engine.getDependencies().remove(dependency);
 279  
         }
 280  16
         Collections.sort(engine.getDependencies());
 281  16
     }
 282  
 
 283  
     /**
 284  
      * Retrieves the next temporary directory to extract an archive too.
 285  
      *
 286  
      * @return a directory
 287  
      * @throws AnalysisException thrown if unable to create temporary directory
 288  
      */
 289  
     private File getNextTempDirectory() throws AnalysisException {
 290  16
         dirCount += 1;
 291  16
         final File directory = new File(tempFileLocation, String.valueOf(dirCount));
 292  
         //getting an exception for some directories not being able to be created; might be because the directory already exists?
 293  16
         if (directory.exists()) {
 294  0
             return getNextTempDirectory();
 295  
         }
 296  16
         if (!directory.mkdirs()) {
 297  0
             final String msg = String.format("Unable to create temp directory '%s'.", directory.getAbsolutePath());
 298  0
             throw new AnalysisException(msg);
 299  
         }
 300  16
         return directory;
 301  
     }
 302  
 
 303  
     /**
 304  
      * Extracts the contents of an archive into the specified directory.
 305  
      *
 306  
      * @param archive an archive file such as a WAR or EAR
 307  
      * @param destination a directory to extract the contents to
 308  
      * @param engine the scanning engine
 309  
      * @throws AnalysisException thrown if the archive is not found
 310  
      */
 311  
     private void extractFiles(File archive, File destination, Engine engine) throws AnalysisException {
 312  16
         if (archive == null || destination == null) {
 313  0
             return;
 314  
         }
 315  
 
 316  16
         FileInputStream fis = null;
 317  
         try {
 318  16
             fis = new FileInputStream(archive);
 319  0
         } catch (FileNotFoundException ex) {
 320  0
             LOGGER.debug("", ex);
 321  0
             throw new AnalysisException("Archive file was not found.", ex);
 322  16
         }
 323  16
         final String archiveExt = FileUtils.getFileExtension(archive.getName()).toLowerCase();
 324  
         try {
 325  16
             if (ZIPPABLES.contains(archiveExt)) {
 326  16
                 extractArchive(new ZipArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 327  0
             } else if ("tar".equals(archiveExt)) {
 328  0
                 extractArchive(new TarArchiveInputStream(new BufferedInputStream(fis)), destination, engine);
 329  0
             } else if ("gz".equals(archiveExt) || "tgz".equals(archiveExt)) {
 330  0
                 final String uncompressedName = GzipUtils.getUncompressedFilename(archive.getName());
 331  0
                 final File f = new File(destination, uncompressedName);
 332  0
                 if (engine.accept(f)) {
 333  0
                     decompressFile(new GzipCompressorInputStream(new BufferedInputStream(fis)), f);
 334  
                 }
 335  
             }
 336  0
         } catch (ArchiveExtractionException ex) {
 337  0
             LOGGER.warn("Exception extracting archive '{}'.", archive.getName());
 338  0
             LOGGER.debug("", ex);
 339  0
         } catch (IOException ex) {
 340  0
             LOGGER.warn("Exception reading archive '{}'.", archive.getName());
 341  0
             LOGGER.debug("", ex);
 342  
         } finally {
 343  0
             try {
 344  16
                 fis.close();
 345  0
             } catch (IOException ex) {
 346  0
                 LOGGER.debug("", ex);
 347  16
             }
 348  0
         }
 349  16
     }
 350  
 
 351  
     /**
 352  
      * Extracts files from an archive.
 353  
      *
 354  
      * @param input the archive to extract files from
 355  
      * @param destination the location to write the files too
 356  
      * @param engine the dependency-check engine
 357  
      * @throws ArchiveExtractionException thrown if there is an exception extracting files from the archive
 358  
      */
 359  
     private void extractArchive(ArchiveInputStream input, File destination, Engine engine) throws ArchiveExtractionException {
 360  
         ArchiveEntry entry;
 361  
         try {
 362  7096
             while ((entry = input.getNextEntry()) != null) {
 363  7080
                 if (entry.isDirectory()) {
 364  288
                     final File d = new File(destination, entry.getName());
 365  288
                     if (!d.exists()) {
 366  288
                         if (!d.mkdirs()) {
 367  0
                             final String msg = String.format("Unable to create directory '%s'.", d.getAbsolutePath());
 368  0
                             throw new AnalysisException(msg);
 369  
                         }
 370  
                     }
 371  288
                 } else {
 372  6792
                     final File file = new File(destination, entry.getName());
 373  6792
                     if (engine.accept(file)) {
 374  0
                         LOGGER.debug("Extracting '{}'", file.getPath());
 375  0
                         BufferedOutputStream bos = null;
 376  0
                         FileOutputStream fos = null;
 377  
                         try {
 378  0
                             final File parent = file.getParentFile();
 379  0
                             if (!parent.isDirectory()) {
 380  0
                                 if (!parent.mkdirs()) {
 381  0
                                     final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath());
 382  0
                                     throw new AnalysisException(msg);
 383  
                                 }
 384  
                             }
 385  0
                             fos = new FileOutputStream(file);
 386  0
                             bos = new BufferedOutputStream(fos, BUFFER_SIZE);
 387  
                             int count;
 388  0
                             final byte[] data = new byte[BUFFER_SIZE];
 389  0
                             while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
 390  0
                                 bos.write(data, 0, count);
 391  
                             }
 392  0
                             bos.flush();
 393  0
                         } catch (FileNotFoundException ex) {
 394  0
                             LOGGER.debug("", ex);
 395  0
                             final String msg = String.format("Unable to find file '%s'.", file.getName());
 396  0
                             throw new AnalysisException(msg, ex);
 397  0
                         } catch (IOException ex) {
 398  0
                             LOGGER.debug("", ex);
 399  0
                             final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
 400  0
                             throw new AnalysisException(msg, ex);
 401  
                         } finally {
 402  0
                             if (bos != null) {
 403  
                                 try {
 404  0
                                     bos.close();
 405  0
                                 } catch (IOException ex) {
 406  0
                                     LOGGER.trace("", ex);
 407  0
                                 }
 408  
                             }
 409  0
                             if (fos != null) {
 410  
                                 try {
 411  0
                                     fos.close();
 412  0
                                 } catch (IOException ex) {
 413  0
                                     LOGGER.trace("", ex);
 414  0
                                 }
 415  
                             }
 416  
                         }
 417  
                     }
 418  6792
                 }
 419  
             }
 420  0
         } catch (IOException ex) {
 421  0
             throw new ArchiveExtractionException(ex);
 422  0
         } catch (Throwable ex) {
 423  0
             throw new ArchiveExtractionException(ex);
 424  
         } finally {
 425  16
             if (input != null) {
 426  
                 try {
 427  16
                     input.close();
 428  0
                 } catch (IOException ex) {
 429  0
                     LOGGER.trace("", ex);
 430  16
                 }
 431  
             }
 432  
         }
 433  16
     }
 434  
 
 435  
     /**
 436  
      * Decompresses a file.
 437  
      *
 438  
      * @param inputStream the compressed file
 439  
      * @param outputFile the location to write the decompressed file
 440  
      * @throws ArchiveExtractionException thrown if there is an exception decompressing the file
 441  
      */
 442  
     private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException {
 443  0
         LOGGER.debug("Decompressing '{}'", outputFile.getPath());
 444  0
         FileOutputStream out = null;
 445  
         try {
 446  0
             out = new FileOutputStream(outputFile);
 447  0
             final byte[] buffer = new byte[BUFFER_SIZE];
 448  0
             int n = 0;
 449  0
             while (-1 != (n = inputStream.read(buffer))) {
 450  0
                 out.write(buffer, 0, n);
 451  
             }
 452  0
         } catch (FileNotFoundException ex) {
 453  0
             LOGGER.debug("", ex);
 454  0
             throw new ArchiveExtractionException(ex);
 455  0
         } catch (IOException ex) {
 456  0
             LOGGER.debug("", ex);
 457  0
             throw new ArchiveExtractionException(ex);
 458  
         } finally {
 459  0
             if (out != null) {
 460  
                 try {
 461  0
                     out.close();
 462  0
                 } catch (IOException ex) {
 463  0
                     LOGGER.trace("", ex);
 464  0
                 }
 465  
             }
 466  
         }
 467  0
     }
 468  
 
 469  
     /**
 470  
      * Attempts to determine if a zip file is actually a JAR file.
 471  
      *
 472  
      * @param dependency the dependency to check
 473  
      * @return true if the dependency appears to be a JAR file; otherwise false
 474  
      */
 475  
     private boolean isZipFileActuallyJarFile(Dependency dependency) {
 476  0
         boolean isJar = false;
 477  0
         ZipFile zip = null;
 478  
         try {
 479  0
             zip = new ZipFile(dependency.getActualFilePath());
 480  0
             if (zip.getEntry("META-INF/MANIFEST.MF") != null
 481  
                     || zip.getEntry("META-INF/maven") != null) {
 482  0
                 final Enumeration<ZipArchiveEntry> entries = zip.getEntries();
 483  0
                 while (entries.hasMoreElements()) {
 484  0
                     final ZipArchiveEntry entry = entries.nextElement();
 485  0
                     if (!entry.isDirectory()) {
 486  0
                         final String name = entry.getName().toLowerCase();
 487  0
                         if (name.endsWith(".class")) {
 488  0
                             isJar = true;
 489  0
                             break;
 490  
                         }
 491  
                     }
 492  0
                 }
 493  
             }
 494  0
         } catch (IOException ex) {
 495  0
             LOGGER.debug("Unable to unzip zip file '{}'", dependency.getFilePath(), ex);
 496  
         } finally {
 497  0
             ZipFile.closeQuietly(zip);
 498  0
         }
 499  
 
 500  0
         return isJar;
 501  
     }
 502  
 }