Coverage Report - org.owasp.dependencycheck.analyzer.PythonPackageAnalyzer
 
Classes in this File Line Coverage Branch Coverage Complexity
PythonPackageAnalyzer
90%
64/71
77%
14/18
2.091
 
 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) 2015 Institute for Defense Analyses. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck.analyzer;
 19  
 
 20  
 import java.io.File;
 21  
 import java.io.FileFilter;
 22  
 import java.io.IOException;
 23  
 import java.net.MalformedURLException;
 24  
 import java.util.ArrayList;
 25  
 import java.util.Collections;
 26  
 import java.util.List;
 27  
 import java.util.Set;
 28  
 import java.util.logging.Logger;
 29  
 import java.util.regex.Matcher;
 30  
 import java.util.regex.Pattern;
 31  
 
 32  
 import org.apache.commons.io.FileUtils;
 33  
 import org.apache.commons.io.filefilter.NameFileFilter;
 34  
 import org.apache.commons.io.filefilter.SuffixFileFilter;
 35  
 import org.owasp.dependencycheck.Engine;
 36  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 37  
 import org.owasp.dependencycheck.dependency.Confidence;
 38  
 import org.owasp.dependencycheck.dependency.Dependency;
 39  
 import org.owasp.dependencycheck.dependency.EvidenceCollection;
 40  
 import org.owasp.dependencycheck.utils.Settings;
 41  
 import org.owasp.dependencycheck.utils.UrlStringUtils;
 42  
 
 43  
 /**
 44  
  * Used to analyze a Python package, and collect information that can be used to determine the associated CPE.
 45  
  *
 46  
  * @author Dale Visser <dvisser@ida.org>
 47  
  */
 48  6
 public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
 49  
 
 50  
     /**
 51  
      * Used when compiling file scanning regex patterns.
 52  
      */
 53  
     private static final int REGEX_OPTIONS = Pattern.DOTALL
 54  
             | Pattern.CASE_INSENSITIVE;
 55  
 
 56  
     /**
 57  
      * The logger.
 58  
      */
 59  1
     private static final Logger LOGGER = Logger
 60  
             .getLogger(PythonDistributionAnalyzer.class.getName());
 61  
 
 62  
     /**
 63  
      * Filename extensions for files to be analyzed.
 64  
      */
 65  1
     private static final Set<String> EXTENSIONS = Collections
 66  
             .unmodifiableSet(Collections.singleton("py"));
 67  
 
 68  
     /**
 69  
      * Pattern for matching the module docstring in a source file.
 70  
      */
 71  1
     private static final Pattern MODULE_DOCSTRING = Pattern.compile(
 72  
             "^(['\\\"]{3})(.*?)\\1", REGEX_OPTIONS);
 73  
 
 74  
     /**
 75  
      * Matches assignments to version variables in Python source code.
 76  
      */
 77  1
     private static final Pattern VERSION_PATTERN = Pattern.compile(
 78  
             "\\b(__)?version(__)? *= *(['\"]+)(\\d+\\.\\d+.*?)\\3",
 79  
             REGEX_OPTIONS);
 80  
 
 81  
     /**
 82  
      * Matches assignments to title variables in Python source code.
 83  
      */
 84  1
     private static final Pattern TITLE_PATTERN = compileAssignPattern("title");
 85  
 
 86  
     /**
 87  
      * Matches assignments to summary variables in Python source code.
 88  
      */
 89  1
     private static final Pattern SUMMARY_PATTERN = compileAssignPattern("summary");
 90  
 
 91  
     /**
 92  
      * Matches assignments to URL/URL variables in Python source code.
 93  
      */
 94  1
     private static final Pattern URI_PATTERN = compileAssignPattern("ur[il]");
 95  
 
 96  
     /**
 97  
      * Matches assignments to home page variables in Python source code.
 98  
      */
 99  1
     private static final Pattern HOMEPAGE_PATTERN = compileAssignPattern("home_?page");
 100  
 
 101  
     /**
 102  
      * Matches assignments to author variables in Python source code.
 103  
      */
 104  1
     private static final Pattern AUTHOR_PATTERN = compileAssignPattern("author");
 105  
 
 106  
     /**
 107  
      * Filter that detects files named "__init__.py".
 108  
      */
 109  1
     private static final FileFilter INIT_PY_FILTER = new NameFileFilter("__init__.py");
 110  
 
 111  
     /**
 112  
      * The file filter for python files.
 113  
      */
 114  1
     private static final FileFilter PY_FILTER = new SuffixFileFilter(".py");
 115  
 
 116  
     /**
 117  
      * Returns the name of the Python Package Analyzer.
 118  
      *
 119  
      * @return the name of the analyzer
 120  
      */
 121  
     @Override
 122  
     public String getName() {
 123  5
         return "Python Package Analyzer";
 124  
     }
 125  
 
 126  
     /**
 127  
      * Tell that we are used for information collection.
 128  
      *
 129  
      * @return INFORMATION_COLLECTION
 130  
      */
 131  
     @Override
 132  
     public AnalysisPhase getAnalysisPhase() {
 133  1
         return AnalysisPhase.INFORMATION_COLLECTION;
 134  
     }
 135  
 
 136  
     /**
 137  
      * Returns the set of supported file extensions.
 138  
      *
 139  
      * @return the set of supported file extensions
 140  
      */
 141  
     @Override
 142  
     protected Set<String> getSupportedExtensions() {
 143  850
         return EXTENSIONS;
 144  
     }
 145  
 
 146  
     /**
 147  
      * No-op initializer implementation.
 148  
      *
 149  
      * @throws Exception never thrown
 150  
      */
 151  
     @Override
 152  
     protected void initializeFileTypeAnalyzer() throws Exception {
 153  
         // Nothing to do here.
 154  4
     }
 155  
 
 156  
     /**
 157  
      * Utility function to create a regex pattern matcher.
 158  
      *
 159  
      * @param name the value to use when constructing the assignment pattern
 160  
      * @return the compiled Pattern
 161  
      */
 162  
     private static Pattern compileAssignPattern(String name) {
 163  5
         return Pattern.compile(
 164  
                 String.format("\\b(__)?%s(__)?\\b *= *(['\"]+)(.*?)\\3", name),
 165  
                 REGEX_OPTIONS);
 166  
     }
 167  
 
 168  
     /**
 169  
      * Analyzes python packages and adds evidence to the dependency.
 170  
      *
 171  
      * @param dependency the dependency being analyzed
 172  
      * @param engine the engine being used to perform the scan
 173  
      * @throws AnalysisException thrown if there is an unrecoverable error analyzing the dependency
 174  
      */
 175  
     @Override
 176  
     protected void analyzeFileType(Dependency dependency, Engine engine)
 177  
             throws AnalysisException {
 178  1
         final File file = dependency.getActualFile();
 179  1
         final File parent = file.getParentFile();
 180  1
         final String parentName = parent.getName();
 181  1
         boolean found = false;
 182  1
         if (INIT_PY_FILTER.accept(file)) {
 183  4
             for (final File sourcefile : parent.listFiles(PY_FILTER)) {
 184  3
                 found |= analyzeFileContents(dependency, sourcefile);
 185  
             }
 186  
         }
 187  1
         if (found) {
 188  1
             dependency.setDisplayFileName(parentName + "/__init__.py");
 189  1
             dependency.getProductEvidence().addEvidence(file.getName(),
 190  
                     "PackageName", parentName, Confidence.MEDIUM);
 191  
         } else {
 192  
             // copy, alter and set in case some other thread is iterating over
 193  0
             final List<Dependency> deps = new ArrayList<Dependency>(
 194  
                     engine.getDependencies());
 195  0
             deps.remove(dependency);
 196  0
             engine.setDependencies(deps);
 197  
         }
 198  1
     }
 199  
 
 200  
     /**
 201  
      * This should gather information from leading docstrings, file comments, and assignments to __version__, __title__,
 202  
      * __summary__, __uri__, __url__, __home*page__, __author__, and their all caps equivalents.
 203  
      *
 204  
      * @param dependency the dependency being analyzed
 205  
      * @param file the file name to analyze
 206  
      * @return whether evidence was found
 207  
      * @throws AnalysisException thrown if there is an unrecoverable error
 208  
      */
 209  
     private boolean analyzeFileContents(Dependency dependency, File file)
 210  
             throws AnalysisException {
 211  3
         String contents = "";
 212  
         try {
 213  3
             contents = FileUtils.readFileToString(file).trim();
 214  0
         } catch (IOException e) {
 215  0
             throw new AnalysisException(
 216  
                     "Problem occured while reading dependency file.", e);
 217  3
         }
 218  3
         boolean found = false;
 219  3
         if (!contents.isEmpty()) {
 220  3
             final String source = file.getName();
 221  3
             found = gatherEvidence(VERSION_PATTERN, contents, source,
 222  
                     dependency.getVersionEvidence(), "SourceVersion",
 223  
                     Confidence.MEDIUM);
 224  3
             found |= addSummaryInfo(dependency, SUMMARY_PATTERN, 4, contents,
 225  
                     source, "summary");
 226  3
             if (INIT_PY_FILTER.accept(file)) {
 227  1
                 found |= addSummaryInfo(dependency, MODULE_DOCSTRING, 2,
 228  
                         contents, source, "docstring");
 229  
             }
 230  3
             found |= gatherEvidence(TITLE_PATTERN, contents, source,
 231  
                     dependency.getProductEvidence(), "SourceTitle",
 232  
                     Confidence.LOW);
 233  3
             final EvidenceCollection vendorEvidence = dependency
 234  
                     .getVendorEvidence();
 235  3
             found |= gatherEvidence(AUTHOR_PATTERN, contents, source,
 236  
                     vendorEvidence, "SourceAuthor", Confidence.MEDIUM);
 237  
             try {
 238  3
                 found |= gatherHomePageEvidence(URI_PATTERN, vendorEvidence,
 239  
                         source, "URL", contents);
 240  3
                 found |= gatherHomePageEvidence(HOMEPAGE_PATTERN,
 241  
                         vendorEvidence, source, "HomePage", contents);
 242  0
             } catch (MalformedURLException e) {
 243  0
                 LOGGER.warning(e.getMessage());
 244  3
             }
 245  
         }
 246  3
         return found;
 247  
     }
 248  
 
 249  
     /**
 250  
      * Adds summary information to the dependency
 251  
      *
 252  
      * @param dependency the dependency being analyzed
 253  
      * @param pattern the pattern used to perform analysis
 254  
      * @param group the group from the pattern that indicates the data to use
 255  
      * @param contents the data being analyzed
 256  
      * @param source the source name to use when recording the evidence
 257  
      * @param key the key name to use when recording the evidence
 258  
      * @return true if evidence was collected; otherwise false
 259  
      */
 260  
     private boolean addSummaryInfo(Dependency dependency, Pattern pattern,
 261  
             int group, String contents, String source, String key) {
 262  4
         final Matcher matcher = pattern.matcher(contents);
 263  4
         final boolean found = matcher.find();
 264  4
         if (found) {
 265  1
             JarAnalyzer.addDescription(dependency, matcher.group(group),
 266  
                     source, key);
 267  
         }
 268  4
         return found;
 269  
     }
 270  
 
 271  
     /**
 272  
      * Collects evidence from the home page URL.
 273  
      *
 274  
      * @param pattern the pattern to match
 275  
      * @param evidence the evidence collection to add the evidence to
 276  
      * @param source the source of the evidence
 277  
      * @param name the name of the evidence
 278  
      * @param contents the home page URL
 279  
      * @return true if evidence was collected; otherwise false
 280  
      * @throws MalformedURLException thrown if the URL is malformed
 281  
      */
 282  
     private boolean gatherHomePageEvidence(Pattern pattern,
 283  
             EvidenceCollection evidence, String source, String name,
 284  
             String contents) throws MalformedURLException {
 285  6
         final Matcher matcher = pattern.matcher(contents);
 286  6
         boolean found = false;
 287  6
         if (matcher.find()) {
 288  1
             final String url = matcher.group(4);
 289  1
             if (UrlStringUtils.isUrl(url)) {
 290  1
                 found = true;
 291  1
                 evidence.addEvidence(source, name, url, Confidence.MEDIUM);
 292  
             }
 293  
         }
 294  6
         return found;
 295  
     }
 296  
 
 297  
     /**
 298  
      * Gather evidence from a Python source file usin the given string assignment regex pattern.
 299  
      *
 300  
      * @param pattern to scan contents with
 301  
      * @param contents of Python source file
 302  
      * @param source for storing evidence
 303  
      * @param evidence to store evidence in
 304  
      * @param name of evidence
 305  
      * @param confidence in evidence
 306  
      * @return whether evidence was found
 307  
      */
 308  
     private boolean gatherEvidence(Pattern pattern, String contents,
 309  
             String source, EvidenceCollection evidence, String name,
 310  
             Confidence confidence) {
 311  9
         final Matcher matcher = pattern.matcher(contents);
 312  9
         final boolean found = matcher.find();
 313  9
         if (found) {
 314  3
             evidence.addEvidence(source, name, matcher.group(4), confidence);
 315  
         }
 316  9
         return found;
 317  
     }
 318  
 
 319  
     @Override
 320  
     protected String getAnalyzerEnabledSettingKey() {
 321  6
         return Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED;
 322  
     }
 323  
 }