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