Compare commits

...

232 Commits

Author SHA1 Message Date
Jeremy Long
bc656c6218 version 1.4.0 2016-06-16 06:49:24 -04:00
Jeremy Long
f46226d055 updated documentation 2016-06-16 06:49:07 -04:00
Jeremy Long
c5ffc21660 Merge branch 'master' of github.com:jeremylong/DependencyCheck 2016-06-15 06:51:18 -04:00
Jeremy Long
d89b1fdc6a updated proxy configuration information 2016-06-15 06:51:05 -04:00
Jeremy Long
8324287bd6 updated proxy configuration information 2016-06-15 06:50:45 -04:00
Jeremy Long
6be161a546 updated experimental documentation 2016-06-15 06:19:06 -04:00
Jeremy Long
027350e1ba Merge pull request #516 from msrb/weightings-bug
Correctly apply weightings when searching for CPEs
2016-06-15 05:48:55 -04:00
Michal Srb
a2309e1c2e Correctly apply weightings when searching for CPEs 2016-06-14 21:34:04 +02:00
Jeremy Long
c34dc97bd4 updated snapshot version 2016-06-11 08:13:14 -04:00
Jeremy Long
7e8749146e updated documentation 2016-06-11 08:12:09 -04:00
Jeremy Long
8680ecd033 updated documentation for experimental analyzers 2016-06-08 06:40:07 -04:00
Jeremy Long
4e4417c7af checkstyle corrections 2016-06-06 18:45:39 -04:00
Jeremy Long
7909bbbbe9 corrected remaining merge conflicts that were missed earlier as they were in comments 2016-06-06 06:45:33 -04:00
Jeremy Long
6fd831e688 corrected JavaDoc links 2016-06-06 06:44:42 -04:00
Jeremy Long
59a4825c70 added license 2016-06-05 17:40:42 -04:00
Jeremy Long
1ba3681457 updated the ci 2016-06-05 17:32:57 -04:00
Jeremy Long
78becffb2e updated CI build status url 2016-06-05 17:29:29 -04:00
Jeremy Long
e7efd7070b Merge pull request #508 from albuch/h2-clean-orphans
Thanks for the PR!
2016-06-05 17:25:53 -04:00
Jeremy Long
ec6471e8c7 added notes for future enhancment 2016-06-05 17:17:38 -04:00
Jeremy Long
b01ae2c6d3 updated to speed-up the unit test 2016-06-05 17:16:43 -04:00
Jeremy Long
ef4a260615 fixed build issue with CveDB being closed before saving the property 2016-06-05 17:16:05 -04:00
Jeremy Long
f6b80630dd temporary travis debugging code 2016-06-05 08:30:22 -04:00
Jeremy Long
f43589589d fixed setup to call super 2016-06-05 08:04:45 -04:00
Jeremy Long
06b59cf79b initial 2016-06-05 07:49:59 -04:00
Jeremy Long
a2187205e0 only update last checked after updates were performed without errors 2016-06-05 06:45:13 -04:00
Jeremy Long
52f269a289 Merge branch 'jabbrwcky-batch-update' 2016-06-05 06:33:45 -04:00
Jeremy Long
310ca967a1 fixed compareTo in order to resolve issue #503 2016-06-05 06:32:49 -04:00
Jeremy Long
c4b423cb0f additional tests resources to fix issue #503 2016-06-05 06:32:11 -04:00
Alexander v. Buchholtz
8a6c940aaf Optimized CLEANUP_ORPHANS query for H2 1.4.x
Original query from dbStatements.properties writes millions of records from subselect to file system due to MAX_MEMORY_ROWS Setting http://www.h2database.com/html/grammar.html?highlight=max_memory_rows&search=MAX_MEM#set_max_memory_rows
Database maintenance task therefore takes forever.
The new query (copied from postgresql) works way faster.
2016-06-04 23:36:43 +02:00
Jeremy Long
b295e927b7 resolved merge conflict 2016-06-04 09:09:57 -04:00
Jeremy Long
63d24737dd Merge pull request #506 from jabbrwcky/issue-503
Thanks for the test cases
2016-06-04 07:47:44 -04:00
Jeremy Long
60ce02ba28 improved logging to assist in resoloving issue #503 2016-06-04 07:46:42 -04:00
Jeremy Long
95939ed66c added javadoc per checkstyle 2016-06-04 07:45:07 -04:00
Jeremy Long
7f609a35be added javadoc per checkstyle 2016-06-04 07:44:42 -04:00
Jeremy Long
f7b534f1ee checkstyle correction 2016-06-04 07:44:08 -04:00
Jeremy Long
cd5f9e2f13 findbugs correction 2016-06-04 07:42:58 -04:00
Jens Hausherr
e79da72711 Use batch update for references and vulnerable software if supported by DB. 2016-06-03 10:22:54 +02:00
Jens Hausherr
1ba081959b Accidentially dropped some imports 2016-06-03 10:09:28 +02:00
Jens Hausherr
578dc63652 Vulnerable Software: Compact toString() output; remove accessor calls for own properties 2016-06-03 09:54:25 +02:00
Jens Hausherr
fccd683b50 add toString() for Vulnerability 2016-06-03 09:52:35 +02:00
Jens Hausherr
f3d3a25856 Add more test cases 2016-06-03 09:50:28 +02:00
Jens Hausherr
6d70c92795 Add to String-Method to Reference 2016-06-03 09:41:48 +02:00
Jeremy Long
3c525d8e3a fixed issue #505 2016-06-02 19:30:38 -04:00
Jeremy Long
a6b47c7c43 clarified note 2016-06-02 19:23:51 -04:00
Jeremy Long
5b52f01f3d updated documentation for issue#498 2016-05-30 08:23:58 -04:00
Jeremy Long
d13bbd43f3 added experimental flag to force users to enable this and by doing so understand that these may not be as production ready as the Java analyzer (see issue #498) 2016-05-30 08:09:14 -04:00
Jeremy Long
0394d1a24f checkstyle correction - reduced method length 2016-05-30 07:59:53 -04:00
Jeremy Long
446222e127 removed unnecessary exclude 2016-05-30 07:59:18 -04:00
Jeremy Long
05d7aa898d minor reformatting to reduce line length (checkstyle) 2016-05-30 07:37:44 -04:00
Jeremy Long
73f7fc1d51 Merge branch 'master' of github.com:jeremylong/DependencyCheck 2016-05-30 07:19:15 -04:00
Jeremy Long
f0262466d4 Merge pull request #504 from awhitford/Upg052816
Plugin updates
2016-05-30 07:19:17 -04:00
Anthony Whitford
1ecde9bbc1 maven-jar-plugin 3.0.0 released; maven-resources-plugin 3.0.0 released. 2016-05-28 08:27:39 -07:00
Jens Hausherr
ae5a766092 Limit split to fix #503 2016-05-27 15:07:59 +02:00
Jeremy Long
6a807bc002 checkstyle/findbugs corrections 2016-05-25 17:21:46 -04:00
Jeremy Long
c0384bb0ee Merge pull request #502 from xthk/master
Update initialize_mysql.sql
2016-05-25 06:12:52 -04:00
Tilmann H
2906b315b3 Update initialize_mysql.sql
lower cased "properties" in UPDATE statement
2016-05-25 11:36:09 +02:00
Jeremy Long
425fd65bd8 added more false positive suppressions 2016-05-21 07:09:08 -04:00
Jeremy Long
7d83362a85 removed stack trace from build when ruby and bundle-audit are not installed 2016-05-15 07:49:17 -04:00
Jeremy Long
0b26894112 checkstyle/pmd/findbugs correction(s) 2016-05-15 07:48:26 -04:00
Jeremy Long
17f810a720 implement issue #498 2016-05-15 07:30:38 -04:00
Jeremy Long
71ef8061f9 merge conflict resolved 2016-05-15 07:29:17 -04:00
Jeremy Long
353b17690f checkstyle/pmd/findbugs correction(s) 2016-05-15 07:22:52 -04:00
Jeremy Long
6790727260 ensured resources are properly closed 2016-05-15 07:02:18 -04:00
Jeremy Long
e129f7db85 Merge branch 'biancajiang-ruby_dependency' 2016-05-15 06:46:18 -04:00
Jeremy Long
ea942398e3 updated test case to use the correct parent class that allows for use of the database during testing 2016-05-15 06:45:57 -04:00
Jeremy Long
5ad72cae3f Merge branch 'ruby_dependency' of git://github.com/biancajiang/DependencyCheck into biancajiang-ruby_dependency 2016-05-14 09:45:26 -04:00
Jeremy Long
5f945bc696 Merge branch 'master' of github.com:jeremylong/DependencyCheck 2016-05-14 07:21:07 -04:00
Jeremy Long
6f451736ba Add ability to flag analyzers as experimental so that they are not always enabled 2016-05-14 07:20:53 -04:00
Jeremy Long
30856f4a4f corrected doxia version 2016-05-14 07:19:12 -04:00
bjiang
9d1408be20 do not use actual path for packagePath from compress case 2016-05-13 13:33:34 -04:00
Jeremy Long
f21f371751 Merge pull request #494 from erikerikson/master
Align documentation with current project name specification flag
2016-05-06 18:23:32 -04:00
bjiang
d5e8f54214 fix RubyBundlerAnalyzer.accept 2016-05-06 17:55:21 -04:00
bjiang
83f83d4eee add RubyBundlerAnalyzerTest 2016-05-06 17:45:40 -04:00
bjiang
b0f4ab9ba5 cleanup & Rakefile support placeholder 2016-05-06 17:25:08 -04:00
bjiang
06dad8f79c javadoc 2016-05-06 17:22:39 -04:00
bjiang
83ab122ddf disable RubyBundlerAnalyzer if RubyBundleAuditAnalyzer 2016-05-06 16:42:39 -04:00
bjiang
8a42fe4ae1 javadoc 2016-05-06 16:19:59 -04:00
bjiang
94c6778b89 better javadoc 2016-05-06 16:14:16 -04:00
bjiang
c0e5973517 rename RubyBundlerAnalyzer and javadoc 2016-05-06 15:50:35 -04:00
bjiang
4de3fb1f2a javadoc 2016-05-06 10:25:49 -04:00
Erik Erikson
ee77fccffd Align documentation with current project name specification flag
When using the "--app" flag, the following warning is produced:

 [WARN] The 'app' argument should no longer be used; use 'project' instead.

 This change updates the documentation from suggesting "--app" to "--project"
2016-05-03 10:31:00 -07:00
bjiang
189da08885 merge upstream 2016-05-03 13:05:56 -04:00
Jeremy Long
9e63ac6d5b Merge pull request #493 from awhitford/CommIO25
Commons-IO 2.5 upgrade
2016-05-02 19:26:52 -04:00
Jeremy Long
4d7ab8b187 Merge pull request #491 from mwieczorek/MSSQL_Support
MSSQL Support
2016-05-02 19:25:39 -04:00
Jeremy Long
4de9818bee original CVE used in test does not exist in the current default DB used for tests. 2016-05-01 20:16:30 -04:00
Jeremy Long
7a2e1fd221 updated bundle audit score to be more accurate 2016-05-01 15:39:12 -04:00
Jeremy Long
d0ca800a23 Merge branch 'geramirez-fix-cvss-for-bundle-audit' 2016-04-30 11:20:39 -04:00
Jeremy Long
35ffd56ea9 fixed compile issues in PR 2016-04-30 11:20:26 -04:00
Jeremy Long
84b992d3a1 Merge branch 'fix-cvss-for-bundle-audit' of git://github.com/geramirez/DependencyCheck into geramirez-fix-cvss-for-bundle-audit 2016-04-30 11:02:16 -04:00
Jeremy Long
9e46364759 updated test cases to track down build issue 2016-04-30 10:56:50 -04:00
Dave Goddard
0f37c2b59c Adding sinatra fixture
Signed-off-by: Gabriel Ramirez <gabriel.e.ramirez@gmail.com>
2016-04-29 16:17:51 -04:00
Michal Wieczorek
33852ea7e3 MSSQL Support 2016-04-27 23:35:05 +02:00
Anthony Whitford
4fbed1cdac Added Charset to avoid deprecated FileUtils methods. 2016-04-27 01:37:00 -07:00
Anthony Whitford
42c61ab457 commons-io 2.5 released; jsoup 1.9.1 released. 2016-04-27 01:22:20 -07:00
David Jahn
8c6b9f9c68 Fixed CVSS for Ruby.
this bug was discovered when scanning ruby applications and getting back
`-1` cvss. this turns out to be a problem with bundle-audit cve
database.

Our solution was to use the NVD database, which dependency check uses to
get the CVSS scores for Ruby only if the Criticality is missing from
bundle-audit output. Keep in mind there are compilation errors with the
commit atm.

Fixes #485

Signed-off-by: Gabriel Ramirez <gabriel.e.ramirez@gmail.com>
2016-04-25 09:40:54 -04:00
Jeremy Long
abebecac4a updated parser and tests to revert to old suppression schema if new schema fails 2016-04-24 09:06:00 -04:00
Jeremy Long
87efe429da fixed broken schema 2016-04-24 09:05:26 -04:00
Jeremy Long
35128b0bd4 updated 2016-04-24 09:04:22 -04:00
Jeremy Long
186cb2270f ensure updated schema is published to the site 2016-04-24 07:25:32 -04:00
Jeremy Long
deda02f879 updated suppression schema to require a CPE, CVE, or CVSS Below per issue #488 2016-04-24 07:20:11 -04:00
Jeremy Long
bcc2478ef7 snapshot version 2016-04-24 07:17:42 -04:00
Jeremy Long
8d54654482 Merge pull request #487 from awhitford/DepUpg160416
Upgraded plugins and dependencies
2016-04-17 21:02:54 -04:00
Jeremy Long
08318107c1 Merge pull request #486 from awhitford/MavenWarnings
Maven warnings
2016-04-17 21:02:35 -04:00
Anthony Whitford
a5e77c85a6 Maven Site Plugin 3.5.1, Doxia 1.7.1, Ant 1.9.7, Maven 3.3.9. 2016-04-16 11:21:24 -07:00
Anthony Whitford
1e8d2aff75 Added code to avoid an unchecked cast warning. 2016-04-16 11:08:13 -07:00
Anthony Whitford
bc0a0f9902 Added missing serialVersionUID. 2016-04-16 11:07:19 -07:00
bjiang
da82f975e4 Add test for project url from pom.xml 2016-04-15 12:30:14 -04:00
bjiang
48af120db8 add project URL evidence from pom 2016-04-15 11:28:33 -04:00
Jeremy Long
8722eae766 version 1.3.6 2016-04-10 07:06:07 -04:00
Jeremy Long
53776936ca fix FP per issue #469 2016-04-09 11:27:08 -04:00
Jeremy Long
dca465b801 fixed minor warning about file encoding during build 2016-04-09 07:31:40 -04:00
Jeremy Long
43cd115dc7 Merge pull request #482 from awhitford/DepUpg-160406
Dependency Updates
2016-04-09 06:59:29 -04:00
Jeremy Long
e7ba08e52c updated log message to assist in debugging an issue 2016-04-09 06:51:00 -04:00
Jeremy Long
9df12e6ff2 updated log message to assist in debugging an issue 2016-04-09 06:49:44 -04:00
Jeremy Long
b5c7fb747c updated log message to assist in debugging an issue 2016-04-09 06:38:37 -04:00
Anthony Whitford
a40a4afe80 SLF4J 1.7.21 released; commons-compress 1.11 released. 2016-04-06 21:39:27 -07:00
bjiang
739f595f13 improve python package identification 2016-04-05 16:12:14 -04:00
bjiang
e07e892969 Merge branch 'master' into ruby_dependency 2016-04-05 14:47:17 -04:00
Jeremy Long
d4a6c58cc8 upgrade the transitive dependency commons-collections 2016-04-05 12:08:16 -04:00
Jeremy Long
d644431a4e Merge pull request #479 from awhitford/SLF4J1720LB117
SLF4J 1.7.20 and Logback 1.1.7 released.
2016-04-03 07:41:54 -04:00
bjiang
33bbb50b43 Ruby .gemspec must before bundler analyzer to get proper package grouping 2016-04-02 13:51:15 -04:00
bjiang
f89d7df305 improve vendor evidences for .gemspec analyzer 2016-04-02 13:49:50 -04:00
bjiang
3b02cd0e39 bundling same Ruby packages from .gemspec and bundler analyzers 2016-04-02 13:48:25 -04:00
bjiang
52cd50e0a8 keep delimitor space in array value 2016-04-01 14:08:41 -04:00
bjiang
996a970081 fix version evidence name 2016-04-01 14:07:03 -04:00
bjiang
6c0b65acd4 capture licenses and homepage in Ruby bundler analyzer 2016-04-01 13:30:36 -04:00
Anthony Whitford
f4df263dfe SLF4J 1.7.20 and Logback 1.1.7 released. 2016-03-30 21:03:51 -07:00
bjiang
8c659acc82 new Ruby bundler analyzer 2016-03-30 20:20:10 -04:00
bjiang
7aba2429af merge from upstream 2016-03-28 14:23:09 -04:00
bjiang
ab48d2c2ff multiple improvements 2016-03-28 14:06:30 -04:00
Jeremy Long
0b699d45bf Merge pull request #467 from colezlaw/python-init
Patch for jeremylong/DependencyCheck/#466
2016-03-25 19:35:06 -04:00
Jeremy Long
54beafa262 Merge pull request #475 from biancajiang/master
Fix test to skip the proper test case when bundle-audit is not available
2016-03-25 19:34:34 -04:00
Jeremy Long
531d4923eb Merge pull request #470 from MrBerg/suppress-osvdb
Make it possible to suppress vulnerabilities from OSVDB
2016-03-25 19:33:43 -04:00
Jeremy Long
b160a4d1dd Merge pull request #478 from swapnilsm/master
Added primary key to "software" table
2016-03-25 19:32:45 -04:00
Swapnil S. Mahajan
ca54daf456 Added primary key to "software" table
"software" is a bridge table so there should always be only one record for a pair of cpeEntryId and cveid.
2016-03-25 16:55:53 +05:30
bjiang
a22fc550b3 #472 fix test to only skip the proper test case. 2016-03-21 11:38:52 -04:00
Jeremy Long
0650d93953 Merge pull request #474 from awhitford/SLF4J1719
SLF4J 1.7.19 released.
2016-03-21 08:18:41 -04:00
Jeremy Long
5633258fa7 Update README.md 2016-03-21 08:16:06 -04:00
Jeremy Long
12278cda58 Update README.md
Fixed broken link to documentation.
2016-03-21 08:12:39 -04:00
Jeremy Long
84d1f08fda updated documentation for NVD urls to match what is hosted by NIST 2016-03-21 07:58:02 -04:00
Jeremy Long
c184292a57 Merge pull request #473 from biancajiang/master
Handle bundle-audit not available case and fix RubyBundleAuditAnalyzer test cases
2016-03-21 07:52:17 -04:00
Anthony Whitford
4cdfcb9f9d SLF4J 1.7.19 released. 2016-03-20 20:47:07 -04:00
bjiang
343a78917c Fixed #472. Disable RubyBundleAuditAnalyzer if exception during initialize.
changes:
1. disable self during initialize before bubbling exception
2. new test case RubyBundleAuditAnalyzerTest#testMissingBundleAudit()
2016-03-20 17:06:03 -04:00
bjiang
ff7d0fdb9d #472 first fix and improve RubyBundleAuditAnalyzerTest.java
Test were failing b/c Gemfile.lock and Gemfile were missing.
The files were missing b/c parent .gitignore them.
Changes:
1. Force added new test files, and updated test with more result
validation.
2. Added error logging from bundle-audit.
3. place holder for bundle-audit install directory in test
dependencycheck.properties.
2016-03-20 15:54:24 -04:00
Jonas Berg
db26b46be0 Make it possible to suppress vulnerabilities from OSVDB 2016-03-16 13:59:23 +02:00
Will Stranathan
d77a70c360 Patch for jeremylong/DependencyCheck/#466
This does two things:
1) Updates the PythonPackageAnalyzer to HIGH evidence for __init__.py
2) Removes evidence from the FileNameAnalyzer for __init__.py[co]?

TODO: Need for the PythonPackageAnalyzer to still add evidence for
__init__.py[co] even though it won't be able to analyze the contents of
it. Also, need to work up the tree for __init__.py files to get the
parent folders (not sure why subfolders are not being inspected).
2016-03-12 15:09:43 -05:00
Jeremy Long
42f4ae65d1 Merge pull request #463 from chadjvw/master
Updated Oracle init script
2016-03-07 20:43:05 -05:00
Chad Van Wyhe
88daac31d2 Merge pull request #1 from chadjvw/oracle-init-fix
fixed trigger compilation and added version number
2016-03-07 12:59:02 -06:00
Chad Van Wyhe
ac04c173a8 fixed trigger compilation and added version number 2016-03-07 12:55:18 -06:00
Jeremy Long
8401494fbc Merge pull request #462 from thc202/issues-page-gradle-purge
Fix issues in Gradle's dependencyCheckPurge task site page
2016-03-06 18:54:03 -05:00
Jeremy Long
97af118cb9 Merge pull request #461 from thc202/broken-link-readme
Fix broken link in README.md file... Thanks!
2016-03-06 18:53:12 -05:00
thc202
091e6026bc Fix issues in Gradle's dependencyCheckPurge task site page
Fix broken link to dependencyCheckUpdate task page, remove repeated
closing character ']'.
Replace $H with # in the heading of the example.
2016-03-06 23:46:12 +00:00
thc202
c798ede7bf Fix broken link in README.md file
Correct the link to NOTICE.txt file, change from NOTICES.txt to
NOTICE.txt.
2016-03-06 23:46:04 +00:00
Jeremy Long
225851f067 Merge pull request #460 from awhitford/DepUpg160306
Dependency Upgrades
2016-03-06 18:01:03 -05:00
Jeremy Long
9dd65ecf70 Merge pull request #459 from awhitford/MPIR29
maven-project-info-reports-plugin 2.9 released.
2016-03-06 18:00:48 -05:00
Jeremy Long
1a9cc4b6be snapshot 2016-03-06 17:42:18 -05:00
Jeremy Long
a612f206bf version 1.3.5.1 2016-03-06 17:30:37 -05:00
Jeremy Long
e51031c62a fix bug in getLastProject for non-site executions 2016-03-06 17:28:40 -05:00
Anthony Whitford
e30c29ef50 SLF4J 1.7.18 released; Logback 1.1.6 released; jMockit 1.22 released. 2016-03-06 08:53:58 -08:00
Anthony Whitford
91ddcadbcd Removed maven-site-plugin from dependencyManagement. 2016-03-06 08:51:04 -08:00
Anthony Whitford
8c145860e5 maven-project-info-reports-plugin 2.9 released. 2016-03-06 08:35:09 -08:00
Jeremy Long
a19dd7687e v 1.3.6-SNAPSHOT 2016-03-05 16:13:29 -05:00
Jeremy Long
550d6ca083 v1.3.5 2016-03-05 16:08:59 -05:00
Jeremy Long
b425411357 doclint fixes 2016-03-05 13:18:42 -05:00
Jeremy Long
a1f0cf749d doclint fixes 2016-03-05 13:18:38 -05:00
Jeremy Long
22e0d1c74e doclint fixes 2016-03-05 13:18:37 -05:00
Jeremy Long
cdc07047aa doclint fixes 2016-03-05 13:18:37 -05:00
Jeremy Long
c832c2da28 doclint fixes 2016-03-05 13:18:37 -05:00
Jeremy Long
8daa713639 doclint fixes 2016-03-05 13:18:36 -05:00
Jeremy Long
e0a2966706 doclint fixes 2016-03-05 13:18:36 -05:00
Jeremy Long
354bfa14f9 doclint fixes 2016-03-05 13:18:35 -05:00
Jeremy Long
46b91702ba doclint fixes 2016-03-05 13:18:35 -05:00
Jeremy Long
de9516e368 doclint fixes 2016-03-05 13:18:35 -05:00
Jeremy Long
3924e07e5c doclint fixes 2016-03-05 13:18:34 -05:00
Jeremy Long
76bcbb5a7e doclint fixes 2016-03-05 13:18:34 -05:00
Jeremy Long
8022381d1c doclint fixes 2016-03-05 13:18:33 -05:00
Jeremy Long
feb1233081 doclint fixes 2016-03-05 13:18:33 -05:00
Jeremy Long
36eefd0836 doclint fixes 2016-03-05 13:18:32 -05:00
Jeremy Long
0e31e59759 doclint fixes 2016-03-05 13:18:32 -05:00
Jeremy Long
4a4c1e75da doclint fixes 2016-03-05 13:18:32 -05:00
Jeremy Long
b0bfd2292a doclint fixes 2016-03-05 13:18:31 -05:00
Jeremy Long
7214b24357 doclint fixes 2016-03-05 13:18:31 -05:00
Jeremy Long
24637f496f doclint fixes 2016-03-05 13:18:30 -05:00
Jeremy Long
d8ecde5265 doclint fixes 2016-03-05 13:18:30 -05:00
Jeremy Long
28840c6209 doclint fixes 2016-03-05 13:18:29 -05:00
Jeremy Long
1696213406 doclint fixes 2016-03-05 13:18:29 -05:00
Jeremy Long
6f315ac765 doclint fixes 2016-03-05 13:18:28 -05:00
Jeremy Long
a485307d92 doclint fixes 2016-03-05 13:18:28 -05:00
Jeremy Long
3d3b861ba0 doclint fixes 2016-03-05 13:18:28 -05:00
Jeremy Long
4b33ed25d5 doclint fixes 2016-03-05 13:18:27 -05:00
Jeremy Long
e264880c7b doclint fixes 2016-03-05 13:18:27 -05:00
Jeremy Long
ef8212701f doclint fixes 2016-03-05 13:18:26 -05:00
Jeremy Long
492157a502 doclint fixes 2016-03-05 13:18:26 -05:00
Jeremy Long
2605bc182e doclint fixes 2016-03-05 13:18:25 -05:00
Jeremy Long
fe8dfdd804 doclint fixes 2016-03-05 13:18:25 -05:00
Jeremy Long
bd917bc990 doclint fixes 2016-03-05 13:18:24 -05:00
Jeremy Long
c5c32f683f doclint fixes 2016-03-05 13:18:24 -05:00
Jeremy Long
5506e58c98 doclint fixes 2016-03-05 13:18:23 -05:00
Jeremy Long
5af2d49b18 doclint fixes 2016-03-05 13:18:23 -05:00
Jeremy Long
0fd35a4925 doclint fixes 2016-03-05 13:18:23 -05:00
Jeremy Long
7ed20b1244 doclint fixes 2016-03-05 13:18:22 -05:00
Jeremy Long
efa6a78255 doclint fixes 2016-03-05 13:18:22 -05:00
Jeremy Long
8b58df3b34 checkstyle/pmd/findbugs corrections 2016-03-05 07:07:53 -05:00
Jeremy Long
0d2a090e1f Merge pull request #456 from awhitford/Site35
Upgrade for Maven Site Plugin 3.5
2016-03-04 17:42:14 -05:00
Jeremy Long
7860d635a9 ensured deserialization is secure 2016-03-04 17:38:48 -05:00
Anthony Whitford
ba91c9fa9b Upgraded maven site plugin to 3.5, and doxia markdown module to 1.7. 2016-02-28 09:34:19 -08:00
Anthony Whitford
b3630e0d5e Upgraded the Fluido 1.5 skin and had to update site head for maven site plugin 3.5. See http://maven.apache.org/plugins/maven-site-plugin/examples/sitedescriptor.html#Inject_xhtml_into_head 2016-02-28 09:33:54 -08:00
Jeremy Long
f752285912 added test for parse manifest per issue #455 2016-02-27 07:14:27 -05:00
Jeremy Long
5a150d9b0e parsed additional entries in the manifest per issue #455 2016-02-27 07:13:57 -05:00
Jeremy Long
f0aa185832 added test dependency per issue #455 2016-02-27 07:12:30 -05:00
Jeremy Long
9592f058d4 add more false positives to the suppression list 2016-02-25 18:01:21 -05:00
Jeremy Long
f630794e22 added warning about site:stage with regards to the aggregate goal 2016-02-24 17:00:31 -05:00
Jeremy Long
93636e89c5 fixed broken hyperlinks 2016-02-23 20:54:24 -05:00
Jeremy Long
585002c25c resolution for issue #386 fixed the conditional so that execution occured on the last non-skipped project in the reactor 2016-02-23 20:42:10 -05:00
Jeremy Long
412ccc1be1 per issue #429 updates will only occur if the database schema and expected schema match exactly 2016-02-21 08:38:29 -05:00
Jeremy Long
8b1306a36c per issue #429 non-h2 databases may be used as long as the database schema is of the same major version and greater then or equal to the expected version. 2016-02-21 08:11:29 -05:00
Jeremy Long
81026e8dca isolate the analyze method to try and resolve multiple threads hitting the Lucene query parsers at the same time per issue #388 2016-02-20 08:18:00 -05:00
Jeremy Long
dd440c8f9f resolve issue #451 2016-02-20 08:12:14 -05:00
Jeremy Long
76f3e4b27e Merge pull request #449 from christiangalsterer/i444
Support nonProxyHosts parameter in settings.xml #444
2016-02-17 19:09:41 -05:00
Jeremy Long
5f5d3fdb66 Merge pull request #447 from kaimago/master
Oracle DB Support
2016-02-17 19:06:13 -05:00
Jeremy Long
853c92b87d Merge pull request #448 from awhitford/UpgFeb6-16
Upgraded SLF4J to 1.7.14 and the maven-compiler-plugin to 3.5.
2016-02-17 19:03:37 -05:00
Anthony Whitford
00080f2abc SLF4J 1.7.16 released; logback 1.1.5 released. 2016-02-15 10:23:07 -08:00
Anthony Whitford
55414208a3 SLF4J 1.7.15 released; maven-compiler-plugin 3.5.1 released. 2016-02-10 00:34:26 -08:00
Christian Galsterer
5091499563 [i444] Support nonProxyHosts parameter in settings.xml 2016-02-09 18:01:36 +01:00
Anthony Whitford
944b54d920 Upgraded SLF4J to 1.7.14 and the maven-compiler-plugin to 3.5. 2016-02-06 12:14:19 -08:00
Christian Galsterer
d023b2b2ff [i444] Support nonProxyHosts parameter in settings.xml 2016-02-06 16:13:01 +01:00
Jeremy Long
b45f9f514b base test case handles settings initialization 2016-02-06 08:40:33 -05:00
Jeremy Long
239a9383e0 fix for issue #446 2016-02-06 08:30:06 -05:00
Jeremy Long
2190c0229c added check to see if the file is xml prior to unzipping it per issue #441 2016-02-06 08:11:24 -05:00
I003306
01ef14dc92 Oracle DB Support 2016-02-04 15:23:57 +01:00
Jeremy Long
7b0784843c updated copyright 2016-01-31 17:23:13 -05:00
Jeremy Long
6fc805369e snapshot version 2016-01-31 17:11:37 -05:00
161 changed files with 4313 additions and 1493 deletions

1
.gitignore vendored
View File

@@ -26,3 +26,4 @@ _site/**
.LCKpom.xml~
#coverity
/cov-int/
/dependency-check-core/nbproject/

2
.travis.yml Normal file
View File

@@ -0,0 +1,2 @@
language: java
jdk: oraclejdk7

View File

@@ -1,4 +1,4 @@
[![Build Status](https://dependency-check.ci.cloudbees.com/buildStatus/icon?job=dependency-check)](https://dependency-check.ci.cloudbees.com/job/dependency-check/)
[![Build Status](https://travis-ci.org/jeremylong/DependencyCheck.svg?branch=master)](https://travis-ci.org/jeremylong/DependencyCheck) [![Apache 2.0 License](https://img.shields.io/badge/license-Apache%202-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0.txt)
Dependency-Check
================
@@ -22,18 +22,18 @@ The latest CLI can be downloaded from bintray's
On *nix
```
$ ./bin/dependency-check.sh -h
$ ./bin/dependency-check.sh --app Testing --out . --scan [path to jar files to be scanned]
$ ./bin/dependency-check.sh --project Testing --out . --scan [path to jar files to be scanned]
```
On Windows
```
> bin/dependency-check.bat -h
> bin/dependency-check.bat --app Testing --out . --scan [path to jar files to be scanned]
> bin/dependency-check.bat --project Testing --out . --scan [path to jar files to be scanned]
```
On Mac with [Homebrew](http://brew.sh)
```
$ brew update && brew install dependency-check
$ dependency-check -h
$ dependency-check --app Testing --out . --scan [path to jar files to be scanned]
$ dependency-check --project Testing --out . --scan [path to jar files to be scanned]
```
### Maven Plugin
@@ -85,13 +85,13 @@ On *nix
```
$ mvn install
$ ./dependency-check-cli/target/release/bin/dependency-check.sh -h
$ ./dependency-check-cli/target/release/bin/dependency-check.sh --app Testing --out . --scan ./src/test/resources
$ ./dependency-check-cli/target/release/bin/dependency-check.sh --project Testing --out . --scan ./src/test/resources
```
On Windows
```
> mvn install
> dependency-check-cli/target/release/bin/dependency-check.bat -h
> dependency-check-cli/target/release/bin/dependency-check.bat --app Testing --out . --scan ./src/test/resources
> dependency-check-cli/target/release/bin/dependency-check.bat --project Testing --out . --scan ./src/test/resources
```
Then load the resulting 'DependencyCheck-Report.html' into your favorite browser.
@@ -108,7 +108,7 @@ Archive: [google group](https://groups.google.com/forum/#!forum/dependency-check
Copyright & License
-
Dependency-Check is Copyright (c) 2012-2015 Jeremy Long. All Rights Reserved.
Dependency-Check is Copyright (c) 2012-2016 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
@@ -118,4 +118,4 @@ Dependency-Check makes use of several other open source libraries. Please see th
[wiki]: https://github.com/jeremylong/DependencyCheck/wiki
[subscribe]: mailto:dependency-check+subscribe@googlegroups.com
[post]: mailto:dependency-check@googlegroups.com
[notices]: https://github.com/jeremylong/DependencyCheck/blob/master/NOTICES.txt
[notices]: https://github.com/jeremylong/DependencyCheck/blob/master/NOTICE.txt

View File

@@ -1,134 +1,25 @@
Dependency-Check-Gradle
Dependency-Check Ant Task
=========
**Working in progress**
Dependency-Check Ant Task can be used to check the project dependencies for published security vulnerabilities. The checks
performed are a "best effort" and as such, there could be false positives as well as false negatives. However,
vulnerabilities in 3rd party components is a well-known problem and is currently documented in the 2013 OWASP
Top 10 as [A9 - Using Components with Known Vulnerabilities](https://www.owasp.org/index.php/Top_10_2013-A9-Using_Components_with_Known_Vulnerabilities).
This is a DependencyCheck gradle plugin designed for project which use Gradle as build script.
Documentation and links to production binary releases can be found on the [github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-ant/index.html).
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.
Mailing List
------------
=========
Subscribe: [dependency-check+subscribe@googlegroups.com](mailto:dependency-check+subscribe@googlegroups.com)
## What's New
Current latest version is `0.0.8`
Post: [dependency-check@googlegroups.com](mailto:dependency-check@googlegroups.com)
## Usage
Copyright & License
-------------------
### Step 1, Apply dependency check gradle plugin
Dependency-Check is Copyright (c) 2012-2014 Jeremy Long. All Rights Reserved.
Install from Maven central repo
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
```groovy
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.owasp:dependency-check-gradle:1.3.2'
}
}
apply plugin: 'dependency-check-gradle'
```
### Step 2, Run gradle task
Once gradle plugin applied, run following gradle task to check dependencies:
```
gradle dependencyCheck --info
```
The reports will be generated automatically under `./reports` folder.
If your project includes multiple sub-projects, the report will be generated for each sub-project in different sub-directory.
## FAQ
> **Questions List:**
> - What if I'm behind a proxy?
> - What if my project includes multiple sub-project? How can I use this plugin for each of them including the root project?
> - How to customize the report directory?
### What if I'm behind a proxy?
Maybe you have to use proxy to access internet, in this case, you could configure proxy settings for this plugin:
```groovy
dependencyCheck {
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"
}
}
```
In addition, if the proxy only allow HTTP `GET` or `POST` methods, you will find that the update process will always fail,
the root cause is that every time you run `dependencyCheck` task, it will try to query the latest timestamp to determine whether need to perform an update action,
and for performance reason the HTTP method it uses by default is `HEAD`, which probably is disabled or not supported by the proxy. To avoid this problem, you can simply change the HTTP method by below configuration:
```groovy
dependencyCheck {
quickQueryTimestamp = false // when set to false, it means use HTTP GET method to query timestamp. (default value is true)
}
```
### What if my project includes multiple sub-project? How can I use this plugin for each of them including the root project?
Try put 'apply plugin: "dependency-check"' inside the 'allprojects' or 'subprojects' if you'd like to check all sub-projects only, see below:
(1) For all projects including root project:
```groovy
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "gradle.plugin.com.tools.security:dependency-check:0.0.8"
}
}
allprojects {
apply plugin: "dependency-check"
}
```
(2) For all sub-projects:
```groovy
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "gradle.plugin.com.tools.security:dependency-check:0.0.8"
}
}
subprojects {
apply plugin: "dependency-check"
}
```
In this way, the dependency check will be executed for all projects (including root project) or just sub projects.
### How to customize the report directory?
By default, all reports will be placed under `./reports` folder, to change the default directory, just modify it in the configuration section like this:
```groovy
subprojects {
apply plugin: "dependency-check"
dependencyCheck {
outputDirectory = "./customized-path/security-report"
}
}
```
Dependency-Check-Ant makes use of other open source libraries. Please see the [NOTICE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/dependency-check-ant/NOTICE.txt) file for more information.

View File

@@ -20,7 +20,7 @@ Copyright (c) 2013 - Jeremy Long. All Rights Reserved.
<parent>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-parent</artifactId>
<version>1.3.4</version>
<version>1.4.0</version>
</parent>
<artifactId>dependency-check-ant</artifactId>
@@ -256,6 +256,7 @@ Copyright (c) 2013 - Jeremy Long. All Rights Reserved.
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<systemProperties>
<property>
<name>data.directory</name>

View File

@@ -86,8 +86,8 @@ public class Check extends Update {
}
/**
* Returns the path. If the path has not been initialized yet, this class is synchronized, and will instantiate the path
* object.
* Returns the path. If the path has not been initialized yet, this class is
* synchronized, and will instantiate the path object.
*
* @return the path
*/
@@ -109,7 +109,8 @@ public class Check extends Update {
}
/**
* Add a reference to a Path, FileSet, DirSet, or FileList defined elsewhere.
* Add a reference to a Path, FileSet, DirSet, or FileList defined
* elsewhere.
*
* @param r the reference to a path, fileset, dirset or filelist.
*/
@@ -121,7 +122,8 @@ public class Check extends Update {
}
/**
* If this is a reference, this method will add the referenced resource collection to the collection of paths.
* If this is a reference, this method will add the referenced resource
* collection to the collection of paths.
*
* @throws BuildException if the reference is not to a resource collection
*/
@@ -196,7 +198,8 @@ public class Check extends Update {
}
/**
* Specifies the destination directory for the generated Dependency-Check report.
* Specifies the destination directory for the generated Dependency-Check
* report.
*/
private String reportOutputDirectory = ".";
@@ -218,9 +221,11 @@ public class Check extends Update {
this.reportOutputDirectory = reportOutputDirectory;
}
/**
* 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 and the CVSS score is set to 11. The valid range
* for the fail build on CVSS is 0 to 11, where anything above 10 will not cause the build to fail.
* 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 and the CVSS score is set
* to 11. The valid range for the fail build on CVSS is 0 to 11, where
* anything above 10 will not cause the build to fail.
*/
private float failBuildOnCVSS = 11;
@@ -242,8 +247,8 @@ public class Check extends Update {
this.failBuildOnCVSS = failBuildOnCVSS;
}
/**
* Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not recommended that this be turned to false. Default
* is true.
* Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not
* recommended that this be turned to false. Default is true.
*/
private Boolean autoUpdate;
@@ -295,7 +300,8 @@ public class Check extends Update {
}
/**
* The report format to be generated (HTML, XML, VULN, ALL). Default is HTML.
* The report format to be generated (HTML, XML, VULN, ALL). Default is
* HTML.
*/
private String reportFormat = "HTML";
@@ -361,6 +367,29 @@ public class Check extends Update {
this.showSummary = showSummary;
}
/**
* Whether experimental analyzers are enabled.
*/
private Boolean enableExperimental;
/**
* Get the value of enableExperimental.
*
* @return the value of enableExperimental
*/
public Boolean isEnableExperimental() {
return enableExperimental;
}
/**
* Set the value of enableExperimental.
*
* @param enableExperimental new value of enableExperimental
*/
public void setEnableExperimental(Boolean enableExperimental) {
this.enableExperimental = enableExperimental;
}
/**
* Whether or not the Jar Analyzer is enabled.
*/
@@ -621,7 +650,8 @@ public class Check extends Update {
/**
* Set the value of pyDistributionAnalyzerEnabled.
*
* @param pyDistributionAnalyzerEnabled new value of pyDistributionAnalyzerEnabled
* @param pyDistributionAnalyzerEnabled new value of
* pyDistributionAnalyzerEnabled
*/
public void setPyDistributionAnalyzerEnabled(Boolean pyDistributionAnalyzerEnabled) {
this.pyDistributionAnalyzerEnabled = pyDistributionAnalyzerEnabled;
@@ -674,7 +704,8 @@ public class Check extends Update {
}
/**
* The URL of a Nexus server's REST API end point (http://domain/nexus/service/local).
* The URL of a Nexus server's REST API end point
* (http://domain/nexus/service/local).
*/
private String nexusUrl;
@@ -719,8 +750,8 @@ public class Check extends Update {
}
/**
* Additional ZIP File extensions to add analyze. This should be a comma-separated list of file extensions to treat like ZIP
* files.
* Additional ZIP File extensions to add analyze. This should be a
* comma-separated list of file extensions to treat like ZIP files.
*/
private String zipExtensions;
@@ -830,7 +861,8 @@ public class Check extends Update {
}
/**
* Validate the configuration to ensure the parameters have been properly configured/initialized.
* Validate the configuration to ensure the parameters have been properly
* configured/initialized.
*
* @throws BuildException if the task was not configured correctly.
*/
@@ -844,8 +876,9 @@ public class Check extends Update {
}
/**
* Takes the properties supplied and updates the dependency-check settings. Additionally, this sets the system properties
* required to change the proxy server, port, and connection timeout.
* Takes the properties supplied and updates the dependency-check settings.
* Additionally, this sets the system properties required to change the
* proxy server, port, and connection timeout.
*
* @throws BuildException thrown when an invalid setting is configured.
*/
@@ -854,6 +887,7 @@ public class Check extends Update {
super.populateSettings();
Settings.setBooleanIfNotNull(Settings.KEYS.AUTO_UPDATE, autoUpdate);
Settings.setStringIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, enableExperimental);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, pyDistributionAnalyzerEnabled);
Settings.setBooleanIfNotNull(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, pyPackageAnalyzerEnabled);
@@ -875,11 +909,12 @@ public class Check extends Update {
}
/**
* Checks to see if a vulnerability has been identified with a CVSS score that is above the threshold set in the
* configuration.
* Checks to see if a vulnerability has been identified with a CVSS score
* that is above the threshold set in the configuration.
*
* @param dependencies the list of dependency objects
* @throws BuildException thrown if a CVSS score is found that is higher then the threshold set
* @throws BuildException thrown if a CVSS score is found that is higher
* then the threshold set
*/
private void checkForFailure(List<Dependency> dependencies) throws BuildException {
final StringBuilder ids = new StringBuilder();
@@ -903,7 +938,8 @@ public class Check extends Update {
}
/**
* Generates a warning message listing a summary of dependencies and their associated CPE and CVE entries.
* Generates a warning message listing a summary of dependencies and their
* associated CPE and CVE entries.
*
* @param dependencies a list of dependency objects
*/
@@ -943,7 +979,8 @@ public class Check extends Update {
}
/**
* An enumeration of supported report formats: "ALL", "HTML", "XML", "VULN", etc..
* An enumeration of supported report formats: "ALL", "HTML", "XML", "VULN",
* etc..
*/
public static class ReportFormats extends EnumeratedAttribute {

View File

@@ -23,16 +23,18 @@ import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;
/**
* The binding of {@link LoggerFactory} class with an actual instance of {@link ILoggerFactory} is performed using information
* returned by this class.
* The binding of org.slf4j.LoggerFactory class with an actual instance of
* org.slf4j.ILoggerFactory is performed using information returned by this
* class.
*
* @author colezlaw
*/
//CSOFF: FinalClass
public class StaticLoggerBinder implements LoggerFactoryBinder {
//CSON: FinalClass
/**
* The unique instance of this class
*
*/
private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
@@ -46,7 +48,8 @@ public class StaticLoggerBinder implements LoggerFactoryBinder {
}
/**
* Ant tasks have the log method we actually want to call. So we hang onto the task as a delegate
* Ant tasks have the log method we actually want to call. So we hang onto
* the task as a delegate
*/
private Task task = null;
@@ -61,16 +64,24 @@ public class StaticLoggerBinder implements LoggerFactoryBinder {
}
/**
* Declare the version of the SLF4J API this implementation is compiled against. The value of this filed is usually modified
* with each release.
* Declare the version of the SLF4J API this implementation is compiled
* against. The value of this filed is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
//CSOFF: StaticVariableName
//CSOFF: VisibilityModifier
public static String REQUESTED_API_VERSION = "1.7.12"; // final
//CSON: VisibilityModifier
//CSON: StaticVariableName
/**
* The logger factory class string.
*/
private static final String LOGGER_FACTORY_CLASS = AntLoggerFactory.class.getName();
/**
* The ILoggerFactory instance returned by the {@link #getLoggerFactory} method should always be the smae object
* The ILoggerFactory instance returned by the {@link #getLoggerFactory}
* method should always be the smae object
*/
private ILoggerFactory loggerFactory;

View File

@@ -27,7 +27,7 @@ the project's dependencies.
Configuration: dependency-check Task
--------------------
The following properties can be set on the dependency-check-update task.
The following properties can be set on the dependency-check task.
Property | Description | Default Value
----------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------
@@ -38,11 +38,12 @@ projectName | The name of the project being scanned.
reportFormat | 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
reportOutputDirectory | The location to write the report(s). Note, this is not used if generating the report as part of a `mvn site` build | 'target'
suppressionFile | The file path to the XML suppression file \- used to suppress [false positives](../general/suppression.html) | &nbsp;
proxyServer | The Proxy Server. | &nbsp;
proxyServer | The Proxy Server; see the [proxy configuration](../data/proxy.html) page for more information. | &nbsp;
proxyPort | The Proxy Port. | &nbsp;
proxyUsername | Defines the proxy user name. | &nbsp;
proxyPassword | Defines the proxy password. | &nbsp;
connectionTimeout | The URL Connection Timeout. | &nbsp;
enableExperimental | Enable the [experimental analyzers](../analyzers/index.html). If not enabled the experimental analyzers (see below) will not be loaded or used. | false
Analyzer Configuration
====================
@@ -52,26 +53,26 @@ Note, that specific analyzers will automatically disable themselves if no file
types that they support are detected - so specifically disabling them may not
be needed.
Property | Description | Default Value
------------------------------|---------------------------------------------------------------------------|------------------
archiveAnalyzerEnabled | Sets whether the Archive Analyzer will be used. | true
Property | Description | Default Value
------------------------------|-----------------------------------------------------------------------------------|------------------
archiveAnalyzerEnabled | Sets whether the Archive Analyzer will be used. | true
zipExtensions | A comma-separated list of additional file extensions to be treated like a ZIP file, the contents will be extracted and analyzed. | &nbsp;
jarAnalyzer | Sets whether the Jar Analyzer will be used. | true
jarAnalyzer | Sets whether the Jar Analyzer will be used. | true
centralAnalyzerEnabled | Sets whether the Central Analyzer will be used. **Disabling this analyzer is not recommended as it could lead to false negatives (e.g. libraries that have vulnerabilities may not be reported correctly).** If this analyzer is being disabled there is a good chance you also want to disable the Nexus Analyzer (see below). | true
nexusAnalyzerEnabled | Sets whether Nexus Analyzer will be used. This analyzer is superceded by the Central Analyzer; however, you can configure this to run against a Nexus Pro installation. | true
nexusUrl | Defines the Nexus web service endpoint (example http://domain.enterprise/nexus/service/local/). If not set the Nexus Analyzer will be disabled. | &nbsp;
nexusUsesProxy | Whether or not the defined proxy should be used when connecting to Nexus. | true
pyDistributionAnalyzerEnabled | Sets whether the Python Distribution Analyzer will be used. | true
pyPackageAnalyzerEnabled | Sets whether the Python Package Analyzer will be used. | true
rubygemsAnalyzerEnabled | Sets whether the Ruby Gemspec Analyzer will be used. | true
opensslAnalyzerEnabled | Sets whether or not the openssl Analyzer should be used. | true
cmakeAnalyzerEnabled | Sets whether or not the CMake Analyzer should be used. | true
autoconfAnalyzerEnabled | Sets whether or not the autoconf Analyzer should be used. | true
composerAnalyzerEnabled | Sets whether or not the PHP Composer Lock File Analyzer should be used. | true
nodeAnalyzerEnabled | Sets whether or not the Node.js Analyzer should be used. | true
nuspecAnalyzerEnabled | Sets whether or not the .NET Nuget Nuspec Analyzer will be used. | true
assemblyAnalyzerEnabled | Sets whether or not the .NET Assembly Analyzer should be used. | true
pathToMono | The path to Mono for .NET assembly analysis on non-windows systems. | &nbsp;
nexusUsesProxy | Whether or not the defined proxy should be used when connecting to Nexus. | true
pyDistributionAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) Python Distribution Analyzer will be used. | true
pyPackageAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) Python Package Analyzer will be used. | true
rubygemsAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) Ruby Gemspec Analyzer will be used. | true
opensslAnalyzerEnabled | Sets whether the openssl Analyzer should be used. | true
cmakeAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) CMake Analyzer should be used. | true
autoconfAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) autoconf Analyzer should be used. | true
composerAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) PHP Composer Lock File Analyzer should be used. | true
nodeAnalyzerEnabled | Sets whether the [experimental](../analyzers/index.html) Node.js Analyzer should be used. | true
nuspecAnalyzerEnabled | Sets whether the .NET Nuget Nuspec Analyzer will be used. | true
assemblyAnalyzerEnabled | Sets whether the .NET Assembly Analyzer should be used. | true
pathToMono | The path to Mono for .NET assembly analysis on non-windows systems. | &nbsp;
Advanced Configuration
====================

View File

@@ -16,8 +16,11 @@ Installation
<property name="dependency-check.home" value="C:/tools/dependency-check-ant"/>
<path id="dependency-check.path">
<pathelement location="${dependency-check.home}/dependency-check-ant.jar"/>
<fileset dir="${dependency-check.home}/lib">
<include name="*.jar"/>
</fileset>
</path>
<taskdef resource="dependency-check-taskdefs.properties">
<taskdef resource="dependency-check-taskdefs.properties">
<classpath refid="dependency-check.path" />
</taskdef>
```

View File

@@ -27,7 +27,7 @@ Copyright (c) 2013 Jeremy Long. All Rights Reserved.
<item name="dependency-check" href="../index.html"/>
</breadcrumbs>
<menu name="Getting Started">
<item name="Installation" href="installation.html"/>
<item name="Installation" href="index.html"/>
<item name="Configuration" href="configuration.html"/>
</menu>
<menu ref="reports" />

View File

@@ -5,7 +5,7 @@ performed are a "best effort" and as such, there could be false positives as wel
vulnerabilities in 3rd party components is a well-known problem and is currently documented in the 2013 OWASP
Top 10 as [A9 - Using Components with Known Vulnerabilities](https://www.owasp.org/index.php/Top_10_2013-A9-Using_Components_with_Known_Vulnerabilities).
Documentation and links to production binary releases can be found on the [github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-cli/installation.html).
Documentation and links to production binary releases can be found on the [github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-cli/index.html).
Mailing List
------------

View File

@@ -20,7 +20,7 @@ Copyright (c) 2012 - Jeremy Long. All Rights Reserved.
<parent>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-parent</artifactId>
<version>1.3.4</version>
<version>1.4.0</version>
</parent>
<artifactId>dependency-check-cli</artifactId>
@@ -110,6 +110,7 @@ Copyright (c) 2012 - Jeremy Long. All Rights Reserved.
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<systemProperties>
<property>
<name>cpe</name>

View File

@@ -280,6 +280,7 @@ public class App {
final String cveBase12 = cli.getBaseCve12Url();
final String cveBase20 = cli.getBaseCve20Url();
final Integer cveValidForHours = cli.getCveValidForHours();
final boolean experimentalEnabled = cli.isExperimentalEnabled();
if (propertiesFile != null) {
try {
@@ -318,6 +319,7 @@ public class App {
Settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
//File Type Analyzer Settings
Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, experimentalEnabled);
Settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, !cli.isJarDisabled());
Settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, !cli.isArchiveDisabled());
Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, !cli.isPythonDistributionDisabled());

View File

@@ -58,7 +58,8 @@ public final class CliParser {
* Parses the arguments passed in and captures the results for later use.
*
* @param args the command line arguments
* @throws FileNotFoundException is thrown when a 'file' argument does not point to a file that exists.
* @throws FileNotFoundException is thrown when a 'file' argument does not
* point to a file that exists.
* @throws ParseException is thrown when a Parse Exception occurs.
*/
public void parse(String[] args) throws FileNotFoundException, ParseException {
@@ -85,9 +86,10 @@ public final class CliParser {
/**
* Validates that the command line arguments are valid.
*
* @throws FileNotFoundException if there is a file specified by either the SCAN or CPE command line arguments that does not
* exist.
* @throws ParseException is thrown if there is an exception parsing the command line.
* @throws FileNotFoundException if there is a file specified by either the
* SCAN or CPE command line arguments that does not exist.
* @throws ParseException is thrown if there is an exception parsing the
* command line.
*/
private void validateArgs() throws FileNotFoundException, ParseException {
if (isUpdateOnly() || isRunScan()) {
@@ -141,12 +143,14 @@ public final class CliParser {
}
/**
* Validates whether or not the path(s) points at a file that exists; if the path(s) does not point to an existing file a
* FileNotFoundException is thrown.
* Validates whether or not the path(s) points at a file that exists; if the
* path(s) does not point to an existing file a FileNotFoundException is
* thrown.
*
* @param paths the paths to validate if they exists
* @param optType the option being validated (e.g. scan, out, etc.)
* @throws FileNotFoundException is thrown if one of the paths being validated does not exist.
* @throws FileNotFoundException is thrown if one of the paths being
* validated does not exist.
*/
private void validatePathExists(String[] paths, String optType) throws FileNotFoundException {
for (String path : paths) {
@@ -155,12 +159,14 @@ public final class CliParser {
}
/**
* Validates whether or not the path points at a file that exists; if the path does not point to an existing file a
* FileNotFoundException is thrown.
* Validates whether or not the path points at a file that exists; if the
* path does not point to an existing file a FileNotFoundException is
* thrown.
*
* @param path the paths to validate if they exists
* @param argumentName the argument being validated (e.g. scan, out, etc.)
* @throws FileNotFoundException is thrown if the path being validated does not exist.
* @throws FileNotFoundException is thrown if the path being validated does
* not exist.
*/
private void validatePathExists(String path, String argumentName) throws FileNotFoundException {
if (path == null) {
@@ -181,12 +187,10 @@ public final class CliParser {
throw new FileNotFoundException(msg);
}
}
} else {
if (!f.exists()) {
isValid = false;
final String msg = String.format("Invalid '%s' argument: '%s'", argumentName, path);
throw new FileNotFoundException(msg);
}
} else if (!f.exists()) {
isValid = false;
final String msg = String.format("Invalid '%s' argument: '%s'", argumentName, path);
throw new FileNotFoundException(msg);
}
} else if (path.startsWith("//") || path.startsWith("\\\\")) {
isValid = false;
@@ -196,7 +200,8 @@ public final class CliParser {
}
/**
* Generates an Options collection that is used to parse the command line and to display the help message.
* Generates an Options collection that is used to parse the command line
* and to display the help message.
*
* @return the command line options used for parsing the command line
*/
@@ -272,6 +277,10 @@ public final class CliParser {
.desc("The number of hours to wait before checking for new updates from the NVD.")
.build();
final Option experimentalEnabled = Option.builder().longOpt(ARGUMENT.EXPERIMENTAL)
.desc("Enables the experimental analzers.")
.build();
//This is an option group because it can be specified more then once.
final OptionGroup og = new OptionGroup();
og.addOption(path);
@@ -292,12 +301,14 @@ public final class CliParser {
.addOption(props)
.addOption(verboseLog)
.addOption(suppressionFile)
.addOption(cveValidForHours);
.addOption(cveValidForHours)
.addOption(experimentalEnabled);
}
/**
* Adds the advanced command line options to the given options collection. These are split out for purposes of being able to
* display two different help messages.
* Adds the advanced command line options to the given options collection.
* These are split out for purposes of being able to display two different
* help messages.
*
* @param options a collection of command line arguments
* @throws IllegalArgumentException thrown if there is an exception
@@ -466,8 +477,10 @@ public final class CliParser {
}
/**
* Adds the deprecated command line options to the given options collection. These are split out for purposes of not including
* them in the help message. We need to add the deprecated options so as not to break existing scripts.
* Adds the deprecated command line options to the given options collection.
* These are split out for purposes of not including them in the help
* message. We need to add the deprecated options so as not to break
* existing scripts.
*
* @param options a collection of command line arguments
* @throws IllegalArgumentException thrown if there is an exception
@@ -514,7 +527,8 @@ public final class CliParser {
}
/**
* Returns the symbolic link depth (how deeply symbolic links will be followed).
* Returns the symbolic link depth (how deeply symbolic links will be
* followed).
*
* @return the symbolic link depth
*/
@@ -534,7 +548,8 @@ public final class CliParser {
/**
* Returns true if the disableJar command line argument was specified.
*
* @return true if the disableJar command line argument was specified; otherwise false
* @return true if the disableJar command line argument was specified;
* otherwise false
*/
public boolean isJarDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_JAR);
@@ -543,7 +558,8 @@ public final class CliParser {
/**
* Returns true if the disableArchive command line argument was specified.
*
* @return true if the disableArchive command line argument was specified; otherwise false
* @return true if the disableArchive command line argument was specified;
* otherwise false
*/
public boolean isArchiveDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_ARCHIVE);
@@ -552,7 +568,8 @@ public final class CliParser {
/**
* Returns true if the disableNuspec command line argument was specified.
*
* @return true if the disableNuspec command line argument was specified; otherwise false
* @return true if the disableNuspec command line argument was specified;
* otherwise false
*/
public boolean isNuspecDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_NUSPEC);
@@ -561,16 +578,19 @@ public final class CliParser {
/**
* Returns true if the disableAssembly command line argument was specified.
*
* @return true if the disableAssembly command line argument was specified; otherwise false
* @return true if the disableAssembly command line argument was specified;
* otherwise false
*/
public boolean isAssemblyDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_ASSEMBLY);
}
/**
* Returns true if the disableBundleAudit command line argument was specified.
* Returns true if the disableBundleAudit command line argument was
* specified.
*
* @return true if the disableBundleAudit command line argument was specified; otherwise false
* @return true if the disableBundleAudit command line argument was
* specified; otherwise false
*/
public boolean isBundleAuditDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_BUNDLE_AUDIT);
@@ -579,7 +599,8 @@ public final class CliParser {
/**
* Returns true if the disablePyDist command line argument was specified.
*
* @return true if the disablePyDist command line argument was specified; otherwise false
* @return true if the disablePyDist command line argument was specified;
* otherwise false
*/
public boolean isPythonDistributionDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_PY_DIST);
@@ -588,7 +609,8 @@ public final class CliParser {
/**
* Returns true if the disablePyPkg command line argument was specified.
*
* @return true if the disablePyPkg command line argument was specified; otherwise false
* @return true if the disablePyPkg command line argument was specified;
* otherwise false
*/
public boolean isPythonPackageDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_PY_PKG);
@@ -597,7 +619,8 @@ public final class CliParser {
/**
* Returns whether the Ruby gemspec analyzer is disabled.
*
* @return true if the {@link ARGUMENT#DISABLE_RUBYGEMS} command line argument was specified; otherwise false
* @return true if the {@link ARGUMENT#DISABLE_RUBYGEMS} command line
* argument was specified; otherwise false
*/
public boolean isRubyGemspecDisabled() {
return (null != line) && line.hasOption(ARGUMENT.DISABLE_RUBYGEMS);
@@ -606,7 +629,8 @@ public final class CliParser {
/**
* Returns true if the disableCmake command line argument was specified.
*
* @return true if the disableCmake command line argument was specified; otherwise false
* @return true if the disableCmake command line argument was specified;
* otherwise false
*/
public boolean isCmakeDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_CMAKE);
@@ -615,7 +639,8 @@ public final class CliParser {
/**
* Returns true if the disableAutoconf command line argument was specified.
*
* @return true if the disableAutoconf command line argument was specified; otherwise false
* @return true if the disableAutoconf command line argument was specified;
* otherwise false
*/
public boolean isAutoconfDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_AUTOCONF);
@@ -624,7 +649,8 @@ public final class CliParser {
/**
* Returns true if the disableComposer command line argument was specified.
*
* @return true if the disableComposer command line argument was specified; otherwise false
* @return true if the disableComposer command line argument was specified;
* otherwise false
*/
public boolean isComposerDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_COMPOSER);
@@ -633,7 +659,8 @@ public final class CliParser {
/**
* Returns true if the disableNexus command line argument was specified.
*
* @return true if the disableNexus command line argument was specified; otherwise false
* @return true if the disableNexus command line argument was specified;
* otherwise false
*/
public boolean isNexusDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_NEXUS);
@@ -642,7 +669,8 @@ public final class CliParser {
/**
* Returns true if the disableOpenSSL command line argument was specified.
*
* @return true if the disableOpenSSL command line argument was specified; otherwise false
* @return true if the disableOpenSSL command line argument was specified;
* otherwise false
*/
public boolean isOpenSSLDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_OPENSSL);
@@ -651,7 +679,8 @@ public final class CliParser {
/**
* Returns true if the disableNodeJS command line argument was specified.
*
* @return true if the disableNodeJS command line argument was specified; otherwise false
* @return true if the disableNodeJS command line argument was specified;
* otherwise false
*/
public boolean isNodeJsDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_NODE_JS);
@@ -660,7 +689,8 @@ public final class CliParser {
/**
* Returns true if the disableCentral command line argument was specified.
*
* @return true if the disableCentral command line argument was specified; otherwise false
* @return true if the disableCentral command line argument was specified;
* otherwise false
*/
public boolean isCentralDisabled() {
return (line != null) && line.hasOption(ARGUMENT.DISABLE_CENTRAL);
@@ -669,7 +699,8 @@ public final class CliParser {
/**
* Returns the url to the nexus server if one was specified.
*
* @return the url to the nexus server; if none was specified this will return null;
* @return the url to the nexus server; if none was specified this will
* return null;
*/
public String getNexusUrl() {
if (line == null || !line.hasOption(ARGUMENT.NEXUS_URL)) {
@@ -680,9 +711,11 @@ public final class CliParser {
}
/**
* Returns true if the Nexus Analyzer should use the configured proxy to connect to Nexus; otherwise false is returned.
* Returns true if the Nexus Analyzer should use the configured proxy to
* connect to Nexus; otherwise false is returned.
*
* @return true if the Nexus Analyzer should use the configured proxy to connect to Nexus; otherwise false
* @return true if the Nexus Analyzer should use the configured proxy to
* connect to Nexus; otherwise false
*/
public boolean isNexusUsesProxy() {
// If they didn't specify whether Nexus needs to use the proxy, we should
@@ -722,7 +755,8 @@ public final class CliParser {
}
/**
* Retrieves the file command line parameter(s) specified for the 'scan' argument.
* Retrieves the file command line parameter(s) specified for the 'scan'
* argument.
*
* @return the file paths specified on the command line for scan
*/
@@ -731,7 +765,8 @@ public final class CliParser {
}
/**
* Retrieves the list of excluded file patterns specified by the 'exclude' argument.
* Retrieves the list of excluded file patterns specified by the 'exclude'
* argument.
*
* @return the excluded file patterns
*/
@@ -740,7 +775,8 @@ public final class CliParser {
}
/**
* Returns the directory to write the reports to specified on the command line.
* Returns the directory to write the reports to specified on the command
* line.
*
* @return the path to the reports directory.
*/
@@ -749,7 +785,8 @@ public final class CliParser {
}
/**
* Returns the path to Mono for .NET Assembly analysis on non-windows systems.
* Returns the path to Mono for .NET Assembly analysis on non-windows
* systems.
*
* @return the path to Mono
*/
@@ -767,7 +804,8 @@ public final class CliParser {
}
/**
* Returns the output format specified on the command line. Defaults to HTML if no format was specified.
* Returns the output format specified on the command line. Defaults to HTML
* if no format was specified.
*
* @return the output format name.
*/
@@ -934,9 +972,11 @@ public final class CliParser {
}
/**
* Checks if the auto update feature has been disabled. If it has been disabled via the command line this will return false.
* Checks if the auto update feature has been disabled. If it has been
* disabled via the command line this will return false.
*
* @return <code>true</code> if auto-update is allowed; otherwise <code>false</code>
* @return <code>true</code> if auto-update is allowed; otherwise
* <code>false</code>
*/
public boolean isAutoUpdate() {
return line != null && !line.hasOption(ARGUMENT.DISABLE_AUTO_UPDATE);
@@ -945,7 +985,8 @@ public final class CliParser {
/**
* Checks if the update only flag has been set.
*
* @return <code>true</code> if the update only flag has been set; otherwise <code>false</code>.
* @return <code>true</code> if the update only flag has been set; otherwise
* <code>false</code>.
*/
public boolean isUpdateOnly() {
return line != null && line.hasOption(ARGUMENT.UPDATE_ONLY);
@@ -954,14 +995,16 @@ public final class CliParser {
/**
* Checks if the purge NVD flag has been set.
*
* @return <code>true</code> if the purge nvd flag has been set; otherwise <code>false</code>.
* @return <code>true</code> if the purge nvd flag has been set; otherwise
* <code>false</code>.
*/
public boolean isPurge() {
return line != null && line.hasOption(ARGUMENT.PURGE_NVD);
}
/**
* Returns the database driver name if specified; otherwise null is returned.
* Returns the database driver name if specified; otherwise null is
* returned.
*
* @return the database driver name if specified; otherwise null is returned
*/
@@ -970,7 +1013,8 @@ public final class CliParser {
}
/**
* Returns the database driver path if specified; otherwise null is returned.
* Returns the database driver path if specified; otherwise null is
* returned.
*
* @return the database driver name if specified; otherwise null is returned
*/
@@ -979,34 +1023,41 @@ public final class CliParser {
}
/**
* Returns the database connection string if specified; otherwise null is returned.
* Returns the database connection string if specified; otherwise null is
* returned.
*
* @return the database connection string if specified; otherwise null is returned
* @return the database connection string if specified; otherwise null is
* returned
*/
public String getConnectionString() {
return line.getOptionValue(ARGUMENT.CONNECTION_STRING);
}
/**
* Returns the database database user name if specified; otherwise null is returned.
* Returns the database database user name if specified; otherwise null is
* returned.
*
* @return the database database user name if specified; otherwise null is returned
* @return the database database user name if specified; otherwise null is
* returned
*/
public String getDatabaseUser() {
return line.getOptionValue(ARGUMENT.DB_NAME);
}
/**
* Returns the database database password if specified; otherwise null is returned.
* Returns the database database password if specified; otherwise null is
* returned.
*
* @return the database database password if specified; otherwise null is returned
* @return the database database password if specified; otherwise null is
* returned
*/
public String getDatabasePassword() {
return line.getOptionValue(ARGUMENT.DB_PASSWORD);
}
/**
* Returns the additional Extensions if specified; otherwise null is returned.
* Returns the additional Extensions if specified; otherwise null is
* returned.
*
* @return the additional Extensions; otherwise null is returned
*/
@@ -1028,7 +1079,17 @@ public final class CliParser {
}
/**
* A collection of static final strings that represent the possible command line arguments.
* Returns true if the experimental analyzers are enabled.
*
* @return true if the experimental analyzers are enabled; otherwise false
*/
public boolean isExperimentalEnabled() {
return line.hasOption(ARGUMENT.EXPERIMENTAL);
}
/**
* A collection of static final strings that represent the possible command
* line arguments.
*/
public static class ARGUMENT {
@@ -1041,50 +1102,61 @@ public final class CliParser {
*/
public static final String SCAN_SHORT = "s";
/**
* The long CLI argument name specifying that the CPE/CVE/etc. data should not be automatically updated.
* The long CLI argument name specifying that the CPE/CVE/etc. data
* should not be automatically updated.
*/
public static final String DISABLE_AUTO_UPDATE = "noupdate";
/**
* The short CLI argument name specifying that the CPE/CVE/etc. data should not be automatically updated.
* The short CLI argument name specifying that the CPE/CVE/etc. data
* should not be automatically updated.
*/
public static final String DISABLE_AUTO_UPDATE_SHORT = "n";
/**
* The long CLI argument name specifying that only the update phase should be executed; no scan should be run.
* The long CLI argument name specifying that only the update phase
* should be executed; no scan should be run.
*/
public static final String UPDATE_ONLY = "updateonly";
/**
* The long CLI argument name specifying that only the update phase should be executed; no scan should be run.
* The long CLI argument name specifying that only the update phase
* should be executed; no scan should be run.
*/
public static final String PURGE_NVD = "purge";
/**
* The long CLI argument name specifying the directory to write the reports to.
* The long CLI argument name specifying the directory to write the
* reports to.
*/
public static final String OUT = "out";
/**
* The short CLI argument name specifying the directory to write the reports to.
* The short CLI argument name specifying the directory to write the
* reports to.
*/
public static final String OUT_SHORT = "o";
/**
* The long CLI argument name specifying the output format to write the reports to.
* The long CLI argument name specifying the output format to write the
* reports to.
*/
public static final String OUTPUT_FORMAT = "format";
/**
* The short CLI argument name specifying the output format to write the reports to.
* The short CLI argument name specifying the output format to write the
* reports to.
*/
public static final String OUTPUT_FORMAT_SHORT = "f";
/**
* The long CLI argument name specifying the name of the project to be scanned.
* The long CLI argument name specifying the name of the project to be
* scanned.
*/
public static final String PROJECT = "project";
/**
* The long CLI argument name specifying the name of the application to be scanned.
* The long CLI argument name specifying the name of the application to
* be scanned.
*
* @deprecated project should be used instead
*/
@Deprecated
public static final String APP_NAME = "app";
/**
* The short CLI argument name specifying the name of the application to be scanned.
* The short CLI argument name specifying the name of the application to
* be scanned.
*
* @deprecated project should be used instead
*/
@@ -1142,11 +1214,13 @@ public final class CliParser {
*/
public static final String CONNECTION_TIMEOUT = "connectiontimeout";
/**
* The short CLI argument name for setting the location of an additional properties file.
* The short CLI argument name for setting the location of an additional
* properties file.
*/
public static final String PROP_SHORT = "P";
/**
* The CLI argument name for setting the location of an additional properties file.
* The CLI argument name for setting the location of an additional
* properties file.
*/
public static final String PROP = "propertyfile";
/**
@@ -1170,7 +1244,8 @@ public final class CliParser {
*/
public static final String CVE_BASE_20 = "cveUrl20Base";
/**
* The short CLI argument name for setting the location of the data directory.
* The short CLI argument name for setting the location of the data
* directory.
*/
public static final String DATA_DIRECTORY_SHORT = "d";
/**
@@ -1178,20 +1253,24 @@ public final class CliParser {
*/
public static final String VERBOSE_LOG = "log";
/**
* The short CLI argument name for setting the location of the data directory.
* The short CLI argument name for setting the location of the data
* directory.
*/
public static final String VERBOSE_LOG_SHORT = "l";
/**
* The CLI argument name for setting the depth of symbolic links that will be followed.
* The CLI argument name for setting the depth of symbolic links that
* will be followed.
*/
public static final String SYM_LINK_DEPTH = "symLink";
/**
* The CLI argument name for setting the location of the suppression file.
* The CLI argument name for setting the location of the suppression
* file.
*/
public static final String SUPPRESSION_FILE = "suppression";
/**
* The CLI argument name for setting the location of the suppression file.
* The CLI argument name for setting the location of the suppression
* file.
*/
public static final String CVE_VALID_FOR_HOURS = "cveValidForHours";
/**
@@ -1259,7 +1338,8 @@ public final class CliParser {
*/
public static final String NEXUS_URL = "nexus";
/**
* Whether or not the defined proxy should be used when connecting to Nexus.
* Whether or not the defined proxy should be used when connecting to
* Nexus.
*/
public static final String NEXUS_USES_PROXY = "nexusUsesProxy";
/**
@@ -1279,11 +1359,13 @@ public final class CliParser {
*/
public static final String DB_DRIVER = "dbDriverName";
/**
* The CLI argument name for setting the path to the database driver; in case it is not on the class path.
* The CLI argument name for setting the path to the database driver; in
* case it is not on the class path.
*/
public static final String DB_DRIVER_PATH = "dbDriverPath";
/**
* The CLI argument name for setting the path to mono for .NET Assembly analysis on non-windows systems.
* The CLI argument name for setting the path to mono for .NET Assembly
* analysis on non-windows systems.
*/
public static final String PATH_TO_MONO = "mono";
/**
@@ -1295,8 +1377,13 @@ public final class CliParser {
*/
public static final String EXCLUDE = "exclude";
/**
* The CLI argument name for setting the path to bundle-audit for Ruby bundle analysis.
* The CLI argument name for setting the path to bundle-audit for Ruby
* bundle analysis.
*/
public static final String PATH_TO_BUNDLE_AUDIT = "bundleAudit";
/**
* The CLI argument to enable the experimental analyzers.
*/
private static final String EXPERIMENTAL = "enableExperimental";
}
}

View File

@@ -18,7 +18,7 @@ Short | Argument&nbsp;Name&nbsp;&nbsp; | Parameter | Description | Requir
| \-\-advancedHelp | | Print the advanced help message. | Optional
\-v | \-\-version | | Print the version information. | Optional
| \-\-cveValidForHours | \<hours\> | The number of hours to wait before checking for new updates from the NVD. The default is 4 hours. | Optional
| \-\-experimental | | Enable the [experimental analyzers](../analyzers/index.html). If not set the analyzers marked as experimental below will not be loaded or used. | Optional
Advanced Options
================
@@ -30,18 +30,18 @@ Short | Argument&nbsp;Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | Paramete
| \-\-cveUrl20Base | \<url\> | Base URL for each year's CVE 2.0, the %d will be replaced with the year | https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml.gz
\-P | \-\-propertyfile | \<file\> | Specifies a file that contains properties to use instead of applicaion defaults. | &nbsp;
| \-\-updateonly | | If set only the update phase of dependency-check will be executed; no scan will be executed and no report will be generated. | &nbsp;
| \-\-disablePyDist | | Sets whether the Python Distribution Analyzer will be used. | false
| \-\-disablePyPkg | | Sets whether the Python Package Analyzer will be used. | false
| \-\-disableNodeJS | | Sets whether the Node.js Package Analyzer will be used. | false
| \-\-disableRubygems | | Sets whether the Ruby Gemspec Analyzer will be used. | false
| \-\-disableBundleAudit | | Sets whether the Ruby Bundler Audit Analyzer will be used. | false
| \-\-disableAutoconf | | Sets whether the Autoconf Analyzer will be used. | false
| \-\-disablePyDist | | Sets whether the [experimental](../analyzers/index.html) Python Distribution Analyzer will be used. | false
| \-\-disablePyPkg | | Sets whether the [experimental](../analyzers/index.html) Python Package Analyzer will be used. | false
| \-\-disableNodeJS | | Sets whether the [experimental](../analyzers/index.html) Node.js Package Analyzer will be used. | false
| \-\-disableRubygems | | Sets whether the [experimental](../analyzers/index.html) Ruby Gemspec Analyzer will be used. | false
| \-\-disableBundleAudit | | Sets whether the [experimental](../analyzers/index.html) Ruby Bundler Audit Analyzer will be used. | false
| \-\-disableAutoconf | | Sets whether the [experimental](../analyzers/index.html) Autoconf Analyzer will be used. | false
| \-\-disableOpenSSL | | Sets whether the OpenSSL Analyzer will be used. | false
| \-\-disableCmake | | Sets whether the Cmake Analyzer will be disabled. | false
| \-\-disableCmake | | Sets whether the [experimental](../analyzers/index.html) Cmake Analyzer will be disabled. | false
| \-\-disableArchive | | Sets whether the Archive Analyzer will be disabled. | false
| \-\-zipExtensions | \<strings\> | A comma-separated list of additional file extensions to be treated like a ZIP file, the contents will be extracted and analyzed. | &nbsp;
| \-\-disableJar | | Sets whether the Jar Analyzer will be disabled. | false
| \-\-disableComposer | | Sets whether the PHP Composer Lock File Analyzer will be disabled. | false
| \-\-disableComposer | | Sets whether the [experimental](../analyzers/index.html) PHP Composer Lock File Analyzer will be disabled. | false
| \-\-disableCentral | | Sets whether the Central Analyzer will be used. **Disabling this analyzer is not recommended as it could lead to false negatives (e.g. libraries that have vulnerabilities may not be reported correctly).** If this analyzer is being disabled there is a good chance you also want to disable the Nexus Analyzer. | false
| \-\-disableNexus | | Sets whether the Nexus Analyzer will be used. Note, this has been superceded by the Central Analyzer. However, you can configure the Nexus URL to utilize an internally hosted Nexus Pro server. | false
| \-\-nexus | \<url\> | The url to the Nexus Server's web service end point (example: http://domain.enterprise/nexus/service/local/). If not set the Nexus Analyzer will be disabled. | &nbsp;
@@ -50,7 +50,7 @@ Short | Argument&nbsp;Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | Paramete
| \-\-disableAssembly | | Sets whether or not the .NET Assembly Analyzer should be used. | false
| \-\-mono | \<path\> | The path to Mono for .NET Assembly analysis on non-windows systems. | &nbsp;
| \-\-bundleAudit | | The path to the bundle-audit executable. | &nbsp;
| \-\-proxyserver | \<server\> | The proxy server to use when downloading resources. | &nbsp;
| \-\-proxyserver | \<server\> | The proxy server to use when downloading resources; see the [proxy configuration](../data/proxy.html) page for more information. | &nbsp;
| \-\-proxyport | \<port\> | The proxy port to use when downloading resources. | &nbsp;
| \-\-connectiontimeout | \<timeout\> | The connection timeout (in milliseconds) to use when downloading resources. | &nbsp;
| \-\-proxypass | \<pass\> | The proxy password to use when downloading resources. | &nbsp;

View File

@@ -20,7 +20,7 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
<parent>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-parent</artifactId>
<version>1.3.4</version>
<version>1.4.0</version>
</parent>
<artifactId>dependency-check-core</artifactId>
@@ -83,9 +83,6 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
</testResource>
<testResource>
<directory>${basedir}/src/test/resources</directory>
<excludes>
<exclude>**/mysql-connector-java-5.1.27-bin.jar</exclude>
</excludes>
<filtering>false</filtering>
</testResource>
</testResources>
@@ -178,6 +175,7 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dfile.encoding=UTF-8</argLine>
<systemProperties>
<property>
<name>data.directory</name>
@@ -454,6 +452,13 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
<scope>test</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.0</version>
<scope>test</scope>
<optional>true</optional>
</dependency>
</dependencies>
<profiles>
<profile>

View File

@@ -126,9 +126,8 @@ public class Engine implements FileFilter {
}
final AnalyzerService service = new AnalyzerService(serviceClassLoader);
final Iterator<Analyzer> iterator = service.getAnalyzers();
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
final List<Analyzer> iterator = service.getAnalyzers();
for (Analyzer a : iterator) {
analyzers.get(a.getAnalysisPhase()).add(a);
if (a instanceof FileTypeAnalyzer) {
this.fileTypeAnalyzers.add((FileTypeAnalyzer) a);

View File

@@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory;
*
* <h2>Example:</h2>
* <pre>
* List<Dependency> dependencies = new ArrayList<Dependency>();
* List&lt;Dependency&gt; dependencies = new ArrayList&lt;Dependency&gt;();
* Dependency dependency = new Dependency(new File(FileUtils.getBitBucket()));
* dependency.getProductEvidence().addEvidence("my-datasource", "name", "Jetty", Confidence.HIGH);
* dependency.getVersionEvidence().addEvidence("my-datasource", "version", "5.1.10", Confidence.HIGH);
@@ -55,7 +55,7 @@ import org.slf4j.LoggerFactory;
* scan.execute();
* </pre>
*
* @author Steve Springett <steve.springett@owasp.org>
* @author Steve Springett
*/
@SuppressWarnings("unused")
public class DependencyCheckScanAgent {

View File

@@ -104,12 +104,11 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
* <p>
* Returns the {@link java.io.FileFilter} used to determine which files are to be analyzed. An example would be an analyzer
* that inspected Java jar files. Implementors may use {@link org.owasp.dependencycheck.utils.FileFilterBuilder}.</p>
*
* @return the file filter used to determine which files are to be analyzed
* <p/>
* <p>
* If the analyzer returns null it will not cause additional files to be analyzed, but will be executed against every file
* loaded.</p>
*
* @return the file filter used to determine which files are to be analyzed
*/
protected abstract FileFilter getFileFilter();
@@ -205,7 +204,6 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
* <p>
* Utility method to help in the creation of the extensions set. This constructs a new Set that can be used in a final static
* declaration.</p>
* <p/>
* <p>
* This implementation was copied from
* http://stackoverflow.com/questions/2041778/initialize-java-hashset-values-by-construction</p>

View File

@@ -34,9 +34,11 @@ import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* Abstract base suppression analyzer that contains methods for parsing the suppression xml file.
* Abstract base suppression analyzer that contains methods for parsing the
* suppression xml file.
*
* @author Jeremy Long
*/
@@ -103,6 +105,10 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
try {
rules = parser.parseSuppressionRules(this.getClass().getClassLoader().getResourceAsStream("dependencycheck-base-suppression.xml"));
} catch (SuppressionParseException ex) {
LOGGER.error("Unable to parse the base suppression data file");
LOGGER.debug("Unable to parse the base suppression data file", ex);
} catch (SAXException ex) {
LOGGER.error("Unable to parse the base suppression data file");
LOGGER.debug("Unable to parse the base suppression data file", ex);
}
final String suppressionFilePath = Settings.getString(Settings.KEYS.SUPPRESSION_FILE);
@@ -167,7 +173,8 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
*
* @param message the exception message
* @param exception the cause of the exception
* @throws SuppressionParseException throws the generated SuppressionParseException
* @throws SuppressionParseException throws the generated
* SuppressionParseException
*/
private void throwSuppressionParseException(String message, Exception exception) throws SuppressionParseException {
LOGGER.warn(message);

View File

@@ -17,8 +17,13 @@
*/
package org.owasp.dependencycheck.analyzer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.LoggerFactory;
/**
* The Analyzer Service Loader. This class loads all services that implement
@@ -27,11 +32,15 @@ import java.util.ServiceLoader;
* @author Jeremy Long
*/
public class AnalyzerService {
/**
* The Logger for use throughout the class.
*/
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(AnalyzerService.class);
/**
* The service loader for analyzers.
*/
private final ServiceLoader<Analyzer> loader;
private final ServiceLoader<Analyzer> service;
/**
* Creates a new instance of AnalyzerService.
@@ -39,15 +48,31 @@ public class AnalyzerService {
* @param classLoader the ClassLoader to use when dynamically loading Analyzer and Update services
*/
public AnalyzerService(ClassLoader classLoader) {
loader = ServiceLoader.load(Analyzer.class, classLoader);
service = ServiceLoader.load(Analyzer.class, classLoader);
}
/**
* Returns an Iterator for all instances of the Analyzer interface.
* Returns a list of all instances of the Analyzer interface.
*
* @return an iterator of Analyzers.
* @return a list of Analyzers.
*/
public Iterator<Analyzer> getAnalyzers() {
return loader.iterator();
public List<Analyzer> getAnalyzers() {
final List<Analyzer> analyzers = new ArrayList<Analyzer>();
final Iterator<Analyzer> iterator = service.iterator();
boolean experimentalEnabled = false;
try {
experimentalEnabled = Settings.getBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false);
} catch (InvalidSettingException ex) {
LOGGER.error("invalide experimental setting", ex);
}
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
if (!experimentalEnabled && a.getClass().isAnnotationPresent(Experimental.class)) {
continue;
}
LOGGER.debug("Loaded Analyzer {}", a.getName());
analyzers.add(a);
}
return analyzers;
}
}

View File

@@ -30,6 +30,7 @@ import org.owasp.dependencycheck.utils.UrlStringUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
@@ -39,9 +40,10 @@ import java.util.regex.Pattern;
* Used to analyze Autoconf input files named configure.ac or configure.in. Files simply named "configure" are also analyzed,
* assuming they are generated by Autoconf, and contain certain special package descriptor variables.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
* @see <a href="https://www.gnu.org/software/autoconf/">Autoconf - GNU Project - Free Software Foundation (FSF)</a>
*/
@Experimental
public class AutoconfAnalyzer extends AbstractFileTypeAnalyzer {
/**
@@ -220,14 +222,12 @@ public class AutoconfAnalyzer extends AbstractFileTypeAnalyzer {
*/
private String getFileContents(final File actualFile)
throws AnalysisException {
String contents = "";
try {
contents = FileUtils.readFileToString(actualFile).trim();
return FileUtils.readFileToString(actualFile, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
}
return contents;
}
/**

View File

@@ -33,24 +33,24 @@ import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>
* Used to analyze CMake build files, and collect information that can be used to determine the associated CPE.</p>
* <p/>
* <p>
* Note: This analyzer catches straightforward invocations of the project command, plus some other observed patterns of version
* inclusion in real CMake projects. Many projects make use of older versions of CMake and/or use custom "homebrew" ways to insert
* version information. Hopefully as the newer CMake call pattern grows in usage, this analyzer allow more CPEs to be
* identified.</p>
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class CMakeAnalyzer extends AbstractFileTypeAnalyzer {
/**
@@ -158,7 +158,7 @@ public class CMakeAnalyzer extends AbstractFileTypeAnalyzer {
dependency.setDisplayFileName(String.format("%s%c%s", parentName, File.separatorChar, name));
String contents;
try {
contents = FileUtils.readFileToString(file).trim();
contents = FileUtils.readFileToString(file, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);

View File

@@ -51,8 +51,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CPEAnalyzer is a utility class that takes a project dependency and attempts to discern if there is an associated CPE. It uses
* the evidence contained within the dependency to search the Lucene index.
* CPEAnalyzer is a utility class that takes a project dependency and attempts
* to discern if there is an associated CPE. It uses the evidence contained
* within the dependency to search the Lucene index.
*
* @author Jeremy Long
*/
@@ -71,15 +72,18 @@ public class CPEAnalyzer implements Analyzer {
*/
static final String WEIGHTING_BOOST = "^5";
/**
* A string representation of a regular expression defining characters utilized within the CPE Names.
* A string representation of a regular expression defining characters
* utilized within the CPE Names.
*/
static final String CLEANSE_CHARACTER_RX = "[^A-Za-z0-9 ._-]";
/**
* A string representation of a regular expression used to remove all but alpha characters.
* A string representation of a regular expression used to remove all but
* alpha characters.
*/
static final String CLEANSE_NONALPHA_RX = "[^A-Za-z]*";
/**
* The additional size to add to a new StringBuilder to account for extra data that will be written into the string.
* The additional size to add to a new StringBuilder to account for extra
* data that will be written into the string.
*/
static final int STRING_BUILDER_BUFFER = 20;
/**
@@ -129,9 +133,10 @@ public class CPEAnalyzer implements Analyzer {
/**
* Opens the data source.
*
* @throws IOException when the Lucene directory to be queried does not exist or is corrupt.
* @throws DatabaseException when the database throws an exception. This usually occurs when the database is in use by another
* process.
* @throws IOException when the Lucene directory to be queried does not
* exist or is corrupt.
* @throws DatabaseException when the database throws an exception. This
* usually occurs when the database is in use by another process.
*/
public void open() throws IOException, DatabaseException {
if (!isOpen()) {
@@ -170,8 +175,9 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Searches the data store of CPE entries, trying to identify the CPE for the given dependency based on the evidence contained
* within. The dependency passed in is updated with any identified CPE values.
* Searches the data store of CPE entries, trying to identify the CPE for
* the given dependency based on the evidence contained within. The
* dependency passed in is updated with any identified CPE values.
*
* @param dependency the dependency to search for CPE entries on.
* @throws CorruptIndexException is thrown when the Lucene index is corrupt.
@@ -192,8 +198,8 @@ public class CPEAnalyzer implements Analyzer {
LOGGER.debug("product search: {}", products);
}
if (!vendors.isEmpty() && !products.isEmpty()) {
final List<IndexEntry> entries = searchCPE(vendors, products, dependency.getProductEvidence().getWeighting(),
dependency.getVendorEvidence().getWeighting());
final List<IndexEntry> entries = searchCPE(vendors, products, dependency.getVendorEvidence().getWeighting(),
dependency.getProductEvidence().getWeighting());
if (entries == null) {
continue;
}
@@ -215,9 +221,10 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Returns the text created by concatenating the text and the values from the EvidenceCollection (filtered for a specific
* confidence). This attempts to prevent duplicate terms from being added.<br/<br/> Note, if the evidence is longer then 200
* characters it will be truncated.
* Returns the text created by concatenating the text and the values from
* the EvidenceCollection (filtered for a specific confidence). This
* attempts to prevent duplicate terms from being added.<br/<br/> Note, if
* the evidence is longer then 200 characters it will be truncated.
*
* @param text the base text.
* @param ec an EvidenceCollection
@@ -248,17 +255,19 @@ public class CPEAnalyzer implements Analyzer {
/**
* <p>
* Searches the Lucene CPE index to identify possible CPE entries associated with the supplied vendor, product, and
* version.</p>
* Searches the Lucene CPE index to identify possible CPE entries associated
* with the supplied vendor, product, and version.</p>
*
* <p>
* If either the vendorWeightings or productWeightings lists have been populated this data is used to add weighting factors to
* the search.</p>
* If either the vendorWeightings or productWeightings lists have been
* populated this data is used to add weighting factors to the search.</p>
*
* @param vendor the text used to search the vendor field
* @param product the text used to search the product field
* @param vendorWeightings a list of strings to use to add weighting factors to the vendor field
* @param productWeightings Adds a list of strings that will be used to add weighting factors to the product search
* @param vendorWeightings a list of strings to use to add weighting factors
* to the vendor field
* @param productWeightings Adds a list of strings that will be used to add
* weighting factors to the product search
* @return a list of possible CPE values
*/
protected List<IndexEntry> searchCPE(String vendor, String product,
@@ -297,16 +306,20 @@ public class CPEAnalyzer implements Analyzer {
/**
* <p>
* Builds a Lucene search string by properly escaping data and constructing a valid search query.</p>
* Builds a Lucene search string by properly escaping data and constructing
* a valid search query.</p>
*
* <p>
* If either the possibleVendor or possibleProducts lists have been populated this data is used to add weighting factors to
* the search string generated.</p>
* If either the possibleVendor or possibleProducts lists have been
* populated this data is used to add weighting factors to the search string
* generated.</p>
*
* @param vendor text to search the vendor field
* @param product text to search the product field
* @param vendorWeighting a list of strings to apply to the vendor to boost the terms weight
* @param productWeightings a list of strings to apply to the product to boost the terms weight
* @param vendorWeighting a list of strings to apply to the vendor to boost
* the terms weight
* @param productWeightings a list of strings to apply to the product to
* boost the terms weight
* @return the Lucene query
*/
protected String buildSearch(String vendor, String product,
@@ -327,13 +340,17 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* This method constructs a Lucene query for a given field. The searchText is split into separate words and if the word is
* within the list of weighted words then an additional weighting is applied to the term as it is appended into the query.
* This method constructs a Lucene query for a given field. The searchText
* is split into separate words and if the word is within the list of
* weighted words then an additional weighting is applied to the term as it
* is appended into the query.
*
* @param sb a StringBuilder that the query text will be appended to.
* @param field the field within the Lucene index that the query is searching.
* @param field the field within the Lucene index that the query is
* searching.
* @param searchText text used to construct the query.
* @param weightedText a list of terms that will be considered higher importance when searching.
* @param weightedText a list of terms that will be considered higher
* importance when searching.
* @return if the append was successful.
*/
private boolean appendWeightedSearch(StringBuilder sb, String field, String searchText, Set<String> weightedText) {
@@ -379,7 +396,8 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Removes characters from the input text that are not used within the CPE index.
* Removes characters from the input text that are not used within the CPE
* index.
*
* @param text is the text to remove the characters from.
* @return the text having removed some characters.
@@ -389,7 +407,8 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Compares two strings after lower casing them and removing the non-alpha characters.
* Compares two strings after lower casing them and removing the non-alpha
* characters.
*
* @param l string one to compare.
* @param r string two to compare.
@@ -406,8 +425,9 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Ensures that the CPE Identified matches the dependency. This validates that the product, vendor, and version information
* for the CPE are contained within the dependencies evidence.
* Ensures that the CPE Identified matches the dependency. This validates
* that the product, vendor, and version information for the CPE are
* contained within the dependencies evidence.
*
* @param entry a CPE entry.
* @param dependency the dependency that the CPE entries could be for.
@@ -474,14 +494,16 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Analyzes a dependency and attempts to determine if there are any CPE identifiers for this dependency.
* Analyzes a dependency and attempts to determine if there are any CPE
* identifiers for this dependency.
*
* @param dependency The Dependency to analyze.
* @param engine The analysis engine
* @throws AnalysisException is thrown if there is an issue analyzing the dependency.
* @throws AnalysisException is thrown if there is an issue analyzing the
* dependency.
*/
@Override
public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
public synchronized void analyze(Dependency dependency, Engine engine) throws AnalysisException {
try {
determineCPE(dependency);
} catch (CorruptIndexException ex) {
@@ -494,15 +516,19 @@ public class CPEAnalyzer implements Analyzer {
}
/**
* Retrieves a list of CPE values from the CveDB based on the vendor and product passed in. The list is then validated to find
* only CPEs that are valid for the given dependency. It is possible that the CPE identified is a best effort "guess" based on
* the vendor, product, and version information.
* Retrieves a list of CPE values from the CveDB based on the vendor and
* product passed in. The list is then validated to find only CPEs that are
* valid for the given dependency. It is possible that the CPE identified is
* a best effort "guess" based on the vendor, product, and version
* information.
*
* @param dependency the Dependency being analyzed
* @param vendor the vendor for the CPE being analyzed
* @param product the product for the CPE being analyzed
* @param currentConfidence the current confidence being used during analysis
* @return <code>true</code> if an identifier was added to the dependency; otherwise <code>false</code>
* @param currentConfidence the current confidence being used during
* analysis
* @return <code>true</code> if an identifier was added to the dependency;
* otherwise <code>false</code>
* @throws UnsupportedEncodingException is thrown if UTF-8 is not supported
*/
protected boolean determineIdentifiers(Dependency dependency, String vendor, String product,
@@ -512,10 +538,11 @@ public class CPEAnalyzer implements Analyzer {
Confidence bestGuessConf = null;
boolean hasBroadMatch = false;
final List<IdentifierMatch> collected = new ArrayList<IdentifierMatch>();
//TODO the following algorithm incorrectly identifies things as a lower version
// if there lower confidence evidence when the current (highest) version number
// is newer then anything in the NVD.
for (Confidence conf : Confidence.values()) {
// if (conf.compareTo(currentConfidence) > 0) {
// break;
// }
for (Evidence evidence : dependency.getVersionEvidence().iterator(conf)) {
final DependencyVersion evVer = DependencyVersionUtil.parseVersion(evidence.getValue());
if (evVer == null) {
@@ -537,15 +564,13 @@ public class CPEAnalyzer implements Analyzer {
final String url = String.format(NVD_SEARCH_URL, URLEncoder.encode(vs.getName(), "UTF-8"));
final IdentifierMatch match = new IdentifierMatch("cpe", vs.getName(), url, IdentifierConfidence.EXACT_MATCH, conf);
collected.add(match);
} else {
//TODO the following isn't quite right is it? need to think about this guessing game a bit more.
if (evVer.getVersionParts().size() <= dbVer.getVersionParts().size()
&& evVer.matchesAtLeastThreeLevels(dbVer)) {
if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
if (bestGuess.getVersionParts().size() < dbVer.getVersionParts().size()) {
bestGuess = dbVer;
bestGuessConf = conf;
}
} else //TODO the following isn't quite right is it? need to think about this guessing game a bit more.
if (evVer.getVersionParts().size() <= dbVer.getVersionParts().size()
&& evVer.matchesAtLeastThreeLevels(dbVer)) {
if (bestGuessConf == null || bestGuessConf.compareTo(conf) > 0) {
if (bestGuess.getVersionParts().size() < dbVer.getVersionParts().size()) {
bestGuess = dbVer;
bestGuessConf = conf;
}
}
}
@@ -604,14 +629,16 @@ public class CPEAnalyzer implements Analyzer {
*/
BEST_GUESS,
/**
* The entire vendor/product group must be added (without a guess at version) because there is a CVE with a VS that only
* specifies vendor/product.
* The entire vendor/product group must be added (without a guess at
* version) because there is a CVE with a VS that only specifies
* vendor/product.
*/
BROAD_MATCH
}
/**
* A simple object to hold an identifier and carry information about the confidence in the identifier.
* A simple object to hold an identifier and carry information about the
* confidence in the identifier.
*/
private static class IdentifierMatch implements Comparable<IdentifierMatch> {
@@ -621,8 +648,10 @@ public class CPEAnalyzer implements Analyzer {
* @param type the type of identifier (such as CPE)
* @param value the value of the identifier
* @param url the URL of the identifier
* @param identifierConfidence the confidence in the identifier: best guess or exact match
* @param evidenceConfidence the confidence of the evidence used to find the identifier
* @param identifierConfidence the confidence in the identifier: best
* guess or exact match
* @param evidenceConfidence the confidence of the evidence used to find
* the identifier
*/
IdentifierMatch(String type, String value, String url, IdentifierConfidence identifierConfidence, Confidence evidenceConfidence) {
this.identifier = new Identifier(type, value, url);
@@ -753,7 +782,8 @@ public class CPEAnalyzer implements Analyzer {
//</editor-fold>
/**
* Standard implementation of compareTo that compares identifier confidence, evidence confidence, and then the identifier.
* Standard implementation of compareTo that compares identifier
* confidence, evidence confidence, and then the identifier.
*
* @param o the IdentifierMatch to compare to
* @return the natural ordering of IdentifierMatch

View File

@@ -41,30 +41,31 @@ import java.security.MessageDigest;
*
* @author colezlaw
*/
@Experimental
public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
/**
* The logger
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ComposerLockAnalyzer.class);
/**
* The analyzer name
* The analyzer name.
*/
private static final String ANALYZER_NAME = "Composer.lock analyzer";
/**
* composer.json
* composer.json.
*/
private static final String COMPOSER_LOCK = "composer.lock";
/**
* The FileFilter
* The FileFilter.
*/
private static final FileFilter FILE_FILTER = FileFilterBuilder.newInstance().addFilenames(COMPOSER_LOCK).build();
/**
* Returns the FileFilter
* Returns the FileFilter.
*
* @return the FileFilter
*/
@@ -74,9 +75,9 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Initializes the analyzer
* Initializes the analyzer.
*
* @throws Exception
* @throws Exception thrown if an exception occurs getting an instance of SHA1
*/
@Override
protected void initializeFileTypeAnalyzer() throws Exception {
@@ -84,7 +85,7 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* The MessageDigest for calculating a new digest for the new dependencies added
* The MessageDigest for calculating a new digest for the new dependencies added.
*/
private MessageDigest sha1 = null;

View File

@@ -35,11 +35,14 @@ import org.slf4j.LoggerFactory;
/**
* <p>
* This analyzer ensures dependencies that should be grouped together, to remove excess noise from the report, are grouped. An
* example would be Spring, Spring Beans, Spring MVC, etc. If they are all for the same version and have the same relative path
* then these should be grouped into a single dependency under the core/main library.</p>
* This analyzer ensures dependencies that should be grouped together, to remove
* excess noise from the report, are grouped. An example would be Spring, Spring
* Beans, Spring MVC, etc. If they are all for the same version and have the
* same relative path then these should be grouped into a single dependency
* under the core/main library.</p>
* <p>
* Note, this grouping only works on dependencies with identified CVE entries</p>
* Note, this grouping only works on dependencies with identified CVE
* entries</p>
*
* @author Jeremy Long
*/
@@ -92,12 +95,14 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
//</editor-fold>
/**
* Analyzes a set of dependencies. If they have been found to have the same base path and the same set of identifiers they are
* likely related. The related dependencies are bundled into a single reportable item.
* Analyzes a set of dependencies. If they have been found to have the same
* base path and the same set of identifiers they are likely related. The
* related dependencies are bundled into a single reportable item.
*
* @param ignore this analyzer ignores the dependency being analyzed
* @param engine the engine that is scanning the dependencies
* @throws AnalysisException is thrown if there is an error reading the JAR file.
* @throws AnalysisException is thrown if there is an error reading the JAR
* file.
*/
@Override
public void analyze(Dependency ignore, Engine engine) throws AnalysisException {
@@ -138,6 +143,14 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
mergeDependencies(nextDependency, dependency, dependenciesToRemove);
break; //since we merged into the next dependency - skip forward to the next in mainIterator
}
} else if (isSameRubyGem(dependency, nextDependency)) {
final Dependency main = getMainGemspecDependency(dependency, nextDependency);
if (main == dependency) {
mergeDependencies(dependency, nextDependency, dependenciesToRemove);
} else {
mergeDependencies(nextDependency, dependency, dependenciesToRemove);
break; //since we merged into the next dependency - skip forward to the next in mainIterator
}
}
}
}
@@ -152,10 +165,11 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
* Adds the relatedDependency to the dependency's related dependencies.
*
* @param dependency the main dependency
* @param relatedDependency a collection of dependencies to be removed from the main analysis loop, this is the source of
* dependencies to remove
* @param dependenciesToRemove a collection of dependencies that will be removed from the main analysis loop, this function
* adds to this collection
* @param relatedDependency a collection of dependencies to be removed from
* the main analysis loop, this is the source of dependencies to remove
* @param dependenciesToRemove a collection of dependencies that will be
* removed from the main analysis loop, this function adds to this
* collection
*/
private void mergeDependencies(final Dependency dependency, final Dependency relatedDependency, final Set<Dependency> dependenciesToRemove) {
dependency.addRelatedDependency(relatedDependency);
@@ -171,7 +185,8 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Attempts to trim a maven repo to a common base path. This is typically [drive]\[repo_location]\repository\[path1]\[path2].
* Attempts to trim a maven repo to a common base path. This is typically
* [drive]\[repo_location]\repository\[path1]\[path2].
*
* @param path the path to trim
* @return a string representing the base path.
@@ -196,11 +211,13 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Returns true if the file names (and version if it exists) of the two dependencies are sufficiently similar.
* Returns true if the file names (and version if it exists) of the two
* dependencies are sufficiently similar.
*
* @param dependency1 a dependency2 to compare
* @param dependency2 a dependency2 to compare
* @return true if the identifiers in the two supplied dependencies are equal
* @return true if the identifiers in the two supplied dependencies are
* equal
*/
private boolean fileNameMatch(Dependency dependency1, Dependency dependency2) {
if (dependency1 == null || dependency1.getFileName() == null
@@ -228,11 +245,13 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Returns true if the CPE identifiers in the two supplied dependencies are equal.
* Returns true if the CPE identifiers in the two supplied dependencies are
* equal.
*
* @param dependency1 a dependency2 to compare
* @param dependency2 a dependency2 to compare
* @return true if the identifiers in the two supplied dependencies are equal
* @return true if the identifiers in the two supplied dependencies are
* equal
*/
private boolean cpeIdentifiersMatch(Dependency dependency1, Dependency dependency2) {
if (dependency1 == null || dependency1.getIdentifiers() == null
@@ -304,12 +323,67 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* This is likely a very broken attempt at determining if the 'left' dependency is the 'core' library in comparison to the
* 'right' library.
* Bundling Ruby gems that are identified from different .gemspec files but
* denote the same package path. This happens when Ruby bundler installs an
* application's dependencies by running "bundle install".
*
* @param dependency1 dependency to compare
* @param dependency2 dependency to compare
* @return true if the the dependencies being analyzed appear to be the
* same; otherwise false
*/
private boolean isSameRubyGem(Dependency dependency1, Dependency dependency2) {
if (dependency1 == null || dependency2 == null
|| !dependency1.getFileName().endsWith(".gemspec")
|| !dependency2.getFileName().endsWith(".gemspec")
|| dependency1.getPackagePath() == null
|| dependency2.getPackagePath() == null) {
return false;
}
if (dependency1.getPackagePath().equalsIgnoreCase(dependency2.getPackagePath())) {
return true;
}
return false;
}
/**
* Ruby gems installed by "bundle install" can have zero or more *.gemspec
* files, all of which have the same packagePath and should be grouped. If
* one of these gemspec is from <parent>/specifications/*.gemspec, because
* it is a stub with fully resolved gem meta-data created by Ruby bundler,
* this dependency should be the main one. Otherwise, use dependency2 as
* main.
*
* This method returns null if any dependency is not from *.gemspec, or the
* two do not have the same packagePath. In this case, they should not be
* grouped.
*
* @param dependency1 dependency to compare
* @param dependency2 dependency to compare
* @return the main dependency; or null if a gemspec is not included in the
* analysis
*/
private Dependency getMainGemspecDependency(Dependency dependency1, Dependency dependency2) {
if (isSameRubyGem(dependency1, dependency2)) {
final File lFile = dependency1.getActualFile();
final File left = lFile.getParentFile();
if (left != null && left.getName().equalsIgnoreCase("specifications")) {
return dependency1;
}
return dependency2;
}
return null;
}
/**
* This is likely a very broken attempt at determining if the 'left'
* dependency is the 'core' library in comparison to the 'right' library.
*
* @param left the dependency to test
* @param right the dependency to test against
* @return a boolean indicating whether or not the left dependency should be considered the "core" version.
* @return a boolean indicating whether or not the left dependency should be
* considered the "core" version.
*/
boolean isCore(Dependency left, Dependency right) {
final String leftName = left.getFileName().toLowerCase();
@@ -345,11 +419,13 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Compares the SHA1 hashes of two dependencies to determine if they are equal.
* Compares the SHA1 hashes of two dependencies to determine if they are
* equal.
*
* @param dependency1 a dependency object to compare
* @param dependency2 a dependency object to compare
* @return true if the sha1 hashes of the two dependencies match; otherwise false
* @return true if the sha1 hashes of the two dependencies match; otherwise
* false
*/
private boolean hashesMatch(Dependency dependency1, Dependency dependency2) {
if (dependency1 == null || dependency2 == null || dependency1.getSha1sum() == null || dependency2.getSha1sum() == null) {
@@ -359,12 +435,13 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Determines if the jar is shaded and the created pom.xml identified the same CPE as the jar - if so, the pom.xml dependency
* should be removed.
* Determines if the jar is shaded and the created pom.xml identified the
* same CPE as the jar - if so, the pom.xml dependency should be removed.
*
* @param dependency a dependency to check
* @param nextDependency another dependency to check
* @return true if on of the dependencies is a pom.xml and the identifiers between the two collections match; otherwise false
* @return true if on of the dependencies is a pom.xml and the identifiers
* between the two collections match; otherwise false
*/
private boolean isShadedJar(Dependency dependency, Dependency nextDependency) {
final String mainName = dependency.getFileName().toLowerCase();
@@ -378,12 +455,13 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
}
/**
* Determines which path is shortest; if path lengths are equal then we use compareTo of the string method to determine if the
* first path is smaller.
* Determines which path is shortest; if path lengths are equal then we use
* compareTo of the string method to determine if the first path is smaller.
*
* @param left the first path to compare
* @param right the second path to compare
* @return <code>true</code> if the leftPath is the shortest; otherwise <code>false</code>
* @return <code>true</code> if the leftPath is the shortest; otherwise
* <code>false</code>
*/
protected boolean firstPathIsShortest(String left, String right) {
final String leftPath = left.replace('\\', '/');

View File

@@ -0,0 +1,34 @@
/*
* 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) 2016 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to flag an analyzer as experimental.
*
* @author jeremy long
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Experimental {
}

View File

@@ -18,7 +18,9 @@
package org.owasp.dependencycheck.analyzer;
import java.io.File;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence;
@@ -65,12 +67,22 @@ public class FileNameAnalyzer extends AbstractAnalyzer implements Analyzer {
}
//</editor-fold>
/**
* Python init files
*/
private static final NameFileFilter IGNORED_FILES = new NameFileFilter(new String[]{
"__init__.py",
"__init__.pyc",
"__init__.pyo",
});
/**
* Collects information about the file name.
*
* @param dependency the dependency to analyze.
* @param engine the engine that is scanning the dependencies
* @throws AnalysisException is thrown if there is an error reading the JAR file.
* @throws AnalysisException is thrown if there is an error reading the JAR
* file.
*/
@Override
public void analyze(Dependency dependency, Engine engine) throws AnalysisException {
@@ -89,20 +101,14 @@ public class FileNameAnalyzer extends AbstractAnalyzer implements Analyzer {
dependency.getVersionEvidence().addEvidence("file", "name",
version.toString(), Confidence.MEDIUM);
} else {
dependency.getVersionEvidence().addEvidence("file", "name",
dependency.getVersionEvidence().addEvidence("file", "version",
version.toString(), Confidence.HIGHEST);
}
dependency.getVersionEvidence().addEvidence("file", "name",
fileName, Confidence.MEDIUM);
}
//add as vendor and product evidence
if (fileName.contains("-")) {
dependency.getProductEvidence().addEvidence("file", "name",
fileName, Confidence.HIGHEST);
dependency.getVendorEvidence().addEvidence("file", "name",
fileName, Confidence.HIGHEST);
} else {
if (!IGNORED_FILES.accept(f)) {
dependency.getProductEvidence().addEvidence("file", "name",
fileName, Confidence.HIGH);
dependency.getVendorEvidence().addEvidence("file", "name",

View File

@@ -59,7 +59,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to load a JAR file and collect information that can be used to determine the associated CPE.
* Used to load a JAR file and collect information that can be used to determine
* the associated CPE.
*
* @author Jeremy Long
*/
@@ -71,7 +72,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*/
private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzer.class);
/**
* The count of directories created during analysis. This is used for creating temporary directories.
* The count of directories created during analysis. This is used for
* creating temporary directories.
*/
private static int dirCount = 0;
/**
@@ -79,7 +81,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*/
private static final String NEWLINE = System.getProperty("line.separator");
/**
* A list of values in the manifest to ignore as they only result in false positives.
* A list of values in the manifest to ignore as they only result in false
* positives.
*/
private static final Set<String> IGNORE_VALUES = newHashSet(
"Sun Java System Application Server");
@@ -122,7 +125,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
"ipojo-extension",
"eclipse-sourcereferences");
/**
* Deprecated Jar manifest attribute, that is, nonetheless, useful for analysis.
* Deprecated Jar manifest attribute, that is, nonetheless, useful for
* analysis.
*/
@SuppressWarnings("deprecation")
private static final String IMPLEMENTATION_VENDOR_ID = Attributes.Name.IMPLEMENTATION_VENDOR_ID
@@ -202,7 +206,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
//</editor-fold>
/**
* Returns the key used in the properties file to reference the analyzer's enabled property.
* Returns the key used in the properties file to reference the analyzer's
* enabled property.
*
* @return the analyzer's enabled property setting key
*/
@@ -212,12 +217,13 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Loads a specified JAR file and collects information from the manifest and checksums to identify the correct CPE
* information.
* Loads a specified JAR file and collects information from the manifest and
* checksums to identify the correct CPE information.
*
* @param dependency the dependency to analyze.
* @param engine the engine that is scanning the dependencies
* @throws AnalysisException is thrown if there is an error reading the JAR file.
* @throws AnalysisException is thrown if there is an error reading the JAR
* file.
*/
@Override
public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
@@ -241,13 +247,15 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Attempts to find a pom.xml within the JAR file. If found it extracts information and adds it to the evidence. This will
* attempt to interpolate the strings contained within the pom.properties if one exists.
* Attempts to find a pom.xml within the JAR file. If found it extracts
* information and adds it to the evidence. This will attempt to interpolate
* the strings contained within the pom.properties if one exists.
*
* @param dependency the dependency being analyzed
* @param classes a collection of class name information
* @param engine the analysis engine, used to add additional dependencies
* @throws AnalysisException is thrown if there is an exception parsing the pom
* @throws AnalysisException is thrown if there is an exception parsing the
* pom
* @return whether or not evidence was added to the dependency
*/
protected boolean analyzePOM(Dependency dependency, List<ClassNameInformation> classes, Engine engine) throws AnalysisException {
@@ -328,12 +336,14 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Given a path to a pom.xml within a JarFile, this method attempts to load a sibling pom.properties if one exists.
* Given a path to a pom.xml within a JarFile, this method attempts to load
* a sibling pom.properties if one exists.
*
* @param path the path to the pom.xml within the JarFile
* @param jar the JarFile to load the pom.properties from
* @return a Properties object or null if no pom.properties was found
* @throws IOException thrown if there is an exception reading the pom.properties
* @throws IOException thrown if there is an exception reading the
* pom.properties
*/
private Properties retrievePomProperties(String path, final JarFile jar) throws IOException {
Properties pomProperties = null;
@@ -360,7 +370,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Searches a JarFile for pom.xml entries and returns a listing of these entries.
* Searches a JarFile for pom.xml entries and returns a listing of these
* entries.
*
* @param jar the JarFile to search
* @return a list of pom.xml entries
@@ -387,8 +398,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
* @param jar the jar file to extract the pom from
* @param dependency the dependency being analyzed
* @return returns the POM object
* @throws AnalysisException is thrown if there is an exception extracting or parsing the POM
* {@link org.owasp.dependencycheck.xml.pom.Model} object
* @throws AnalysisException is thrown if there is an exception extracting
* or parsing the POM {@link org.owasp.dependencycheck.xml.pom.Model} object
*/
private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException {
InputStream input = null;
@@ -446,9 +457,10 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*
* @param dependency the dependency to set data on
* @param pom the information from the pom
* @param classes a collection of ClassNameInformation - containing data about the fully qualified class names within the JAR
* file being analyzed
* @return true if there was evidence within the pom that we could use; otherwise false
* @param classes a collection of ClassNameInformation - containing data
* about the fully qualified class names within the JAR file being analyzed
* @return true if there was evidence within the pom that we could use;
* otherwise false
*/
public static boolean setPomEvidence(Dependency dependency, Model pom, List<ClassNameInformation> classes) {
boolean foundSomething = false;
@@ -565,17 +577,25 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
addMatchingValues(classes, trimmedDescription, dependency.getProductEvidence());
}
final String projectURL = pom.getProjectURL();
if (projectURL != null && !projectURL.trim().isEmpty()) {
dependency.getVendorEvidence().addEvidence("pom", "url", projectURL, Confidence.HIGHEST);
}
extractLicense(pom, dependency);
return foundSomething;
}
/**
* Analyzes the path information of the classes contained within the JarAnalyzer to try and determine possible vendor or
* product names. If any are found they are stored in the packageVendor and packageProduct hashSets.
* Analyzes the path information of the classes contained within the
* JarAnalyzer to try and determine possible vendor or product names. If any
* are found they are stored in the packageVendor and packageProduct
* hashSets.
*
* @param classNames a list of class names
* @param dependency a dependency to analyze
* @param addPackagesAsEvidence a flag indicating whether or not package names should be added as evidence.
* @param addPackagesAsEvidence a flag indicating whether or not package
* names should be added as evidence.
*/
protected void analyzePackageNames(List<ClassNameInformation> classNames,
Dependency dependency, boolean addPackagesAsEvidence) {
@@ -610,11 +630,13 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
/**
* <p>
* Reads the manifest from the JAR file and collects the entries. Some vendorKey entries are:</p>
* Reads the manifest from the JAR file and collects the entries. Some
* vendorKey entries are:</p>
* <ul><li>Implementation Title</li>
* <li>Implementation Version</li> <li>Implementation Vendor</li>
* <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle Version</li> <li>Bundle Vendor</li> <li>Bundle
* Description</li> <li>Main Class</li> </ul>
* <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle
* Version</li> <li>Bundle Vendor</li> <li>Bundle Description</li> <li>Main
* Class</li> </ul>
* However, all but a handful of specific entries are read in.
*
* @param dependency A reference to the dependency
@@ -622,16 +644,15 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
* @return whether evidence was identified parsing the manifest
* @throws IOException if there is an issue reading the JAR file
*/
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) throws IOException {
protected boolean parseManifest(Dependency dependency,
List<ClassNameInformation> classInformation)
throws IOException {
boolean foundSomething = false;
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
final Manifest manifest = jar.getManifest();
if (manifest == null) {
//don't log this for javadoc or sources jar files
if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-src.jar")
@@ -641,17 +662,14 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
return false;
}
final Attributes atts = manifest.getMainAttributes();
final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
final EvidenceCollection productEvidence = dependency.getProductEvidence();
final EvidenceCollection versionEvidence = dependency.getVersionEvidence();
final String source = "Manifest";
String source = "Manifest";
String specificationVersion = null;
boolean hasImplementationVersion = false;
Attributes atts = manifest.getMainAttributes();
for (Entry<Object, Object> entry : atts.entrySet()) {
String key = entry.getKey().toString();
String value = atts.getValue(key);
@@ -681,7 +699,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
} else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
foundSomething = true;
addDescription(dependency, value, "manifest", key);
//productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
foundSomething = true;
@@ -700,14 +717,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
//skipping main class as if this has important information to add
// it will be added during class name analysis... if other fields
// have the information from the class name then they will get added...
// foundSomething = true;
// productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
// addMatchingValues(classInformation, value, vendorEvidence);
// addMatchingValues(classInformation, value, productEvidence);
} else {
key = key.toLowerCase();
if (!IGNORE_KEYS.contains(key)
&& !key.endsWith("jdk")
&& !key.contains("lastmodified")
@@ -719,12 +730,9 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
&& !value.trim().startsWith("scm:")
&& !isImportPackage(key, value)
&& !isPackage(key, value)) {
foundSomething = true;
if (key.contains("version")) {
if (!key.contains("specification")) {
//versionEvidence.addEvidence(source, key, value, Confidence.LOW);
//} else {
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
}
} else if ("build-id".equals(key)) {
@@ -754,21 +762,19 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
addMatchingValues(classInformation, value, productEvidence);
} else if (key.contains("license")) {
addLicense(dependency, value);
} else if (key.contains("description")) {
addDescription(dependency, value, "manifest", key);
} else {
if (key.contains("description")) {
addDescription(dependency, value, "manifest", key);
} else {
productEvidence.addEvidence(source, key, value, Confidence.LOW);
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
if (value.matches(".*\\d.*")) {
final StringTokenizer tokenizer = new StringTokenizer(value, " ");
while (tokenizer.hasMoreElements()) {
final String s = tokenizer.nextToken();
if (s.matches("^[0-9.]+$")) {
versionEvidence.addEvidence(source, key, s, Confidence.LOW);
}
productEvidence.addEvidence(source, key, value, Confidence.LOW);
vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
addMatchingValues(classInformation, value, vendorEvidence);
addMatchingValues(classInformation, value, productEvidence);
if (value.matches(".*\\d.*")) {
final StringTokenizer tokenizer = new StringTokenizer(value, " ");
while (tokenizer.hasMoreElements()) {
final String s = tokenizer.nextToken();
if (s.matches("^[0-9.]+$")) {
versionEvidence.addEvidence(source, key, s, Confidence.LOW);
}
}
}
@@ -776,9 +782,35 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
}
}
for (Map.Entry<String, Attributes> item : manifest.getEntries().entrySet()) {
final String name = item.getKey();
source = "manifest: " + name;
atts = item.getValue();
for (Entry<Object, Object> entry : atts.entrySet()) {
final String key = entry.getKey().toString();
final String value = atts.getValue(key);
if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
foundSomething = true;
versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
} else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
foundSomething = true;
vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, vendorEvidence);
} else if (key.equalsIgnoreCase(Attributes.Name.SPECIFICATION_TITLE.toString())) {
foundSomething = true;
productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
addMatchingValues(classInformation, value, productEvidence);
}
}
}
if (specificationVersion != null && !hasImplementationVersion) {
foundSomething = true;
versionEvidence.addEvidence(source, "specificationn-version", specificationVersion, Confidence.HIGH);
versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH);
}
} finally {
if (jar != null) {
@@ -789,15 +821,18 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Adds a description to the given dependency. If the description contains one of the following strings beyond 100 characters,
* then the description used will be trimmed to that position:
* <ul><li>"such as"</li><li>"like "</li><li>"will use "</li><li>"* uses "</li></ul>
* Adds a description to the given dependency. If the description contains
* one of the following strings beyond 100 characters, then the description
* used will be trimmed to that position:
* <ul><li>"such as"</li><li>"like "</li><li>"will use "</li><li>"* uses
* "</li></ul>
*
* @param dependency a dependency
* @param description the description
* @param source the source of the evidence
* @param key the "name" of the evidence
* @return if the description is trimmed, the trimmed version is returned; otherwise the original description is returned
* @return if the description is trimmed, the trimmed version is returned;
* otherwise the original description is returned
*/
public static String addDescription(Dependency dependency, String description, String source, String key) {
if (dependency.getDescription() == null) {
@@ -868,7 +903,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
/**
* Initializes the JarAnalyzer.
*
* @throws Exception is thrown if there is an exception creating a temporary directory
* @throws Exception is thrown if there is an exception creating a temporary
* directory
*/
@Override
public void initializeFileTypeAnalyzer() throws Exception {
@@ -899,11 +935,13 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Determines if the key value pair from the manifest is for an "import" type entry for package names.
* Determines if the key value pair from the manifest is for an "import"
* type entry for package names.
*
* @param key the key from the manifest
* @param value the value from the manifest
* @return true or false depending on if it is believed the entry is an "import" entry
* @return true or false depending on if it is believed the entry is an
* "import" entry
*/
private boolean isImportPackage(String key, String value) {
final Pattern packageRx = Pattern.compile("^([a-zA-Z0-9_#\\$\\*\\.]+\\s*[,;]\\s*)+([a-zA-Z0-9_#\\$\\*\\.]+\\s*)?$");
@@ -912,8 +950,9 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Cycles through an enumeration of JarEntries, contained within the dependency, and returns a list of the class names. This
* does not include core Java package names (i.e. java.* or javax.*).
* Cycles through an enumeration of JarEntries, contained within the
* dependency, and returns a list of the class names. This does not include
* core Java package names (i.e. java.* or javax.*).
*
* @param dependency the dependency being analyzed
* @return an list of fully qualified class names
@@ -949,12 +988,16 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Cycles through the list of class names and places the package levels 0-3 into the provided maps for vendor and product.
* This is helpful when analyzing vendor/product as many times this is included in the package name.
* Cycles through the list of class names and places the package levels 0-3
* into the provided maps for vendor and product. This is helpful when
* analyzing vendor/product as many times this is included in the package
* name.
*
* @param classNames a list of class names
* @param vendor HashMap of possible vendor names from package names (e.g. owasp)
* @param product HashMap of possible product names from package names (e.g. dependencycheck)
* @param vendor HashMap of possible vendor names from package names (e.g.
* owasp)
* @param product HashMap of possible product names from package names (e.g.
* dependencycheck)
*/
private void analyzeFullyQualifiedClassNames(List<ClassNameInformation> classNames,
Map<String, Integer> vendor, Map<String, Integer> product) {
@@ -981,8 +1024,9 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Adds an entry to the specified collection and sets the Integer (e.g. the count) to 1. If the entry already exists in the
* collection then the Integer is incremented by 1.
* Adds an entry to the specified collection and sets the Integer (e.g. the
* count) to 1. If the entry already exists in the collection then the
* Integer is incremented by 1.
*
* @param collection a collection of strings and their occurrence count
* @param key the key to add to the collection
@@ -996,9 +1040,10 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Cycles through the collection of class name information to see if parts of the package names are contained in the provided
* value. If found, it will be added as the HIGHEST confidence evidence because we have more then one source corroborating the
* value.
* Cycles through the collection of class name information to see if parts
* of the package names are contained in the provided value. If found, it
* will be added as the HIGHEST confidence evidence because we have more
* then one source corroborating the value.
*
* @param classes a collection of class name information
* @param value the value to check to see if it contains a package name
@@ -1011,7 +1056,9 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
final String text = value.toLowerCase();
for (ClassNameInformation cni : classes) {
for (String key : cni.getPackageStructure()) {
if (text.contains(key)) { //note, package structure elements are already lowercase.
final Pattern p = Pattern.compile("\b" + key + "\b");
if (p.matcher(text).find()) {
//if (text.contains(key)) { //note, package structure elements are already lowercase.
evidence.addEvidence("jar", "package name", key, Confidence.HIGHEST);
}
}
@@ -1019,7 +1066,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Simple check to see if the attribute from a manifest is just a package name.
* Simple check to see if the attribute from a manifest is just a package
* name.
*
* @param key the key of the value to check
* @param value the value to check
@@ -1033,7 +1081,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Extracts the license information from the pom and adds it to the dependency.
* Extracts the license information from the pom and adds it to the
* dependency.
*
* @param pom the pom object
* @param dependency the dependency to add license information too
@@ -1080,9 +1129,11 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
/**
* <p>
* Stores information about a given class name. This class will keep the fully qualified class name and a list of the
* important parts of the package structure. Up to the first four levels of the package structure are stored, excluding a
* leading "org" or "com". Example:</p>
* Stores information about a given class name. This class will keep the
* fully qualified class name and a list of the important parts of the
* package structure. Up to the first four levels of the package
* structure are stored, excluding a leading "org" or "com".
* Example:</p>
* <code>ClassNameInformation obj = new ClassNameInformation("org.owasp.dependencycheck.analyzer.JarAnalyzer");
* System.out.println(obj.getName());
* for (String p : obj.getPackageStructure())
@@ -1141,7 +1192,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
this.name = name;
}
/**
* Up to the first four levels of the package structure, excluding a leading "org" or "com".
* Up to the first four levels of the package structure, excluding a
* leading "org" or "com".
*/
private final ArrayList<String> packageStructure = new ArrayList<String>();

View File

@@ -43,8 +43,9 @@ import javax.json.JsonValue;
* 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 <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer {
/**

View File

@@ -28,16 +28,20 @@ import org.owasp.dependencycheck.utils.Settings;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Used to analyze OpenSSL source code present in the file system.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class OpenSSLAnalyzer extends AbstractFileTypeAnalyzer {
/**
* Hexadecimal.
*/
private static final int HEXADECIMAL = 16;
/**
* Filename to analyze. All other .h files get removed from consideration.
@@ -48,17 +52,47 @@ public class OpenSSLAnalyzer extends AbstractFileTypeAnalyzer {
* Filter that detects files named "__init__.py".
*/
private static final FileFilter OPENSSLV_FILTER = FileFilterBuilder.newInstance().addFilenames(OPENSSLV_H).build();
/**
* Open SSL Version number pattern.
*/
private static final Pattern VERSION_PATTERN = Pattern.compile(
"define\\s+OPENSSL_VERSION_NUMBER\\s+0x([0-9a-zA-Z]{8})L", Pattern.DOTALL
| Pattern.CASE_INSENSITIVE);
/**
* The offset of the major version number.
*/
private static final int MAJOR_OFFSET = 28;
/**
* The mask for the minor version number.
*/
private static final long MINOR_MASK = 0x0ff00000L;
/**
* The offset of the minor version number.
*/
private static final int MINOR_OFFSET = 20;
/**
* The max for the fix version.
*/
private static final long FIX_MASK = 0x000ff000L;
/**
* The offset for the fix version.
*/
private static final int FIX_OFFSET = 12;
/**
* The mask for the patch version.
*/
private static final long PATCH_MASK = 0x00000ff0L;
/**
* The offset for the patch version.
*/
private static final int PATCH_OFFSET = 4;
/**
* Number of letters.
*/
private static final int NUM_LETTERS = 26;
/**
* The status mask.
*/
private static final int STATUS_MASK = 0x0000000f;
/**
@@ -123,7 +157,8 @@ public class OpenSSLAnalyzer extends AbstractFileTypeAnalyzer {
*
* @param dependency the dependency being analyzed
* @param engine the engine being used to perform the scan
* @throws AnalysisException thrown if there is an unrecoverable error analyzing the dependency
* @throws AnalysisException thrown if there is an unrecoverable error
* analyzing the dependency
*/
@Override
protected void analyzeFileType(Dependency dependency, Engine engine)
@@ -158,16 +193,19 @@ public class OpenSSLAnalyzer extends AbstractFileTypeAnalyzer {
*/
private String getFileContents(final File actualFile)
throws AnalysisException {
String contents;
try {
contents = FileUtils.readFileToString(actualFile).trim();
return FileUtils.readFileToString(actualFile, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
}
return contents;
}
/**
* Returns the setting for the analyzer enabled setting key.
*
* @return the setting for the analyzer enabled setting key
*/
@Override
protected String getAnalyzerEnabledSettingKey() {
return Settings.KEYS.ANALYZER_OPENSSL_ENABLED;

View File

@@ -48,8 +48,9 @@ import org.owasp.dependencycheck.utils.UrlStringUtils;
* Used to analyze a Wheel or egg distribution files, or their contents in unzipped form, and collect information that can be used
* to determine the associated CPE.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
/**

View File

@@ -32,16 +32,19 @@ import org.owasp.dependencycheck.utils.UrlStringUtils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Used to analyze a Python package, and collect information that can be used to determine the associated CPE.
* Used to analyze a Python package, and collect information that can be used to
* determine the associated CPE.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
/**
@@ -165,7 +168,8 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
*
* @param dependency the dependency being analyzed
* @param engine the engine being used to perform the scan
* @throws AnalysisException thrown if there is an unrecoverable error analyzing the dependency
* @throws AnalysisException thrown if there is an unrecoverable error
* analyzing the dependency
*/
@Override
protected void analyzeFileType(Dependency dependency, Engine engine)
@@ -173,19 +177,20 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
final File file = dependency.getActualFile();
final File parent = file.getParentFile();
final String parentName = parent.getName();
boolean found = false;
if (INIT_PY_FILTER.accept(file)) {
//by definition, the containing folder of __init__.py is considered the package, even the file is empty:
//"The __init__.py files are required to make Python treat the directories as containing packages"
//see section "6.4 Packages" from https://docs.python.org/2/tutorial/modules.html;
dependency.setDisplayFileName(parentName + "/__init__.py");
dependency.getProductEvidence().addEvidence(file.getName(),
"PackageName", parentName, Confidence.HIGHEST);
final File[] fileList = parent.listFiles(PY_FILTER);
if (fileList != null) {
for (final File sourceFile : fileList) {
found |= analyzeFileContents(dependency, sourceFile);
analyzeFileContents(dependency, sourceFile);
}
}
}
if (found) {
dependency.setDisplayFileName(parentName + "/__init__.py");
dependency.getProductEvidence().addEvidence(file.getName(),
"PackageName", parentName, Confidence.MEDIUM);
} else {
// copy, alter and set in case some other thread is iterating over
final List<Dependency> dependencies = new ArrayList<Dependency>(
@@ -196,8 +201,9 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* This should gather information from leading docstrings, file comments, and assignments to __version__, __title__,
* __summary__, __uri__, __url__, __home*page__, __author__, and their all caps equivalents.
* This should gather information from leading docstrings, file comments,
* and assignments to __version__, __title__, __summary__, __uri__, __url__,
* __home*page__, __author__, and their all caps equivalents.
*
* @param dependency the dependency being analyzed
* @param file the file name to analyze
@@ -208,7 +214,7 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
throws AnalysisException {
String contents;
try {
contents = FileUtils.readFileToString(file).trim();
contents = FileUtils.readFileToString(file, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
@@ -288,7 +294,8 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Gather evidence from a Python source file using 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

View File

@@ -17,9 +17,20 @@
*/
package org.owasp.dependencycheck.analyzer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Reference;
@@ -28,15 +39,15 @@ import org.owasp.dependencycheck.utils.FileFilterBuilder;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
/**
* Used to analyze Ruby Bundler Gemspec.lock files utilizing the 3rd party bundle-audit tool.
* Used to analyze Ruby Bundler Gemspec.lock files utilizing the 3rd party
* bundle-audit tool.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzer.class);
@@ -50,14 +61,32 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
* The phase that this analyzer is intended to run in.
*/
private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.PRE_INFORMATION_COLLECTION;
private static final FileFilter FILTER
= FileFilterBuilder.newInstance().addFilenames("Gemfile.lock").build();
/**
* The filter defining which files will be analyzed.
*/
private static final FileFilter FILTER = FileFilterBuilder.newInstance().addFilenames("Gemfile.lock").build();
/**
* Name.
*/
public static final String NAME = "Name: ";
/**
* Version.
*/
public static final String VERSION = "Version: ";
/**
* Advisory.
*/
public static final String ADVISORY = "Advisory: ";
/**
* Criticality.
*/
public static final String CRITICALITY = "Criticality: ";
/**
* The DAL.
*/
private CveDB cvedb;
/**
* @return a filter that accepts files named Gemfile.lock
*/
@@ -69,7 +98,10 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
/**
* Launch bundle-audit.
*
* @param folder directory that contains bundle audit
* @return a handle to the process
* @throws AnalysisException thrown when there is an issue launching bundle
* audit
*/
private Process launchBundleAudit(File folder) throws AnalysisException {
if (!folder.isDirectory()) {
@@ -83,6 +115,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
final ProcessBuilder builder = new ProcessBuilder(args);
builder.directory(folder);
try {
LOGGER.info("Launching: " + args + " from " + folder);
return builder.start();
} catch (IOException ioe) {
throw new AnalysisException("bundle-audit failure", ioe);
@@ -90,15 +123,35 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Initialize the analyzer. In this case, extract GrokAssembly.exe to a temporary location.
* Initialize the analyzer. In this case, extract GrokAssembly.exe to a
* temporary location.
*
* @throws Exception if anything goes wrong
*/
@Override
public void initializeFileTypeAnalyzer() throws Exception {
try {
cvedb = new CveDB();
cvedb.open();
} catch (DatabaseException ex) {
LOGGER.warn("Exception opening the database");
LOGGER.debug("error", ex);
setEnabled(false);
throw ex;
}
// Now, need to see if bundle-audit actually runs from this location.
Process process = launchBundleAudit(Settings.getTempDirectory());
int exitValue = process.waitFor();
Process process = null;
try {
process = launchBundleAudit(Settings.getTempDirectory());
} catch (AnalysisException ae) {
LOGGER.warn("Exception from bundle-audit process: {}. Disabling {}", ae.getCause(), ANALYZER_NAME);
setEnabled(false);
cvedb.close();
cvedb = null;
throw ae;
}
final int exitValue = process.waitFor();
if (0 == exitValue) {
LOGGER.warn("Unexpected exit code from bundle-audit process. Disabling {}: {}", ANALYZER_NAME, exitValue);
setEnabled(false);
@@ -125,6 +178,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
}
}
if (isEnabled()) {
LOGGER.info(ANALYZER_NAME + " is enabled. It is necessary to manually run \"bundle-audit update\" "
+ "occasionally to keep its database up to date.");
@@ -152,7 +206,8 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Returns the key used in the properties file to reference the analyzer's enabled property.
* Returns the key used in the properties file to reference the analyzer's
* enabled property.
*
* @return the analyzer's enabled property setting key
*/
@@ -162,11 +217,19 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* If {@link #analyzeFileType(Dependency, Engine)} is called, then we have successfully initialized, and it will be necessary
* to disable {@link RubyGemspecAnalyzer}.
* If {@link #analyzeFileType(Dependency, Engine)} is called, then we have
* successfully initialized, and it will be necessary to disable
* {@link RubyGemspecAnalyzer}.
*/
private boolean needToDisableGemspecAnalyzer = true;
/**
* Determines if the analyzer can analyze the given file type.
*
* @param dependency the dependency to determine if it can analyze
* @param engine the dependency-check engine
* @throws AnalysisException thrown if there is an analysis exception.
*/
@Override
protected void analyzeFileType(Dependency dependency, Engine engine)
throws AnalysisException {
@@ -174,14 +237,17 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
boolean failed = true;
final String className = RubyGemspecAnalyzer.class.getName();
for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) {
if (analyzer instanceof RubyGemspecAnalyzer) {
if (analyzer instanceof RubyBundlerAnalyzer) {
((RubyBundlerAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled " + RubyBundlerAnalyzer.class.getName() + " to avoid noisy duplicate results.");
} else if (analyzer instanceof RubyGemspecAnalyzer) {
((RubyGemspecAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled " + className + " to avoid noisy duplicate results.");
failed = false;
}
}
if (failed) {
LOGGER.warn("Did not find" + className + '.');
LOGGER.warn("Did not find " + className + '.');
}
needToDisableGemspecAnalyzer = false;
}
@@ -193,12 +259,25 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
throw new AnalysisException("bundle-audit process interrupted", ie);
}
BufferedReader rdr = null;
BufferedReader errReader = null;
try {
errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
while (errReader.ready()) {
final String error = errReader.readLine();
LOGGER.warn(error);
}
rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
processBundlerAuditOutput(dependency, engine, rdr);
} catch (IOException ioe) {
LOGGER.warn("bundle-audit failure", ioe);
} finally {
if (errReader != null) {
try {
errReader.close();
} catch (IOException ioe) {
LOGGER.warn("bundle-audit close failure", ioe);
}
}
if (null != rdr) {
try {
rdr.close();
@@ -210,9 +289,18 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Processes the bundler audit output.
*
* @param original the dependency
* @param engine the dependency-check engine
* @param rdr the reader of the report
* @throws IOException thrown if the report cannot be read.
*/
private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException {
final String parentName = original.getActualFile().getParentFile().getName();
final String fileName = original.getFileName();
final String filePath = original.getFilePath();
Dependency dependency = null;
Vulnerability vulnerability = null;
String gem = null;
@@ -226,12 +314,12 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
appendToDescription = false;
gem = nextLine.substring(NAME.length());
if (!map.containsKey(gem)) {
map.put(gem, createDependencyForGem(engine, parentName, fileName, gem));
map.put(gem, createDependencyForGem(engine, parentName, fileName, filePath, gem));
}
dependency = map.get(gem);
LOGGER.debug(String.format("bundle-audit (%s): %s", parentName, nextLine));
} else if (nextLine.startsWith(VERSION)) {
vulnerability = createVulnerability(parentName, dependency, vulnerability, gem, nextLine);
vulnerability = createVulnerability(parentName, dependency, gem, nextLine);
} else if (nextLine.startsWith(ADVISORY)) {
setVulnerabilityName(parentName, dependency, vulnerability, nextLine);
} else if (nextLine.startsWith(CRITICALITY)) {
@@ -241,7 +329,9 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
} else if (nextLine.startsWith("Description:")) {
appendToDescription = true;
if (null != vulnerability) {
vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 indicates unknown). See link below for full details. *** ");
vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. "
+ "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 "
+ " indicates unknown). See link below for full details. *** ");
}
} else if (appendToDescription) {
if (null != vulnerability) {
@@ -251,6 +341,14 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
}
}
/**
* Sets the vulnerability name.
*
* @param parentName the parent name
* @param dependency the dependency
* @param vulnerability the vulnerability
* @param nextLine the line to parse
*/
private void setVulnerabilityName(String parentName, Dependency dependency, Vulnerability vulnerability, String nextLine) {
final String advisory = nextLine.substring((ADVISORY.length()));
if (null != vulnerability) {
@@ -262,10 +360,17 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.debug(String.format("bundle-audit (%s): %s", parentName, nextLine));
}
/**
* Adds a reference to the vulnerability.
*
* @param parentName the parent name
* @param vulnerability the vulnerability
* @param nextLine the line to parse
*/
private void addReferenceToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
final String url = nextLine.substring(("URL: ").length());
if (null != vulnerability) {
Reference ref = new Reference();
final Reference ref = new Reference();
ref.setName(vulnerability.getName());
ref.setSource("bundle-audit");
ref.setUrl(url);
@@ -274,23 +379,48 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.debug(String.format("bundle-audit (%s): %s", parentName, nextLine));
}
/**
* Adds the criticality to the vulnerability
*
* @param parentName the parent name
* @param vulnerability the vulnerability
* @param nextLine the line to parse
*/
private void addCriticalityToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
if (null != vulnerability) {
final String criticality = nextLine.substring(CRITICALITY.length()).trim();
if ("High".equals(criticality)) {
vulnerability.setCvssScore(8.5f);
} else if ("Medium".equals(criticality)) {
vulnerability.setCvssScore(5.5f);
} else if ("Low".equals(criticality)) {
vulnerability.setCvssScore(2.0f);
} else {
vulnerability.setCvssScore(-1.0f);
float score = -1.0f;
Vulnerability v = null;
try {
v = cvedb.getVulnerability(vulnerability.getName());
} catch (DatabaseException ex) {
LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName());
}
if (v != null) {
score = v.getCvssScore();
} else if ("High".equalsIgnoreCase(criticality)) {
score = 8.5f;
} else if ("Medium".equalsIgnoreCase(criticality)) {
score = 5.5f;
} else if ("Low".equalsIgnoreCase(criticality)) {
score = 2.0f;
}
vulnerability.setCvssScore(score);
}
LOGGER.debug(String.format("bundle-audit (%s): %s", parentName, nextLine));
}
private Vulnerability createVulnerability(String parentName, Dependency dependency, Vulnerability vulnerability, String gem, String nextLine) {
/**
* Creates a vulnerability.
*
* @param parentName the parent name
* @param dependency the dependency
* @param gem the gem name
* @param nextLine the line to parse
* @return the vulnerability
*/
private Vulnerability createVulnerability(String parentName, Dependency dependency, String gem, String nextLine) {
Vulnerability vulnerability = null;
if (null != dependency) {
final String version = nextLine.substring(VERSION.length());
dependency.getVersionEvidence().addEvidence(
@@ -313,13 +443,28 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
return vulnerability;
}
private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String gem) throws IOException {
final File tempFile = File.createTempFile("Gemfile-" + gem, ".lock", Settings.getTempDirectory());
/**
* Creates the dependency based off of the gem.
*
* @param engine the engine used for scanning
* @param parentName the gem parent
* @param fileName the file name
* @param filePath the file path
* @param gem the gem name
* @return the dependency to add
* @throws IOException thrown if a temporary gem file could not be written
*/
private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String filePath, String gem) throws IOException {
final File gemFile = new File(Settings.getTempDirectory(), gem + "_Gemfile.lock");
gemFile.createNewFile();
final String displayFileName = String.format("%s%c%s:%s", parentName, File.separatorChar, fileName, gem);
FileUtils.write(tempFile, displayFileName); // unique contents to avoid dependency bundling
final Dependency dependency = new Dependency(tempFile);
FileUtils.write(gemFile, displayFileName, Charset.defaultCharset()); // unique contents to avoid dependency bundling
final Dependency dependency = new Dependency(gemFile);
dependency.getProductEvidence().addEvidence("bundler-audit", "Name", gem, Confidence.HIGHEST);
dependency.setDisplayFileName(displayFileName);
dependency.setFileName(fileName);
dependency.setFilePath(filePath);
engine.getDependencies().add(dependency);
return dependency;
}

View File

@@ -0,0 +1,139 @@
/*
* 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) 2016 Bianca Jiang. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import java.io.File;
import java.io.FilenameFilter;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency;
/**
* This analyzer accepts the fully resolved .gemspec created by the Ruby bundler
* (http://bundler.io) for better evidence results. It also tries to resolve the
* dependency packagePath to where the gem is actually installed. Then during {@link org.owasp.dependencycheck.analyzer.AnalysisPhase#PRE_FINDING_ANALYSIS}
* {@link DependencyBundlingAnalyzer} will merge two .gemspec dependencies
* together if <code>Dependency.getPackagePath()</code> are the same.
*
* Ruby bundler creates new .gemspec files under a folder called
* "specifications" at deploy time, in addition to the original .gemspec files
* from source. The bundler generated .gemspec files always contain fully
* resolved attributes thus provide more accurate evidences, whereas the
* original .gemspec from source often contain variables for attributes that
* can't be used for evidences.
*
* Note this analyzer share the same
* {@link org.owasp.dependencycheck.utils.Settings.KEYS#ANALYZER_RUBY_GEMSPEC_ENABLED} as
* {@link RubyGemspecAnalyzer}, so it will enabled/disabled with
* {@link RubyGemspecAnalyzer}.
*
* @author Bianca Jiang (biancajiang@gmail.com)
*/
@Experimental
public class RubyBundlerAnalyzer extends RubyGemspecAnalyzer {
/**
* The name of the analyzer.
*/
private static final String ANALYZER_NAME = "Ruby Bundler Analyzer";
/**
* Folder name that contains .gemspec files created by "bundle install"
*/
private static final String SPECIFICATIONS = "specifications";
/**
* Folder name that contains the gems by "bundle install"
*/
private static final String GEMS = "gems";
/**
* Returns the name of the analyzer.
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
/**
* Only accept *.gemspec files generated by "bundle install --deployment"
* under "specifications" folder.
*
* @param pathname the path name to test
* @return true if the analyzer can process the given file; otherwise false
*/
@Override
public boolean accept(File pathname) {
boolean accepted = super.accept(pathname);
if (accepted) {
final File parentDir = pathname.getParentFile();
accepted = parentDir != null && parentDir.getName().equals(SPECIFICATIONS);
}
return accepted;
}
@Override
protected void analyzeFileType(Dependency dependency, Engine engine)
throws AnalysisException {
super.analyzeFileType(dependency, engine);
//find the corresponding gem folder for this .gemspec stub by "bundle install --deployment"
final File gemspecFile = dependency.getActualFile();
final String gemFileName = gemspecFile.getName();
final String gemName = gemFileName.substring(0, gemFileName.lastIndexOf(".gemspec"));
final File specificationsDir = gemspecFile.getParentFile();
if (specificationsDir != null && specificationsDir.getName().equals(SPECIFICATIONS) && specificationsDir.exists()) {
final File parentDir = specificationsDir.getParentFile();
if (parentDir != null && parentDir.exists()) {
final File gemsDir = new File(parentDir, GEMS);
if (gemsDir.exists()) {
final File[] matchingFiles = gemsDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.equals(gemName);
}
});
if (matchingFiles != null && matchingFiles.length > 0) {
final String gemPath = matchingFiles[0].getAbsolutePath();
if (dependency.getActualFilePath().equals(dependency.getFilePath())) {
if (gemPath != null) {
dependency.setPackagePath(gemPath);
}
} else {
//.gemspec's actualFilePath and filePath are different when it's from a compressed file
//in which case actualFilePath is the temp directory used by decompression.
//packagePath should use the filePath of the identified gem file in "gems" folder
final File gemspecStub = new File(dependency.getFilePath());
final File specDir = gemspecStub.getParentFile();
if (specDir != null && specDir.getName().equals(SPECIFICATIONS)) {
final File gemsDir2 = new File(specDir.getParentFile(), GEMS);
final File packageDir = new File(gemsDir2, gemName);
dependency.setPackagePath(packageDir.getAbsolutePath());
}
}
}
}
}
}
}
}

View File

@@ -17,6 +17,15 @@
*/
package org.owasp.dependencycheck.analyzer;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
@@ -25,20 +34,23 @@ 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 java.io.FileFilter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to analyze Ruby Gem specifications and collect information that can be used to determine the associated CPE.
* Regular expressions are used to parse the well-defined Ruby syntax that forms the specification.
* Used to analyze Ruby Gem specifications and collect information that can be
* used to determine the associated CPE. Regular expressions are used to parse
* the well-defined Ruby syntax that forms the specification.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
@Experimental
public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(RubyGemspecAnalyzer.class);
/**
* The name of the analyzer.
*/
@@ -49,15 +61,26 @@ public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer {
*/
private static final AnalysisPhase ANALYSIS_PHASE = AnalysisPhase.INFORMATION_COLLECTION;
/**
* The gemspec file extension.
*/
private static final String GEMSPEC = "gemspec";
private static final FileFilter FILTER =
FileFilterBuilder.newInstance().addExtensions(GEMSPEC).addFilenames("Rakefile").build();
private static final String EMAIL = "email";
/**
* The file filter containing the list of file extensions that can be
* analyzed.
*/
private static final FileFilter FILTER = FileFilterBuilder.newInstance().addExtensions(GEMSPEC).build();
//TODO: support Rakefile
//= FileFilterBuilder.newInstance().addExtensions(GEMSPEC).addFilenames("Rakefile").build();
/**
* @return a filter that accepts files named Rakefile or matching the glob pattern, *.gemspec
* The name of the version file.
*/
private static final String VERSION_FILE_NAME = "VERSION";
/**
* @return a filter that accepts files matching the glob pattern, *.gemspec
*/
@Override
protected FileFilter getFileFilter() {
@@ -90,7 +113,8 @@ public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer {
}
/**
* Returns the key used in the properties file to reference the analyzer's enabled property.
* Returns the key used in the properties file to reference the analyzer's
* enabled property.
*
* @return the analyzer's enabled property setting key
*/
@@ -102,15 +126,14 @@ public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer {
/**
* The capture group #1 is the block variable.
*/
private static final Pattern GEMSPEC_BLOCK_INIT =
Pattern.compile("Gem::Specification\\.new\\s+?do\\s+?\\|(.+?)\\|");
private static final Pattern GEMSPEC_BLOCK_INIT = Pattern.compile("Gem::Specification\\.new\\s+?do\\s+?\\|(.+?)\\|");
@Override
protected void analyzeFileType(Dependency dependency, Engine engine)
throws AnalysisException {
String contents;
try {
contents = FileUtils.readFileToString(dependency.getActualFile());
contents = FileUtils.readFileToString(dependency.getActualFile(), Charset.defaultCharset());
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
@@ -119,43 +142,103 @@ public class RubyGemspecAnalyzer extends AbstractFileTypeAnalyzer {
if (matcher.find()) {
contents = contents.substring(matcher.end());
final String blockVariable = matcher.group(1);
final EvidenceCollection vendor = dependency.getVendorEvidence();
addStringEvidence(vendor, contents, blockVariable, "author", Confidence.HIGHEST);
addListEvidence(vendor, contents, blockVariable, "authors", Confidence.HIGHEST);
final String email = addStringEvidence(vendor, contents, blockVariable, EMAIL, Confidence.MEDIUM);
if (email.isEmpty()) {
addListEvidence(vendor, contents, blockVariable, EMAIL, Confidence.MEDIUM);
}
addStringEvidence(vendor, contents, blockVariable, "homepage", Confidence.MEDIUM);
final EvidenceCollection product = dependency.getProductEvidence();
final String name = addStringEvidence(product, contents, blockVariable, "name", Confidence.HIGHEST);
final String name = addStringEvidence(product, contents, blockVariable, "name", "name", Confidence.HIGHEST);
if (!name.isEmpty()) {
vendor.addEvidence(GEMSPEC, "name_project", name + "_project", Confidence.LOW);
}
addStringEvidence(product, contents, blockVariable, "summary", Confidence.LOW);
addStringEvidence(dependency.getVersionEvidence(), contents, blockVariable, "version", Confidence.HIGHEST);
}
}
private void addListEvidence(EvidenceCollection evidences, String contents,
String blockVariable, String field, Confidence confidence) {
final Matcher matcher = Pattern.compile(
String.format("\\s+?%s\\.%s\\s*?=\\s*?\\[(.*?)\\]", blockVariable, field)).matcher(contents);
if (matcher.find()) {
final String value = matcher.group(1).replaceAll("['\"]", " ").trim();
evidences.addEvidence(GEMSPEC, field, value, confidence);
addStringEvidence(product, contents, blockVariable, "summary", "summary", Confidence.LOW);
addStringEvidence(vendor, contents, blockVariable, "author", "authors?", Confidence.HIGHEST);
addStringEvidence(vendor, contents, blockVariable, "email", "emails?", Confidence.MEDIUM);
addStringEvidence(vendor, contents, blockVariable, "homepage", "homepage", Confidence.HIGHEST);
addStringEvidence(vendor, contents, blockVariable, "license", "licen[cs]es?", Confidence.HIGHEST);
final String value = addStringEvidence(dependency.getVersionEvidence(), contents,
blockVariable, "version", "version", Confidence.HIGHEST);
if (value.length() < 1) {
addEvidenceFromVersionFile(dependency.getActualFile(), dependency.getVersionEvidence());
}
}
setPackagePath(dependency);
}
/**
* Adds the specified evidence to the given evidence collection.
*
* @param evidences the collection to add the evidence to
* @param contents the evidence contents
* @param blockVariable the variable
* @param field the field
* @param fieldPattern the field pattern
* @param confidence the confidence of the evidence
* @return the evidence string value added
*/
private String addStringEvidence(EvidenceCollection evidences, String contents,
String blockVariable, String field, Confidence confidence) {
final Matcher matcher = Pattern.compile(
String.format("\\s+?%s\\.%s\\s*?=\\s*?(['\"])(.*?)\\1", blockVariable, field)).matcher(contents);
String blockVariable, String field, String fieldPattern, Confidence confidence) {
String value = "";
if (matcher.find()) {
value = matcher.group(2);
//capture array value between [ ]
final Matcher arrayMatcher = Pattern.compile(
String.format("\\s*?%s\\.%s\\s*?=\\s*?\\[(.*?)\\]", blockVariable, fieldPattern), Pattern.CASE_INSENSITIVE).matcher(contents);
if (arrayMatcher.find()) {
final String arrayValue = arrayMatcher.group(1);
value = arrayValue.replaceAll("['\"]", "").trim(); //strip quotes
} else { //capture single value between quotes
final Matcher matcher = Pattern.compile(
String.format("\\s*?%s\\.%s\\s*?=\\s*?(['\"])(.*?)\\1", blockVariable, fieldPattern), Pattern.CASE_INSENSITIVE).matcher(contents);
if (matcher.find()) {
value = matcher.group(2);
}
}
if (value.length() > 0) {
evidences.addEvidence(GEMSPEC, field, value, confidence);
}
return value;
}
/**
* Adds evidence from the version file.
*
* @param dependencyFile the dependency being analyzed
* @param versionEvidences the version evidence
*/
private void addEvidenceFromVersionFile(File dependencyFile, EvidenceCollection versionEvidences) {
final File parentDir = dependencyFile.getParentFile();
if (parentDir != null) {
final File[] matchingFiles = parentDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains(VERSION_FILE_NAME);
}
});
for (File f : matchingFiles) {
try {
final List<String> lines = FileUtils.readLines(f, Charset.defaultCharset());
if (lines.size() == 1) { //TODO other checking?
final String value = lines.get(0).trim();
versionEvidences.addEvidence(GEMSPEC, "version", value, Confidence.HIGH);
}
} catch (IOException e) {
LOGGER.debug("Error reading gemspec", e);
}
}
}
}
/**
* Sets the package path on the dependency.
*
* @param dep the dependency to alter
*/
private void setPackagePath(Dependency dep) {
final File file = new File(dep.getFilePath());
final String parent = file.getParent();
if (parent != null) {
dep.setPackagePath(parent);
}
}
}

View File

@@ -1,6 +1,6 @@
/**
*
* Contains classes related to searching Maven Central.<br/><br/>
* Contains classes related to searching Maven Central.<br><br>
*
* These are used to abstract Maven Central searching away from OWASP Dependency Check so they can be reused elsewhere.
*/

View File

@@ -37,7 +37,7 @@ public class CweHandler extends DefaultHandler {
/**
* Returns the HashMap of CWE entries (CWE-ID, Full CWE Name).
*
* @return a HashMap of CWE entries <String, String>
* @return a HashMap of CWE entries &lt;String, String&gt;
*/
public HashMap<String, String> getCwe() {
return cwe;

View File

@@ -27,7 +27,7 @@ import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
* <p>
* Takes a TokenStream and adds additional tokens by concatenating pairs of words.</p>
* <p>
* <b>Example:</b> "Spring Framework Core" -> "Spring SpringFramework Framework FrameworkCore Core".</p>
* <b>Example:</b> "Spring Framework Core" -&gt; "Spring SpringFramework Framework FrameworkCore Core".</p>
*
* @author Jeremy Long
*/

View File

@@ -31,15 +31,17 @@ import org.slf4j.LoggerFactory;
* <p>
* Takes a TokenStream and splits or adds tokens to correctly index version numbers.</p>
* <p>
* <b>Example:</b> "3.0.0.RELEASE" -> "3 3.0 3.0.0 RELEASE 3.0.0.RELEASE".</p>
* <b>Example:</b> "3.0.0.RELEASE" -&gt; "3 3.0 3.0.0 RELEASE 3.0.0.RELEASE".</p>
*
* @author Jeremy Long
*/
public final class UrlTokenizingFilter extends AbstractTokenizingFilter {
/**
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(UrlTokenizingFilter.class);
/**
* Constructs a new VersionTokenizingFilter.
*
@@ -50,8 +52,8 @@ public final class UrlTokenizingFilter extends AbstractTokenizingFilter {
}
/**
* Increments the underlying TokenStream and sets CharTermAttributes to construct an expanded set of tokens by
* concatenating tokens with the previous token.
* Increments the underlying TokenStream and sets CharTermAttributes to construct an expanded set of tokens by concatenating
* tokens with the previous token.
*
* @return whether or not we have hit the end of the TokenStream
* @throws IOException is thrown when an IOException occurs

View File

@@ -1,5 +1,5 @@
/**
* Contains classes related to searching a Nexus repository.<br/><br/>
* Contains classes related to searching a Nexus repository.<br><br>
*
* These are used to abstract Nexus searching away from OWASP Dependency Check so they can be reused elsewhere.
*/

View File

@@ -1,5 +1,5 @@
/**
* Contains classes related to parsing Nuget related files<br/><br/>
* Contains classes related to parsing Nuget related files<br><br>
* These are used to abstract away Nuget-related handling from Dependency Check so they can be used elsewhere.
*/
package org.owasp.dependencycheck.data.nuget;

View File

@@ -276,10 +276,13 @@ public final class ConnectionFactory {
* execute it against the database. The upgrade script must update the 'version' in the properties table.
*
* @param conn the database connection object
* @param schema the current schema version that is being upgraded
* @param appExpectedVersion the schema version that the application expects
* @param currentDbVersion the current schema version of the database
* @throws DatabaseException thrown if there is an exception upgrading the database schema
*/
private static void updateSchema(Connection conn, String schema) throws DatabaseException {
private static void updateSchema(Connection conn, DependencyVersion appExpectedVersion, DependencyVersion currentDbVersion)
throws DatabaseException {
final String databaseProductName;
try {
databaseProductName = conn.getMetaData().getDatabaseProductName();
@@ -291,7 +294,7 @@ public final class ConnectionFactory {
InputStream is = null;
String updateFile = null;
try {
updateFile = String.format(DB_STRUCTURE_UPDATE_RESOURCE, schema);
updateFile = String.format(DB_STRUCTURE_UPDATE_RESOURCE, currentDbVersion.toString());
is = ConnectionFactory.class.getClassLoader().getResourceAsStream(updateFile);
if (is == null) {
throw new DatabaseException(String.format("Unable to load update file '%s'", updateFile));
@@ -303,7 +306,8 @@ public final class ConnectionFactory {
statement = conn.createStatement();
final boolean success = statement.execute(dbStructureUpdate);
if (!success && statement.getUpdateCount() <= 0) {
throw new DatabaseException(String.format("Unable to upgrade the database schema to %s", schema));
throw new DatabaseException(String.format("Unable to upgrade the database schema to %s",
currentDbVersion.toString()));
}
} catch (SQLException ex) {
LOGGER.debug("", ex);
@@ -318,8 +322,20 @@ public final class ConnectionFactory {
IOUtils.closeQuietly(is);
}
} else {
LOGGER.error("The database schema must be upgraded to use this version of dependency-check. Please see {} for more information.", UPGRADE_HELP_URL);
throw new DatabaseException("Database schema is out of date");
final int e0 = Integer.parseInt(appExpectedVersion.getVersionParts().get(0));
final int c0 = Integer.parseInt(currentDbVersion.getVersionParts().get(0));
final int e1 = Integer.parseInt(appExpectedVersion.getVersionParts().get(1));
final int c1 = Integer.parseInt(currentDbVersion.getVersionParts().get(1));
if (e0 == c0 && e1 < c1) {
LOGGER.warn("A new version of dependency-check is available; consider upgrading");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
} else if (e0 == c0 && e1 == c1) {
//do nothing - not sure how we got here, but just incase...
} else {
LOGGER.error("The database schema must be upgraded to use this version of dependency-check. Please see {} for more information.",
UPGRADE_HELP_URL);
throw new DatabaseException("Database schema is out of date");
}
}
}
@@ -342,12 +358,12 @@ public final class ConnectionFactory {
cs = conn.prepareCall("SELECT value FROM properties WHERE id = 'version'");
rs = cs.executeQuery();
if (rs.next()) {
final DependencyVersion current = DependencyVersionUtil.parseVersion(DB_SCHEMA_VERSION);
final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(DB_SCHEMA_VERSION);
final DependencyVersion db = DependencyVersionUtil.parseVersion(rs.getString(1));
if (current.compareTo(db) > 0) {
if (appDbVersion.compareTo(db) > 0) {
LOGGER.debug("Current Schema: {}", DB_SCHEMA_VERSION);
LOGGER.debug("DB Schema: {}", rs.getString(1));
updateSchema(conn, rs.getString(1));
updateSchema(conn, appDbVersion, db);
if (++callDepth < 10) {
ensureSchemaVersion(conn);
}

View File

@@ -69,10 +69,19 @@ public class CveDB {
private ResourceBundle statementBundle = null;
/**
* Creates a new CveDB object and opens the database connection. Note, the connection must be closed by the caller by calling
* the close method.
*
* @throws DatabaseException thrown if there is an exception opening the database.
* Creates a new CveDB object and opens the database
* connection. Note, the connection must be closed by the caller by calling
* the close method. ======= Does the underlying connection support batch
* operations?
*/
private boolean batchSupported;
/**
* Creates a new CveDB object and opens the database connection. Note, the
* connection must be closed by the caller by calling the close method.
*
* @throws DatabaseException thrown if there is an exception opening the
* database.
*/
public CveDB() throws DatabaseException {
super();
@@ -80,6 +89,7 @@ public class CveDB {
open();
try {
final String databaseProductName = conn.getMetaData().getDatabaseProductName();
batchSupported = conn.getMetaData().supportsBatchUpdates();
LOGGER.debug("Database dialect: {}", databaseProductName);
final Locale dbDialect = new Locale(databaseProductName);
statementBundle = ResourceBundle.getBundle("data/dbStatements", dbDialect);
@@ -103,9 +113,11 @@ public class CveDB {
}
/**
* Opens the database connection. If the database does not exist, it will create a new one.
* Opens the database connection. If the database does not exist, it will
* create a new one.
*
* @throws DatabaseException thrown if there is an error opening the database connection
* @throws DatabaseException thrown if there is an error opening the
* database connection
*/
public final void open() throws DatabaseException {
if (!isOpen()) {
@@ -114,7 +126,8 @@ public class CveDB {
}
/**
* Closes the DB4O database. Close should be called on this object when it is done being used.
* Closes the DB4O database. Close should be called on this object when it
* is done being used.
*/
public void close() {
if (conn != null) {
@@ -165,7 +178,8 @@ public class CveDB {
super.finalize();
}
/**
* Database properties object containing the 'properties' from the database table.
* Database properties object containing the 'properties' from the database
* table.
*/
private DatabaseProperties databaseProperties;
@@ -179,11 +193,13 @@ public class CveDB {
}
/**
* Searches the CPE entries in the database and retrieves all entries for a given vendor and product combination. The returned
* list will include all versions of the product that are registered in the NVD CVE data.
* Searches the CPE entries in the database and retrieves all entries for a
* given vendor and product combination. The returned list will include all
* versions of the product that are registered in the NVD CVE data.
*
* @param vendor the identified vendor name of the dependency being analyzed
* @param product the identified name of the product of the dependency being analyzed
* @param product the identified name of the product of the dependency being
* analyzed
* @return a set of vulnerable software
*/
public Set<VulnerableSoftware> getCPEs(String vendor, String product) {
@@ -215,7 +231,8 @@ public class CveDB {
* Returns the entire list of vendor/product combinations.
*
* @return the entire list of vendor/product combinations
* @throws DatabaseException thrown when there is an error retrieving the data from the DB
* @throws DatabaseException thrown when there is an error retrieving the
* data from the DB
*/
public Set<Pair<String, String>> getVendorProductList() throws DatabaseException {
final Set<Pair<String, String>> data = new HashSet<Pair<String, String>>();
@@ -372,7 +389,7 @@ public class CveDB {
* @return a vulnerability object
* @throws DatabaseException if an exception occurs
*/
private Vulnerability getVulnerability(String cve) throws DatabaseException {
public Vulnerability getVulnerability(String cve) throws DatabaseException {
PreparedStatement psV = null;
PreparedStatement psR = null;
PreparedStatement psS = null;
@@ -380,6 +397,7 @@ public class CveDB {
ResultSet rsR = null;
ResultSet rsS = null;
Vulnerability vuln = null;
try {
psV = getConnection().prepareStatement(statementBundle.getString("SELECT_VULNERABILITY"));
psV.setString(1, cve);
@@ -438,7 +456,8 @@ public class CveDB {
}
/**
* Updates the vulnerability within the database. If the vulnerability does not exist it will be added.
* Updates the vulnerability within the database. If the vulnerability does
* not exist it will be added.
*
* @param vuln the vulnerability to add to the database
* @throws DatabaseException is thrown if the database
@@ -484,6 +503,7 @@ public class CveDB {
}
DBUtils.closeResultSet(rs);
rs = null;
if (vulnerabilityId != 0) {
if (vuln.getDescription().contains("** REJECT **")) {
deleteVulnerability.setInt(1, vulnerabilityId);
@@ -525,13 +545,24 @@ public class CveDB {
rs = null;
}
}
insertReference.setInt(1, vulnerabilityId);
for (Reference r : vuln.getReferences()) {
insertReference.setInt(1, vulnerabilityId);
insertReference.setString(2, r.getName());
insertReference.setString(3, r.getUrl());
insertReference.setString(4, r.getSource());
insertReference.execute();
if (batchSupported) {
insertReference.addBatch();
} else {
insertReference.execute();
}
}
if (batchSupported) {
insertReference.executeBatch();
}
for (VulnerableSoftware s : vuln.getVulnerableSoftware()) {
int cpeProductId = 0;
selectCpeId.setString(1, s.getName());
@@ -560,17 +591,33 @@ public class CveDB {
insertSoftware.setInt(1, vulnerabilityId);
insertSoftware.setInt(2, cpeProductId);
if (s.getPreviousVersion() == null) {
insertSoftware.setNull(3, java.sql.Types.VARCHAR);
} else {
insertSoftware.setString(3, s.getPreviousVersion());
}
insertSoftware.execute();
if (batchSupported) {
insertSoftware.addBatch();
} else {
try {
insertSoftware.execute();
} catch (SQLException ex) {
if (ex.getMessage().contains("Duplicate entry")) {
final String msg = String.format("Duplicate software key identified in '%s:%s'", vuln.getName(), s.getName());
LOGGER.debug(msg, ex);
} else {
throw ex;
}
}
}
}
if (batchSupported) {
insertSoftware.executeBatch();
}
} catch (SQLException ex) {
final String msg = String.format("Error updating '%s'", vuln.getName());
LOGGER.debug("", ex);
LOGGER.debug(msg, ex);
throw new DatabaseException(msg, ex);
} finally {
DBUtils.closeStatement(selectVulnerabilityId);
@@ -623,8 +670,9 @@ public class CveDB {
}
/**
* It is possible that orphaned rows may be generated during database updates. This should be called after all updates have
* been completed to ensure orphan entries are removed.
* It is possible that orphaned rows may be generated during database
* updates. This should be called after all updates have been completed to
* ensure orphan entries are removed.
*/
public void cleanupDatabase() {
PreparedStatement ps = null;
@@ -642,13 +690,17 @@ public class CveDB {
}
/**
* Determines if the given identifiedVersion is affected by the given cpeId and previous version flag. A non-null, non-empty
* string passed to the previous version argument indicates that all previous versions are affected.
* Determines if the given identifiedVersion is affected by the given cpeId
* and previous version flag. A non-null, non-empty string passed to the
* previous version argument indicates that all previous versions are
* affected.
*
* @param vendor the vendor of the dependency being analyzed
* @param product the product name of the dependency being analyzed
* @param vulnerableSoftware a map of the vulnerable software with a boolean indicating if all previous versions are affected
* @param identifiedVersion the identified version of the dependency being analyzed
* @param vulnerableSoftware a map of the vulnerable software with a boolean
* indicating if all previous versions are affected
* @param identifiedVersion the identified version of the dependency being
* analyzed
* @return true if the identified version is affected, otherwise false
*/
Entry<String, Boolean> getMatchingSoftware(Map<String, Boolean> vulnerableSoftware, String vendor, String product,
@@ -715,7 +767,8 @@ public class CveDB {
}
/**
* Parses the version (including revision) from a CPE identifier. If no version is identified then a '-' is returned.
* Parses the version (including revision) from a CPE identifier. If no
* version is identified then a '-' is returned.
*
* @param cpeStr a cpe identifier
* @return a dependency version
@@ -732,7 +785,8 @@ public class CveDB {
}
/**
* Takes a CPE and parses out the version number. If no version is identified then a '-' is returned.
* Takes a CPE and parses out the version number. If no version is
* identified then a '-' is returned.
*
* @param cpe a cpe object
* @return a dependency version
@@ -771,7 +825,8 @@ public class CveDB {
}
/**
* This method is only referenced in unused code and will likely break on MySQL if ever used due to the MERGE statement.
* This method is only referenced in unused code and will likely break on
* MySQL if ever used due to the MERGE statement.
*
* Merges CPE entries into the database.
*

View File

@@ -35,7 +35,6 @@ import org.owasp.dependencycheck.data.update.nvd.DownloadTask;
import org.owasp.dependencycheck.data.update.nvd.NvdCveInfo;
import org.owasp.dependencycheck.data.update.nvd.ProcessTask;
import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve;
import org.owasp.dependencycheck.exception.NoDataException;
import org.owasp.dependencycheck.utils.DateUtil;
import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.InvalidSettingException;
@@ -61,16 +60,25 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
/**
* <p>
* Downloads the latest NVD CVE XML file from the web and imports it into the current CVE Database.</p>
* Downloads the latest NVD CVE XML file from the web and imports it into
* the current CVE Database.</p>
*
* @throws UpdateException is thrown if there is an error updating the database
* @throws UpdateException is thrown if there is an error updating the
* database
*/
@Override
public void update() throws UpdateException {
try {
openDataStores();
if (checkUpdate()) {
boolean autoUpdate = true;
try {
autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
} catch (InvalidSettingException ex) {
LOGGER.debug("Invalid setting for auto-update; using true.");
}
if (autoUpdate && checkUpdate()) {
final UpdateableNvdCve updateable = getUpdatesNeeded();
getProperties().save(DatabaseProperties.LAST_CHECKED, Long.toString(System.currentTimeMillis()));
if (updateable.isUpdateNeeded()) {
performUpdate(updateable);
}
@@ -93,12 +101,15 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
}
/**
* Checks if the NVD CVE XML files were last checked recently. As an optimization, we can avoid repetitive checks against the
* NVD. Setting CVE_CHECK_VALID_FOR_HOURS determines the duration since last check before checking again. A database property
* stores the timestamp of the last check.
* Checks if the NVD CVE XML files were last checked recently. As an
* optimization, we can avoid repetitive checks against the NVD. Setting
* CVE_CHECK_VALID_FOR_HOURS determines the duration since last check before
* checking again. A database property stores the timestamp of the last
* check.
*
* @return true to proceed with the check, or false to skip.
* @throws UpdateException thrown when there is an issue checking for updates.
* @throws UpdateException thrown when there is an issue checking for
* updates.
*/
private boolean checkUpdate() throws UpdateException {
boolean proceed = true;
@@ -110,9 +121,7 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
final long lastChecked = Long.parseLong(getProperties().getProperty(DatabaseProperties.LAST_CHECKED, "0"));
final long now = System.currentTimeMillis();
proceed = (now - lastChecked) > msValid;
if (proceed) {
getProperties().save(DatabaseProperties.LAST_CHECKED, Long.toString(now));
} else {
if (!proceed) {
LOGGER.info("Skipping NVD check since last check was within {} hours.", validForHours);
LOGGER.debug("Last NVD was at {}, and now {} is within {} ms.",
lastChecked, now, msValid);
@@ -122,7 +131,9 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
}
/**
* Checks the CPE Index to ensure documents exists.
* Checks the CVE Index to ensure data exists and analysis can continue.
*
* @return true if the database contains data
*/
private boolean dataExists() {
CveDB cve = null;
@@ -140,11 +151,13 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
}
/**
* Downloads the latest NVD CVE XML file from the web and imports it into the current CVE Database.
* Downloads the latest NVD CVE XML file from the web and imports it into
* the current CVE Database.
*
* @param updateable a collection of NVD CVE data file references that need to be downloaded and processed to update the
* @param updateable a collection of NVD CVE data file references that need
* to be downloaded and processed to update the database
* @throws UpdateException is thrown if there is an error updating the
* database
* @throws UpdateException is thrown if there is an error updating the database
*/
public void performUpdate(UpdateableNvdCve updateable) throws UpdateException {
int maxUpdates = 0;
@@ -238,13 +251,18 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
}
/**
* Determines if the index needs to be updated. This is done by fetching the NVD CVE meta data and checking the last update
* date. If the data needs to be refreshed this method will return the NvdCveUrl for the files that need to be updated.
* Determines if the index needs to be updated. This is done by fetching the
* NVD CVE meta data and checking the last update date. If the data needs to
* be refreshed this method will return the NvdCveUrl for the files that
* need to be updated.
*
* @return the collection of files that need to be updated
* @throws MalformedURLException is thrown if the URL for the NVD CVE Meta data is incorrect
* @throws DownloadFailedException is thrown if there is an error. downloading the NVD CVE download data file
* @throws UpdateException Is thrown if there is an issue with the last updated properties file
* @throws MalformedURLException is thrown if the URL for the NVD CVE Meta
* data is incorrect
* @throws DownloadFailedException is thrown if there is an error.
* downloading the NVD CVE download data file
* @throws UpdateException Is thrown if there is an issue with the last
* updated properties file
*/
protected final UpdateableNvdCve getUpdatesNeeded() throws MalformedURLException, DownloadFailedException, UpdateException {
UpdateableNvdCve updates = null;
@@ -308,9 +326,12 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
* Retrieves the timestamps from the NVD CVE meta data file.
*
* @return the timestamp from the currently published nvdcve downloads page
* @throws MalformedURLException thrown if the URL for the NVD CCE Meta data is incorrect.
* @throws DownloadFailedException thrown if there is an error downloading the nvd cve meta data file
* @throws InvalidDataException thrown if there is an exception parsing the timestamps
* @throws MalformedURLException thrown if the URL for the NVD CCE Meta data
* is incorrect.
* @throws DownloadFailedException thrown if there is an error downloading
* the nvd cve meta data file
* @throws InvalidDataException thrown if there is an exception parsing the
* timestamps
* @throws InvalidSettingException thrown if the settings are invalid
*/
private UpdateableNvdCve retrieveCurrentTimestampsFromWeb()
@@ -332,5 +353,4 @@ public class NvdCveUpdater extends BaseUpdater implements CachedWebDataSource {
}
return updates;
}
}

View File

@@ -1,5 +1,5 @@
/**
* Contains classes used to parse the CPE XML file from NIST.<br/><br/>
* Contains classes used to parse the CPE XML file from NIST.<br><br>
*
* These classes are not used as they add no value over the existing CPE data contained within the CVE data from the NVD. However,
* we may consider pulling the more descriptive data from the CPE data in the future.

View File

@@ -22,6 +22,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
@@ -176,15 +177,15 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
LOGGER.debug("", ex);
return null;
}
if (url1.toExternalForm().endsWith(".xml.gz")) {
if (url1.toExternalForm().endsWith(".xml.gz") && !isXml(first)) {
extractGzip(first);
}
if (url2.toExternalForm().endsWith(".xml.gz")) {
if (url2.toExternalForm().endsWith(".xml.gz") && !isXml(second)) {
extractGzip(second);
}
LOGGER.info("Download Complete for NVD CVE - {} ({} ms)", nvdCveInfo.getId(),
System.currentTimeMillis() - startDownload);
System.currentTimeMillis() - startDownload);
if (this.processorService == null) {
return null;
}
@@ -226,6 +227,46 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
}
}
/**
* Checks the file header to see if it is an XML file.
*
* @param file the file to check
* @return true if the file is XML
*/
public static boolean isXml(File file) {
if (file == null || !file.isFile()) {
return false;
}
InputStream is = null;
try {
is = new FileInputStream(file);
final byte[] buf = new byte[5];
int read = 0;
try {
read = is.read(buf);
} catch (IOException ex) {
return false;
}
return read == 5
&& buf[0] == '<'
&& (buf[1] == '?')
&& (buf[2] == 'x' || buf[2] == 'X')
&& (buf[3] == 'm' || buf[3] == 'M')
&& (buf[4] == 'l' || buf[4] == 'L');
} catch (FileNotFoundException ex) {
return false;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
LOGGER.debug("Error closing stream", ex);
}
}
}
}
/**
* Extracts the file contained in a gzip archive. The extracted file is placed in the exact same path as the file specified.
*

View File

@@ -254,17 +254,16 @@ public class NvdCve20Handler extends DefaultHandler {
* @throws IOException thrown if there is an IOException with the CPE Index
*/
private void saveEntry(Vulnerability vuln) throws DatabaseException, CorruptIndexException, IOException {
if (cveDB == null) {
return;
}
final String cveName = vuln.getName();
if (prevVersionVulnMap.containsKey(cveName)) {
if (prevVersionVulnMap != null && prevVersionVulnMap.containsKey(cveName)) {
final List<VulnerableSoftware> vulnSoftware = prevVersionVulnMap.get(cveName);
for (VulnerableSoftware vs : vulnSoftware) {
vuln.updateVulnerableSoftware(vs);
}
}
cveDB.updateVulnerability(vuln);
if (cveDB != null) {
cveDB.updateVulnerability(vuln);
}
}
// <editor-fold defaultstate="collapsed" desc="The Element Class that maintains state information about the current node">

View File

@@ -1,4 +1,4 @@
/**
* Contains classes used to download, parse, and load the NVD CVE data from NIST into the local database.<br/><br/>
* Contains classes used to download, parse, and load the NVD CVE data from NIST into the local database.<br><br>
*/
package org.owasp.dependencycheck.data.update.nvd;

View File

@@ -1,6 +1,6 @@
/**
*
* Contains classes used to update the data stores.<br/><br/>
* Contains classes used to update the data stores.<br><br>
*
* The UpdateService will load, any correctly defined CachedWebDataSource(s) and call update() on them. The Cached Data Source
* must determine if it needs to be updated and if so perform the update. The sub packages contain classes used to perform the

View File

@@ -36,9 +36,10 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A program dependency. This object is one of the core components within DependencyCheck. It is used to collect information about
* the dependency in the form of evidence. The Evidence is then used to determine if there are any known, published,
* vulnerabilities associated with the program dependency.
* A program dependency. This object is one of the core components within
* DependencyCheck. It is used to collect information about the dependency in
* the form of evidence. The Evidence is then used to determine if there are any
* known, published, vulnerabilities associated with the program dependency.
*
* @author Jeremy Long
*/
@@ -72,6 +73,30 @@ public class Dependency implements Serializable, Comparable<Dependency> {
* The file name of the dependency.
*/
private String fileName;
/**
* The package path.
*/
private String packagePath;
/**
* Returns the package path.
*
* @return the package path
*/
public String getPackagePath() {
return packagePath;
}
/**
* Sets the package path.
*
* @param packagePath the package path
*/
public void setPackagePath(String packagePath) {
this.packagePath = packagePath;
}
/**
* The md5 hash of the dependency.
*/
@@ -120,6 +145,7 @@ public class Dependency implements Serializable, Comparable<Dependency> {
this.actualFilePath = file.getAbsolutePath();
this.filePath = this.actualFilePath;
this.fileName = file.getName();
this.packagePath = filePath;
determineHashes(file);
}
@@ -133,10 +159,12 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Returns the file name of the dependency with the backslash escaped for use in JavaScript. This is a complete hack as I
* could not get the replace to work in the template itself.
* Returns the file name of the dependency with the backslash escaped for
* use in JavaScript. This is a complete hack as I could not get the replace
* to work in the template itself.
*
* @return the file name of the dependency with the backslash escaped for use in JavaScript
* @return the file name of the dependency with the backslash escaped for
* use in JavaScript
*/
public String getFileNameForJavaScript() {
return this.fileName.replace("\\", "\\\\");
@@ -188,6 +216,9 @@ public class Dependency implements Serializable, Comparable<Dependency> {
* @param filePath the file path of the dependency
*/
public void setFilePath(String filePath) {
if (this.packagePath == null || this.packagePath.equals(this.filePath)) {
this.packagePath = filePath;
}
this.filePath = filePath;
}
@@ -206,7 +237,8 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Returns the file name to display in reports; if no display file name has been set it will default to the actual file name.
* Returns the file name to display in reports; if no display file name has
* been set it will default to the actual file name.
*
* @return the file name to display
*/
@@ -221,8 +253,9 @@ public class Dependency implements Serializable, Comparable<Dependency> {
* <p>
* Gets the file path of the dependency.</p>
* <p>
* <b>NOTE:</b> This may not be the actual path of the file on disk. The actual path of the file on disk can be obtained via
* the getActualFilePath().</p>
* <b>NOTE:</b> This may not be the actual path of the file on disk. The
* actual path of the file on disk can be obtained via the
* getActualFilePath().</p>
*
* @return the file path of the dependency
*/
@@ -285,7 +318,8 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Adds an entry to the list of detected Identifiers for the dependency file.
* Adds an entry to the list of detected Identifiers for the dependency
* file.
*
* @param type the type of identifier (such as CPE)
* @param value the value of the identifier
@@ -297,7 +331,8 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Adds an entry to the list of detected Identifiers for the dependency file.
* Adds an entry to the list of detected Identifiers for the dependency
* file.
*
* @param type the type of identifier (such as CPE)
* @param value the value of the identifier
@@ -348,7 +383,8 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Adds an entry to the list of detected Identifiers for the dependency file.
* Adds an entry to the list of detected Identifiers for the dependency
* file.
*
* @param identifier the identifier to add
*/
@@ -580,8 +616,9 @@ public class Dependency implements Serializable, Comparable<Dependency> {
private Set<Dependency> relatedDependencies = new TreeSet<Dependency>();
/**
* Get the value of {@link #relatedDependencies}. This field is used to collect other dependencies which really represent the
* same dependency, and may be presented as one item in reports.
* Get the value of {@link #relatedDependencies}. This field is used to
* collect other dependencies which really represent the same dependency,
* and may be presented as one item in reports.
*
* @return the value of relatedDependencies
*/
@@ -640,9 +677,11 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Adds a related dependency. The internal collection is normally a {@link java.util.TreeSet}, which relies on
* {@link #compareTo(Dependency)}. A consequence of this is that if you attempt to add a dependency with the same file path
* (modulo character case) as one that is already in the collection, it won't get added.
* Adds a related dependency. The internal collection is normally a
* {@link java.util.TreeSet}, which relies on
* {@link #compareTo(Dependency)}. A consequence of this is that if you
* attempt to add a dependency with the same file path (modulo character
* case) as one that is already in the collection, it won't get added.
*
* @param dependency a reference to the related dependency
*/
@@ -692,7 +731,8 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
/**
* Implementation of the Comparable<Dependency> interface. The comparison is solely based on the file path.
* Implementation of the Comparable&lt;Dependency&gt; interface. The
* comparison is solely based on the file path.
*
* @param o a dependency to compare
* @return an integer representing the natural ordering
@@ -715,23 +755,24 @@ public class Dependency implements Serializable, Comparable<Dependency> {
}
final Dependency other = (Dependency) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(this.actualFilePath, other.actualFilePath)
.append(this.filePath, other.filePath)
.append(this.fileName, other.fileName)
.append(this.md5sum, other.md5sum)
.append(this.sha1sum, other.sha1sum)
.append(this.identifiers, other.identifiers)
.append(this.vendorEvidence, other.vendorEvidence)
.append(this.productEvidence, other.productEvidence)
.append(this.versionEvidence, other.versionEvidence)
.append(this.description, other.description)
.append(this.license, other.license)
.append(this.vulnerabilities, other.vulnerabilities)
//.append(this.relatedDependencies, other.relatedDependencies)
.append(this.projectReferences, other.projectReferences)
.append(this.availableVersions, other.availableVersions)
.isEquals();
.appendSuper(super.equals(obj))
.append(this.actualFilePath, other.actualFilePath)
.append(this.filePath, other.filePath)
.append(this.fileName, other.fileName)
.append(this.packagePath, other.packagePath)
.append(this.md5sum, other.md5sum)
.append(this.sha1sum, other.sha1sum)
.append(this.identifiers, other.identifiers)
.append(this.vendorEvidence, other.vendorEvidence)
.append(this.productEvidence, other.productEvidence)
.append(this.versionEvidence, other.versionEvidence)
.append(this.description, other.description)
.append(this.license, other.license)
.append(this.vulnerabilities, other.vulnerabilities)
//.append(this.relatedDependencies, other.relatedDependencies)
.append(this.projectReferences, other.projectReferences)
.append(this.availableVersions, other.availableVersions)
.isEquals();
}
/**
@@ -742,31 +783,33 @@ public class Dependency implements Serializable, Comparable<Dependency> {
@Override
public int hashCode() {
return new HashCodeBuilder(MAGIC_HASH_INIT_VALUE, MAGIC_HASH_MULTIPLIER)
.append(actualFilePath)
.append(filePath)
.append(fileName)
.append(md5sum)
.append(sha1sum)
.append(identifiers)
.append(vendorEvidence)
.append(productEvidence)
.append(versionEvidence)
.append(description)
.append(license)
.append(vulnerabilities)
//.append(relatedDependencies)
.append(projectReferences)
.append(availableVersions)
.toHashCode();
.append(actualFilePath)
.append(filePath)
.append(fileName)
.append(md5sum)
.append(sha1sum)
.append(identifiers)
.append(vendorEvidence)
.append(productEvidence)
.append(versionEvidence)
.append(description)
.append(license)
.append(vulnerabilities)
//.append(relatedDependencies)
.append(projectReferences)
.append(availableVersions)
.toHashCode();
}
/**
* Standard toString() implementation showing the filename, actualFilePath, and filePath.
* Standard toString() implementation showing the filename, actualFilePath,
* and filePath.
*
* @return the string representation of the file
*/
@Override
public String toString() {
return "Dependency{ fileName='" + fileName + "', actualFilePath='" + actualFilePath + "', filePath='" + filePath + "'}";
return "Dependency{ fileName='" + fileName + "', actualFilePath='" + actualFilePath
+ "', filePath='" + filePath + "', packagePath='" + packagePath + "'}";
}
}

View File

@@ -97,7 +97,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over evidence of the specified confidence.
*
* @param confidence the confidence level for the evidence to be iterated over.
* @return Iterable<Evidence> an iterable collection of evidence
* @return Iterable&lt;Evidence&gt; an iterable collection of evidence
*/
public final Iterable<Evidence> iterator(Confidence confidence) {
if (confidence == Confidence.HIGHEST) {
@@ -168,7 +168,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Returns a set of Weightings - a list of terms that are believed to be of higher confidence when also found in another
* location.
*
* @return Set<String>
* @return Set&lt;String&gt;
*/
public Set<String> getWeighting() {
return weightedStrings;
@@ -225,7 +225,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
/**
* Implements the iterator interface for the Evidence Collection.
*
* @return an Iterator<Evidence>.
* @return an Iterator&lt;Evidence&gt;
*/
@Override
public Iterator<Evidence> iterator() {

View File

@@ -20,7 +20,8 @@ package org.owasp.dependencycheck.dependency;
import java.io.Serializable;
/**
* An external reference for a vulnerability. This contains a name, URL, and a source.
* An external reference for a vulnerability. This contains a name, URL, and a
* source.
*
* @author Jeremy Long
*/
@@ -97,6 +98,11 @@ public class Reference implements Serializable, Comparable<Reference> {
this.source = source;
}
@Override
public String toString() {
return "Reference: { name='" + this.name + "', url='" + this.url + "', source='" + this.source + "' }";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {

View File

@@ -21,6 +21,7 @@ import java.io.Serializable;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Iterator;
/**
* Contains the information about a vulnerability.
@@ -33,6 +34,7 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
* The serial version uid.
*/
private static final long serialVersionUID = 307319490326651052L;
/**
* The name of the vulnerability.
*/
@@ -383,6 +385,24 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
return hash;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Vulnerability ");
sb.append(this.name);
sb.append("\nReferences:\n");
for (Iterator i = this.references.iterator(); i.hasNext();) {
sb.append("=> ");
sb.append(i.next());
sb.append("\n");
}
sb.append("\nSoftware:\n");
for (Iterator i = this.vulnerableSoftware.iterator(); i.hasNext();) {
sb.append("=> ");
sb.append(i.next());
sb.append("\n");
}
return sb.toString();
}
/**
* Compares two vulnerabilities.
*

View File

@@ -138,7 +138,7 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
return false;
}
final VulnerableSoftware other = (VulnerableSoftware) obj;
if ((this.getName() == null) ? (other.getName() != null) : !this.getName().equals(other.getName())) {
if ((this.name == null) ? (other.getName() != null) : !this.name.equals(other.getName())) {
return false;
}
return true;
@@ -152,7 +152,7 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
@Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + (this.getName() != null ? this.getName().hashCode() : 0);
hash = 83 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
@@ -163,7 +163,7 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
*/
@Override
public String toString() {
return "VulnerableSoftware{ name=" + name + ", previousVersion=" + previousVersion + '}';
return "VulnerableSoftware{" + name + "[" + previousVersion + "]}";
}
/**
@@ -175,28 +175,19 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
@Override
public int compareTo(VulnerableSoftware vs) {
int result = 0;
final String[] left = this.getName().split(":");
final String[] left = this.name.split(":");
final String[] right = vs.getName().split(":");
final int max = (left.length <= right.length) ? left.length : right.length;
if (max > 0) {
for (int i = 0; result == 0 && i < max; i++) {
final String[] subLeft = left[i].split("\\.");
final String[] subRight = right[i].split("\\.");
final String[] subLeft = left[i].split("(\\.|-)");
final String[] subRight = right[i].split("(\\.|-)");
final int subMax = (subLeft.length <= subRight.length) ? subLeft.length : subRight.length;
if (subMax > 0) {
for (int x = 0; result == 0 && x < subMax; x++) {
if (isPositiveInteger(subLeft[x]) && isPositiveInteger(subRight[x])) {
try {
result = Long.valueOf(subLeft[x]).compareTo(Long.valueOf(subRight[x]));
// final long iLeft = Long.parseLong(subLeft[x]);
// final long iRight = Long.parseLong(subRight[x]);
// if (iLeft != iRight) {
// if (iLeft > iRight) {
// result = 2;
// } else {
// result = -2;
// }
// }
} catch (NumberFormatException ex) {
//ignore the exception - they obviously aren't numbers
if (!subLeft[x].equalsIgnoreCase(subRight[x])) {

View File

@@ -22,7 +22,7 @@ import java.io.IOException;
/**
* An exception used when using @{link DependencyCheckScanAgent} to conduct a scan and the scan fails.
*
* @author Steve Springett <steve.springett@owasp.org>
* @author Steve Springett
*/
public class ScanAgentException extends IOException {

View File

@@ -24,15 +24,14 @@ import org.slf4j.LoggerFactory;
/**
* <p>
* DependencyCheck uses {@link org.slf4j.Logger} as a logging framework, and Apache Velocity uses a custom
* logging implementation that outputs to a file named velocity.log by default. This class is an implementation of a
* custom Velocity logger that redirects all velocity logging to the Java Logger class.
* DependencyCheck uses {@link org.slf4j.Logger} as a logging framework, and Apache Velocity uses a custom logging implementation
* that outputs to a file named velocity.log by default. This class is an implementation of a custom Velocity logger that
* redirects all velocity logging to the Java Logger class.
* </p><p>
* This class was written to address permission issues when using Dependency-Check in a server environment (such as the
* Jenkins plugin). In some circumstances, Velocity would attempt to create velocity.log in an un-writable
* directory.</p>
* This class was written to address permission issues when using Dependency-Check in a server environment (such as the Jenkins
* plugin). In some circumstances, Velocity would attempt to create velocity.log in an un-writable directory.</p>
*
* @author Steve Springett <steve.springett@owasp.org>
* @author Steve Springett
*/
public class VelocityLoggerRedirect implements LogChute {
@@ -52,8 +51,7 @@ public class VelocityLoggerRedirect implements LogChute {
}
/**
* Given a Velocity log level and message, this method will call the appropriate Logger level and log the specified
* values.
* Given a Velocity log level and message, this method will call the appropriate Logger level and log the specified values.
*
* @param level the logging level
* @param message the message to be logged
@@ -82,8 +80,8 @@ public class VelocityLoggerRedirect implements LogChute {
}
/**
* Given a Velocity log level, message and Throwable, this method will call the appropriate Logger level and log the
* specified values.
* Given a Velocity log level, message and Throwable, this method will call the appropriate Logger level and log the specified
* values.
*
* @param level the logging level
* @param message the message to be logged

View File

@@ -47,20 +47,24 @@ public class SuppressionParser {
*/
private static final Logger LOGGER = LoggerFactory.getLogger(SuppressionParser.class);
/**
* JAXP Schema Language. Source: http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
* JAXP Schema Language. Source:
* http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
*/
public static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/**
* W3C XML Schema. Source: http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
* W3C XML Schema. Source:
* http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
*/
public static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
/**
* JAXP Schema Source. Source: http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
* JAXP Schema Source. Source:
* http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
*/
public static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
/**
* Parses the given xml file and returns a list of the suppression rules contained.
* Parses the given xml file and returns a list of the suppression rules
* contained.
*
* @param file an xml file containing suppression rules
* @return a list of suppression rules
@@ -74,6 +78,20 @@ public class SuppressionParser {
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
} catch (SAXException ex) {
try {
if (fis != null) {
try {
fis.close();
} catch (IOException ex1) {
LOGGER.debug("Unable to close stream", ex1);
}
}
fis = new FileInputStream(file);
} catch (FileNotFoundException ex1) {
throw new SuppressionParseException(ex);
}
return parseOldSuppressionRules(fis);
} finally {
if (fis != null) {
try {
@@ -86,13 +104,63 @@ public class SuppressionParser {
}
/**
* Parses the given xml stream and returns a list of the suppression rules contained.
* Parses the given xml stream and returns a list of the suppression rules
* contained.
*
* @param inputStream an InputStream containing suppression rues
* @return a list of suppression rules
* @throws SuppressionParseException thrown if the xml cannot be parsed
* @throws SAXException thrown if the xml cannot be parsed
*/
public List<SuppressionRule> parseSuppressionRules(InputStream inputStream) throws SuppressionParseException, SAXException {
try {
final InputStream schemaStream = this.getClass().getClassLoader().getResourceAsStream("schema/dependency-suppression.1.1.xsd");
final SuppressionHandler handler = new SuppressionHandler();
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
final SAXParser saxParser = factory.newSAXParser();
saxParser.setProperty(SuppressionParser.JAXP_SCHEMA_LANGUAGE, SuppressionParser.W3C_XML_SCHEMA);
saxParser.setProperty(SuppressionParser.JAXP_SCHEMA_SOURCE, new InputSource(schemaStream));
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new SuppressionErrorHandler());
xmlReader.setContentHandler(handler);
final Reader reader = new InputStreamReader(inputStream, "UTF-8");
final InputSource in = new InputSource(reader);
//in.setEncoding("UTF-8");
xmlReader.parse(in);
return handler.getSuppressionRules();
} catch (ParserConfigurationException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'suppressions'.")) {
throw ex;
} else {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
}
/**
* Parses the given xml stream and returns a list of the suppression rules
* contained.
*
* @param inputStream an InputStream containing suppression rues
* @return a list of suppression rules
* @throws SuppressionParseException if the xml cannot be parsed
*/
public List<SuppressionRule> parseSuppressionRules(InputStream inputStream) throws SuppressionParseException {
private List<SuppressionRule> parseOldSuppressionRules(InputStream inputStream) throws SuppressionParseException {
try {
final InputStream schemaStream = this.getClass().getClassLoader().getResourceAsStream("schema/suppression.xsd");
final SuppressionHandler handler = new SuppressionHandler();

View File

@@ -48,10 +48,11 @@ public final class DependencyVersionUtil {
/**
* <p>
* A utility class to extract version numbers from file names (or other strings containing version numbers.<br/>
* Example:<br/>
* Give the file name: library-name-1.4.1r2-release.jar<br/>
* This function would return: 1.4.1.r2</p>
* A utility class to extract version numbers from file names (or other strings containing version numbers.</p>
* <pre>
* Example:
* Give the file name: library-name-1.4.1r2-release.jar
* This function would return: 1.4.1.r2</pre>
*
* @param text the text being analyzed
* @return a DependencyVersion containing the version

View File

@@ -40,7 +40,7 @@ import java.util.Set;
* FileFilter filter = FileFilterBuilder.newInstance().addExtensions("jar", "war").build();
* </pre>
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
* @see <a href="https://en.wikipedia.org/wiki/Builder_pattern">Builder pattern</a>
*/
public class FileFilterBuilder {

View File

@@ -261,6 +261,29 @@ public class Model {
licenses.add(license);
}
/**
* The project URL.
*/
private String projectURL;
/**
* Get the value of projectURL.
*
* @return the value of projectURL
*/
public String getProjectURL() {
return projectURL;
}
/**
* Set the value of projectURL.
*
* @param projectURL new value of projectURL
*/
public void setProjectURL(String projectURL) {
this.projectURL = projectURL;
}
/**
* Process the Maven properties file and interpolate all properties.
*
@@ -276,20 +299,23 @@ public class Model {
l.setUrl(interpolateString(l.getUrl(), properties));
}
this.name = interpolateString(this.name, properties);
this.projectURL = interpolateString(this.projectURL, properties);
this.organization = interpolateString(this.organization, properties);
this.parentGroupId = interpolateString(this.parentGroupId, properties);
this.parentArtifactId = interpolateString(this.parentArtifactId, properties);
this.parentVersion = interpolateString(this.parentVersion, properties);
}
/**
* <p>
* A utility function that will interpolate strings based on values given in the properties file. It will also interpolate the
* strings contained within the properties file so that properties can reference other properties.</p>
* A utility function that will interpolate strings based on values given in
* the properties file. It will also interpolate the strings contained
* within the properties file so that properties can reference other
* properties.</p>
* <p>
* <b>Note:</b> if there is no property found the reference will be removed. In other words, if the interpolated string will
* be replaced with an empty string.
* <b>Note:</b> if there is no property found the reference will be removed.
* In other words, if the interpolated string will be replaced with an empty
* string.
* </p>
* <p>
* Example:</p>
@@ -306,7 +332,8 @@ public class Model {
* </code>
*
* @param text the string that contains references to properties.
* @param properties a collection of properties that may be referenced within the text.
* @param properties a collection of properties that may be referenced
* within the text.
* @return the interpolated text.
*/
public static String interpolateString(String text, Properties properties) {
@@ -318,7 +345,8 @@ public class Model {
}
/**
* Utility class that can provide values from a Properties object to a StrSubstitutor.
* Utility class that can provide values from a Properties object to a
* StrSubstitutor.
*/
private static class PropertyLookup extends StrLookup {

View File

@@ -145,6 +145,8 @@ public class PomHandler extends DefaultHandler {
model.setOrganization(currentText.toString());
} else if (DESCRIPTION.equals(qName)) {
model.setDescription(currentText.toString());
} else if (URL.equals(qName)) {
model.setProjectURL(currentText.toString());
}
} else if (PARENT.equals(parentNode)) {
if (GROUPID.equals(qName)) {

View File

@@ -19,5 +19,6 @@ org.owasp.dependencycheck.analyzer.OpenSSLAnalyzer
org.owasp.dependencycheck.analyzer.CMakeAnalyzer
org.owasp.dependencycheck.analyzer.NodePackageAnalyzer
org.owasp.dependencycheck.analyzer.RubyGemspecAnalyzer
org.owasp.dependencycheck.analyzer.RubyBundlerAnalyzer
org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer
org.owasp.dependencycheck.analyzer.ComposerLockAnalyzer

View File

@@ -13,3 +13,4 @@
# limitations under the License.
MERGE_PROPERTY=MERGE INTO properties (id, value) KEY(id) VALUES(?, ?)
CLEANUP_ORPHANS=DELETE FROM cpeEntry WHERE id IN (SELECT id FROM cpeEntry LEFT JOIN software ON cpeEntry.id = software.CPEEntryId WHERE software.CPEEntryId IS NULL)

View File

@@ -0,0 +1 @@
CLEANUP_ORPHANS=DELETE FROM cpeEntry WHERE id not in (SELECT CPEEntryId FROM software)

View File

@@ -0,0 +1,36 @@
if exists (SELECT 1 FROM sysobjects WHERE name='software' AND xtype='U')
drop table software
if exists (SELECT 1 FROM sysobjects WHERE name='cpeEntry' AND xtype='U')
drop table cpeEntry
if exists (SELECT 1 FROM sysobjects WHERE name='reference' AND xtype='U')
drop table reference
if exists (SELECT 1 FROM sysobjects WHERE name='vulnerability' AND xtype='U')
drop table vulnerability
if exists (SELECT 1 FROM sysobjects WHERE name='properties' AND xtype='U')
drop table properties
CREATE TABLE properties (id varchar(50) PRIMARY KEY, value varchar(500));
CREATE TABLE vulnerability (id int identity(1,1) PRIMARY KEY, cve VARCHAR(20) UNIQUE,
description VARCHAR(8000), cwe VARCHAR(10), cvssScore DECIMAL(3,1), cvssAccessVector VARCHAR(20),
cvssAccessComplexity VARCHAR(20), cvssAuthentication VARCHAR(20), cvssConfidentialityImpact VARCHAR(20),
cvssIntegrityImpact VARCHAR(20), cvssAvailabilityImpact VARCHAR(20));
CREATE TABLE reference (cveid INT, name VARCHAR(1000), url VARCHAR(1000), source VARCHAR(255),
CONSTRAINT FK_Reference FOREIGN KEY (cveid) REFERENCES vulnerability(id) ON DELETE CASCADE);
CREATE TABLE cpeEntry (id INT identity(1,1) PRIMARY KEY, cpe VARCHAR(250), vendor VARCHAR(255), product VARCHAR(255));
CREATE TABLE software (cveid INT, cpeEntryId INT, previousVersion VARCHAR(50)
, CONSTRAINT FK_SoftwareCve FOREIGN KEY (cveid) REFERENCES vulnerability(id) ON DELETE CASCADE
, CONSTRAINT FK_SoftwareCpeProduct FOREIGN KEY (cpeEntryId) REFERENCES cpeEntry(id)
, PRIMARY KEY (cveid, cpeEntryId));
CREATE INDEX idxVulnerability ON vulnerability(cve);
CREATE INDEX idxReference ON reference(cveid);
CREATE INDEX idxCpe ON cpeEntry(cpe);
CREATE INDEX idxCpeEntry ON cpeEntry(vendor, product);
CREATE INDEX idxSoftwareCve ON software(cveid);
CREATE INDEX idxSoftwareCpe ON software(cpeEntryId);
INSERT INTO properties(id,value) VALUES ('version','3.0');

View File

@@ -25,7 +25,8 @@ CREATE TABLE cpeEntry (id INT auto_increment PRIMARY KEY, cpe VARCHAR(250), vend
CREATE TABLE software (cveid INT, cpeEntryId INT, previousVersion VARCHAR(50)
, CONSTRAINT fkSoftwareCve FOREIGN KEY (cveid) REFERENCES vulnerability(id) ON DELETE CASCADE
, CONSTRAINT fkSoftwareCpeProduct FOREIGN KEY (cpeEntryId) REFERENCES cpeEntry(id));
, CONSTRAINT fkSoftwareCpeProduct FOREIGN KEY (cpeEntryId) REFERENCES cpeEntry(id)
, PRIMARY KEY (cveid, cpeEntryId));
CREATE INDEX idxVulnerability ON vulnerability(cve);
CREATE INDEX idxReference ON reference(cveid);
@@ -53,4 +54,4 @@ DELIMITER ;
GRANT EXECUTE ON PROCEDURE dependencycheck.save_property TO 'dcuser';
UPDATE Properties SET value='3.0' WHERE ID='version';
UPDATE properties SET value='3.0' WHERE ID='version';

View File

@@ -0,0 +1,112 @@
-- Drop
BEGIN
EXECUTE IMMEDIATE 'DROP SEQUENCE vulnerability_seq';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -2289 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP SEQUENCE cpeEntry_seq';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -2289 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE software CASCADE CONSTRAINTS';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE cpeEntry CASCADE CONSTRAINTS';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE reference CASCADE CONSTRAINTS';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE vulnerability CASCADE CONSTRAINTS';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE properties CASCADE CONSTRAINTS';
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE != -942 THEN
RAISE;
END IF;
END;
CREATE TABLE vulnerability (id INT NOT NULL PRIMARY KEY, cve VARCHAR(20) UNIQUE,
description CLOB, cwe VARCHAR(10), cvssScore DECIMAL(3,1), cvssAccessVector VARCHAR(20),
cvssAccessComplexity VARCHAR(20), cvssAuthentication VARCHAR(20), cvssConfidentialityImpact VARCHAR(20),
cvssIntegrityImpact VARCHAR(20), cvssAvailabilityImpact VARCHAR(20));
CREATE TABLE reference (cveid INT, name VARCHAR(1000), url VARCHAR(1000), source VARCHAR(255),
CONSTRAINT fkReference FOREIGN KEY (cveid) REFERENCES vulnerability(id) ON DELETE CASCADE);
CREATE TABLE cpeEntry (id INT NOT NULL PRIMARY KEY, cpe VARCHAR(250), vendor VARCHAR(255), product VARCHAR(255));
CREATE TABLE software (cveid INT, cpeEntryId INT, previousVersion VARCHAR(50)
, CONSTRAINT fkSoftwareCve FOREIGN KEY (cveid) REFERENCES vulnerability(id) ON DELETE CASCADE
, CONSTRAINT fkSoftwareCpeProduct FOREIGN KEY (cpeEntryId) REFERENCES cpeEntry(id));
CREATE INDEX idxVulnerability ON vulnerability(cve);
CREATE INDEX idxReference ON reference(cveid);
CREATE INDEX idxCpe ON cpeEntry(cpe);
CREATE INDEX idxCpeEntry ON cpeEntry(vendor, product);
CREATE INDEX idxSoftwareCve ON software(cveid);
CREATE INDEX idxSoftwareCpe ON software(cpeEntryId);
CREATE TABLE properties (id varchar(50) PRIMARY KEY, value varchar(500));
CREATE SEQUENCE cpeEntry_seq;
CREATE SEQUENCE vulnerability_seq;
CREATE OR REPLACE TRIGGER VULNERABILITY_TRG
BEFORE INSERT
ON VULNERABILITY
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
:new.ID := VULNERABILITY_SEQ.nextval;
END VULNERABILITY_TRG;
/
CREATE OR REPLACE TRIGGER CPEENTRY_TRG
BEFORE INSERT
ON CPEENTRY
REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
:new.ID := CPEENTRY_SEQ.nextval;
END CPEENTRY_TRG;
/
INSERT INTO properties(id,value) VALUES ('version','3.0');

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<suppressions xmlns="https://www.owasp.org/index.php/OWASP_Dependency_Check_Suppression">
<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd">
<suppress base="true">
<notes><![CDATA[
This suppresses false positives identified on spring security.
@@ -161,6 +161,13 @@
<gav regex="true">.*\bhk2\b.*</gav>
<cpe>cpe:/a:oracle:glassfish</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
HK2-utils is flagged as glassfish.
]]></notes>
<filePath regex="true">.*\bhk2-utils.*\.jar</filePath>
<cpe>cpe:/a:oracle:glassfish</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
file name: petals-se-camel-1.0.0.jar - false positive for apache camel.
@@ -233,6 +240,177 @@
Note, there will be more false positives for Netty. Trying to figure out a better suppression.
]]></notes>
<gav regex="true">com.typesafe.netty:netty-http-pipelining:.*</gav>
<cpe>cpe:/a:netty_project:netty:1.1.4</cpe>
<cpe>cpe:/a:netty_project:netty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
JVM instrumentation to Ganglia
]]></notes>
<gav regex="true">info\.ganglia\.gmetric4j:gmetric4j:.*</gav>
<cpe>cpe:/a:ganglia:ganglia</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
A reporter for Metrics which announces measurements to a Ganglia cluster
]]></notes>
<gav regex="true">io\.dropwizard\.metrics:metrics-ganglia:.*</gav>
<cpe>cpe:/a:ganglia:ganglia</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">io\.dropwizard:dropwizard-jetty:.*</gav>
<cpe>cpe:/a:jetty:jetty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">io\.dropwizard\.metrics:metrics-jetty:.*</gav>
<cpe>cpe:/a:jetty:jetty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">org\.eclipse\.jetty\.toolchain\.setuid:jetty-setuid-java:.*</gav>
<cpe>cpe:/a:jetty:jetty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">org\.eclipse\.jetty:jetty-io:.*</gav>
<cpe>cpe:/a:jetty:jetty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">org\.eclipse\.jetty\.http2:http2-hpack:.*</gav>
<cpe>cpe:/a:jetty:jetty</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
drop wizard false positives
]]></notes>
<gav regex="true">io\.dropwizard\.metrics:metrics-httpclient:.*</gav>
<cpe>cpe:/a:apache:httpclient</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
javax.transaction false positives
]]></notes>
<gav regex="true">javax\.transaction:javax\.transaction-api:.*</gav>
<cpe>cpe:/a:oracle:glassfish</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
false positive in drop wizard
]]></notes>
<filePath regex="true">.*\.(jar|ear|war|pom)</filePath>
<cpe>cpe:/a:tiger:tiger</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
php cpe
]]></notes>
<filePath regex="true">.*\.(jar|exe|dll|ear|war|pom)</filePath>
<cpe>cpe:/a:class:class</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Linux ssh False Positives
]]></notes>
<filePath regex="true">.*\.(jar|ear|war|pom)</filePath>
<cpe>cpe:/a:pam:pam</cpe>
<cpe>cpe:/a:pam_ssh:pam_ssh</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
elastic search false postivies
]]></notes>
<gav regex="true">org\.elasticsearch:securesm:.*</gav>
<cpe>cpe:/a:elasticsearch:elasticsearch</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Glassfish false positives.
]]></notes>
<gav regex="true">org\.glassfish:javax.el:.*</gav>
<cpe>cpe:/a:oracle:glassfish</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Struts false positives.
]]></notes>
<gav regex="true">sslext:sslext:.*</gav>
<cpe>cpe:/a:apache:struts</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
ACtiveMQ false positives.
]]></notes>
<gav regex="true">org\.apache\.activemq:activemq-pool.*</gav>
<cpe>cpe:/a:apache:activemq</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
ACtiveMQ false positives.
]]></notes>
<gav regex="true">org\.apache\.activemq:artemis.*</gav>
<cpe>cpe:/a:apache:activemq</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Spring data mongodb false positives.
]]></notes>
<gav regex="true">org\.springframework\.data:spring-data-mongodb.*</gav>
<cpe>cpe:/a:mongodb:mongodb</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Spring data neo4j false positives.
]]></notes>
<gav regex="true">org\.springframework\.data:spring-data-neo4j:.*</gav>
<cpe>cpe:/a:vmware:springsource_spring_framework</cpe>
<cpe>cpe:/a:pivotal:spring_framework</cpe>
<cpe>cpe:/a:neo4j:neo4j</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Spring data solr false positives.
]]></notes>
<gav regex="true">org\.springframework\.data:spring-data-solr:.*</gav>
<cpe>cpe:/a:apache:solr</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Spring social facebook false positive.
]]></notes>
<gav regex="true">org\.springframework\.social:spring-social-facebook:.*</gav>
<cpe>cpe:/a:facebook:facebook</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Spring Security JWT false positive.
]]></notes>
<gav regex="true">org\.springframework\.security:spring-security-jwt.*</gav>
<cpe>cpe:/a:vmware:springsource_spring_security</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Aether false positive.
]]></notes>
<gav regex="true">org.eclipse.aether:aether.*</gav>
<cpe>cpe:/a:eclipse:eclipse_ide</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Drupal services false positive.
]]></notes>
<filePath regex="true">.*\.(jar|ear|war|pom)</filePath>
<cpe>cpe:/a:services_project:services</cpe>
</suppress>
</suppressions>

View File

@@ -63,13 +63,6 @@ cve.url-2.0.base=https://nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml.gz
cpe.validfordays=30
cpe.url=http://static.nvd.nist.gov/feeds/xml/cpe/dictionary/official-cpe-dictionary_v2.3.xml.gz
# file type analyzer settings:
analyzer.archive.enabled=true
analyzer.jar.enabled=true
analyzer.nuspec.enabled=true
analyzer.assembly.enabled=true
analyzer.composer.lock.enabled=true
# the URL for searching Nexus for SHA-1 hashes and whether it's enabled
analyzer.nexus.enabled=true
analyzer.nexus.url=https://repository.sonatype.org/service/local/
@@ -87,7 +80,7 @@ archive.scan.depth=3
# use HEAD (default) or GET as HTTP request method for query timestamp
downloader.quick.query.timestamp=true
analyzer.experimental.enabled=false
analyzer.jar.enabled=true
analyzer.archive.enabled=true
analyzer.node.package.enabled=true

View File

@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema id="suppressions"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd"
xmlns:dc="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd">
<xs:complexType name="regexStringType">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="regex" use="optional" type="xs:boolean" default="false"/>
<xs:attribute name="caseSensitive" use="optional" type="xs:boolean" default="false"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:simpleType name="cvssScoreType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="10"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cveType">
<xs:restriction base="xs:string">
<xs:pattern value="((\w+\-)?CVE\-\d\d\d\d\-\d+|\d+)"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="sha1Type">
<xs:restriction base="xs:string">
<xs:pattern value="[a-fA-F0-9]{40}"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="suppressions">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="suppress">
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:sequence minOccurs="0" maxOccurs="1">
<xs:element name="notes" type="xs:string"/>
</xs:sequence>
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="filePath" type="dc:regexStringType"/>
<xs:element name="sha1" type="dc:sha1Type"/>
<xs:element name="gav" type="dc:regexStringType"/>
</xs:choice>
<xs:choice minOccurs="1" maxOccurs="unbounded">
<xs:element name="cpe" type="dc:regexStringType"/>
<xs:element name="cve" type="dc:cveType"/>
<xs:element name="cwe" type="xs:positiveInteger"/>
<xs:element name="cvssBelow" type="dc:cvssScoreType"/>
</xs:choice>
</xs:sequence>
<xs:attribute name="base" use="optional" type="xs:boolean" default="false"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

View File

@@ -21,7 +21,7 @@
</xs:simpleType>
<xs:simpleType name="cveType">
<xs:restriction base="xs:string">
<xs:pattern value="(\w+\-)?CVE\-\d\d\d\d\-\d+"/>
<xs:pattern value="((\w+\-)?CVE\-\d\d\d\d\-\d+|\d+)"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="sha1Type">

View File

@@ -79,7 +79,7 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
setTimeout('$("#modal-content,#modal-background").toggleClass("active");',100);
});
$('#modal-add-header').click(function () {
xml = '<?xml version="1.0" encoding="UTF-8"?>\n<suppressions xmlns="https://www.owasp.org/index.php/OWASP_Dependency_Check_Suppression">\n ';
xml = '<?xml version="1.0" encoding="UTF-8"?>\n<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd">\n ';
xml += $("#modal-text").text().replace(/\n/g,'\n ');
xml += '\n</suppressions>';
$('#modal-text').text(xml).focus().select();

View File

@@ -31,8 +31,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An abstract database test case that is used to ensure the H2 DB exists prior to performing tests that utilize the data
* contained within.
* An abstract database test case that is used to ensure the H2 DB exists prior
* to performing tests that utilize the data contained within.
*
* @author Jeremy Long
*/
@@ -49,6 +49,11 @@ public abstract class BaseDBTestCase extends BaseTest {
public static void ensureDBExists() throws Exception {
File f = new File("./target/data/dc.h2.db");
if (f.exists() && f.isFile() && f.length() < 71680) {
f.delete();
}
java.io.File dataPath = Settings.getDataDirectory();
String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME);
LOGGER.trace("DB file name {}", fileName);

View File

@@ -39,7 +39,7 @@ public class BaseTest {
if (f.exists() && f.isFile() && f.length() < 71680) {
System.err.println("------------------------------------------------");
System.err.println("------------------------------------------------");
System.err.println("I broke the build");
System.err.println("Test referenced CveDB() and does not extend BaseDbTestCases?");
System.err.println("------------------------------------------------");
System.err.println("------------------------------------------------");
}

View File

@@ -30,16 +30,7 @@ import org.owasp.dependencycheck.utils.Settings;
*
* @author Jeremy Long
*/
public class EngineIntegrationTest extends BaseTest {
@Before
public void setUp() throws Exception {
org.owasp.dependencycheck.BaseDBTestCase.ensureDBExists();
}
@After
public void tearDown() {
}
public class EngineIntegrationTest extends BaseDBTestCase {
/**
* Test running the entire engine.

View File

@@ -77,8 +77,8 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest {
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, "suppressions.xml");
instance.initialize();
int expCount = 5;
List<SuppressionRule> result = instance.getRules();
assertTrue(expCount <= result.size());
int currentSize = instance.getRules().size();
assertTrue(expCount <= currentSize);
}
@Test(expected = SuppressionParseException.class)

View File

@@ -18,15 +18,18 @@
package org.owasp.dependencycheck.analyzer;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.utils.Settings;
/**
*
* @author Jeremy Long
*/
public class AnalyzerServiceTest extends BaseTest {
public class AnalyzerServiceTest extends BaseDBTestCase {
/**
* Test of getAnalyzers method, of class AnalyzerService.
@@ -34,15 +37,42 @@ public class AnalyzerServiceTest extends BaseTest {
@Test
public void testGetAnalyzers() {
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader());
Iterator<Analyzer> result = instance.getAnalyzers();
List<Analyzer> result = instance.getAnalyzers();
boolean found = false;
while (result.hasNext()) {
Analyzer a = result.next();
for (Analyzer a : result) {
if ("Jar Analyzer".equals(a.getName())) {
found = true;
}
}
assertTrue("JarAnalyzer loaded", found);
}
/**
* Test of getAnalyzers method, of class AnalyzerService.
*/
@Test
public void testGetExperimentalAnalyzers() {
Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false);
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader());
List<Analyzer> result = instance.getAnalyzers();
String experimental = "CMake Analyzer";
boolean found = false;
for (Analyzer a : result) {
if (experimental.equals(a.getName())) {
found = true;
}
}
assertFalse("Experimental analyzer loaded when set to false", found);
Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, true);
result = instance.getAnalyzers();
found = false;
for (Analyzer a : result) {
if (experimental.equals(a.getName())) {
found = true;
}
}
assertTrue("Experimental analyzer not loaded when set to true", found);
}
}

View File

@@ -30,147 +30,137 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were
* obtained from outside open source software projects. Links to those projects
* are given below.
* Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were obtained from outside open source software projects.
* Links to those projects are given below.
*
* @author Dale Visser <dvisser@ida.org>
* @see <a href="http://readable.sourceforge.net/">Readable Lisp S-expressions
* Project</a>
* @author Dale Visser
* @see <a href="http://readable.sourceforge.net/">Readable Lisp S-expressions Project</a>
* @see <a href="https://gnu.org/software/binutils/">GNU Binutils</a>
* @see <a href="https://gnu.org/software/ghostscript/">GNU Ghostscript</a>
*/
public class AutoconfAnalyzerTest extends BaseTest {
/**
* The analyzer to test.
*/
AutoconfAnalyzer analyzer;
/**
* The analyzer to test.
*/
AutoconfAnalyzer analyzer;
private void assertCommonEvidence(Dependency result, String product,
String version, String vendor) {
assertProductAndVersion(result, product, version);
assertTrue("Expected vendor evidence to contain \"" + vendor + "\".",
result.getVendorEvidence().toString().contains(vendor));
}
private void assertCommonEvidence(Dependency result, String product,
String version, String vendor) {
assertProductAndVersion(result, product, version);
assertTrue("Expected vendor evidence to contain \"" + vendor + "\".",
result.getVendorEvidence().toString().contains(vendor));
}
private void assertProductAndVersion(Dependency result, String product,
String version) {
assertTrue("Expected product evidence to contain \"" + product + "\".",
result.getProductEvidence().toString().contains(product));
assertTrue("Expected version evidence to contain \"" + version + "\".",
result.getVersionEvidence().toString().contains(version));
}
private void assertProductAndVersion(Dependency result, String product,
String version) {
assertTrue("Expected product evidence to contain \"" + product + "\".",
result.getProductEvidence().toString().contains(product));
assertTrue("Expected version evidence to contain \"" + version + "\".",
result.getVersionEvidence().toString().contains(version));
}
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception
* thrown if there is a problem
*/
@Before
public void setUp() throws Exception {
analyzer = new AutoconfAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
}
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
public void setUp() throws Exception {
analyzer = new AutoconfAnalyzer();
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;
}
/**
* 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 whether expected evidence is gathered from Ghostscript's
* configure.ac.
*
* @throws AnalysisException
* is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureAC1() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/ghostscript/configure.ac"));
analyzer.analyze(result, null);
assertCommonEvidence(result, "ghostscript", "8.62.0", "gnu");
}
/**
* Test whether expected evidence is gathered from Ghostscript's configure.ac.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureAC1() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/ghostscript/configure.ac"));
analyzer.analyze(result, null);
assertCommonEvidence(result, "ghostscript", "8.62.0", "gnu");
}
/**
* Test whether expected evidence is gathered from Readable's configure.ac.
*
* @throws AnalysisException
* is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureAC2() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/readable-code/configure.ac"));
analyzer.analyze(result, null);
assertReadableCodeEvidence(result);
}
/**
* Test whether expected evidence is gathered from Readable's configure.ac.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureAC2() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/readable-code/configure.ac"));
analyzer.analyze(result, null);
assertReadableCodeEvidence(result);
}
private void assertReadableCodeEvidence(final Dependency result) {
assertCommonEvidence(result, "readable", "1.0.7", "dwheeler");
final String url = "http://readable.sourceforge.net/";
assertTrue("Expected product evidence to contain \"" + url + "\".",
result.getVendorEvidence().toString().contains(url));
}
private void assertReadableCodeEvidence(final Dependency result) {
assertCommonEvidence(result, "readable", "1.0.7", "dwheeler");
final String url = "http://readable.sourceforge.net/";
assertTrue("Expected product evidence to contain \"" + url + "\".",
result.getVendorEvidence().toString().contains(url));
}
/**
* Test whether expected evidence is gathered from GNU Binutil's configure.
*
* @throws AnalysisException
* is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureScript() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/binutils/configure"));
analyzer.analyze(result, null);
assertProductAndVersion(result, "binutils", "2.25.51");
}
/**
* Test whether expected evidence is gathered from GNU Binutil's configure.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzeConfigureScript() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/binutils/configure"));
analyzer.analyze(result, null);
assertProductAndVersion(result, "binutils", "2.25.51");
}
/**
* Test whether expected evidence is gathered from GNU Ghostscript's
* configure.
*
* @throws AnalysisException
* is thrown when an exception occurs.
*/
@Test
public void testAnalyzeReadableConfigureScript() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/readable-code/configure"));
analyzer.analyze(result, null);
assertReadableCodeEvidence(result);
}
/**
* Test whether expected evidence is gathered from GNU Ghostscript's configure.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzeReadableConfigureScript() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "autoconf/readable-code/configure"));
analyzer.analyze(result, null);
assertReadableCodeEvidence(result);
}
/**
* Test of getName method, of {@link AutoconfAnalyzer}.
*/
@Test
public void testGetName() {
assertEquals("Analyzer name wrong.", "Autoconf Analyzer",
analyzer.getName());
}
/**
* Test of getName method, of {@link AutoconfAnalyzer}.
*/
@Test
public void testGetName() {
assertEquals("Analyzer name wrong.", "Autoconf Analyzer",
analyzer.getName());
}
/**
* Test of {@link AutoconfAnalyzer#accept(File)}.
*/
@Test
public void testSupportsFileExtension() {
assertTrue("Should support \"ac\" extension.",
analyzer.accept(new File("configure.ac")));
assertTrue("Should support \"in\" extension.",
analyzer.accept(new File("configure.in")));
assertTrue("Should support \"configure\" extension.",
analyzer.accept(new File("configure")));
}
}
/**
* Test of {@link AutoconfAnalyzer#accept(File)}.
*/
@Test
public void testSupportsFileExtension() {
assertTrue("Should support \"ac\" extension.",
analyzer.accept(new File("configure.ac")));
assertTrue("Should support \"in\" extension.",
analyzer.accept(new File("configure.in")));
assertTrue("Should support \"configure\" extension.",
analyzer.accept(new File("configure")));
}
}

View File

@@ -38,7 +38,7 @@ import org.owasp.dependencycheck.BaseDBTestCase;
/**
* Unit tests for CmakeAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class CMakeAnalyzerTest extends BaseDBTestCase {

View File

@@ -240,7 +240,7 @@ public class CPEAnalyzerIntegrationTest extends BaseDBTestCase {
Set<String> vendorWeightings = Collections.singleton("apache");
List<IndexEntry> result = instance.searchCPE(vendor, product, productWeightings, vendorWeightings);
List<IndexEntry> result = instance.searchCPE(vendor, product, vendorWeightings, productWeightings);
instance.close();
boolean found = false;

View File

@@ -39,7 +39,7 @@ import org.owasp.dependencycheck.BaseDBTestCase;
/**
* Unit tests for NodePackageAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class ComposerLockAnalyzerTest extends BaseDBTestCase {
@@ -55,6 +55,7 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase {
*/
@Before
public void setUp() throws Exception {
super.setUp();
analyzer = new ComposerLockAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();

View File

@@ -18,6 +18,7 @@ package org.owasp.dependencycheck.analyzer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.dependency.Dependency;
@@ -25,7 +26,7 @@ import org.owasp.dependencycheck.dependency.Dependency;
*
* @author Jeremy Long
*/
public class FalsePositiveAnalyzerTest {
public class FalsePositiveAnalyzerTest extends BaseTest {
/**
* Test of getName method, of class FalsePositiveAnalyzer.

View File

@@ -28,7 +28,7 @@ import org.owasp.dependencycheck.dependency.Dependency;
*
* @author Jeremy Long
*/
public class FileNameAnalyzerTest {
public class FileNameAnalyzerTest extends BaseTest {
/**
* Test of getName method, of class FileNameAnalyzer.

View File

@@ -17,21 +17,25 @@
*/
package org.owasp.dependencycheck.analyzer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import java.io.File;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Jeremy Long
*/
public class JarAnalyzerTest extends BaseTest {
// private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzerTest.class);
/**
* Test of inspect method, of class JarAnalyzer.
*
@@ -46,12 +50,25 @@ public class JarAnalyzerTest extends BaseTest {
instance.analyze(result, null);
assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache"));
assertTrue(result.getVendorEvidence().getWeighting().contains("apache"));
file = BaseTest.getResourceAsFile(this, "dwr.jar");
result = new Dependency(file);
instance.analyze(result, null);
boolean found = false;
for (Evidence e : result.getVendorEvidence()) {
if (e.getName().equals("url")) {
assertEquals("Project url was not as expected in dwr.jar", e.getValue(), "http://getahead.ltd.uk/dwr");
found = true;
break;
}
}
assertTrue("Project url was not found in dwr.jar", found);
//file = new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath());
file = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar");
result = new Dependency(file);
instance.analyze(result, null);
boolean found = false;
found = false;
for (Evidence e : result.getProductEvidence()) {
if (e.getName().equalsIgnoreCase("package-title")
&& e.getValue().equalsIgnoreCase("org.mortbay.http")) {
@@ -113,4 +130,14 @@ public class JarAnalyzerTest extends BaseTest {
assertEquals(expResult, result);
}
@Test
public void testParseManifest() throws Exception {
File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
List<JarAnalyzer.ClassNameInformation> cni = new ArrayList<JarAnalyzer.ClassNameInformation>();
instance.parseManifest(result, cni);
assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0);
}
}

View File

@@ -33,7 +33,7 @@ import static org.junit.Assert.*;
/**
* Unit tests for NodePackageAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class NodePackageAnalyzerTest extends BaseTest {

View File

@@ -32,7 +32,7 @@ import static org.junit.Assert.*;
/**
* Unit tests for OpenSSLAnalyzerAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class OpenSSLAnalyzerTest extends BaseTest {
@@ -84,22 +84,15 @@ public class OpenSSLAnalyzerTest extends BaseTest {
@Test
public void testVersionConstantExamples() {
final long[] constants = {0x1000203fL
, 0x00903000
, 0x00903001
, 0x00903002l
, 0x0090300f
, 0x0090301f
, 0x0090400f
, 0x102031af};
final long[] constants = {0x1000203fL, 0x00903000, 0x00903001, 0x00903002l, 0x0090300f, 0x0090301f, 0x0090400f, 0x102031af};
final String[] versions = {"1.0.2c",
"0.9.3-dev",
"0.9.3-beta1",
"0.9.3-beta2",
"0.9.3",
"0.9.3a",
"0.9.4",
"1.2.3z"};
"0.9.3-dev",
"0.9.3-beta1",
"0.9.3-beta2",
"0.9.3",
"0.9.3a",
"0.9.4",
"1.2.3z"};
assertEquals(constants.length, versions.length);
for (int i = 0; i < constants.length; i++) {
assertEquals(versions[i], OpenSSLAnalyzer.getOpenSSLVersion(constants[i]));

View File

@@ -33,7 +33,7 @@ import static org.junit.Assert.assertTrue;
/**
* Unit tests for PythonDistributionAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class PythonDistributionAnalyzerTest extends BaseTest {

View File

@@ -33,7 +33,7 @@ import static org.junit.Assert.assertTrue;
/**
* Unit tests for PythonPackageAnalyzer.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class PythonPackageAnalyzerTest extends BaseTest {

View File

@@ -17,30 +17,39 @@
*/
package org.owasp.dependencycheck.analyzer;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
/**
* Unit tests for {@link RubyBundleAuditAnalyzer}.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class RubyBundleAuditAnalyzerTest extends BaseTest {
public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzerTest.class);
@@ -56,14 +65,12 @@ public class RubyBundleAuditAnalyzerTest extends BaseTest {
*/
@Before
public void setUp() throws Exception {
try {
analyzer = new RubyBundleAuditAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
} catch (Exception e) {
//LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Tests will be incomplete", e);
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed. Tests will be incomplete", e);
}
super.setUp();
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
analyzer = new RubyBundleAuditAnalyzer();
analyzer.setFilesMatched(true);
}
/**
@@ -100,10 +107,119 @@ public class RubyBundleAuditAnalyzerTest extends BaseTest {
*/
@Test
public void testAnalysis() throws AnalysisException, DatabaseException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/Gemfile.lock"));
try {
analyzer.initialize();
final String resource = "ruby/vulnerable/gems/rails-4.1.15/Gemfile.lock";
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, resource));
final Engine engine = new Engine();
analyzer.analyze(result, engine);
int size = engine.getDependencies().size();
assertTrue(size >= 1);
Dependency dependency = engine.getDependencies().get(0);
assertTrue(dependency.getProductEvidence().toString().toLowerCase().contains("redcarpet"));
assertTrue(dependency.getVersionEvidence().toString().toLowerCase().contains("2.2.2"));
assertTrue(dependency.getFilePath().endsWith(resource));
assertTrue(dependency.getFileName().equals("Gemfile.lock"));
} catch (Exception e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test Ruby addCriticalityToVulnerability
*/
@Test
public void testAddCriticalityToVulnerability() throws AnalysisException, DatabaseException {
try {
analyzer.initialize();
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/sinatra/Gemfile.lock"));
final Engine engine = new Engine();
analyzer.analyze(result, engine);
Dependency dependency = engine.getDependencies().get(0);
Vulnerability vulnerability = dependency.getVulnerabilities().first();
assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0);
} catch (Exception e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".", e);
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test when Ruby bundle-audit is not available on the system.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testMissingBundleAudit() throws AnalysisException, DatabaseException {
//set a non-exist bundle-audit
Settings.setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit");
try {
//initialize should fail.
analyzer.initialize();
} catch (Exception e) {
//expected, so ignore.
} finally {
assertThat(analyzer.isEnabled(), is(false));
LOGGER.info("phantom-bundle-audit is not available. Ruby Bundle Audit Analyzer is disabled as expected.");
}
}
/**
* Test Ruby dependencies and their paths.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
final Engine engine = new Engine();
analyzer.analyze(result, engine);
assertThat(engine.getDependencies().size(), is(not(0)));
engine.scan(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/rails-4.1.15/"));
try {
engine.analyzeDependencies();
} catch (NullPointerException ex) {
LOGGER.error("NPE", ex);
throw ex;
}
List<Dependency> dependencies = engine.getDependencies();
LOGGER.info(dependencies.size() + " dependencies found.");
Iterator<Dependency> dIterator = dependencies.iterator();
while (dIterator.hasNext()) {
Dependency dept = dIterator.next();
LOGGER.info("dept path: " + dept.getActualFilePath());
Set<Identifier> identifiers = dept.getIdentifiers();
Iterator<Identifier> idIterator = identifiers.iterator();
while (idIterator.hasNext()) {
Identifier id = idIterator.next();
LOGGER.info(" Identifier: " + id.getValue() + ", type=" + id.getType() + ", url=" + id.getUrl() + ", conf=" + id.getConfidence());
}
Set<Evidence> prodEv = dept.getProductEvidence().getEvidence();
Iterator<Evidence> it = prodEv.iterator();
while (it.hasNext()) {
Evidence e = it.next();
LOGGER.info(" prod: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> versionEv = dept.getVersionEvidence().getEvidence();
Iterator<Evidence> vIt = versionEv.iterator();
while (vIt.hasNext()) {
Evidence e = vIt.next();
LOGGER.info(" version: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
Set<Evidence> vendorEv = dept.getVendorEvidence().getEvidence();
Iterator<Evidence> vendorIt = vendorEv.iterator();
while (vendorIt.hasNext()) {
Evidence e = vendorIt.next();
LOGGER.info(" vendor: name=" + e.getName() + ", value=" + e.getValue() + ", source=" + e.getSource() + ", confidence=" + e.getConfidence());
}
}
}
}

View File

@@ -0,0 +1,106 @@
/*
* 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) 2016 Bianca Jiang. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency;
import java.io.File;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
/**
* Unit tests for {@link RubyBundlerAnalyzer}.
*
* @author Bianca Jiang
*/
public class RubyBundlerAnalyzerTest extends BaseTest {
/**
* The analyzer to test.
*/
RubyBundlerAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
public void setUp() throws Exception {
analyzer = new RubyBundlerAnalyzer();
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 Analyzer name.
*/
@Test
public void testGetName() {
assertThat(analyzer.getName(), is("Ruby Bundler Analyzer"));
}
/**
* Test Ruby Gemspec file support.
*/
@Test
public void testSupportsFiles() {
assertThat(analyzer.accept(new File("test.gemspec")), is(false));
assertThat(analyzer.accept(new File("specifications" + File.separator + "test.gemspec")), is(true));
}
/**
* Test Ruby Bundler created gemspec analysis.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalyzeGemspec() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/rails-4.1.15/vendor/bundle/ruby/2.2.0/specifications/dalli-2.7.5.gemspec"));
analyzer.analyze(result, null);
final String vendorString = result.getVendorEvidence().toString();
assertThat(vendorString, containsString("Peter M. Goldstein"));
assertThat(vendorString, containsString("Mike Perham"));
assertThat(vendorString, containsString("peter.m.goldstein@gmail.com"));
assertThat(vendorString, containsString("https://github.com/petergoldstein/dalli"));
assertThat(vendorString, containsString("MIT"));
assertThat(result.getProductEvidence().toString(), containsString("dalli"));
assertThat(result.getProductEvidence().toString(), containsString("High performance memcached client for Ruby"));
assertThat(result.getVersionEvidence().toString(), containsString("2.7.5"));
}
}

View File

@@ -33,7 +33,7 @@ import static org.junit.Assert.*;
/**
* Unit tests for {@link RubyGemspecAnalyzer}.
*
* @author Dale Visser <dvisser@ida.org>
* @author Dale Visser
*/
public class RubyGemspecAnalyzerTest extends BaseTest {
@@ -79,7 +79,7 @@ public class RubyGemspecAnalyzerTest extends BaseTest {
@Test
public void testSupportsFiles() {
assertThat(analyzer.accept(new File("test.gemspec")), is(true));
assertThat(analyzer.accept(new File("Rakefile")), is(true));
// assertThat(analyzer.accept(new File("Rakefile")), is(true));
}
/**
@@ -100,4 +100,17 @@ public class RubyGemspecAnalyzerTest extends BaseTest {
assertThat(result.getProductEvidence().toString(), containsString("rest-client"));
assertThat(result.getVersionEvidence().toString(), containsString("1.7.2"));
}
/**
* Test Rakefile analysis.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
//@Test TODO: place holder to test Rakefile support
public void testAnalyzeRakefile() throws AnalysisException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/rails-4.1.15/vendor/bundle/ruby/2.2.0/gems/pg-0.18.4/Rakefile"));
analyzer.analyze(result, null);
//TODO add verification
}
}

View File

@@ -25,11 +25,12 @@ import java.io.InputStream;
import java.nio.charset.Charset;
import static org.junit.Assert.*;
import org.owasp.dependencycheck.BaseTest;
/**
* Created by colezlaw on 9/5/15.
*/
public class ComposerLockParserTest {
public class ComposerLockParserTest extends BaseTest {
private InputStream inputStream;

View File

@@ -19,12 +19,13 @@ package org.owasp.dependencycheck.data.cpe;
import org.junit.Assert;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
/**
*
* @author Jeremy Long
*/
public class IndexEntryTest {
public class IndexEntryTest extends BaseTest {
/**
* Test of setName method, of class IndexEntry.

View File

@@ -23,31 +23,13 @@ import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
/**
*
* @author Jeremy Long
*/
public class CweDBTest {
public CweDBTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
public class CweDBTest extends BaseTest {
/**
* Method to serialize the CWE HashMap. This is not used in production; this is only used once during dev to create

View File

@@ -43,28 +43,13 @@ import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
/**
*
* @author Jeremy Long
*/
public class FieldAnalyzerTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
public class FieldAnalyzerTest extends BaseTest {
@Test
public void testAnalyzers() throws Exception {

View File

@@ -23,28 +23,13 @@ import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
/**
*
* @author Jeremy Long
*/
public class LuceneUtilsTest {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
public class LuceneUtilsTest extends BaseTest {
/**
* Test of appendEscapedLuceneQuery method, of class LuceneUtils.

View File

@@ -39,14 +39,6 @@ import org.junit.Test;
*/
public class TokenPairConcatenatingFilterTest extends BaseTokenStreamTestCase {
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Override
@Before
public void setUp() throws Exception {

View File

@@ -24,6 +24,8 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.owasp.dependencycheck.dependency.Vulnerability;
@@ -73,6 +75,25 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
}
}
/**
* Test of getVulnerability method, of class CveDB.
*/
@Test
public void testgetVulnerability() throws Exception {
CveDB instance = null;
try {
instance = new CveDB();
instance.open();
Vulnerability result = instance.getVulnerability("CVE-2014-0094");
assertEquals("The ParametersInterceptor in Apache Struts before 2.3.16.1 allows remote attackers to \"manipulate\" the ClassLoader via the class parameter, which is passed to the getClass method.", result.getDescription());
} finally {
if (instance != null) {
instance.close();
}
}
}
/**
* Test of getVulnerabilities method, of class CveDB.
*/

View File

@@ -25,6 +25,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.Settings;
@@ -33,25 +34,7 @@ import org.owasp.dependencycheck.utils.Settings;
*
* @author Jeremy Long
*/
public class CveDBMySQLTest {
@BeforeClass
public static void setUpClass() {
Settings.initialize();
}
@AfterClass
public static void tearDownClass() {
Settings.cleanup();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
public class CveDBMySQLTest extends BaseTest {
/**
* Pretty useless tests of open, commit, and close methods, of class CveDB.

Some files were not shown because too many files have changed in this diff Show More