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