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