diff --git a/README.md b/README.md index 5f09b24ab..fab943828 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Current Releases ------------- ### Jenkins Plugin -For instructions on the use of the Jenkins plugin please see the [Jenkins dependency-check page](http://wiki.jenkins-ci.org/x/CwDgAQ). +For instructions on the use of the Jenkins plugin please see the [OWASP Dependency-Check Plugin page](https://wiki.jenkins-ci.org/display/JENKINS/OWASP+Dependency-Check+Plugin). ### Command Line @@ -37,7 +37,7 @@ $ dependency-check --app Testing --out . --scan [path to jar files to be scanned ### Maven Plugin -More detailed instructions can be found on the [dependency-check-maven github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-maven/usage.html). +More detailed instructions can be found on the [dependency-check-maven github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-maven). The plugin can be configured using the following: ```xml @@ -66,7 +66,7 @@ The plugin can be configured using the following: ### Ant Task -For instructions on the use of the Ant Task, please see the [dependency-check-ant github page](http://jeremylong.github.io/DependencyCheck/dependency-check-ant/installation.html). +For instructions on the use of the Ant Task, please see the [dependency-check-ant github page](http://jeremylong.github.io/DependencyCheck/dependency-check-ant). Development Usage ------------- diff --git a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java index 5d33a9b66..4a1d1084a 100644 --- a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java +++ b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java @@ -326,6 +326,7 @@ public class App { Settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, !nuspecDisabled); Settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, !assemblyDisabled); Settings.setBoolean(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, !cli.isOpenSSLDisabled()); + Settings.setBoolean(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, !cli.isNodeJsDisabled()); Settings.setBoolean(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, !cli.isRubyGemspecDisabled()); Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, !centralDisabled); diff --git a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java index dbd48215f..2cd4cb00b 100644 --- a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java +++ b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/CliParser.java @@ -427,6 +427,8 @@ public final class CliParser { .addOption(disableNuspecAnalyzer) .addOption(disableCentralAnalyzer) .addOption(disableNexusAnalyzer) + .addOption(OptionBuilder.withLongOpt(ARGUMENT.DISABLE_NODE_JS) + .withDescription("Disable the Node.js Package Analyzer.").create()) .addOption(nexusUrl) .addOption(nexusUsesProxy) .addOption(additionalZipExtensions) @@ -595,6 +597,15 @@ public final class CliParser { return (line != null) && line.hasOption(ARGUMENT.DISABLE_OPENSSL); } + /** + * Returns true if the disableNodeJS command line argument was specified. + * + * @return true if the disableNodeJS command line argument was specified; otherwise false + */ + public boolean isNodeJsDisabled() { + return (line != null) && line.hasOption(ARGUMENT.DISABLE_NODE_JS); + } + /** * Returns true if the disableCentral command line argument was specified. * @@ -1134,6 +1145,10 @@ public final class CliParser { * Disables the OpenSSL Analyzer. */ public static final String DISABLE_OPENSSL = "disableOpenSSL"; + /** + * Disables the Node.js Package Analyzer. + */ + public static final String DISABLE_NODE_JS = "disableNodeJS"; /** * The URL of the nexus server. */ diff --git a/dependency-check-cli/src/site/markdown/arguments.md b/dependency-check-cli/src/site/markdown/arguments.md index cd7160a62..ededf1f2d 100644 --- a/dependency-check-cli/src/site/markdown/arguments.md +++ b/dependency-check-cli/src/site/markdown/arguments.md @@ -13,7 +13,7 @@ Short | Argument Name   | Parameter | Description | Requir \-f | \-\-format | \ | The output format to write to (XML, HTML, VULN, ALL). The default is HTML. | Required \-l | \-\-log | \ | The file path to write verbose logging information. | Optional \-n | \-\-noupdate | | Disables the automatic updating of the CPE data. | Optional - | \-\-suppression | \ | The file path to the suppression XML file; used to suppress [false positives](../suppression.html). | Optional + | \-\-suppression | \ | The file path to the suppression XML file; used to suppress [false positives](../general/suppression.html). | Optional \-h | \-\-help | | Print the help message. | Optional | \-\-advancedHelp | | Print the advanced help message. | Optional \-v | \-\-version | | Print the version information. | Optional @@ -30,7 +30,8 @@ Short | Argument Name        | Paramete | \-\-updateonly | | If set only the update phase of dependency-check will be executed; no scan will be executed and no report will be generated. |   | \-\-disablePyDist | | Sets whether the Python Distribution Analyzer will be used. | false | \-\-disablePyPkg | | Sets whether the Python Package Analyzer will be used. | false - | \-\-disableRubygems | | Sets whether the Ruby Gemspec Analyzer will be used. | false + | \-\-disableNodeJS | | Sets whehter the Node.js Package Analyzer will be used. | false + | \-\-disableRubygems | | Sets whether the Ruby Gemspec Analyzer will be used. | false | \-\-disableAutoconf | | Sets whether the Autoconf Analyzer will be used. | false | \-\-disableOpenSSL | | Sets whether the OpenSSL Analyzer will be used. | false | \-\-disableCmake | | Sets whether the Cmake Analyzer will be used. | false diff --git a/dependency-check-core/pom.xml b/dependency-check-core/pom.xml index 4276d35e9..f77e3b9b4 100644 --- a/dependency-check-core/pom.xml +++ b/dependency-check-core/pom.xml @@ -439,6 +439,10 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved. com.h2database h2 + + org.glassfish + javax.json + org.jsoup jsoup diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java index d25ad57de..291c011bc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzer.java @@ -173,10 +173,10 @@ public class AutoconfAnalyzer extends AbstractFileTypeAnalyzer { } } else { // copy, alter and set in case some other thread is iterating over - final List deps = new ArrayList( + final List dependencies = new ArrayList( engine.getDependencies()); - deps.remove(dependency); - engine.setDependencies(deps); + dependencies.remove(dependency); + engine.setDependencies(dependencies); } } @@ -225,7 +225,7 @@ public class AutoconfAnalyzer extends AbstractFileTypeAnalyzer { contents = FileUtils.readFileToString(actualFile).trim(); } catch (IOException e) { throw new AnalysisException( - "Problem occured while reading dependency file.", e); + "Problem occurred while reading dependency file.", e); } return contents; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java new file mode 100644 index 000000000..d489d97c0 --- /dev/null +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java @@ -0,0 +1,170 @@ +/* + * This file is part of dependency-check-core. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (c) 2015 Institute for Defense Analyses. All Rights Reserved. + */ +package org.owasp.dependencycheck.analyzer; + +import org.apache.commons.io.FileUtils; +import org.owasp.dependencycheck.Engine; +import org.owasp.dependencycheck.analyzer.exception.AnalysisException; +import org.owasp.dependencycheck.dependency.Confidence; +import org.owasp.dependencycheck.dependency.Dependency; +import org.owasp.dependencycheck.dependency.EvidenceCollection; +import org.owasp.dependencycheck.utils.FileFilterBuilder; +import org.owasp.dependencycheck.utils.Settings; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.json.*; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; + +/** + * Used to analyze Node Package Manager (npm) package.json files, and collect information that can be used to determine + * the associated CPE. + * + * @author Dale Visser + */ +public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer { + + /** + * The logger. + */ + private static final Logger LOGGER = LoggerFactory.getLogger(NodePackageAnalyzer.class); + + /** + * The name of the analyzer. + */ + private static final String ANALYZER_NAME = "Node.js Package Analyzer"; + + /** + * The phase that this analyzer is intended to run in. + */ + private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION; + + public static final String PACKAGE_JSON = "package.json"; + /** + * Filter that detects files named "package.json". + */ + private static final FileFilter PACKAGE_JSON_FILTER = + FileFilterBuilder.newInstance().addFilenames(PACKAGE_JSON).build(); + + /** + * Returns the FileFilter + * + * @return the FileFilter + */ + @Override + protected FileFilter getFileFilter() { + return PACKAGE_JSON_FILTER; + } + + @Override + protected void initializeFileTypeAnalyzer() throws Exception { + // NO-OP + } + + /** + * Returns the name of the analyzer. + * + * @return the name of the analyzer. + */ + @Override + public String getName() { + return ANALYZER_NAME; + } + + /** + * Returns the phase that the analyzer is intended to run in. + * + * @return the phase that the analyzer is intended to run in. + */ + @Override + public AnalysisPhase getAnalysisPhase() { + return ANALYSIS_PHASE; + } + + /** + * Returns the key used in the properties file to reference the analyzer's enabled property. + * + * @return the analyzer's enabled property setting key + */ + @Override + protected String getAnalyzerEnabledSettingKey() { + return Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED; + } + + @Override + protected void analyzeFileType(Dependency dependency, Engine engine) + throws AnalysisException { + final File file = dependency.getActualFile(); + JsonReader jsonReader; + try { + jsonReader = Json.createReader(FileUtils.openInputStream(file)); + } catch (IOException e) { + throw new AnalysisException( + "Problem occurred while reading dependency file.", e); + } + try { + JsonObject json = jsonReader.readObject(); + final EvidenceCollection productEvidence = dependency.getProductEvidence(); + final EvidenceCollection vendorEvidence = dependency.getVendorEvidence(); + if (json.containsKey("name")) { + Object value = json.get("name"); + if (value instanceof JsonString) { + String valueString = ((JsonString) value).getString(); + productEvidence.addEvidence(PACKAGE_JSON, "name", valueString, Confidence.HIGHEST); + vendorEvidence.addEvidence(PACKAGE_JSON, "name_project", String.format("%s_project", valueString), Confidence.LOW); + } else { + LOGGER.warn("JSON value not string as expected: %s", value); + } + } + addToEvidence(json, productEvidence, "description"); + addToEvidence(json, vendorEvidence, "author"); + addToEvidence(json, dependency.getVersionEvidence(), "version"); + dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName())); + } catch (JsonException e) { + LOGGER.warn("Failed to parse package.json file.", e); + } finally { + jsonReader.close(); + } + } + + private void addToEvidence(JsonObject json, EvidenceCollection collection, String key) { + if (json.containsKey(key)) { + Object value = json.get(key); + if (value instanceof JsonString) { + collection.addEvidence(PACKAGE_JSON, key, ((JsonString) value).getString(), Confidence.HIGHEST); + } else if (value instanceof JsonObject) { + final JsonObject jsonObject = (JsonObject) value; + for (String property : jsonObject.keySet()) { + final Object subValue = jsonObject.get(property); + if (subValue instanceof JsonString) { + collection.addEvidence(PACKAGE_JSON, + String.format("%s.%s", key, property), + ((JsonString) subValue).getString(), + Confidence.HIGHEST); + } else { + LOGGER.warn("JSON sub-value not string as expected: %s"); + } + } + } else { + LOGGER.warn("JSON value not string or JSON object as expected: %s", value); + } + } + } +} diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java index ff2064d91..c89aaed6f 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java @@ -53,7 +53,7 @@ import org.owasp.dependencycheck.utils.UrlStringUtils; public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { /** - * Name of egg metatdata files to analyze. + * Name of egg metadata files to analyze. */ private static final String PKG_INFO = "PKG-INFO"; @@ -269,10 +269,8 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { * * @param dependency the dependency being analyzed * @param file a reference to the manifest/properties file - * @throws AnalysisException thrown when there is an error */ - private static void collectWheelMetadata(Dependency dependency, File file) - throws AnalysisException { + private static void collectWheelMetadata(Dependency dependency, File file) { final InternetHeaders headers = getManifestProperties(file); addPropertyToEvidence(headers, dependency.getVersionEvidence(), "Version", Confidence.HIGHEST); @@ -352,7 +350,7 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Retrieves the next temporary destingation directory for extracting an archive. + * Retrieves the next temporary destination directory for extracting an archive. * * @return a directory * @throws AnalysisException thrown if unable to create temporary directory diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java index 8f909614b..f5d27e981 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzer.java @@ -28,13 +28,10 @@ import org.owasp.dependencycheck.dependency.EvidenceCollection; import org.owasp.dependencycheck.utils.FileFilterBuilder; import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.UrlStringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileFilter; import java.io.IOException; -import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; @@ -53,12 +50,6 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { private static final int REGEX_OPTIONS = Pattern.DOTALL | Pattern.CASE_INSENSITIVE; - /** - * The logger. - */ - private static final Logger LOGGER = LoggerFactory - .getLogger(PythonPackageAnalyzer.class); - /** * Filename extensions for files to be analyzed. */ @@ -173,7 +164,7 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { * Analyzes python packages and adds evidence to the dependency. * * @param dependency the dependency being analyzed - * @param engine the engine being used to perform the scan + * @param engine the engine being used to perform the scan * @throws AnalysisException thrown if there is an unrecoverable error analyzing the dependency */ @Override @@ -184,8 +175,8 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { final String parentName = parent.getName(); boolean found = false; if (INIT_PY_FILTER.accept(file)) { - for (final File sourcefile : parent.listFiles(PY_FILTER)) { - found |= analyzeFileContents(dependency, sourcefile); + for (final File sourceFile : parent.listFiles(PY_FILTER)) { + found |= analyzeFileContents(dependency, sourceFile); } } if (found) { @@ -194,10 +185,10 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { "PackageName", parentName, Confidence.MEDIUM); } else { // copy, alter and set in case some other thread is iterating over - final List deps = new ArrayList( + final List dependencies = new ArrayList( engine.getDependencies()); - deps.remove(dependency); - engine.setDependencies(deps); + dependencies.remove(dependency); + engine.setDependencies(dependencies); } } @@ -206,7 +197,7 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { * __summary__, __uri__, __url__, __home*page__, __author__, and their all caps equivalents. * * @param dependency the dependency being analyzed - * @param file the file name to analyze + * @param file the file name to analyze * @return whether evidence was found * @throws AnalysisException thrown if there is an unrecoverable error */ @@ -238,14 +229,10 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { .getVendorEvidence(); found |= gatherEvidence(AUTHOR_PATTERN, contents, source, vendorEvidence, "SourceAuthor", Confidence.MEDIUM); - try { - found |= gatherHomePageEvidence(URI_PATTERN, vendorEvidence, - source, "URL", contents); - found |= gatherHomePageEvidence(HOMEPAGE_PATTERN, - vendorEvidence, source, "HomePage", contents); - } catch (MalformedURLException e) { - LOGGER.warn(e.getMessage()); - } + found |= gatherHomePageEvidence(URI_PATTERN, vendorEvidence, + source, "URL", contents); + found |= gatherHomePageEvidence(HOMEPAGE_PATTERN, + vendorEvidence, source, "HomePage", contents); } return found; } @@ -254,15 +241,15 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { * Adds summary information to the dependency * * @param dependency the dependency being analyzed - * @param pattern the pattern used to perform analysis - * @param group the group from the pattern that indicates the data to use - * @param contents the data being analyzed - * @param source the source name to use when recording the evidence - * @param key the key name to use when recording the evidence + * @param pattern the pattern used to perform analysis + * @param group the group from the pattern that indicates the data to use + * @param contents the data being analyzed + * @param source the source name to use when recording the evidence + * @param key the key name to use when recording the evidence * @return true if evidence was collected; otherwise false */ private boolean addSummaryInfo(Dependency dependency, Pattern pattern, - int group, String contents, String source, String key) { + int group, String contents, String source, String key) { final Matcher matcher = pattern.matcher(contents); final boolean found = matcher.find(); if (found) { @@ -275,17 +262,16 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { /** * Collects evidence from the home page URL. * - * @param pattern the pattern to match + * @param pattern the pattern to match * @param evidence the evidence collection to add the evidence to - * @param source the source of the evidence - * @param name the name of the evidence + * @param source the source of the evidence + * @param name the name of the evidence * @param contents the home page URL * @return true if evidence was collected; otherwise false - * @throws MalformedURLException thrown if the URL is malformed */ private boolean gatherHomePageEvidence(Pattern pattern, - EvidenceCollection evidence, String source, String name, - String contents) throws MalformedURLException { + EvidenceCollection evidence, String source, String name, + String contents) { final Matcher matcher = pattern.matcher(contents); boolean found = false; if (matcher.find()) { @@ -299,19 +285,19 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer { } /** - * Gather evidence from a Python source file usin the given string assignment regex pattern. + * Gather evidence from a Python source file using the given string assignment regex pattern. * - * @param pattern to scan contents with - * @param contents of Python source file - * @param source for storing evidence - * @param evidence to store evidence in - * @param name of evidence + * @param pattern to scan contents with + * @param contents of Python source file + * @param source for storing evidence + * @param evidence to store evidence in + * @param name of evidence * @param confidence in evidence * @return whether evidence was found */ private boolean gatherEvidence(Pattern pattern, String contents, - String source, EvidenceCollection evidence, String name, - Confidence confidence) { + String source, EvidenceCollection evidence, String name, + Confidence confidence) { final Matcher matcher = pattern.matcher(contents); final boolean found = matcher.find(); if (found) { diff --git a/dependency-check-core/src/main/resources/META-INF/services/org.owasp.dependencycheck.analyzer.Analyzer b/dependency-check-core/src/main/resources/META-INF/services/org.owasp.dependencycheck.analyzer.Analyzer index a4d0f78c8..760ecfa14 100644 --- a/dependency-check-core/src/main/resources/META-INF/services/org.owasp.dependencycheck.analyzer.Analyzer +++ b/dependency-check-core/src/main/resources/META-INF/services/org.owasp.dependencycheck.analyzer.Analyzer @@ -17,5 +17,6 @@ org.owasp.dependencycheck.analyzer.PythonPackageAnalyzer org.owasp.dependencycheck.analyzer.AutoconfAnalyzer org.owasp.dependencycheck.analyzer.OpenSSLAnalyzer org.owasp.dependencycheck.analyzer.CMakeAnalyzer +org.owasp.dependencycheck.analyzer.NodePackageAnalyzer org.owasp.dependencycheck.analyzer.RubyGemspecAnalyzer -org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer \ No newline at end of file +org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer diff --git a/dependency-check-core/src/main/resources/dependencycheck-base-suppression.xml b/dependency-check-core/src/main/resources/dependencycheck-base-suppression.xml index 40ae34dc0..98ad6a000 100644 --- a/dependency-check-core/src/main/resources/dependencycheck-base-suppression.xml +++ b/dependency-check-core/src/main/resources/dependencycheck-base-suppression.xml @@ -17,6 +17,7 @@ cpe:/a:mod_security:mod_security cpe:/a:springsource:spring_framework cpe:/a:vmware:springsource_spring_framework + cpe:/a:pivotal:spring_framework + */ +public class NodePackageAnalyzerTest extends BaseTest { + + /** + * The analyzer to test. + */ + NodePackageAnalyzer analyzer; + + /** + * Correctly setup the analyzer for testing. + * + * @throws Exception thrown if there is a problem + */ + @Before + public void setUp() throws Exception { + analyzer = new NodePackageAnalyzer(); + analyzer.setFilesMatched(true); + analyzer.initialize(); + } + + /** + * Cleanup the analyzer's temp files, etc. + * + * @throws Exception thrown if there is a problem + */ + @After + public void tearDown() throws Exception { + analyzer.close(); + analyzer = null; + } + + /** + * Test of getName method, of class PythonDistributionAnalyzer. + */ + @Test + public void testGetName() { + assertThat(analyzer.getName(), is("Node.js Package Analyzer")); + } + + /** + * Test of supportsExtension method, of class PythonDistributionAnalyzer. + */ + @Test + public void testSupportsFiles() { + assertThat(analyzer.accept(new File("package.json")), is(true)); + } + + /** + * Test of inspect method, of class PythonDistributionAnalyzer. + * + * @throws AnalysisException is thrown when an exception occurs. + */ + @Test + public void testAnalyzePackageJson() throws AnalysisException { + final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, + "nodejs/node_modules/dns-sync/package.json")); + analyzer.analyze(result, null); + final String vendorString = result.getVendorEvidence().toString(); + assertThat(vendorString, containsString("Sanjeev Koranga")); + assertThat(vendorString, containsString("dns-sync_project")); + assertThat(result.getProductEvidence().toString(), containsString("dns-sync")); + assertThat(result.getVersionEvidence().toString(), containsString("0.1.0")); + } +} diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java index c5fcc289e..f0ee9f7ac 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzerTest.java @@ -39,10 +39,10 @@ public class OpenSSLAnalyzerTest extends BaseTest { /** * The package analyzer to test. */ - OpenSSLAnalyzer analyzer; + private OpenSSLAnalyzer analyzer; /** - * Setup the PtyhonPackageAnalyzer. + * Setup the {@link OpenSSLAnalyzer}. * * @throws Exception if there is a problem */ diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java index ded6cb20b..954d02274 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzerTest.java @@ -40,7 +40,7 @@ public class PythonDistributionAnalyzerTest extends BaseTest { /** * The analyzer to test. */ - PythonDistributionAnalyzer analyzer; + private PythonDistributionAnalyzer analyzer; /** * Correctly setup the analyzer for testing. diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java index b132c2ec8..82bb3af09 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/PythonPackageAnalyzerTest.java @@ -40,10 +40,10 @@ public class PythonPackageAnalyzerTest extends BaseTest { /** * The package analyzer to test. */ - PythonPackageAnalyzer analyzer; + private PythonPackageAnalyzer analyzer; /** - * Setup the PtyhonPackageAnalyzer. + * Setup the {@link PythonPackageAnalyzer}. * * @throws Exception if there is a problem */ @@ -85,14 +85,9 @@ public class PythonPackageAnalyzerTest extends BaseTest { @Test public void testAnalyzeSourceMetadata() throws AnalysisException { - eggtestAssertions(this, - "python/eggtest/__init__.py"); - } - - public void eggtestAssertions(Object context, final String resource) throws AnalysisException { boolean found = false; final Dependency result = new Dependency(BaseTest.getResourceAsFile( - context, resource)); + this, "python/eggtest/__init__.py")); analyzer.analyze(result, null); assertTrue("Expected vendor evidence to contain \"example\".", result .getVendorEvidence().toString().contains("example")); @@ -104,4 +99,5 @@ public class PythonPackageAnalyzerTest extends BaseTest { } assertTrue("Version 0.0.1 not found in EggTest dependency.", found); } + } diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.jshintrc b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.jshintrc new file mode 100644 index 000000000..bfabd7ff2 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.jshintrc @@ -0,0 +1,155 @@ +{ + // Whether the scan should stop on first error. + "passfail": false, + // Maximum errors before stopping. + "maxerr": 100, + + + // Predefined globals + + // Whether the standard browser globals should be predefined. + "browser": false, + // Whether the Node.js environment globals should be predefined. + "node": true, + // Whether the Rhino environment globals should be predefined. + "rhino": false, + // Whether CouchDB globals should be predefined. + "couch": false, + // Whether the Windows Scripting Host environment globals should be predefined. + "wsh": false, + + // Whether jQuery globals should be predefined. + "jquery": false, + // Whether Prototype and Scriptaculous globals should be predefined. + "prototypejs": false, + // Whether MooTools globals should be predefined. + "mootools": false, + // Whether Dojo Toolkit globals should be predefined. + "dojo": false, + + // Custom predefined globals. + "predef": [ + "describe", "it", "before", "after" + ], + + // Development + + // Whether debugger statements should be allowed. + "debug": false, + // Whether logging globals should be predefined (console, alert, etc.). + "devel": false, + + + // ECMAScript 5 + + // Whether the "use strict"; pragma should be required. + "strict": true, + // Whether global "use strict"; should be allowed (also enables strict). + "globalstrict": true, + + + // The Good Parts + + // Whether automatic semicolon insertion should be allowed. + "asi": false, + // Whether line breaks should not be checked, e.g. `return [\n] x`. + "laxbreak": false, + // Whether bitwise operators (&, |, ^, etc.) should be forbidden. + "bitwise": false, + // Whether assignments inside `if`, `for` and `while` should be allowed. Usually + // conditions and loops are for comparison, not assignments. + "boss": true, + // Whether curly braces around all blocks should be required. + "curly": true, + // Whether `===` and `!==` should be required (instead of `==` and `!=`). + "eqeqeq": true, + // Whether `== null` comparisons should be allowed, even if `eqeqeq` is `true`. + "eqnull": false, + // Whether `eval` should be allowed. + "evil": false, + // Whether ExpressionStatement should be allowed as Programs. + "expr": true, + // Whether `for in` loops must filter with `hasOwnPrototype`. + "forin": false, + // Whether immediate invocations must be wrapped in parens, e.g. + // `( function(){}() );`. + "immed": true, + // Whether use before define should be forbidden. + "latedef": false, + // Whether functions should be allowed to be defined within loops. + "loopfunc": false, + // Whether arguments.caller and arguments.callee should be forbidden. + "noarg": false, + // Whether `.` should be forbidden in regexp literals. + "regexp": false, + // Whether unescaped first/last dash (-) inside brackets in regexps should be allowed. + "regexdash": false, + // Whether script-targeted URLs should be allowed. + "scripturl": false, + // Whether variable shadowing should be allowed. + "shadow": false, + // Whether `new function () { ... };` and `new Object;` should be allowed. + "supernew": false, + // Whether variables must be declared before used. + "undef": true, + // Whether `this` inside a non-constructor function should be allowed. + "validthis": false, + // Whether smarttabs should be allowed + // (http://www.emacswiki.org/emacs/SmartTabs). + "smarttabs": true, + // Whether the `__proto__` property should be allowed. + "proto": false, + // Whether one-case switch statements should be allowed. + "onecase": false, + // Whether non-standard (but widely adopted) globals should be predefined. + "nonstandard": false, + // Allow multiline strings. + "multistr": false, + // Whether line breaks should not be checked around commas. + "laxcomma": false, + // Whether semicolons may be ommitted for the trailing statements inside of a + // one-line blocks. + "lastsemic": false, + // Whether the `__iterator__` property should be allowed. + "iterator": false, + // Whether only function scope should be used for scope tests. + "funcscope": false, + // Whether es.next specific syntax should be allowed. + "esnext": false, + + + // Style preferences + + // Whether constructor names must be capitalized. + "newcap": false, + // Whether empty blocks should be forbidden. + "noempty": false, + // Whether using `new` for side-effects should be forbidden. + "nonew": false, + // Whether names should be checked for leading or trailing underscores + // (object._attribute would be forbidden). + "nomen": false, + // Whether only one var statement per function should be allowed. + "onevar": false, + // Whether increment and decrement (`++` and `--`) should be forbidden. + "plusplus": false, + // Whether all forms of subscript notation are allowed. + "sub": false, + // Whether trailing whitespace rules apply. + "trailing": false, + // Specify indentation. + "indent": 4, + // Whether strict whitespace rules apply. + "white": true, + + // Complexity + + // Maximum number of function parameters. + "maxparams": 6, + // Maximum block nesting depth. + "maxdepth": 3, + // Maximum number of statements per function. + "maxstatements": 25, + // Maximum cyclomatic complexity. + "maxcomplexity": 10 +} \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.npmignore b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.npmignore new file mode 100644 index 000000000..a72b52ebe --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.travis.yml b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.travis.yml new file mode 100644 index 000000000..f714fc077 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/.travis.yml @@ -0,0 +1,4 @@ +language: node_js + +node_js: + - "0.10" \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/LICENSE b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/LICENSE new file mode 100644 index 000000000..5dfeaa9cc --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 skoranga + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/Makefile b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/Makefile new file mode 100644 index 000000000..5726f0c2e --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/Makefile @@ -0,0 +1,16 @@ +REPORTER = spec +BASE = . +JSHINT = ./node_modules/.bin/jshint + +all: lint test + +test: + @NODE_ENV=test ./node_modules/.bin/mocha \ + --reporter $(REPORTER) + +lint: + $(JSHINT) index.js --config $(BASE)/.jshintrc && \ + $(JSHINT) ./lib --config $(BASE)/.jshintrc && \ + $(JSHINT) ./test --config $(BASE)/.jshintrc + +.PHONY: test docs \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/README.md b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/README.md new file mode 100644 index 000000000..6c7aba017 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/README.md @@ -0,0 +1,15 @@ +node-dns-sync +============= + +[![Build Status](https://travis-ci.org/skoranga/node-dns-sync.png)](https://travis-ci.org/skoranga/node-dns-sync) + +Sync/Blocking DNS resolve. Main usecase is in node server startup. + +### How to Use +```javascript +var dnsSync = require('dns-sync'); + +console.log(dnsSync.resolve('www.paypal.com')); //should return the IP address +console.log(dnsSync.resolve('www.yahoo.com')); +console.log(dnsSync.resolve('www.non-host.something')); //should return null +``` \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/index.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/index.js new file mode 100644 index 000000000..204a98a0d --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/index.js @@ -0,0 +1 @@ +exports = module.exports = require('./lib/dns-sync'); \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/lib/dns-sync.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/lib/dns-sync.js new file mode 100644 index 000000000..5f63607f4 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/lib/dns-sync.js @@ -0,0 +1,31 @@ +'use strict'; + +var net = require('net'), + util = require('util'), + path = require('path'), + shell = require('shelljs'), + debug = require('debug')('dns-sync'); + +/** + * Resolve hostname to IP address, + * returns null in case of error + */ +module.exports = { + resolve: function resolve(hostname) { + var output, + nodeBinary = process.execPath, + scriptPath = path.join(__dirname, "../scripts/dns-lookup-script"), + response, + cmd = util.format('"%s" "%s" %s', nodeBinary, scriptPath, hostname); + + response = shell.exec(cmd, {silent: true}); + if (response && response.code === 0) { + output = response.output; + if (output && net.isIP(output)) { + return output; + } + } + debug('hostname', "fail to resolve hostname " + hostname); + return null; + } +}; \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/.bin/shjs b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/.bin/shjs new file mode 120000 index 000000000..a0449975b --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/.bin/shjs @@ -0,0 +1 @@ +../shelljs/bin/shjs \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/Readme.md b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/Readme.md new file mode 100644 index 000000000..c5a34e8b8 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/Readme.md @@ -0,0 +1,115 @@ +# debug + + tiny node.js debugging utility modelled after node core's debugging technique. + +## Installation + +``` +$ npm install debug +``` + +## Usage + + With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_ + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". + +## Browser support + + Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + a('doing some work'); +}, 1200); +``` + +## License + +(The MIT License) + +Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/debug.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/debug.js new file mode 100644 index 000000000..509dc0ded --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/debug.js @@ -0,0 +1,137 @@ + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + if (!debug.enabled(name)) return function(){}; + + return function(fmt){ + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (debug[name] || curr); + debug[name] = curr; + + fmt = name + + ' ' + + fmt + + ' +' + debug.humanize(ms); + + // This hackery is required for IE8 + // where `console.log` doesn't have 'apply' + window.console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); + } +} + +/** + * The currently active debug mode names. + */ + +debug.names = []; +debug.skips = []; + +/** + * Enables a debug mode by name. This can include modes + * separated by a colon and wildcards. + * + * @param {String} name + * @api public + */ + +debug.enable = function(name) { + try { + localStorage.debug = name; + } catch(e){} + + var split = (name || '').split(/[\s,]+/) + , len = split.length; + + for (var i = 0; i < len; i++) { + name = split[i].replace('*', '.*?'); + if (name[0] === '-') { + debug.skips.push(new RegExp('^' + name.substr(1) + '$')); + } + else { + debug.names.push(new RegExp('^' + name + '$')); + } + } +}; + +/** + * Disable debug output. + * + * @api public + */ + +debug.disable = function(){ + debug.enable(''); +}; + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +debug.humanize = function(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +}; + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +debug.enabled = function(name) { + for (var i = 0, len = debug.skips.length; i < len; i++) { + if (debug.skips[i].test(name)) { + return false; + } + } + for (var i = 0, len = debug.names.length; i < len; i++) { + if (debug.names[i].test(name)) { + return true; + } + } + return false; +}; + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +// persist + +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/index.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/index.js new file mode 100644 index 000000000..e02c13b7f --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/index.js @@ -0,0 +1,5 @@ +if ('undefined' == typeof window) { + module.exports = require('./lib/debug'); +} else { + module.exports = require('./debug'); +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/lib/debug.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/lib/debug.js new file mode 100644 index 000000000..3b0a9183d --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/lib/debug.js @@ -0,0 +1,147 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); + +/** + * Expose `debug()` as the module. + */ + +module.exports = debug; + +/** + * Enabled debuggers. + */ + +var names = [] + , skips = []; + +(process.env.DEBUG || '') + .split(/[\s,]+/) + .forEach(function(name){ + name = name.replace('*', '.*?'); + if (name[0] === '-') { + skips.push(new RegExp('^' + name.substr(1) + '$')); + } else { + names.push(new RegExp('^' + name + '$')); + } + }); + +/** + * Colors. + */ + +var colors = [6, 2, 3, 4, 5, 1]; + +/** + * Previous debug() call. + */ + +var prev = {}; + +/** + * Previously assigned color. + */ + +var prevColor = 0; + +/** + * Is stdout a TTY? Colored output is disabled when `true`. + */ + +var isatty = tty.isatty(2); + +/** + * Select a color. + * + * @return {Number} + * @api private + */ + +function color() { + return colors[prevColor++ % colors.length]; +} + +/** + * Humanize the given `ms`. + * + * @param {Number} m + * @return {String} + * @api private + */ + +function humanize(ms) { + var sec = 1000 + , min = 60 * 1000 + , hour = 60 * min; + + if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; + if (ms >= min) return (ms / min).toFixed(1) + 'm'; + if (ms >= sec) return (ms / sec | 0) + 's'; + return ms + 'ms'; +} + +/** + * Create a debugger with the given `name`. + * + * @param {String} name + * @return {Type} + * @api public + */ + +function debug(name) { + function disabled(){} + disabled.enabled = false; + + var match = skips.some(function(re){ + return re.test(name); + }); + + if (match) return disabled; + + match = names.some(function(re){ + return re.test(name); + }); + + if (!match) return disabled; + var c = color(); + + function colored(fmt) { + fmt = coerce(fmt); + + var curr = new Date; + var ms = curr - (prev[name] || curr); + prev[name] = curr; + + fmt = ' \u001b[9' + c + 'm' + name + ' ' + + '\u001b[3' + c + 'm\u001b[90m' + + fmt + '\u001b[3' + c + 'm' + + ' +' + humanize(ms) + '\u001b[0m'; + + console.error.apply(this, arguments); + } + + function plain(fmt) { + fmt = coerce(fmt); + + fmt = new Date().toUTCString() + + ' ' + name + ' ' + fmt; + console.error.apply(this, arguments); + } + + colored.enabled = plain.enabled = true; + + return isatty || process.env.DEBUG_COLORS + ? colored + : plain; +} + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/package.json b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/package.json new file mode 100644 index 000000000..fded430e6 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/debug/package.json @@ -0,0 +1,62 @@ +{ + "name": "debug", + "version": "0.7.4", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "dependencies": {}, + "devDependencies": { + "mocha": "*" + }, + "main": "lib/debug.js", + "browser": "./debug.js", + "engines": { + "node": "*" + }, + "files": [ + "lib/debug.js", + "debug.js", + "index.js" + ], + "component": { + "scripts": { + "debug/index.js": "index.js", + "debug/debug.js": "debug.js" + } + }, + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "homepage": "https://github.com/visionmedia/debug", + "_id": "debug@0.7.4", + "dist": { + "shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "tarball": "http://registry.npmjs.org/debug/-/debug-0.7.4.tgz" + }, + "_from": "debug@~0.7", + "_npmVersion": "1.3.13", + "_npmUser": { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + }, + "maintainers": [ + { + "name": "tjholowaychuk", + "email": "tj@vision-media.ca" + } + ], + "directories": {}, + "_shasum": "06e1ea8082c2cb14e39806e22e2f6f757f92af39", + "_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.4.tgz" +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.documentup.json b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.documentup.json new file mode 100644 index 000000000..57fe30116 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.documentup.json @@ -0,0 +1,6 @@ +{ + "name": "ShellJS", + "twitter": [ + "r2r" + ] +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.jshintrc b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.jshintrc new file mode 100644 index 000000000..a80c559aa --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.jshintrc @@ -0,0 +1,7 @@ +{ + "loopfunc": true, + "sub": true, + "undef": true, + "unused": true, + "node": true +} \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.npmignore b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.npmignore new file mode 100644 index 000000000..6b20c38ae --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.npmignore @@ -0,0 +1,2 @@ +test/ +tmp/ \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.travis.yml b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.travis.yml new file mode 100644 index 000000000..99cdc7439 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/LICENSE b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/LICENSE new file mode 100644 index 000000000..1b35ee9fb --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2012, Artur Adib +All rights reserved. + +You may use this project under the terms of the New BSD license as follows: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Artur Adib nor the + names of the contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL ARTUR ADIB BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/README.md b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/README.md new file mode 100644 index 000000000..912062313 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/README.md @@ -0,0 +1,552 @@ +# ShellJS - Unix shell commands for Node.js [![Build Status](https://secure.travis-ci.org/arturadib/shelljs.png)](http://travis-ci.org/arturadib/shelljs) + +ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! + +The project is [unit-tested](http://travis-ci.org/arturadib/shelljs) and battled-tested in projects like: + ++ [PDF.js](http://github.com/mozilla/pdf.js) - Firefox's next-gen PDF reader ++ [Firebug](http://getfirebug.com/) - Firefox's infamous debugger ++ [JSHint](http://jshint.com) - Most popular JavaScript linter ++ [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers ++ [Yeoman](http://yeoman.io/) - Web application stack and development tool ++ [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + +and [many more](https://npmjs.org/browse/depended/shelljs). + +## Installing + +Via npm: + +```bash +$ npm install [-g] shelljs +``` + +If the global option `-g` is specified, the binary `shjs` will be installed. This makes it possible to +run ShellJS scripts much like any shell script from the command line, i.e. without requiring a `node_modules` folder: + +```bash +$ shjs my_script +``` + +You can also just copy `shell.js` into your project's directory, and `require()` accordingly. + + +## Examples + +### JavaScript + +```javascript +require('shelljs/global'); + +if (!which('git')) { + echo('Sorry, this script requires git'); + exit(1); +} + +// Copy files to release dir +mkdir('-p', 'out/Release'); +cp('-R', 'stuff/*', 'out/Release'); + +// Replace macros in each .js file +cd('lib'); +ls('*.js').forEach(function(file) { + sed('-i', 'BUILD_VERSION', 'v0.1.2', file); + sed('-i', /.*REMOVE_THIS_LINE.*\n/, '', file); + sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat('macro.js'), file); +}); +cd('..'); + +// Run external tool synchronously +if (exec('git commit -am "Auto-commit"').code !== 0) { + echo('Error: Git commit failed'); + exit(1); +} +``` + +### CoffeeScript + +```coffeescript +require 'shelljs/global' + +if not which 'git' + echo 'Sorry, this script requires git' + exit 1 + +# Copy files to release dir +mkdir '-p', 'out/Release' +cp '-R', 'stuff/*', 'out/Release' + +# Replace macros in each .js file +cd 'lib' +for file in ls '*.js' + sed '-i', 'BUILD_VERSION', 'v0.1.2', file + sed '-i', /.*REMOVE_THIS_LINE.*\n/, '', file + sed '-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, cat 'macro.js', file +cd '..' + +# Run external tool synchronously +if (exec 'git commit -am "Auto-commit"').code != 0 + echo 'Error: Git commit failed' + exit 1 +``` + +## Global vs. Local + +The example above uses the convenience script `shelljs/global` to reduce verbosity. If polluting your global namespace is not desirable, simply require `shelljs`. + +Example: + +```javascript +var shell = require('shelljs'); +shell.echo('hello world'); +``` + +## Make tool + +A convenience script `shelljs/make` is also provided to mimic the behavior of a Unix Makefile. In this case all shell objects are global, and command line arguments will cause the script to execute only the corresponding function in the global `target` object. To avoid redundant calls, target functions are executed only once per script. + +Example (CoffeeScript): + +```coffeescript +require 'shelljs/make' + +target.all = -> + target.bundle() + target.docs() + +target.bundle = -> + cd __dirname + mkdir 'build' + cd 'lib' + (cat '*.js').to '../build/output.js' + +target.docs = -> + cd __dirname + mkdir 'docs' + cd 'lib' + for file in ls '*.js' + text = grep '//@', file # extract special comments + text.replace '//@', '' # remove comment tags + text.to 'docs/my_docs.md' +``` + +To run the target `all`, call the above script without arguments: `$ node make`. To run the target `docs`: `$ node make docs`, and so on. + + + + + + +## Command reference + + +All commands run synchronously, unless otherwise stated. + + +### cd('dir') +Changes to directory `dir` for the duration of the script + + +### pwd() +Returns the current directory. + + +### ls([options ,] path [,path ...]) +### ls([options ,] path_array) +Available options: + ++ `-R`: recursive ++ `-A`: all files (include files beginning with `.`, except for `.` and `..`) + +Examples: + +```javascript +ls('projs/*.js'); +ls('-R', '/users/me', '/tmp'); +ls('-R', ['/users/me', '/tmp']); // same as above +``` + +Returns array of files in the given path, or in current directory if no path provided. + + +### find(path [,path ...]) +### find(path_array) +Examples: + +```javascript +find('src', 'lib'); +find(['src', 'lib']); // same as above +find('.').filter(function(file) { return file.match(/\.js$/); }); +``` + +Returns array of all files (however deep) in the given paths. + +The main difference from `ls('-R', path)` is that the resulting file names +include the base directories, e.g. `lib/resources/file1` instead of just `file1`. + + +### cp([options ,] source [,source ...], dest) +### cp([options ,] source_array, dest) +Available options: + ++ `-f`: force ++ `-r, -R`: recursive + +Examples: + +```javascript +cp('file1', 'dir1'); +cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); +cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above +``` + +Copies files. The wildcard `*` is accepted. + + +### rm([options ,] file [, file ...]) +### rm([options ,] file_array) +Available options: + ++ `-f`: force ++ `-r, -R`: recursive + +Examples: + +```javascript +rm('-rf', '/tmp/*'); +rm('some_file.txt', 'another_file.txt'); +rm(['some_file.txt', 'another_file.txt']); // same as above +``` + +Removes files. The wildcard `*` is accepted. + + +### mv(source [, source ...], dest') +### mv(source_array, dest') +Available options: + ++ `f`: force + +Examples: + +```javascript +mv('-f', 'file', 'dir/'); +mv('file1', 'file2', 'dir/'); +mv(['file1', 'file2'], 'dir/'); // same as above +``` + +Moves files. The wildcard `*` is accepted. + + +### mkdir([options ,] dir [, dir ...]) +### mkdir([options ,] dir_array) +Available options: + ++ `p`: full path (will create intermediate dirs if necessary) + +Examples: + +```javascript +mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); +mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above +``` + +Creates directories. + + +### test(expression) +Available expression primaries: + ++ `'-b', 'path'`: true if path is a block device ++ `'-c', 'path'`: true if path is a character device ++ `'-d', 'path'`: true if path is a directory ++ `'-e', 'path'`: true if path exists ++ `'-f', 'path'`: true if path is a regular file ++ `'-L', 'path'`: true if path is a symboilc link ++ `'-p', 'path'`: true if path is a pipe (FIFO) ++ `'-S', 'path'`: true if path is a socket + +Examples: + +```javascript +if (test('-d', path)) { /* do something with dir */ }; +if (!test('-f', path)) continue; // skip if it's a regular file +``` + +Evaluates expression using the available primaries and returns corresponding value. + + +### cat(file [, file ...]) +### cat(file_array) + +Examples: + +```javascript +var str = cat('file*.txt'); +var str = cat('file1', 'file2'); +var str = cat(['file1', 'file2']); // same as above +``` + +Returns a string containing the given file, or a concatenated string +containing the files if more than one file is given (a new line character is +introduced between each file). Wildcard `*` accepted. + + +### 'string'.to(file) + +Examples: + +```javascript +cat('input.txt').to('output.txt'); +``` + +Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as +those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ + + +### 'string'.toEnd(file) + +Examples: + +```javascript +cat('input.txt').toEnd('output.txt'); +``` + +Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as +those returned by `cat`, `grep`, etc). + + +### sed([options ,] search_regex, replace_str, file) +Available options: + ++ `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ + +Examples: + +```javascript +sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); +sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); +``` + +Reads an input string from `file` and performs a JavaScript `replace()` on the input +using the given search regex and replacement string. Returns the new string after replacement. + + +### grep([options ,] regex_filter, file [, file ...]) +### grep([options ,] regex_filter, file_array) +Available options: + ++ `-v`: Inverse the sense of the regex and print the lines not matching the criteria. + +Examples: + +```javascript +grep('-v', 'GLOBAL_VARIABLE', '*.js'); +grep('GLOBAL_VARIABLE', '*.js'); +``` + +Reads input string from given files and returns a string containing all lines of the +file that match the given `regex_filter`. Wildcard `*` accepted. + + +### which(command) + +Examples: + +```javascript +var nodeExec = which('node'); +``` + +Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions. +Returns string containing the absolute path to the command. + + +### echo(string [,string ...]) + +Examples: + +```javascript +echo('hello world'); +var str = echo('hello world'); +``` + +Prints string to stdout, and returns string with additional utility methods +like `.to()`. + + +### pushd([options,] [dir | '-N' | '+N']) + +Available options: + ++ `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + +Arguments: + ++ `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`. ++ `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. ++ `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + +Examples: + +```javascript +// process.cwd() === '/usr' +pushd('/etc'); // Returns /etc /usr +pushd('+1'); // Returns /usr /etc +``` + +Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. + +### popd([options,] ['-N' | '+N']) + +Available options: + ++ `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. + +Arguments: + ++ `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. ++ `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. + +Examples: + +```javascript +echo(process.cwd()); // '/usr' +pushd('/etc'); // '/etc /usr' +echo(process.cwd()); // '/etc' +popd(); // '/usr' +echo(process.cwd()); // '/usr' +``` + +When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. + +### dirs([options | '+N' | '-N']) + +Available options: + ++ `-c`: Clears the directory stack by deleting all of the elements. + +Arguments: + ++ `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. ++ `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. + +Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. + +See also: pushd, popd + + +### exit(code) +Exits the current process with the given exit code. + +### env['VAR_NAME'] +Object containing environment variables (both getter and setter). Shortcut to process.env. + +### exec(command [, options] [, callback]) +Available options (all `false` by default): + ++ `async`: Asynchronous execution. Defaults to true if a callback is provided. ++ `silent`: Do not echo program output to console. + +Examples: + +```javascript +var version = exec('node --version', {silent:true}).output; + +var child = exec('some_long_running_process', {async:true}); +child.stdout.on('data', function(data) { + /* ... do something with data ... */ +}); + +exec('some_long_running_process', function(code, output) { + console.log('Exit code:', code); + console.log('Program output:', output); +}); +``` + +Executes the given `command` _synchronously_, unless otherwise specified. +When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's +`output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and +the `callback` gets the arguments `(code, output)`. + +**Note:** For long-lived processes, it's best to run `exec()` asynchronously as +the current synchronous implementation uses a lot of CPU. This should be getting +fixed soon. + + +### chmod(octal_mode || octal_string, file) +### chmod(symbolic_mode, file) + +Available options: + ++ `-v`: output a diagnostic for every file processed ++ `-c`: like verbose but report only when a change is made ++ `-R`: change files and directories recursively + +Examples: + +```javascript +chmod(755, '/Users/brandon'); +chmod('755', '/Users/brandon'); // same as above +chmod('u+x', '/Users/brandon'); +``` + +Alters the permissions of a file or directory by either specifying the +absolute permissions in octal form or expressing the changes in symbols. +This command tries to mimic the POSIX behavior as much as possible. +Notable exceptions: + ++ In symbolic modes, 'a-r' and '-r' are identical. No consideration is + given to the umask. ++ There is no "quiet" option since default behavior is to run silent. + + +## Non-Unix commands + + +### tempdir() + +Examples: + +```javascript +var tmp = tempdir(); // "/tmp" for most *nix platforms +``` + +Searches and returns string containing a writeable, platform-dependent temporary directory. +Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). + + +### error() +Tests if error occurred in the last command. Returns `null` if no error occurred, +otherwise returns string explaining the error + + +## Configuration + + +### config.silent +Example: + +```javascript +var silentState = config.silent; // save old silent state +config.silent = true; +/* ... */ +config.silent = silentState; // restore old silent state +``` + +Suppresses all command output if `true`, except for `echo()` calls. +Default is `false`. + +### config.fatal +Example: + +```javascript +config.fatal = true; +cp('this_file_does_not_exist', '/dev/null'); // dies here +/* more commands... */ +``` + +If `true` the script will die on errors. Default is `false`. diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/bin/shjs b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/bin/shjs new file mode 100755 index 000000000..d239a7ad4 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/bin/shjs @@ -0,0 +1,51 @@ +#!/usr/bin/env node +require('../global'); + +if (process.argv.length < 3) { + console.log('ShellJS: missing argument (script name)'); + console.log(); + process.exit(1); +} + +var args, + scriptName = process.argv[2]; +env['NODE_PATH'] = __dirname + '/../..'; + +if (!scriptName.match(/\.js/) && !scriptName.match(/\.coffee/)) { + if (test('-f', scriptName + '.js')) + scriptName += '.js'; + if (test('-f', scriptName + '.coffee')) + scriptName += '.coffee'; +} + +if (!test('-f', scriptName)) { + console.log('ShellJS: script not found ('+scriptName+')'); + console.log(); + process.exit(1); +} + +args = process.argv.slice(3); + +for (var i = 0, l = args.length; i < l; i++) { + if (args[i][0] !== "-"){ + args[i] = '"' + args[i] + '"'; // fixes arguments with multiple words + } +} + +if (scriptName.match(/\.coffee$/)) { + // + // CoffeeScript + // + if (which('coffee')) { + exec('coffee ' + scriptName + ' ' + args.join(' '), { async: true }); + } else { + console.log('ShellJS: CoffeeScript interpreter not found'); + console.log(); + process.exit(1); + } +} else { + // + // JavaScript + // + exec('node ' + scriptName + ' ' + args.join(' '), { async: true }); +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/global.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/global.js new file mode 100644 index 000000000..97f0033cc --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/global.js @@ -0,0 +1,3 @@ +var shell = require('./shell.js'); +for (var cmd in shell) + global[cmd] = shell[cmd]; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/make.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/make.js new file mode 100644 index 000000000..53e5e8126 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/make.js @@ -0,0 +1,47 @@ +require('./global'); + +global.config.fatal = true; +global.target = {}; + +// This ensures we only execute the script targets after the entire script has +// been evaluated +var args = process.argv.slice(2); +setTimeout(function() { + var t; + + if (args.length === 1 && args[0] === '--help') { + console.log('Available targets:'); + for (t in global.target) + console.log(' ' + t); + return; + } + + // Wrap targets to prevent duplicate execution + for (t in global.target) { + (function(t, oldTarget){ + + // Wrap it + global.target[t] = function(force) { + if (oldTarget.done && !force) + return; + oldTarget.done = true; + return oldTarget.apply(oldTarget, arguments); + }; + + })(t, global.target[t]); + } + + // Execute desired targets + if (args.length > 0) { + args.forEach(function(arg) { + if (arg in global.target) + global.target[arg](); + else { + console.log('no such target: ' + arg); + } + }); + } else if ('all' in global.target) { + global.target.all(); + } + +}, 0); diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/package.json b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/package.json new file mode 100644 index 000000000..fec144d65 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/package.json @@ -0,0 +1,60 @@ +{ + "name": "shelljs", + "version": "0.2.6", + "author": { + "name": "Artur Adib", + "email": "aadib@mozilla.com" + }, + "description": "Portable Unix shell commands for Node.js", + "keywords": [ + "unix", + "shell", + "makefile", + "make", + "jake", + "synchronous" + ], + "repository": { + "type": "git", + "url": "git://github.com/arturadib/shelljs.git" + }, + "homepage": "http://github.com/arturadib/shelljs", + "main": "./shell.js", + "scripts": { + "test": "node scripts/run-tests" + }, + "bin": { + "shjs": "./bin/shjs" + }, + "dependencies": {}, + "devDependencies": { + "jshint": "~2.1.11" + }, + "optionalDependencies": {}, + "engines": { + "node": ">=0.8.0" + }, + "bugs": { + "url": "https://github.com/arturadib/shelljs/issues" + }, + "_id": "shelljs@0.2.6", + "dist": { + "shasum": "90492d72ffcc8159976baba62fb0f6884f0c3378", + "tarball": "http://registry.npmjs.org/shelljs/-/shelljs-0.2.6.tgz" + }, + "_from": "shelljs@~0.2", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "artur", + "email": "arturadib@gmail.com" + }, + "maintainers": [ + { + "name": "artur", + "email": "arturadib@gmail.com" + } + ], + "directories": {}, + "_shasum": "90492d72ffcc8159976baba62fb0f6884f0c3378", + "_resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.2.6.tgz" +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/generate-docs.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/generate-docs.js new file mode 100755 index 000000000..532fed9f0 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/generate-docs.js @@ -0,0 +1,21 @@ +#!/usr/bin/env node +require('../global'); + +echo('Appending docs to README.md'); + +cd(__dirname + '/..'); + +// Extract docs from shell.js +var docs = grep('//@', 'shell.js'); + +docs = docs.replace(/\/\/\@include (.+)/g, function(match, path) { + var file = path.match('.js$') ? path : path+'.js'; + return grep('//@', file); +}); + +// Remove '//@' +docs = docs.replace(/\/\/\@ ?/g, ''); +// Append docs to README +sed('-i', /## Command reference(.|\n)*/, '## Command reference\n\n' + docs, 'README.md'); + +echo('All done.'); diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/run-tests.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/run-tests.js new file mode 100755 index 000000000..f9d31e068 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/scripts/run-tests.js @@ -0,0 +1,50 @@ +#!/usr/bin/env node +require('../global'); + +var path = require('path'); + +var failed = false; + +// +// Lint +// +JSHINT_BIN = './node_modules/jshint/bin/jshint'; +cd(__dirname + '/..'); + +if (!test('-f', JSHINT_BIN)) { + echo('JSHint not found. Run `npm install` in the root dir first.'); + exit(1); +} + +if (exec(JSHINT_BIN + ' *.js test/*.js').code !== 0) { + failed = true; + echo('*** JSHINT FAILED! (return code != 0)'); + echo(); +} else { + echo('All JSHint tests passed'); + echo(); +} + +// +// Unit tests +// +cd(__dirname + '/../test'); +ls('*.js').forEach(function(file) { + echo('Running test:', file); + if (exec('node ' + file).code !== 123) { // 123 avoids false positives (e.g. premature exit) + failed = true; + echo('*** TEST FAILED! (missing exit code "123")'); + echo(); + } +}); + +if (failed) { + echo(); + echo('*******************************************************'); + echo('WARNING: Some tests did not pass!'); + echo('*******************************************************'); + exit(1); +} else { + echo(); + echo('All tests passed.'); +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/shell.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/shell.js new file mode 100644 index 000000000..e56c5de9f --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/shell.js @@ -0,0 +1,153 @@ +// +// ShellJS +// Unix shell commands on top of Node's API +// +// Copyright (c) 2012 Artur Adib +// http://github.com/arturadib/shelljs +// + +var common = require('./src/common'); + + +//@ +//@ All commands run synchronously, unless otherwise stated. +//@ + +//@include ./src/cd +var _cd = require('./src/cd'); +exports.cd = common.wrap('cd', _cd); + +//@include ./src/pwd +var _pwd = require('./src/pwd'); +exports.pwd = common.wrap('pwd', _pwd); + +//@include ./src/ls +var _ls = require('./src/ls'); +exports.ls = common.wrap('ls', _ls); + +//@include ./src/find +var _find = require('./src/find'); +exports.find = common.wrap('find', _find); + +//@include ./src/cp +var _cp = require('./src/cp'); +exports.cp = common.wrap('cp', _cp); + +//@include ./src/rm +var _rm = require('./src/rm'); +exports.rm = common.wrap('rm', _rm); + +//@include ./src/mv +var _mv = require('./src/mv'); +exports.mv = common.wrap('mv', _mv); + +//@include ./src/mkdir +var _mkdir = require('./src/mkdir'); +exports.mkdir = common.wrap('mkdir', _mkdir); + +//@include ./src/test +var _test = require('./src/test'); +exports.test = common.wrap('test', _test); + +//@include ./src/cat +var _cat = require('./src/cat'); +exports.cat = common.wrap('cat', _cat); + +//@include ./src/to +var _to = require('./src/to'); +String.prototype.to = common.wrap('to', _to); + +//@include ./src/toEnd +var _toEnd = require('./src/toEnd'); +String.prototype.toEnd = common.wrap('toEnd', _toEnd); + +//@include ./src/sed +var _sed = require('./src/sed'); +exports.sed = common.wrap('sed', _sed); + +//@include ./src/grep +var _grep = require('./src/grep'); +exports.grep = common.wrap('grep', _grep); + +//@include ./src/which +var _which = require('./src/which'); +exports.which = common.wrap('which', _which); + +//@include ./src/echo +var _echo = require('./src/echo'); +exports.echo = _echo; // don't common.wrap() as it could parse '-options' + +//@include ./src/dirs +var _dirs = require('./src/dirs').dirs; +exports.dirs = common.wrap("dirs", _dirs); +var _pushd = require('./src/dirs').pushd; +exports.pushd = common.wrap('pushd', _pushd); +var _popd = require('./src/dirs').popd; +exports.popd = common.wrap("popd", _popd); + +//@ +//@ ### exit(code) +//@ Exits the current process with the given exit code. +exports.exit = process.exit; + +//@ +//@ ### env['VAR_NAME'] +//@ Object containing environment variables (both getter and setter). Shortcut to process.env. +exports.env = process.env; + +//@include ./src/exec +var _exec = require('./src/exec'); +exports.exec = common.wrap('exec', _exec, {notUnix:true}); + +//@include ./src/chmod +var _chmod = require('./src/chmod'); +exports.chmod = common.wrap('chmod', _chmod); + + + +//@ +//@ ## Non-Unix commands +//@ + +//@include ./src/tempdir +var _tempDir = require('./src/tempdir'); +exports.tempdir = common.wrap('tempdir', _tempDir); + + +//@include ./src/error +var _error = require('./src/error'); +exports.error = _error; + + + +//@ +//@ ## Configuration +//@ + +exports.config = common.config; + +//@ +//@ ### config.silent +//@ Example: +//@ +//@ ```javascript +//@ var silentState = config.silent; // save old silent state +//@ config.silent = true; +//@ /* ... */ +//@ config.silent = silentState; // restore old silent state +//@ ``` +//@ +//@ Suppresses all command output if `true`, except for `echo()` calls. +//@ Default is `false`. + +//@ +//@ ### config.fatal +//@ Example: +//@ +//@ ```javascript +//@ config.fatal = true; +//@ cp('this_file_does_not_exist', '/dev/null'); // dies here +//@ /* more commands... */ +//@ ``` +//@ +//@ If `true` the script will die on errors. Default is `false`. diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cat.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cat.js new file mode 100644 index 000000000..f6f4d254a --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cat.js @@ -0,0 +1,43 @@ +var common = require('./common'); +var fs = require('fs'); + +//@ +//@ ### cat(file [, file ...]) +//@ ### cat(file_array) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var str = cat('file*.txt'); +//@ var str = cat('file1', 'file2'); +//@ var str = cat(['file1', 'file2']); // same as above +//@ ``` +//@ +//@ Returns a string containing the given file, or a concatenated string +//@ containing the files if more than one file is given (a new line character is +//@ introduced between each file). Wildcard `*` accepted. +function _cat(options, files) { + var cat = ''; + + if (!files) + common.error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 1); + // if it's array leave it as it is + + files = common.expand(files); + + files.forEach(function(file) { + if (!fs.existsSync(file)) + common.error('no such file or directory: ' + file); + + cat += fs.readFileSync(file, 'utf8') + '\n'; + }); + + if (cat[cat.length-1] === '\n') + cat = cat.substring(0, cat.length-1); + + return common.ShellString(cat); +} +module.exports = _cat; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cd.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cd.js new file mode 100644 index 000000000..230f43265 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/cd.js @@ -0,0 +1,19 @@ +var fs = require('fs'); +var common = require('./common'); + +//@ +//@ ### cd('dir') +//@ Changes to directory `dir` for the duration of the script +function _cd(options, dir) { + if (!dir) + common.error('directory not specified'); + + if (!fs.existsSync(dir)) + common.error('no such file or directory: ' + dir); + + if (!fs.statSync(dir).isDirectory()) + common.error('not a directory: ' + dir); + + process.chdir(dir); +} +module.exports = _cd; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/chmod.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/chmod.js new file mode 100644 index 000000000..f2888930b --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/chmod.js @@ -0,0 +1,208 @@ +var common = require('./common'); +var fs = require('fs'); +var path = require('path'); + +var PERMS = (function (base) { + return { + OTHER_EXEC : base.EXEC, + OTHER_WRITE : base.WRITE, + OTHER_READ : base.READ, + + GROUP_EXEC : base.EXEC << 3, + GROUP_WRITE : base.WRITE << 3, + GROUP_READ : base.READ << 3, + + OWNER_EXEC : base.EXEC << 6, + OWNER_WRITE : base.WRITE << 6, + OWNER_READ : base.READ << 6, + + // Literal octal numbers are apparently not allowed in "strict" javascript. Using parseInt is + // the preferred way, else a jshint warning is thrown. + STICKY : parseInt('01000', 8), + SETGID : parseInt('02000', 8), + SETUID : parseInt('04000', 8), + + TYPE_MASK : parseInt('0770000', 8) + }; +})({ + EXEC : 1, + WRITE : 2, + READ : 4 +}); + +//@ +//@ ### chmod(octal_mode || octal_string, file) +//@ ### chmod(symbolic_mode, file) +//@ +//@ Available options: +//@ +//@ + `-v`: output a diagnostic for every file processed//@ +//@ + `-c`: like verbose but report only when a change is made//@ +//@ + `-R`: change files and directories recursively//@ +//@ +//@ Examples: +//@ +//@ ```javascript +//@ chmod(755, '/Users/brandon'); +//@ chmod('755', '/Users/brandon'); // same as above +//@ chmod('u+x', '/Users/brandon'); +//@ ``` +//@ +//@ Alters the permissions of a file or directory by either specifying the +//@ absolute permissions in octal form or expressing the changes in symbols. +//@ This command tries to mimic the POSIX behavior as much as possible. +//@ Notable exceptions: +//@ +//@ + In symbolic modes, 'a-r' and '-r' are identical. No consideration is +//@ given to the umask. +//@ + There is no "quiet" option since default behavior is to run silent. +function _chmod(options, mode, filePattern) { + if (!filePattern) { + if (options.length > 0 && options.charAt(0) === '-') { + // Special case where the specified file permissions started with - to subtract perms, which + // get picked up by the option parser as command flags. + // If we are down by one argument and options starts with -, shift everything over. + filePattern = mode; + mode = options; + options = ''; + } + else { + common.error('You must specify a file.'); + } + } + + options = common.parseOptions(options, { + 'R': 'recursive', + 'c': 'changes', + 'v': 'verbose' + }); + + if (typeof filePattern === 'string') { + filePattern = [ filePattern ]; + } + + var files; + + if (options.recursive) { + files = []; + common.expand(filePattern).forEach(function addFile(expandedFile) { + var stat = fs.lstatSync(expandedFile); + + if (!stat.isSymbolicLink()) { + files.push(expandedFile); + + if (stat.isDirectory()) { // intentionally does not follow symlinks. + fs.readdirSync(expandedFile).forEach(function (child) { + addFile(expandedFile + '/' + child); + }); + } + } + }); + } + else { + files = common.expand(filePattern); + } + + files.forEach(function innerChmod(file) { + file = path.resolve(file); + if (!fs.existsSync(file)) { + common.error('File not found: ' + file); + } + + // When recursing, don't follow symlinks. + if (options.recursive && fs.lstatSync(file).isSymbolicLink()) { + return; + } + + var perms = fs.statSync(file).mode; + var type = perms & PERMS.TYPE_MASK; + + var newPerms = perms; + + if (isNaN(parseInt(mode, 8))) { + // parse options + mode.split(',').forEach(function (symbolicMode) { + /*jshint regexdash:true */ + var pattern = /([ugoa]*)([=\+-])([rwxXst]*)/i; + var matches = pattern.exec(symbolicMode); + + if (matches) { + var applyTo = matches[1]; + var operator = matches[2]; + var change = matches[3]; + + var changeOwner = applyTo.indexOf('u') != -1 || applyTo === 'a' || applyTo === ''; + var changeGroup = applyTo.indexOf('g') != -1 || applyTo === 'a' || applyTo === ''; + var changeOther = applyTo.indexOf('o') != -1 || applyTo === 'a' || applyTo === ''; + + var changeRead = change.indexOf('r') != -1; + var changeWrite = change.indexOf('w') != -1; + var changeExec = change.indexOf('x') != -1; + var changeSticky = change.indexOf('t') != -1; + var changeSetuid = change.indexOf('s') != -1; + + var mask = 0; + if (changeOwner) { + mask |= (changeRead ? PERMS.OWNER_READ : 0) + (changeWrite ? PERMS.OWNER_WRITE : 0) + (changeExec ? PERMS.OWNER_EXEC : 0) + (changeSetuid ? PERMS.SETUID : 0); + } + if (changeGroup) { + mask |= (changeRead ? PERMS.GROUP_READ : 0) + (changeWrite ? PERMS.GROUP_WRITE : 0) + (changeExec ? PERMS.GROUP_EXEC : 0) + (changeSetuid ? PERMS.SETGID : 0); + } + if (changeOther) { + mask |= (changeRead ? PERMS.OTHER_READ : 0) + (changeWrite ? PERMS.OTHER_WRITE : 0) + (changeExec ? PERMS.OTHER_EXEC : 0); + } + + // Sticky bit is special - it's not tied to user, group or other. + if (changeSticky) { + mask |= PERMS.STICKY; + } + + switch (operator) { + case '+': + newPerms |= mask; + break; + + case '-': + newPerms &= ~mask; + break; + + case '=': + newPerms = type + mask; + + // According to POSIX, when using = to explicitly set the permissions, setuid and setgid can never be cleared. + if (fs.statSync(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; + } + break; + } + + if (options.verbose) { + log(file + ' -> ' + newPerms.toString(8)); + } + + if (perms != newPerms) { + if (!options.verbose && options.changes) { + log(file + ' -> ' + newPerms.toString(8)); + } + fs.chmodSync(file, newPerms); + } + } + else { + common.error('Invalid symbolic mode change: ' + symbolicMode); + } + }); + } + else { + // they gave us a full number + newPerms = type + parseInt(mode, 8); + + // POSIX rules are that setuid and setgid can only be added using numeric form, but not cleared. + if (fs.statSync(file).isDirectory()) { + newPerms |= (PERMS.SETUID + PERMS.SETGID) & perms; + } + + fs.chmodSync(file, newPerms); + } + }); +} +module.exports = _chmod; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/common.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/common.js new file mode 100644 index 000000000..fe2087194 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/common.js @@ -0,0 +1,189 @@ +var os = require('os'); +var fs = require('fs'); +var _ls = require('./ls'); + +// Module globals +var config = { + silent: false, + fatal: false +}; +exports.config = config; + +var state = { + error: null, + currentCmd: 'shell.js', + tempDir: null +}; +exports.state = state; + +var platform = os.type().match(/^Win/) ? 'win' : 'unix'; +exports.platform = platform; + +function log() { + if (!config.silent) + console.log.apply(this, arguments); +} +exports.log = log; + +// Shows error message. Throws unless _continue or config.fatal are true +function error(msg, _continue) { + if (state.error === null) + state.error = ''; + state.error += state.currentCmd + ': ' + msg + '\n'; + + if (msg.length > 0) + log(state.error); + + if (config.fatal) + process.exit(1); + + if (!_continue) + throw ''; +} +exports.error = error; + +// In the future, when Proxies are default, we can add methods like `.to()` to primitive strings. +// For now, this is a dummy function to bookmark places we need such strings +function ShellString(str) { + return str; +} +exports.ShellString = ShellString; + +// Returns {'alice': true, 'bob': false} when passed a dictionary, e.g.: +// parseOptions('-a', {'a':'alice', 'b':'bob'}); +function parseOptions(str, map) { + if (!map) + error('parseOptions() internal error: no map given'); + + // All options are false by default + var options = {}; + for (var letter in map) + options[map[letter]] = false; + + if (!str) + return options; // defaults + + if (typeof str !== 'string') + error('parseOptions() internal error: wrong str'); + + // e.g. match[1] = 'Rf' for str = '-Rf' + var match = str.match(/^\-(.+)/); + if (!match) + return options; + + // e.g. chars = ['R', 'f'] + var chars = match[1].split(''); + + chars.forEach(function(c) { + if (c in map) + options[map[c]] = true; + else + error('option not recognized: '+c); + }); + + return options; +} +exports.parseOptions = parseOptions; + +// Expands wildcards with matching (ie. existing) file names. +// For example: +// expand(['file*.js']) = ['file1.js', 'file2.js', ...] +// (if the files 'file1.js', 'file2.js', etc, exist in the current dir) +function expand(list) { + var expanded = []; + list.forEach(function(listEl) { + // Wildcard present? + if (listEl.search(/\*/) > -1) { + _ls('', listEl).forEach(function(file) { + expanded.push(file); + }); + } else { + expanded.push(listEl); + } + }); + return expanded; +} +exports.expand = expand; + +// Normalizes _unlinkSync() across platforms to match Unix behavior, i.e. +// file can be unlinked even if it's read-only, see https://github.com/joyent/node/issues/3006 +function unlinkSync(file) { + try { + fs.unlinkSync(file); + } catch(e) { + // Try to override file permission + if (e.code === 'EPERM') { + fs.chmodSync(file, '0666'); + fs.unlinkSync(file); + } else { + throw e; + } + } +} +exports.unlinkSync = unlinkSync; + +// e.g. 'shelljs_a5f185d0443ca...' +function randomFileName() { + function randomHash(count) { + if (count === 1) + return parseInt(16*Math.random(), 10).toString(16); + else { + var hash = ''; + for (var i=0; i and/or '); + } else if (arguments.length > 3) { + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; + } else if (typeof sources === 'string') { + sources = [sources]; + } else if ('length' in sources) { + sources = sources; // no-op for array + } else { + common.error('invalid arguments'); + } + + var exists = fs.existsSync(dest), + stats = exists && fs.statSync(dest); + + // Dest is not existing dir, but multiple sources given + if ((!exists || !stats.isDirectory()) && sources.length > 1) + common.error('dest is not a directory (too many sources)'); + + // Dest is an existing file, but no -f given + if (exists && stats.isFile() && !options.force) + common.error('dest file already exists: ' + dest); + + if (options.recursive) { + // Recursive allows the shortcut syntax "sourcedir/" for "sourcedir/*" + // (see Github issue #15) + sources.forEach(function(src, i) { + if (src[src.length - 1] === '/') + sources[i] += '*'; + }); + + // Create dest + try { + fs.mkdirSync(dest, parseInt('0777', 8)); + } catch (e) { + // like Unix's cp, keep going even if we can't create dest dir + } + } + + sources = common.expand(sources); + + sources.forEach(function(src) { + if (!fs.existsSync(src)) { + common.error('no such file or directory: '+src, true); + return; // skip file + } + + // If here, src exists + if (fs.statSync(src).isDirectory()) { + if (!options.recursive) { + // Non-Recursive + common.log(src + ' is a directory (not copied)'); + } else { + // Recursive + // 'cp /a/source dest' should create 'source' in 'dest' + var newDest = path.join(dest, path.basename(src)), + checkDir = fs.statSync(src); + try { + fs.mkdirSync(newDest, checkDir.mode); + } catch (e) { + //if the directory already exists, that's okay + if (e.code !== 'EEXIST') throw e; + } + + cpdirSyncRecursive(src, newDest, {force: options.force}); + } + return; // done with dir + } + + // If here, src is a file + + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + thisDest = path.normalize(dest + '/' + path.basename(src)); + + if (fs.existsSync(thisDest) && !options.force) { + common.error('dest file already exists: ' + thisDest, true); + return; // skip file + } + + copyFileSync(src, thisDest); + }); // forEach(src) +} +module.exports = _cp; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/dirs.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/dirs.js new file mode 100644 index 000000000..58fae8b3c --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/dirs.js @@ -0,0 +1,191 @@ +var common = require('./common'); +var _cd = require('./cd'); +var path = require('path'); + +// Pushd/popd/dirs internals +var _dirStack = []; + +function _isStackIndex(index) { + return (/^[\-+]\d+$/).test(index); +} + +function _parseStackIndex(index) { + if (_isStackIndex(index)) { + if (Math.abs(index) < _dirStack.length + 1) { // +1 for pwd + return (/^-/).test(index) ? Number(index) - 1 : Number(index); + } else { + common.error(index + ': directory stack index out of range'); + } + } else { + common.error(index + ': invalid number'); + } +} + +function _actualDirStack() { + return [process.cwd()].concat(_dirStack); +} + +//@ +//@ ### pushd([options,] [dir | '-N' | '+N']) +//@ +//@ Available options: +//@ +//@ + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. +//@ +//@ Arguments: +//@ +//@ + `dir`: Makes the current working directory be the top of the stack, and then executes the equivalent of `cd dir`. +//@ + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ // process.cwd() === '/usr' +//@ pushd('/etc'); // Returns /etc /usr +//@ pushd('+1'); // Returns /usr /etc +//@ ``` +//@ +//@ Save the current directory on the top of the directory stack and then cd to `dir`. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. +function _pushd(options, dir) { + if (_isStackIndex(options)) { + dir = options; + options = ''; + } + + options = common.parseOptions(options, { + 'n' : 'no-cd' + }); + + var dirs = _actualDirStack(); + + if (dir === '+0') { + return dirs; // +0 is a noop + } else if (!dir) { + if (dirs.length > 1) { + dirs = dirs.splice(1, 1).concat(dirs); + } else { + return common.error('no other directory'); + } + } else if (_isStackIndex(dir)) { + var n = _parseStackIndex(dir); + dirs = dirs.slice(n).concat(dirs.slice(0, n)); + } else { + if (options['no-cd']) { + dirs.splice(1, 0, dir); + } else { + dirs.unshift(dir); + } + } + + if (options['no-cd']) { + dirs = dirs.slice(1); + } else { + dir = path.resolve(dirs.shift()); + _cd('', dir); + } + + _dirStack = dirs; + return _dirs(''); +} +exports.pushd = _pushd; + +//@ +//@ ### popd([options,] ['-N' | '+N']) +//@ +//@ Available options: +//@ +//@ + `-n`: Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. +//@ +//@ Arguments: +//@ +//@ + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. +//@ + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ echo(process.cwd()); // '/usr' +//@ pushd('/etc'); // '/etc /usr' +//@ echo(process.cwd()); // '/etc' +//@ popd(); // '/usr' +//@ echo(process.cwd()); // '/usr' +//@ ``` +//@ +//@ When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. +function _popd(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } + + options = common.parseOptions(options, { + 'n' : 'no-cd' + }); + + if (!_dirStack.length) { + return common.error('directory stack empty'); + } + + index = _parseStackIndex(index || '+0'); + + if (options['no-cd'] || index > 0 || _dirStack.length + index === 0) { + index = index > 0 ? index - 1 : index; + _dirStack.splice(index, 1); + } else { + var dir = path.resolve(_dirStack.shift()); + _cd('', dir); + } + + return _dirs(''); +} +exports.popd = _popd; + +//@ +//@ ### dirs([options | '+N' | '-N']) +//@ +//@ Available options: +//@ +//@ + `-c`: Clears the directory stack by deleting all of the elements. +//@ +//@ Arguments: +//@ +//@ + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. +//@ + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. +//@ +//@ Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. +//@ +//@ See also: pushd, popd +function _dirs(options, index) { + if (_isStackIndex(options)) { + index = options; + options = ''; + } + + options = common.parseOptions(options, { + 'c' : 'clear' + }); + + if (options['clear']) { + _dirStack = []; + return _dirStack; + } + + var stack = _actualDirStack(); + + if (index) { + index = _parseStackIndex(index); + + if (index < 0) { + index = stack.length + index; + } + + common.log(stack[index]); + return stack[index]; + } + + common.log(stack.join(' ')); + + return stack; +} +exports.dirs = _dirs; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/echo.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/echo.js new file mode 100644 index 000000000..760ea840f --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/echo.js @@ -0,0 +1,20 @@ +var common = require('./common'); + +//@ +//@ ### echo(string [,string ...]) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ echo('hello world'); +//@ var str = echo('hello world'); +//@ ``` +//@ +//@ Prints string to stdout, and returns string with additional utility methods +//@ like `.to()`. +function _echo() { + var messages = [].slice.call(arguments, 0); + console.log.apply(this, messages); + return common.ShellString(messages.join(' ')); +} +module.exports = _echo; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/error.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/error.js new file mode 100644 index 000000000..cca3efb60 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/error.js @@ -0,0 +1,10 @@ +var common = require('./common'); + +//@ +//@ ### error() +//@ Tests if error occurred in the last command. Returns `null` if no error occurred, +//@ otherwise returns string explaining the error +function error() { + return common.state.error; +}; +module.exports = error; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/exec.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/exec.js new file mode 100644 index 000000000..7ccdbc004 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/exec.js @@ -0,0 +1,181 @@ +var common = require('./common'); +var _tempDir = require('./tempdir'); +var _pwd = require('./pwd'); +var path = require('path'); +var fs = require('fs'); +var child = require('child_process'); + +// Hack to run child_process.exec() synchronously (sync avoids callback hell) +// Uses a custom wait loop that checks for a flag file, created when the child process is done. +// (Can't do a wait loop that checks for internal Node variables/messages as +// Node is single-threaded; callbacks and other internal state changes are done in the +// event loop). +function execSync(cmd, opts) { + var tempDir = _tempDir(); + var stdoutFile = path.resolve(tempDir+'/'+common.randomFileName()), + codeFile = path.resolve(tempDir+'/'+common.randomFileName()), + scriptFile = path.resolve(tempDir+'/'+common.randomFileName()), + sleepFile = path.resolve(tempDir+'/'+common.randomFileName()); + + var options = common.extend({ + silent: common.config.silent + }, opts); + + var previousStdoutContent = ''; + // Echoes stdout changes from running process, if not silent + function updateStdout() { + if (options.silent || !fs.existsSync(stdoutFile)) + return; + + var stdoutContent = fs.readFileSync(stdoutFile, 'utf8'); + // No changes since last time? + if (stdoutContent.length <= previousStdoutContent.length) + return; + + process.stdout.write(stdoutContent.substr(previousStdoutContent.length)); + previousStdoutContent = stdoutContent; + } + + function escape(str) { + return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0"); + } + + cmd += ' > '+stdoutFile+' 2>&1'; // works on both win/unix + + var script = + "var child = require('child_process')," + + " fs = require('fs');" + + "child.exec('"+escape(cmd)+"', {env: process.env, maxBuffer: 20*1024*1024}, function(err) {" + + " fs.writeFileSync('"+escape(codeFile)+"', err ? err.code.toString() : '0');" + + "});"; + + if (fs.existsSync(scriptFile)) common.unlinkSync(scriptFile); + if (fs.existsSync(stdoutFile)) common.unlinkSync(stdoutFile); + if (fs.existsSync(codeFile)) common.unlinkSync(codeFile); + + fs.writeFileSync(scriptFile, script); + child.exec('"'+process.execPath+'" '+scriptFile, { + env: process.env, + cwd: _pwd(), + maxBuffer: 20*1024*1024 + }); + + // The wait loop + // sleepFile is used as a dummy I/O op to mitigate unnecessary CPU usage + // (tried many I/O sync ops, writeFileSync() seems to be only one that is effective in reducing + // CPU usage, though apparently not so much on Windows) + while (!fs.existsSync(codeFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } + while (!fs.existsSync(stdoutFile)) { updateStdout(); fs.writeFileSync(sleepFile, 'a'); } + + // At this point codeFile exists, but it's not necessarily flushed yet. + // Keep reading it until it is. + var code = parseInt('', 10); + while (isNaN(code)) { + code = parseInt(fs.readFileSync(codeFile, 'utf8'), 10); + } + + var stdout = fs.readFileSync(stdoutFile, 'utf8'); + + // No biggie if we can't erase the files now -- they're in a temp dir anyway + try { common.unlinkSync(scriptFile); } catch(e) {} + try { common.unlinkSync(stdoutFile); } catch(e) {} + try { common.unlinkSync(codeFile); } catch(e) {} + try { common.unlinkSync(sleepFile); } catch(e) {} + + // some shell return codes are defined as errors, per http://tldp.org/LDP/abs/html/exitcodes.html + if (code === 1 || code === 2 || code >= 126) { + common.error('', true); // unix/shell doesn't really give an error message after non-zero exit codes + } + // True if successful, false if not + var obj = { + code: code, + output: stdout + }; + return obj; +} // execSync() + +// Wrapper around exec() to enable echoing output to console in real time +function execAsync(cmd, opts, callback) { + var output = ''; + + var options = common.extend({ + silent: common.config.silent + }, opts); + + var c = child.exec(cmd, {env: process.env, maxBuffer: 20*1024*1024}, function(err) { + if (callback) + callback(err ? err.code : 0, output); + }); + + c.stdout.on('data', function(data) { + output += data; + if (!options.silent) + process.stdout.write(data); + }); + + c.stderr.on('data', function(data) { + output += data; + if (!options.silent) + process.stdout.write(data); + }); + + return c; +} + +//@ +//@ ### exec(command [, options] [, callback]) +//@ Available options (all `false` by default): +//@ +//@ + `async`: Asynchronous execution. Defaults to true if a callback is provided. +//@ + `silent`: Do not echo program output to console. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var version = exec('node --version', {silent:true}).output; +//@ +//@ var child = exec('some_long_running_process', {async:true}); +//@ child.stdout.on('data', function(data) { +//@ /* ... do something with data ... */ +//@ }); +//@ +//@ exec('some_long_running_process', function(code, output) { +//@ console.log('Exit code:', code); +//@ console.log('Program output:', output); +//@ }); +//@ ``` +//@ +//@ Executes the given `command` _synchronously_, unless otherwise specified. +//@ When in synchronous mode returns the object `{ code:..., output:... }`, containing the program's +//@ `output` (stdout + stderr) and its exit `code`. Otherwise returns the child process object, and +//@ the `callback` gets the arguments `(code, output)`. +//@ +//@ **Note:** For long-lived processes, it's best to run `exec()` asynchronously as +//@ the current synchronous implementation uses a lot of CPU. This should be getting +//@ fixed soon. +function _exec(command, options, callback) { + if (!command) + common.error('must specify command'); + + // Callback is defined instead of options. + if (typeof options === 'function') { + callback = options; + options = { async: true }; + } + + // Callback is defined with options. + if (typeof options === 'object' && typeof callback === 'function') { + options.async = true; + } + + options = common.extend({ + silent: common.config.silent, + async: false + }, options); + + if (options.async) + return execAsync(command, options, callback); + else + return execSync(command, options); +} +module.exports = _exec; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/find.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/find.js new file mode 100644 index 000000000..d9eeec26a --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/find.js @@ -0,0 +1,51 @@ +var fs = require('fs'); +var common = require('./common'); +var _ls = require('./ls'); + +//@ +//@ ### find(path [,path ...]) +//@ ### find(path_array) +//@ Examples: +//@ +//@ ```javascript +//@ find('src', 'lib'); +//@ find(['src', 'lib']); // same as above +//@ find('.').filter(function(file) { return file.match(/\.js$/); }); +//@ ``` +//@ +//@ Returns array of all files (however deep) in the given paths. +//@ +//@ The main difference from `ls('-R', path)` is that the resulting file names +//@ include the base directories, e.g. `lib/resources/file1` instead of just `file1`. +function _find(options, paths) { + if (!paths) + common.error('no path specified'); + else if (typeof paths === 'object') + paths = paths; // assume array + else if (typeof paths === 'string') + paths = [].slice.call(arguments, 1); + + var list = []; + + function pushFile(file) { + if (common.platform === 'win') + file = file.replace(/\\/g, '/'); + list.push(file); + } + + // why not simply do ls('-R', paths)? because the output wouldn't give the base dirs + // to get the base dir in the output, we need instead ls('-R', 'dir/*') for every directory + + paths.forEach(function(file) { + pushFile(file); + + if (fs.statSync(file).isDirectory()) { + _ls('-RA', file+'/*').forEach(function(subfile) { + pushFile(subfile); + }); + } + }); + + return list; +} +module.exports = _find; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/grep.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/grep.js new file mode 100644 index 000000000..00c7d6a40 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/grep.js @@ -0,0 +1,52 @@ +var common = require('./common'); +var fs = require('fs'); + +//@ +//@ ### grep([options ,] regex_filter, file [, file ...]) +//@ ### grep([options ,] regex_filter, file_array) +//@ Available options: +//@ +//@ + `-v`: Inverse the sense of the regex and print the lines not matching the criteria. +//@ +//@ Examples: +//@ +//@ ```javascript +//@ grep('-v', 'GLOBAL_VARIABLE', '*.js'); +//@ grep('GLOBAL_VARIABLE', '*.js'); +//@ ``` +//@ +//@ Reads input string from given files and returns a string containing all lines of the +//@ file that match the given `regex_filter`. Wildcard `*` accepted. +function _grep(options, regex, files) { + options = common.parseOptions(options, { + 'v': 'inverse' + }); + + if (!files) + common.error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 2); + // if it's array leave it as it is + + files = common.expand(files); + + var grep = ''; + files.forEach(function(file) { + if (!fs.existsSync(file)) { + common.error('no such file or directory: ' + file, true); + return; + } + + var contents = fs.readFileSync(file, 'utf8'), + lines = contents.split(/\r*\n/); + lines.forEach(function(line) { + var matched = line.match(regex); + if ((options.inverse && !matched) || (!options.inverse && matched)) + grep += line + '\n'; + }); + }); + + return common.ShellString(grep); +} +module.exports = _grep; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/ls.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/ls.js new file mode 100644 index 000000000..3345db446 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/ls.js @@ -0,0 +1,126 @@ +var path = require('path'); +var fs = require('fs'); +var common = require('./common'); +var _cd = require('./cd'); +var _pwd = require('./pwd'); + +//@ +//@ ### ls([options ,] path [,path ...]) +//@ ### ls([options ,] path_array) +//@ Available options: +//@ +//@ + `-R`: recursive +//@ + `-A`: all files (include files beginning with `.`, except for `.` and `..`) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ ls('projs/*.js'); +//@ ls('-R', '/users/me', '/tmp'); +//@ ls('-R', ['/users/me', '/tmp']); // same as above +//@ ``` +//@ +//@ Returns array of files in the given path, or in current directory if no path provided. +function _ls(options, paths) { + options = common.parseOptions(options, { + 'R': 'recursive', + 'A': 'all', + 'a': 'all_deprecated' + }); + + if (options.all_deprecated) { + // We won't support the -a option as it's hard to image why it's useful + // (it includes '.' and '..' in addition to '.*' files) + // For backwards compatibility we'll dump a deprecated message and proceed as before + common.log('ls: Option -a is deprecated. Use -A instead'); + options.all = true; + } + + if (!paths) + paths = ['.']; + else if (typeof paths === 'object') + paths = paths; // assume array + else if (typeof paths === 'string') + paths = [].slice.call(arguments, 1); + + var list = []; + + // Conditionally pushes file to list - returns true if pushed, false otherwise + // (e.g. prevents hidden files to be included unless explicitly told so) + function pushFile(file, query) { + // hidden file? + if (path.basename(file)[0] === '.') { + // not explicitly asking for hidden files? + if (!options.all && !(path.basename(query)[0] === '.' && path.basename(query).length > 1)) + return false; + } + + if (common.platform === 'win') + file = file.replace(/\\/g, '/'); + + list.push(file); + return true; + } + + paths.forEach(function(p) { + if (fs.existsSync(p)) { + var stats = fs.statSync(p); + // Simple file? + if (stats.isFile()) { + pushFile(p, p); + return; // continue + } + + // Simple dir? + if (stats.isDirectory()) { + // Iterate over p contents + fs.readdirSync(p).forEach(function(file) { + if (!pushFile(file, p)) + return; + + // Recursive? + if (options.recursive) { + var oldDir = _pwd(); + _cd('', p); + if (fs.statSync(file).isDirectory()) + list = list.concat(_ls('-R'+(options.all?'A':''), file+'/*')); + _cd('', oldDir); + } + }); + return; // continue + } + } + + // p does not exist - possible wildcard present + + var basename = path.basename(p); + var dirname = path.dirname(p); + // Wildcard present on an existing dir? (e.g. '/tmp/*.js') + if (basename.search(/\*/) > -1 && fs.existsSync(dirname) && fs.statSync(dirname).isDirectory) { + // Escape special regular expression chars + var regexp = basename.replace(/(\^|\$|\(|\)|<|>|\[|\]|\{|\}|\.|\+|\?)/g, '\\$1'); + // Translates wildcard into regex + regexp = '^' + regexp.replace(/\*/g, '.*') + '$'; + // Iterate over directory contents + fs.readdirSync(dirname).forEach(function(file) { + if (file.match(new RegExp(regexp))) { + if (!pushFile(path.normalize(dirname+'/'+file), basename)) + return; + + // Recursive? + if (options.recursive) { + var pp = dirname + '/' + file; + if (fs.lstatSync(pp).isDirectory()) + list = list.concat(_ls('-R'+(options.all?'A':''), pp+'/*')); + } // recursive + } // if file matches + }); // forEach + return; + } + + common.error('no such file or directory: ' + p, true); + }); + + return list; +} +module.exports = _ls; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mkdir.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mkdir.js new file mode 100644 index 000000000..5a7088f26 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mkdir.js @@ -0,0 +1,68 @@ +var common = require('./common'); +var fs = require('fs'); +var path = require('path'); + +// Recursively creates 'dir' +function mkdirSyncRecursive(dir) { + var baseDir = path.dirname(dir); + + // Base dir exists, no recursion necessary + if (fs.existsSync(baseDir)) { + fs.mkdirSync(dir, parseInt('0777', 8)); + return; + } + + // Base dir does not exist, go recursive + mkdirSyncRecursive(baseDir); + + // Base dir created, can create dir + fs.mkdirSync(dir, parseInt('0777', 8)); +} + +//@ +//@ ### mkdir([options ,] dir [, dir ...]) +//@ ### mkdir([options ,] dir_array) +//@ Available options: +//@ +//@ + `p`: full path (will create intermediate dirs if necessary) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); +//@ mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above +//@ ``` +//@ +//@ Creates directories. +function _mkdir(options, dirs) { + options = common.parseOptions(options, { + 'p': 'fullpath' + }); + if (!dirs) + common.error('no paths given'); + + if (typeof dirs === 'string') + dirs = [].slice.call(arguments, 1); + // if it's array leave it as it is + + dirs.forEach(function(dir) { + if (fs.existsSync(dir)) { + if (!options.fullpath) + common.error('path already exists: ' + dir, true); + return; // skip dir + } + + // Base dir does not exist, and no -p option given + var baseDir = path.dirname(dir); + if (!fs.existsSync(baseDir) && !options.fullpath) { + common.error('no such file or directory: ' + baseDir, true); + return; // skip dir + } + + if (options.fullpath) + mkdirSyncRecursive(dir); + else + fs.mkdirSync(dir, parseInt('0777', 8)); + }); +} // mkdir +module.exports = _mkdir; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mv.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mv.js new file mode 100644 index 000000000..11f960718 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/mv.js @@ -0,0 +1,80 @@ +var fs = require('fs'); +var path = require('path'); +var common = require('./common'); + +//@ +//@ ### mv(source [, source ...], dest') +//@ ### mv(source_array, dest') +//@ Available options: +//@ +//@ + `f`: force +//@ +//@ Examples: +//@ +//@ ```javascript +//@ mv('-f', 'file', 'dir/'); +//@ mv('file1', 'file2', 'dir/'); +//@ mv(['file1', 'file2'], 'dir/'); // same as above +//@ ``` +//@ +//@ Moves files. The wildcard `*` is accepted. +function _mv(options, sources, dest) { + options = common.parseOptions(options, { + 'f': 'force' + }); + + // Get sources, dest + if (arguments.length < 3) { + common.error('missing and/or '); + } else if (arguments.length > 3) { + sources = [].slice.call(arguments, 1, arguments.length - 1); + dest = arguments[arguments.length - 1]; + } else if (typeof sources === 'string') { + sources = [sources]; + } else if ('length' in sources) { + sources = sources; // no-op for array + } else { + common.error('invalid arguments'); + } + + sources = common.expand(sources); + + var exists = fs.existsSync(dest), + stats = exists && fs.statSync(dest); + + // Dest is not existing dir, but multiple sources given + if ((!exists || !stats.isDirectory()) && sources.length > 1) + common.error('dest is not a directory (too many sources)'); + + // Dest is an existing file, but no -f given + if (exists && stats.isFile() && !options.force) + common.error('dest file already exists: ' + dest); + + sources.forEach(function(src) { + if (!fs.existsSync(src)) { + common.error('no such file or directory: '+src, true); + return; // skip file + } + + // If here, src exists + + // When copying to '/path/dir': + // thisDest = '/path/dir/file1' + var thisDest = dest; + if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) + thisDest = path.normalize(dest + '/' + path.basename(src)); + + if (fs.existsSync(thisDest) && !options.force) { + common.error('dest file already exists: ' + thisDest, true); + return; // skip file + } + + if (path.resolve(src) === path.dirname(path.resolve(thisDest))) { + common.error('cannot move to self: '+src, true); + return; // skip file + } + + fs.renameSync(src, thisDest); + }); // forEach(src) +} // mv +module.exports = _mv; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/popd.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/popd.js new file mode 100644 index 000000000..11ea24fa4 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/popd.js @@ -0,0 +1 @@ +// see dirs.js \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pushd.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pushd.js new file mode 100644 index 000000000..11ea24fa4 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pushd.js @@ -0,0 +1 @@ +// see dirs.js \ No newline at end of file diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pwd.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pwd.js new file mode 100644 index 000000000..41727bb91 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/pwd.js @@ -0,0 +1,11 @@ +var path = require('path'); +var common = require('./common'); + +//@ +//@ ### pwd() +//@ Returns the current directory. +function _pwd(options) { + var pwd = path.resolve(process.cwd()); + return common.ShellString(pwd); +} +module.exports = _pwd; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/rm.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/rm.js new file mode 100644 index 000000000..3abe6e1d0 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/rm.js @@ -0,0 +1,145 @@ +var common = require('./common'); +var fs = require('fs'); + +// Recursively removes 'dir' +// Adapted from https://github.com/ryanmcgrath/wrench-js +// +// Copyright (c) 2010 Ryan McGrath +// Copyright (c) 2012 Artur Adib +// +// Licensed under the MIT License +// http://www.opensource.org/licenses/mit-license.php +function rmdirSyncRecursive(dir, force) { + var files; + + files = fs.readdirSync(dir); + + // Loop through and delete everything in the sub-tree after checking it + for(var i = 0; i < files.length; i++) { + var file = dir + "/" + files[i], + currFile = fs.lstatSync(file); + + if(currFile.isDirectory()) { // Recursive function back to the beginning + rmdirSyncRecursive(file, force); + } + + else if(currFile.isSymbolicLink()) { // Unlink symlinks + if (force || isWriteable(file)) { + try { + common.unlinkSync(file); + } catch (e) { + common.error('could not remove file (code '+e.code+'): ' + file, true); + } + } + } + + else // Assume it's a file - perhaps a try/catch belongs here? + if (force || isWriteable(file)) { + try { + common.unlinkSync(file); + } catch (e) { + common.error('could not remove file (code '+e.code+'): ' + file, true); + } + } + } + + // Now that we know everything in the sub-tree has been deleted, we can delete the main directory. + // Huzzah for the shopkeep. + + var result; + try { + result = fs.rmdirSync(dir); + } catch(e) { + common.error('could not remove directory (code '+e.code+'): ' + dir, true); + } + + return result; +} // rmdirSyncRecursive + +// Hack to determine if file has write permissions for current user +// Avoids having to check user, group, etc, but it's probably slow +function isWriteable(file) { + var writePermission = true; + try { + var __fd = fs.openSync(file, 'a'); + fs.closeSync(__fd); + } catch(e) { + writePermission = false; + } + + return writePermission; +} + +//@ +//@ ### rm([options ,] file [, file ...]) +//@ ### rm([options ,] file_array) +//@ Available options: +//@ +//@ + `-f`: force +//@ + `-r, -R`: recursive +//@ +//@ Examples: +//@ +//@ ```javascript +//@ rm('-rf', '/tmp/*'); +//@ rm('some_file.txt', 'another_file.txt'); +//@ rm(['some_file.txt', 'another_file.txt']); // same as above +//@ ``` +//@ +//@ Removes files. The wildcard `*` is accepted. +function _rm(options, files) { + options = common.parseOptions(options, { + 'f': 'force', + 'r': 'recursive', + 'R': 'recursive' + }); + if (!files) + common.error('no paths given'); + + if (typeof files === 'string') + files = [].slice.call(arguments, 1); + // if it's array leave it as it is + + files = common.expand(files); + + files.forEach(function(file) { + if (!fs.existsSync(file)) { + // Path does not exist, no force flag given + if (!options.force) + common.error('no such file or directory: '+file, true); + + return; // skip file + } + + // If here, path exists + + var stats = fs.lstatSync(file); + if (stats.isFile() || stats.isSymbolicLink()) { + + // Do not check for file writing permissions + if (options.force) { + common.unlinkSync(file); + return; + } + + if (isWriteable(file)) + common.unlinkSync(file); + else + common.error('permission denied: '+file, true); + + return; + } // simple file + + // Path is an existing directory, but no -r flag given + if (stats.isDirectory() && !options.recursive) { + common.error('path is a directory', true); + return; // skip path + } + + // Recursively remove existing directory + if (stats.isDirectory() && options.recursive) { + rmdirSyncRecursive(file, options.force); + } + }); // forEach(file) +} // rm +module.exports = _rm; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/sed.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/sed.js new file mode 100644 index 000000000..97832524a --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/sed.js @@ -0,0 +1,43 @@ +var common = require('./common'); +var fs = require('fs'); + +//@ +//@ ### sed([options ,] search_regex, replace_str, file) +//@ Available options: +//@ +//@ + `-i`: Replace contents of 'file' in-place. _Note that no backups will be created!_ +//@ +//@ Examples: +//@ +//@ ```javascript +//@ sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); +//@ sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); +//@ ``` +//@ +//@ Reads an input string from `file` and performs a JavaScript `replace()` on the input +//@ using the given search regex and replacement string. Returns the new string after replacement. +function _sed(options, regex, replacement, file) { + options = common.parseOptions(options, { + 'i': 'inplace' + }); + + if (typeof replacement === 'string') + replacement = replacement; // no-op + else if (typeof replacement === 'number') + replacement = replacement.toString(); // fallback + else + common.error('invalid replacement string'); + + if (!file) + common.error('no file given'); + + if (!fs.existsSync(file)) + common.error('no such file or directory: ' + file); + + var result = fs.readFileSync(file, 'utf8').replace(regex, replacement); + if (options.inplace) + fs.writeFileSync(file, result, 'utf8'); + + return common.ShellString(result); +} +module.exports = _sed; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/tempdir.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/tempdir.js new file mode 100644 index 000000000..45953c24e --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/tempdir.js @@ -0,0 +1,56 @@ +var common = require('./common'); +var os = require('os'); +var fs = require('fs'); + +// Returns false if 'dir' is not a writeable directory, 'dir' otherwise +function writeableDir(dir) { + if (!dir || !fs.existsSync(dir)) + return false; + + if (!fs.statSync(dir).isDirectory()) + return false; + + var testFile = dir+'/'+common.randomFileName(); + try { + fs.writeFileSync(testFile, ' '); + common.unlinkSync(testFile); + return dir; + } catch (e) { + return false; + } +} + + +//@ +//@ ### tempdir() +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var tmp = tempdir(); // "/tmp" for most *nix platforms +//@ ``` +//@ +//@ Searches and returns string containing a writeable, platform-dependent temporary directory. +//@ Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). +function _tempDir() { + var state = common.state; + if (state.tempDir) + return state.tempDir; // from cache + + state.tempDir = writeableDir(os.tempDir && os.tempDir()) || // node 0.8+ + writeableDir(process.env['TMPDIR']) || + writeableDir(process.env['TEMP']) || + writeableDir(process.env['TMP']) || + writeableDir(process.env['Wimp$ScrapDir']) || // RiscOS + writeableDir('C:\\TEMP') || // Windows + writeableDir('C:\\TMP') || // Windows + writeableDir('\\TEMP') || // Windows + writeableDir('\\TMP') || // Windows + writeableDir('/tmp') || + writeableDir('/var/tmp') || + writeableDir('/usr/tmp') || + writeableDir('.'); // last resort + + return state.tempDir; +} +module.exports = _tempDir; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/test.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/test.js new file mode 100644 index 000000000..8a4ac7d4d --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/test.js @@ -0,0 +1,85 @@ +var common = require('./common'); +var fs = require('fs'); + +//@ +//@ ### test(expression) +//@ Available expression primaries: +//@ +//@ + `'-b', 'path'`: true if path is a block device +//@ + `'-c', 'path'`: true if path is a character device +//@ + `'-d', 'path'`: true if path is a directory +//@ + `'-e', 'path'`: true if path exists +//@ + `'-f', 'path'`: true if path is a regular file +//@ + `'-L', 'path'`: true if path is a symboilc link +//@ + `'-p', 'path'`: true if path is a pipe (FIFO) +//@ + `'-S', 'path'`: true if path is a socket +//@ +//@ Examples: +//@ +//@ ```javascript +//@ if (test('-d', path)) { /* do something with dir */ }; +//@ if (!test('-f', path)) continue; // skip if it's a regular file +//@ ``` +//@ +//@ Evaluates expression using the available primaries and returns corresponding value. +function _test(options, path) { + if (!path) + common.error('no path given'); + + // hack - only works with unary primaries + options = common.parseOptions(options, { + 'b': 'block', + 'c': 'character', + 'd': 'directory', + 'e': 'exists', + 'f': 'file', + 'L': 'link', + 'p': 'pipe', + 'S': 'socket' + }); + + var canInterpret = false; + for (var key in options) + if (options[key] === true) { + canInterpret = true; + break; + } + + if (!canInterpret) + common.error('could not interpret expression'); + + if (options.link) { + try { + return fs.lstatSync(path).isSymbolicLink(); + } catch(e) { + return false; + } + } + + if (!fs.existsSync(path)) + return false; + + if (options.exists) + return true; + + var stats = fs.statSync(path); + + if (options.block) + return stats.isBlockDevice(); + + if (options.character) + return stats.isCharacterDevice(); + + if (options.directory) + return stats.isDirectory(); + + if (options.file) + return stats.isFile(); + + if (options.pipe) + return stats.isFIFO(); + + if (options.socket) + return stats.isSocket(); +} // test +module.exports = _test; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/to.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/to.js new file mode 100644 index 000000000..f0299993a --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/to.js @@ -0,0 +1,29 @@ +var common = require('./common'); +var fs = require('fs'); +var path = require('path'); + +//@ +//@ ### 'string'.to(file) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cat('input.txt').to('output.txt'); +//@ ``` +//@ +//@ Analogous to the redirection operator `>` in Unix, but works with JavaScript strings (such as +//@ those returned by `cat`, `grep`, etc). _Like Unix redirections, `to()` will overwrite any existing file!_ +function _to(options, file) { + if (!file) + common.error('wrong arguments'); + + if (!fs.existsSync( path.dirname(file) )) + common.error('no such file or directory: ' + path.dirname(file)); + + try { + fs.writeFileSync(file, this.toString(), 'utf8'); + } catch(e) { + common.error('could not write to file (code '+e.code+'): '+file, true); + } +} +module.exports = _to; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/toEnd.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/toEnd.js new file mode 100644 index 000000000..f6d099d9a --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/toEnd.js @@ -0,0 +1,29 @@ +var common = require('./common'); +var fs = require('fs'); +var path = require('path'); + +//@ +//@ ### 'string'.toEnd(file) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ cat('input.txt').toEnd('output.txt'); +//@ ``` +//@ +//@ Analogous to the redirect-and-append operator `>>` in Unix, but works with JavaScript strings (such as +//@ those returned by `cat`, `grep`, etc). +function _toEnd(options, file) { + if (!file) + common.error('wrong arguments'); + + if (!fs.existsSync( path.dirname(file) )) + common.error('no such file or directory: ' + path.dirname(file)); + + try { + fs.appendFileSync(file, this.toString(), 'utf8'); + } catch(e) { + common.error('could not append to file (code '+e.code+'): '+file, true); + } +} +module.exports = _toEnd; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/which.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/which.js new file mode 100644 index 000000000..fadb96cd3 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/node_modules/shelljs/src/which.js @@ -0,0 +1,79 @@ +var common = require('./common'); +var fs = require('fs'); +var path = require('path'); + +// Cross-platform method for splitting environment PATH variables +function splitPath(p) { + for (i=1;i<2;i++) {} + + if (!p) + return []; + + if (common.platform === 'win') + return p.split(';'); + else + return p.split(':'); +} + +//@ +//@ ### which(command) +//@ +//@ Examples: +//@ +//@ ```javascript +//@ var nodeExec = which('node'); +//@ ``` +//@ +//@ Searches for `command` in the system's PATH. On Windows looks for `.exe`, `.cmd`, and `.bat` extensions. +//@ Returns string containing the absolute path to the command. +function _which(options, cmd) { + if (!cmd) + common.error('must specify command'); + + var pathEnv = process.env.path || process.env.Path || process.env.PATH, + pathArray = splitPath(pathEnv), + where = null; + + // No relative/absolute paths provided? + if (cmd.search(/\//) === -1) { + // Search for command in PATH + pathArray.forEach(function(dir) { + if (where) + return; // already found it + + var attempt = path.resolve(dir + '/' + cmd); + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + + if (common.platform === 'win') { + var baseAttempt = attempt; + attempt = baseAttempt + '.exe'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + attempt = baseAttempt + '.cmd'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + attempt = baseAttempt + '.bat'; + if (fs.existsSync(attempt)) { + where = attempt; + return; + } + } // if 'win' + }); + } + + // Command not found anywhere? + if (!fs.existsSync(cmd) && !where) + return null; + + where = where || path.resolve(cmd); + + return common.ShellString(where); +} +module.exports = _which; diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/package.json b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/package.json new file mode 100644 index 000000000..55762cc8e --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/package.json @@ -0,0 +1,54 @@ +{ + "name": "dns-sync", + "version": "0.1.0", + "description": "dns-sync", + "main": "index.js", + "scripts": { + "test": "make test" + }, + "homepage": "https://github.com/skoranga/node-dns-sync", + "repository": { + "type": "git", + "url": "git@github.com:skoranga/node-dns-sync.git" + }, + "keywords": [ + "dns sync", + "server startup", + "nodejs" + ], + "author": { + "name": "Sanjeev Koranga" + }, + "license": "MIT", + "dependencies": { + "debug": "~0.7", + "shelljs": "~0.2" + }, + "devDependencies": { + "mocha": "~1", + "jshint": "*" + }, + "bugs": { + "url": "https://github.com/skoranga/node-dns-sync/issues" + }, + "_id": "dns-sync@0.1.0", + "dist": { + "shasum": "9c2b193b78d18772b8a08fe3ab8104ddc93d6dc0", + "tarball": "http://registry.npmjs.org/dns-sync/-/dns-sync-0.1.0.tgz" + }, + "_from": "dns-sync@0.1.0", + "_npmVersion": "1.4.3", + "_npmUser": { + "name": "skoranga", + "email": "skoranga@paypal.com" + }, + "maintainers": [ + { + "name": "skoranga", + "email": "skoranga@paypal.com" + } + ], + "directories": {}, + "_shasum": "9c2b193b78d18772b8a08fe3ab8104ddc93d6dc0", + "_resolved": "https://registry.npmjs.org/dns-sync/-/dns-sync-0.1.0.tgz" +} diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/scripts/dns-lookup-script.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/scripts/dns-lookup-script.js new file mode 100644 index 000000000..9fc28fc44 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/scripts/dns-lookup-script.js @@ -0,0 +1,15 @@ +'use strict'; + +var dns = require('dns'), + name = process.argv[2], + debug = require('debug')('dns-sync'); + +dns.lookup(name, function (err, ip) { + if (err) { + process.exit(1); + debug(err); + } else { + debug(name, 'resolved to', ip); + process.stdout.write(ip); + } +}); diff --git a/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/test/test.js b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/test/test.js new file mode 100644 index 000000000..7a0a81582 --- /dev/null +++ b/dependency-check-core/src/test/resources/nodejs/node_modules/dns-sync/test/test.js @@ -0,0 +1,19 @@ +'use strict'; + +var assert = require('assert'), + dnsSync = require('../index'); + +describe('dns sync', function () { + + it('should resolve dns', function () { + assert.ok(dnsSync.resolve('www.paypal.com')); + assert.ok(dnsSync.resolve('www.google.com')); + assert.ok(dnsSync.resolve('www.yahoo.com')); + }); + + it('should fail to resolve dns', function () { + assert.ok(!dnsSync.resolve('www.paypal.con')); + assert.ok(!dnsSync.resolve('www.not-google.first')); + assert.ok(!dnsSync.resolve('www.hello-yahoo.next')); + }); +}); diff --git a/dependency-check-gradle/README.md b/dependency-check-gradle/README.md index 7707db3ec..6c931ecf1 100644 --- a/dependency-check-gradle/README.md +++ b/dependency-check-gradle/README.md @@ -7,17 +7,18 @@ This is a DependencyCheck gradle plugin designed for project which use Gradle as Dependency-Check is a utility that attempts to detect publicly disclosed vulnerabilities contained within project dependencies. It does this by determining if there is a Common Platform Enumeration (CPE) identifier for a given dependency. If found, it will generate a report linking to the associated CVE entries. -Current latest version is `0.0.6` - ========= +## What's New +Current latest version is `0.0.7` +- Implement nested configuration for proxy settings +- Bug fix: Remove duplicated configuration items + ## Usage ### Step 1, Apply dependency check gradle plugin -Please refer to either one of the solution - -#### Solution 1,Install from Maven Central (Recommended) +Install from Maven central repo ```groovy buildscript { @@ -25,65 +26,16 @@ buildscript { mavenCentral() } dependencies { - classpath 'com.thoughtworks.tools:dependency-check:0.0.6' + classpath 'com.thoughtworks.tools:dependency-check:0.0.7' } } -``` apply plugin: 'dependency.check' - -#### Solution 2,Install from Gradle Plugin Portal - -[dependency check gradle plugin on Gradle Plugin Portal](https://plugins.gradle.org/plugin/dependency.check) - -**Build script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:** - -```groovy -plugins { - id "dependency.check" version "0.0.6" -} -``` - -**Build script snippet for use in all Gradle versions:** - -```groovy -buildscript { - repositories { - maven { - url "https://plugins.gradle.org/m2/" - } - } - dependencies { - classpath "gradle.plugin.com.tools.security:dependency-check:0.0.6" - } -} - -apply plugin: "dependency-check" -``` - -#### Solution 3,Install from Bintray - -```groovy -apply plugin: "dependency-check" - -buildscript { - repositories { - maven { - url 'http://dl.bintray.com/wei/maven' - } - mavenCentral() - } - dependencies { - classpath( - 'com.tools.security:dependency-check:0.0.6' - ) - } -} ``` ### Step 2, Run gradle task -Once gradle plugin applied, run following gradle task to check the dependencies: +Once gradle plugin applied, run following gradle task to check dependencies: ``` gradle dependencyCheck @@ -106,14 +58,16 @@ Maybe you have to use proxy to access internet, in this case, you could configur ```groovy dependencyCheck { - proxyServer = "127.0.0.1" // required, the server name or IP address of the proxy - proxyPort = 3128 // required, the port number of the proxy - - // optional, the proxy server might require username - // proxyUsername = "username" - - // optional, the proxy server might require password - // proxyPassword = "password" + proxy { + server = "127.0.0.1" // required, the server name or IP address of the proxy + port = 3128 // required, the port number of the proxy + + // optional, the proxy server might require username + // username = "username" + + // optional, the proxy server might require password + // password = "password" + } } ``` @@ -123,9 +77,6 @@ In addition, if the proxy only allow HTTP `GET` or `POST` methods, you will find ```groovy dependencyCheck { - proxyServer = "127.0.0.1" // required, the server name or IP address of the proxy - proxyPort = 3128 // required, the port number of the proxy - quickQueryTimestamp = false // when set to false, it means use HTTP GET method to query timestamp. (default value is true) } ``` @@ -142,7 +93,7 @@ buildscript { mavenCentral() } dependencies { - classpath "gradle.plugin.com.tools.security:dependency-check:0.0.6" + classpath "gradle.plugin.com.tools.security:dependency-check:0.0.7" } } @@ -159,7 +110,7 @@ buildscript { mavenCentral() } dependencies { - classpath "gradle.plugin.com.tools.security:dependency-check:0.0.6" + classpath "gradle.plugin.com.tools.security:dependency-check:0.0.7" } } diff --git a/dependency-check-gradle/build.gradle b/dependency-check-gradle/build.gradle index 18f7454a7..13508a3c4 100644 --- a/dependency-check-gradle/build.gradle +++ b/dependency-check-gradle/build.gradle @@ -73,7 +73,9 @@ task integTest(type: Test) { } group = 'com.thoughtworks.tools' -version = '0.0.6' +version = '0.0.7' + +targetCompatibility = 1.7 apply from: 'conf/publish/local.gradle' //apply from: 'conf/publish/maven.gradle' diff --git a/dependency-check-gradle/src/main/groovy/com/tools/security/extension/CveExtension.groovy b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/CveExtension.groovy new file mode 100644 index 000000000..a91eee97f --- /dev/null +++ b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/CveExtension.groovy @@ -0,0 +1,27 @@ +/* + * This file is part of dependency-check-gradle. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (c) 2015 Wei Ma. All Rights Reserved. + */ + +package com.tools.security.extension + +class CveExtension { + String url20Modified + String url12Modified + Integer startYear + String url20Base + String url12Base +} diff --git a/dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckConfigurationExtension.groovy b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckExtension.groovy similarity index 57% rename from dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckConfigurationExtension.groovy rename to dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckExtension.groovy index e86f66e25..e38f63dee 100644 --- a/dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckConfigurationExtension.groovy +++ b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/DependencyCheckExtension.groovy @@ -18,19 +18,10 @@ package com.tools.security.extension -class DependencyCheckConfigurationExtension { - String proxyServer - Integer proxyPort - String proxyUsername = "" - String proxyPassword = "" - - String cveUrl12Modified = "https://nvd.nist.gov/download/nvdcve-Modified.xml.gz" - String cveUrl20Modified = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-Modified.xml.gz" - Integer cveStartYear = 2002 - String cveUrl12Base = "https://nvd.nist.gov/download/nvdcve-%d.xml.gz" - String cveUrl20Base = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml.gz" +class DependencyCheckExtension { + ProxyExtension proxyExtension + CveExtension cveExtension String outputDirectory = "./reports" - - Boolean quickQueryTimestamp = true; + Boolean quickQueryTimestamp; } diff --git a/dependency-check-gradle/src/main/groovy/com/tools/security/extension/ProxyExtension.groovy b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/ProxyExtension.groovy new file mode 100644 index 000000000..97763ad76 --- /dev/null +++ b/dependency-check-gradle/src/main/groovy/com/tools/security/extension/ProxyExtension.groovy @@ -0,0 +1,26 @@ +/* + * This file is part of dependency-check-gradle. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (c) 2015 Wei Ma. All Rights Reserved. + */ + +package com.tools.security.extension + +class ProxyExtension { + String server + Integer port + String username + String password +} diff --git a/dependency-check-gradle/src/main/groovy/com/tools/security/plugin/DependencyCheckGradlePlugin.groovy b/dependency-check-gradle/src/main/groovy/com/tools/security/plugin/DependencyCheckGradlePlugin.groovy index 2274c9af4..a1f94a13c 100644 --- a/dependency-check-gradle/src/main/groovy/com/tools/security/plugin/DependencyCheckGradlePlugin.groovy +++ b/dependency-check-gradle/src/main/groovy/com/tools/security/plugin/DependencyCheckGradlePlugin.groovy @@ -18,13 +18,18 @@ package com.tools.security.plugin -import com.tools.security.extension.DependencyCheckConfigurationExtension +import com.tools.security.extension.CveExtension +import com.tools.security.extension.DependencyCheckExtension +import com.tools.security.extension.ProxyExtension import com.tools.security.tasks.DependencyCheckTask import org.gradle.api.Plugin import org.gradle.api.Project class DependencyCheckGradlePlugin implements Plugin { - static final String EXTENSION_NAME = 'dependencyCheck' + private static final String ROOT_EXTENSION_NAME = 'dependencyCheck' + private static final String TASK_NAME = 'dependencyCheck' + private static final String PROXY_EXTENSION_NAME = "proxy" + private static final String CVE_EXTENSION_NAME = "cve" @Override void apply(Project project) { @@ -33,23 +38,12 @@ class DependencyCheckGradlePlugin implements Plugin { } def initializeConfigurations(Project project) { - project.extensions.create(EXTENSION_NAME, DependencyCheckConfigurationExtension) + project.extensions.create(ROOT_EXTENSION_NAME, DependencyCheckExtension) + project.dependencyCheck.extensions.create(PROXY_EXTENSION_NAME, ProxyExtension) + project.dependencyCheck.extensions.create(CVE_EXTENSION_NAME, CveExtension) } def registerTasks(Project project) { - project.task('dependencyCheck', type: DependencyCheckTask) { - def extension = project.extensions.findByName(EXTENSION_NAME) - conventionMapping.proxyServer = { extension.proxyServer } - conventionMapping.proxyPort = { extension.proxyPort } - conventionMapping.proxyUsername = { extension.proxyUsername } - conventionMapping.proxyPassword = { extension.proxyPassword } - conventionMapping.cveUrl12Modified = { extension.cveUrl12Modified } - conventionMapping.cveUrl20Modified = { extension.cveUrl20Modified } - conventionMapping.cveStartYear = { extension.cveStartYear } - conventionMapping.cveUrl12Base = { extension.cveUrl12Base } - conventionMapping.cveUrl20Base = { extension.cveUrl20Base } - conventionMapping.outputDirectory = { extension.outputDirectory } - conventionMapping.quickQueryTimestamp = { extension.quickQueryTimestamp } - } + project.task(TASK_NAME, type: DependencyCheckTask) } } \ No newline at end of file diff --git a/dependency-check-gradle/src/main/groovy/com/tools/security/tasks/DependencyCheckTask.groovy b/dependency-check-gradle/src/main/groovy/com/tools/security/tasks/DependencyCheckTask.groovy index 3e371ec81..e81e89e01 100644 --- a/dependency-check-gradle/src/main/groovy/com/tools/security/tasks/DependencyCheckTask.groovy +++ b/dependency-check-gradle/src/main/groovy/com/tools/security/tasks/DependencyCheckTask.groovy @@ -28,27 +28,23 @@ import org.owasp.dependencycheck.dependency.Dependency import org.owasp.dependencycheck.reporting.ReportGenerator import org.owasp.dependencycheck.utils.Settings +import static org.owasp.dependencycheck.utils.Settings.KEYS.CVE_MODIFIED_12_URL +import static org.owasp.dependencycheck.utils.Settings.KEYS.CVE_MODIFIED_20_URL +import static org.owasp.dependencycheck.utils.Settings.KEYS.CVE_SCHEMA_1_2 +import static org.owasp.dependencycheck.utils.Settings.KEYS.CVE_SCHEMA_2_0 +import static org.owasp.dependencycheck.utils.Settings.KEYS.CVE_START_YEAR +import static org.owasp.dependencycheck.utils.Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP +import static org.owasp.dependencycheck.utils.Settings.KEYS.PROXY_PASSWORD +import static org.owasp.dependencycheck.utils.Settings.KEYS.PROXY_PORT +import static org.owasp.dependencycheck.utils.Settings.KEYS.PROXY_SERVER +import static org.owasp.dependencycheck.utils.Settings.KEYS.PROXY_USERNAME import static org.owasp.dependencycheck.utils.Settings.setBoolean import static org.owasp.dependencycheck.utils.Settings.setString class DependencyCheckTask extends DefaultTask { def currentProjectName = project.getName() - - String proxyServer - Integer proxyPort - String proxyUsername = "" - String proxyPassword = "" - - String cveUrl12Modified = "https://nvd.nist.gov/download/nvdcve-Modified.xml.gz" - String cveUrl20Modified = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-Modified.xml.gz" - Integer cveStartYear = 2002 - String cveUrl12Base = "https://nvd.nist.gov/download/nvdcve-%d.xml.gz" - String cveUrl20Base = "https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml.gz" - - String outputDirectory = "./reports" - - Boolean quickQueryTimestamp = true; + def config = project.dependencyCheck DependencyCheckTask() { group = 'Dependency Check' @@ -111,22 +107,22 @@ class DependencyCheckTask extends DefaultTask { } def generateReportDirectory(String currentProjectName) { - "${getOutputDirectory()}/${currentProjectName}" + "${config.outputDirectory}/${currentProjectName}" } def overrideProxySetting() { if (isProxySettingExist()) { - logger.lifecycle("Using proxy ${getProxyServer()}:${getProxyPort()}") + logger.lifecycle("Using proxy ${config.proxy.server}:${config.proxy.port}") - setString(Settings.KEYS.PROXY_SERVER, getProxyServer()) - setString(Settings.KEYS.PROXY_PORT, "${getProxyPort()}") - setString(Settings.KEYS.PROXY_USERNAME, getProxyUsername()) - setString(Settings.KEYS.PROXY_PASSWORD, getProxyPassword()) + overrideStringSetting(PROXY_SERVER, config.proxy.server) + overrideStringSetting(PROXY_PORT, "${config.proxy.port}") + overrideStringSetting(PROXY_USERNAME, config.proxy.username) + overrideStringSetting(PROXY_PASSWORD, config.proxy.password) } } def isProxySettingExist() { - getProxyServer() != null && getProxyPort() != null + config.proxy.server != null && config.proxy.port != null } def getAllDependencies(project) { @@ -138,14 +134,35 @@ class DependencyCheckTask extends DefaultTask { } def overrideCveUrlSetting() { - setString(Settings.KEYS.CVE_MODIFIED_20_URL, getCveUrl20Modified()) - setString(Settings.KEYS.CVE_MODIFIED_12_URL, getCveUrl12Modified()) - setString(Settings.KEYS.CVE_START_YEAR, "${getCveStartYear()}") - setString(Settings.KEYS.CVE_SCHEMA_2_0, getCveUrl20Base()) - setString(Settings.KEYS.CVE_SCHEMA_1_2, getCveUrl12Base()) + overrideStringSetting(CVE_MODIFIED_20_URL, config.cve.url20Modified) + overrideStringSetting(CVE_MODIFIED_12_URL, config.cve.url12Modified) + overrideIntegerSetting(CVE_START_YEAR, config.cve.startYear) + overrideStringSetting(CVE_SCHEMA_2_0, config.cve.url20Base) + overrideStringSetting(CVE_SCHEMA_1_2, config.cve.url12Base) } def overrideDownloaderSetting() { - setBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, getQuickQueryTimestamp()) + overrideBooleanSetting(DOWNLOADER_QUICK_QUERY_TIMESTAMP, config.quickQueryTimestamp) + } + + private overrideStringSetting(String key, String providedValue) { + if (providedValue != null) { + logger.lifecycle("Setting [${key}] overrided with value [${providedValue}]") + setString(key, providedValue) + } + } + + private overrideIntegerSetting(String key, Integer providedValue) { + if (providedValue != null) { + logger.lifecycle("Setting [${key}] overrided with value [${providedValue}]") + setString(key, "${providedValue}") + } + } + + private overrideBooleanSetting(String key, Boolean providedValue) { + if (providedValue != null) { + logger.lifecycle("Setting [${key}] overrided with value [${providedValue}]") + setBoolean(key, providedValue) + } } } diff --git a/dependency-check-gradle/src/main/resources/META-INF/gradle-plugins/dependency.check.properties b/dependency-check-gradle/src/main/resources/META-INF/gradle-plugins/dependency.check.properties deleted file mode 100644 index 877c70050..000000000 --- a/dependency-check-gradle/src/main/resources/META-INF/gradle-plugins/dependency.check.properties +++ /dev/null @@ -1,19 +0,0 @@ -# -# This file is part of dependency-check-gradle. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Copyright (c) 2015 Wei Ma. All Rights Reserved. -# - -implementation-class=com.tools.security.plugin.DependencyCheckGradlePlugin \ No newline at end of file diff --git a/dependency-check-gradle/src/test/groovy/com/tools/security/plugin/DependencyCheckGradlePluginSpec.groovy b/dependency-check-gradle/src/test/groovy/com/tools/security/plugin/DependencyCheckGradlePluginSpec.groovy index 6a9666240..43ddd93b0 100644 --- a/dependency-check-gradle/src/test/groovy/com/tools/security/plugin/DependencyCheckGradlePluginSpec.groovy +++ b/dependency-check-gradle/src/test/groovy/com/tools/security/plugin/DependencyCheckGradlePluginSpec.groovy @@ -48,47 +48,52 @@ class DependencyCheckGradlePluginSpec extends PluginProjectSpec { expect: task.group == 'Dependency Check' task.description == 'Produce dependency security report.' - task.proxyServer == null - task.proxyPort == null - task.proxyUsername == '' - task.proxyPassword == '' - task.cveUrl12Modified == 'https://nvd.nist.gov/download/nvdcve-Modified.xml.gz' - task.cveUrl20Modified == 'https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-Modified.xml.gz' - task.cveStartYear == 2002 - task.cveUrl12Base == 'https://nvd.nist.gov/download/nvdcve-%d.xml.gz' - task.cveUrl20Base == 'https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml.gz' - task.outputDirectory == './reports' - task.quickQueryTimestamp == true + project.dependencyCheck.proxy.server == null + project.dependencyCheck.proxy.port == null + project.dependencyCheck.proxy.username == null + project.dependencyCheck.proxy.password == null + project.dependencyCheck.cve.url12Modified == null + project.dependencyCheck.cve.url20Modified == null + project.dependencyCheck.cve.startYear == null + project.dependencyCheck.cve.url12Base == null + project.dependencyCheck.cve.url20Base == null + project.dependencyCheck.outputDirectory == './reports' + project.dependencyCheck.quickQueryTimestamp == null } def 'tasks use correct values when extension is used'() { when: project.dependencyCheck { - proxyServer = '127.0.0.1' - proxyPort = 3128 - proxyUsername = 'proxyUsername' - proxyPassword = 'proxyPassword' - cveUrl12Modified = 'cveUrl12Modified' - cveUrl20Modified = 'cveUrl20Modified' - cveStartYear = 2002 - cveUrl12Base = 'cveUrl12Base' - cveUrl20Base = 'cveUrl20Base' + proxy { + server = '127.0.0.1' + port = 3128 + username = 'proxyUsername' + password = 'proxyPassword' + } + + cve { + startYear = 2002 + url12Base = 'cveUrl12Base' + url20Base = 'cveUrl20Base' + url12Modified = 'cveUrl12Modified' + url20Modified = 'cveUrl20Modified' + } + outputDirectory = 'outputDirectory' quickQueryTimestamp = false } then: - Task task = project.tasks.findByName( 'dependencyCheck' ) - task.proxyServer == '127.0.0.1' - task.proxyPort == 3128 - task.proxyUsername == 'proxyUsername' - task.proxyPassword == 'proxyPassword' - task.cveUrl12Modified == 'cveUrl12Modified' - task.cveUrl20Modified == 'cveUrl20Modified' - task.cveStartYear == 2002 - task.cveUrl12Base == 'cveUrl12Base' - task.cveUrl20Base == 'cveUrl20Base' - task.outputDirectory == 'outputDirectory' - task.quickQueryTimestamp == false + project.dependencyCheck.proxy.server == '127.0.0.1' + project.dependencyCheck.proxy.port == 3128 + project.dependencyCheck.proxy.username == 'proxyUsername' + project.dependencyCheck.proxy.password == 'proxyPassword' + project.dependencyCheck.cve.url12Modified == 'cveUrl12Modified' + project.dependencyCheck.cve.url20Modified == 'cveUrl20Modified' + project.dependencyCheck.cve.startYear == 2002 + project.dependencyCheck.cve.url12Base == 'cveUrl12Base' + project.dependencyCheck.cve.url20Base == 'cveUrl20Base' + project.dependencyCheck.outputDirectory == 'outputDirectory' + project.dependencyCheck.quickQueryTimestamp == false } } diff --git a/dependency-check-maven/src/site/markdown/configuration.md b/dependency-check-maven/src/site/markdown/configuration.md index 7f767f0c3..afe2e9e99 100644 --- a/dependency-check-maven/src/site/markdown/configuration.md +++ b/dependency-check-maven/src/site/markdown/configuration.md @@ -18,7 +18,7 @@ autoUpdate | Sets whether auto-updating of the NVD CVE/CPE data is ena outputDirectory | The location to write the report(s). Note, this is not used if generating the report as part of a `mvn site` build | 'target' failBuildOnCVSS | Specifies if the build should be failed if a CVSS score above a specified level is identified. The default is 11 which means since the CVSS scores are 0-10, by default the build will never fail. | 11 format | The report format to be generated (HTML, XML, VULN, ALL). This configuration option has no affect if using this within the Site plugin unless the externalReport is set to true. | HTML -suppressionFile | The file path to the XML suppression file \- used to suppress [false positives](../suppression.html) |   +suppressionFile | The file path to the XML suppression file \- used to suppress [false positives](../general/suppression.html) |   skipTestScope | Should be skip analysis for artifacts with Test Scope | true skipProvidedScope | Should be skip analysis for artifacts with Provided Scope | false skipRuntimeScope | Should be skip analysis for artifacts with Runtime Scope | false diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index ec99710d5..94600032e 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -222,6 +222,10 @@ public final class Settings { * The properties key for whether the Nexus analyzer is enabled. */ public static final String ANALYZER_NEXUS_ENABLED = "analyzer.nexus.enabled"; + /** + * The properties key for whether the node.js package analyzer is enabled. + */ + public static final String ANALYZER_NODE_PACKAGE_ENABLED = "analyzer.node.package.enabled"; /** * The properties key for the Nexus search URL. */ diff --git a/pom.xml b/pom.xml index 2c712d053..7badae07c 100644 --- a/pom.xml +++ b/pom.xml @@ -521,6 +521,11 @@ Copyright (c) 2012 - Jeremy Long velocity 1.7 + + org.glassfish + javax.json + 1.0.4 + org.hamcrest hamcrest-core diff --git a/src/site/markdown/analyzers/index.md b/src/site/markdown/analyzers/index.md index 30dfb3a21..298c2cd22 100644 --- a/src/site/markdown/analyzers/index.md +++ b/src/site/markdown/analyzers/index.md @@ -3,12 +3,14 @@ File Type Analyzers OWASP dependency-check contains several file type analyzers that are used to extract identification information from the files analyzed. -- [Archive Analyzer](./archive-analyzer.html) -- [Assembly Analyzer](./assembly-analyzer.html) -- [Autoconf Analyzer](./autoconf-analyzer.html) -- [Central Analyzer](./central-analyzer.html) -- [Jar Analyzer](./jar-analyzer.html) -- [Nexus Analyzer](./nexus-analyzer.html) -- [Nuspec Analyzer](./nuspec-analyzer.html) -- [OpenSSL Analyzer](./openssl-analyzer.html) -- [Python Analyzer](./python-analyzer.html) +| Analyzer | File Types Scanned | Analysis Method | +| -------- | ------------------ | --------------- | +| [Archive Analyzer](./archive-analyzer.html) | Zip archive format (\*.zip, \*.ear, \*.war, \*.jar, \*.sar, \*.apk, \*.nupkg); Tape Archive Format (\*.tar); Gzip format (\*.gz, \*.tgz); Bzip2 format (\*.bz2, \*.tbz2) | Extracts archive contents, then scans contents with all available analyzers. | +| [Assembly Analyzer](./assembly-analyzer.html) | .NET Assemblies (\*.exe, \*.dll) | Uses [GrokAssembly.exe](https://github.com/colezlaw/GrokAssembly), which requires .NET Framework or Mono runtime to be installed. | +| [Autoconf Analyzer](./autoconf-analyzer.html) | Autoconf project configuration files (configure, configure.in, configure.ac) | Regex scan for AC_INIT metadata, including in generated configuration script. | +| [Central Analyzer](./central-analyzer.html) | Java archive files (\*.jar) | Searches Maven Central or a configured Nexus repository for the file's SHA1 hash. | +| [Jar Analyzer](./jar-analyzer.html) | Java archive files (\*.jar); Web application archive (\*.war) | Examines archive manifest metadata, and Maven Project Object Model files (pom.xml). | +| [Nexus Analyzer](./nexus-analyzer.html) | Java archive files (\*.jar) | Searches Sonatype or a configured Nexus repository for the file's SHA1 hash. In most cases, superceded by Central Analyzer. | +| [Nuspec Analyzer](./nuspec-analyzer.html) | Nuget package specification file (\*.nuspec) | Uses XPath to parse specification XML. | +| [OpenSSL Analyzer](./openssl-analyzer.html) | OpenSSL Version Source Header File (opensslv.h) | Regex parse of the OPENSSL_VERSION_NUMBER macro definition. | +| [Python Analyzer](./python-analyzer.html) | Python source files (\*.py); Package metadata files (PKG-INFO, METADATA); Package Distribution Files (\*.whl, \*.egg, \*.zip) | Regex scan of Python source files for setuptools metadata; Parse RFC822 header format for metadata in all other artifacts. | diff --git a/src/site/markdown/general/scan_iso.md b/src/site/markdown/general/scan_iso.md new file mode 100644 index 000000000..66e3c03a7 --- /dev/null +++ b/src/site/markdown/general/scan_iso.md @@ -0,0 +1,122 @@ +How to Mount ISO Files for Scanning +=================================== + +Dependency-Check can be used as one of your tools for vetting software +distributed via an [ISO image](https://en.wikipedia.org/wiki/ISO_image). (See +[File Type Analyzers](../analyzers/) for a list of what types of artifacts +Dependency-Check is capable of scanning.) These disk image files are not a standard archive format, however. Tools must be used that can interpret the contained file system. As will be shown below, Linux, Mac OS X, and recent versions of Windows can be used to mount the image's file system, which can +then be scanned by Dependency-Check. + +ISO images are named for the fact that they nearly always contain one of a +pair of international file system standards published by +[ISO](http://www.iso.org/): [ISO 9660](https://en.wikipedia.org/wiki/ISO_9660) +and ISO/IEC 13346, a.k.a. [UDF](https://en.wikipedia.org/wiki/Universal_Disk_Format). Other types of disk images (e.g., +[VHD](https://en.wikipedia.org/wiki/VHD_%28file_format%29)) are outside the +scope of this article, though the ideas presented here may likely be +succesfully applied. + +Linux +----- + +Assume you've downloaded an ISO image called `foo.iso`, and you want to mount +it at /mnt/foo. (Why /mnt? See the +[Filesystem Hierarchy Standard](http://refspecs.linuxfoundation.org/FHS_3.0/fhs/ch03s12.html).) +First make sure that the mount point exists using `mkdir /mnt/foo`. Then, the +[mount](http://linux.die.net/man/8/mount) command *must be run with root +privileges*. On Debian and Ubuntu Linux, this is accomplished by prefacing the +command with `sudo`. + +```sh +$ sudo mount -o loop foo.iso /mnt/foo +``` + +Next, you can use Dependency-Check's [command line tool](dependency-check-cli/) +to scan the mount point. When you are finished, run the +[umount](http://linux.die.net/man/8/umount) command with root privileges: + +```sh +$ sudo umount -d /mnt/foo +``` + +This will unmount the file system, and detach the loop device. + +Mac OS X +-------- + +### Using the GUI + +Simply double-click on the image file in Mac OS X Finder. + +### Using a Terminal Window + +Use the [hdiutil](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/hdiutil.1.html) +command. + +```sh +$ hdiutil attach foo.iso +``` + +The output will show the `/dev` entry assigned as well as the mount point, +which is where you may now read the files in the image's file system. + +To detach: + +```sh +$ hdiutil detach foo.iso +``` + +Windows +------- + +Windows 8 and later versions support mounting ISO images as a virtual drive. + +### Using the GUI + +1. In *File Explorer*, right-click on "foo.iso". +2. Select "Mount" + +File Explorer then redirects to showing the files on your virtual drive. You can then use the [command line tool](dependency-check-cli/) to scan the +virtual drive. When finished, "Windows-E" will open File Explorer showing the various drives on your computer. To eject the virtual drive: + +1. Right-click on the virtual drive. +2. Select "Eject" + +### Using PowerShell + +To mount, use the [Mount-DiskImage](https://technet.microsoft.com/en-us/%5Clibrary/Hh848706%28v=WPS.630%29.aspx) +cmdlet: + +```posh +$ Mount-DiskImage -ImagePath C:\Full\Path\to\foo.iso +``` + +To view all drives (and find your virtual drive), use the +[Get-PSDrive](https://technet.microsoft.com/en-us/library/Hh849796.aspx) +cmdlet: + +```posh +$ Get-PSDrive -PSProvider 'FileSystem' +``` + +To dismount, use the [Dismount-DiskImage](https://technet.microsoft.com/en-us/library/hh848693%28v=wps.630%29.aspx) +cmdlet: + +```posh +$ Dismount-DiskImage -ImagePath C:\Full\Path\to\file.iso +``` + +### Windows 7 + +Third-party tools exist that can be used to mount ISO images. Without such +tools, it is still possible to burn the ISO image to physical media, and scan +the media: + +1. Right-click on "foo.iso" +2. Select "Windows Disc Image Burner" +3. Follow the instructions to burn the image. + +### Windows Vista + +Just as with Windows 7, you will need a third-party tool to mount an ISO +image. You will also need a third-party tool to burn the image to media. +Many machines are shipped with such a tool included. \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml index 6ca795342..314bf2cbf 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -102,31 +102,34 @@ Copyright (c) 2013 Jeremy Long. All Rights Reserved. Sample Report + + How to Scan an ISO Image + Archive Analyzer - - Jar Analyzer + + Assembly Analyzer - - Python Analyzer + + Autoconf Analyzer Central Analyzer + + Jar Analyzer + Nexus Analyzer - - Assembly Analyzer - Nuspec Analyzer - - Autoconf Analyzer + + Python Analyzer OpenSSL Analyzer