dependagrab 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: aece265264bb3c2edca450d0136c6412e1155cefe2f50fdc29b4961bf3041676
4
+ data.tar.gz: 8ff6d6ca94e374971421ca0f038f65af5a6f9cb33aae83b50b2259ee9ec10298
5
+ SHA512:
6
+ metadata.gz: b91b6dfcae48f521b5ec19eb53abac3ea0a79d8c12d1df5752dcf25509b1ba645393846407758bf1e537f72c8c7bc638e9da342ce01f5cf93bcaf91de1567781
7
+ data.tar.gz: 566d298e0c41af8d79bddd9a107f672359c14f9aee053c12787b200af228d26890c88705cb458f743f93d23e1d4a1cea53465ed3dc12e483eafdb798e852bbdb
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ *.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 1.17.2
data/CHANGE_LOG.md ADDED
@@ -0,0 +1,3 @@
1
+ # V0.1
2
+ Initial Release
3
+
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in dependagrab.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,59 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dependagrab (0.1.0)
5
+ graphql-client (= 0.17.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ activesupport (6.1.4.1)
11
+ concurrent-ruby (~> 1.0, >= 1.0.2)
12
+ i18n (>= 1.6, < 2)
13
+ minitest (>= 5.1)
14
+ tzinfo (~> 2.0)
15
+ zeitwerk (~> 2.3)
16
+ coderay (1.1.3)
17
+ concurrent-ruby (1.1.9)
18
+ diff-lcs (1.4.4)
19
+ graphql (1.13.0)
20
+ graphql-client (0.17.0)
21
+ activesupport (>= 3.0)
22
+ graphql (~> 1.10)
23
+ i18n (1.8.11)
24
+ concurrent-ruby (~> 1.0)
25
+ method_source (1.0.0)
26
+ minitest (5.14.4)
27
+ pry (0.14.1)
28
+ coderay (~> 1.1)
29
+ method_source (~> 1.0)
30
+ rake (10.5.0)
31
+ rspec (3.10.0)
32
+ rspec-core (~> 3.10.0)
33
+ rspec-expectations (~> 3.10.0)
34
+ rspec-mocks (~> 3.10.0)
35
+ rspec-core (3.10.1)
36
+ rspec-support (~> 3.10.0)
37
+ rspec-expectations (3.10.1)
38
+ diff-lcs (>= 1.2.0, < 2.0)
39
+ rspec-support (~> 3.10.0)
40
+ rspec-mocks (3.10.2)
41
+ diff-lcs (>= 1.2.0, < 2.0)
42
+ rspec-support (~> 3.10.0)
43
+ rspec-support (3.10.3)
44
+ tzinfo (2.0.4)
45
+ concurrent-ruby (~> 1.0)
46
+ zeitwerk (2.5.1)
47
+
48
+ PLATFORMS
49
+ ruby
50
+
51
+ DEPENDENCIES
52
+ bundler (~> 1.17)
53
+ dependagrab!
54
+ pry (~> 0.14)
55
+ rake (~> 10.0)
56
+ rspec (~> 3.0)
57
+
58
+ BUNDLED WITH
59
+ 1.17.2
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Dave Elliott
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # Dependagrab
2
+
3
+ Tool for extracting GitHub dependency warnings and converting it into a ThreadFix compatible file
4
+
5
+ ## Installation
6
+
7
+ Install it with:
8
+
9
+ $ gem install dependagrab
10
+
11
+ ## Usage
12
+
13
+ `$ dependagrab --help`
14
+
15
+ `$ export GITHUB_API_TOKEN=<TOKEN>`
16
+ `$ dependagrab DDAZZA/dependagrab`
17
+
18
+ ## Development
19
+
20
+ ```
21
+ $ git clone https://github.com/DDAZZA/dependagrab.git
22
+ $ bundle install
23
+ $ ruby -Ilib ./bin/dependagrab --help
24
+ ```
25
+
26
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
27
+
28
+ ## Contributing
29
+
30
+ Bug reports and pull requests are welcome on GitHub at https://github.com/DDAZZA/dependagrab.
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "dependagrab"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/dependagrab ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env ruby
2
+ require "dependagrab/cli"
3
+
4
+ Dependagrab::CLI.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,46 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "dependagrab/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "dependagrab"
8
+ spec.version = Dependagrab::VERSION
9
+ spec.authors = ["Dave Elliott"]
10
+ spec.email = ["ddazza@gmail.com"]
11
+
12
+ spec.summary = %q{Utility for extracting dependency warnings from GitHub}
13
+
14
+ # spec.description = %q{TODO: Write a longer description or delete this line.}
15
+ spec.homepage = "https://github.com/DDAZZA/dependagrab"
16
+
17
+
18
+ spec.license = 'MIT'
19
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
20
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
21
+ if spec.respond_to?(:metadata)
22
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
23
+
24
+ spec.metadata["homepage_uri"] = spec.homepage
25
+ spec.metadata["source_code_uri"] = "https://github.com/DDAZZA/dependagrab"
26
+ spec.metadata["changelog_uri"] = "https://github.com/DDAZZA/dependagrab/blob/master/CHange_LOG.md"
27
+ else
28
+ raise "RubyGems 2.0 or newer is required to protect against " \
29
+ "public gem pushes."
30
+ end
31
+
32
+ # Specify which files should be added to the gem when it is released.
33
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
34
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
35
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
36
+ end
37
+ spec.bindir = "exe"
38
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
39
+ spec.require_paths = ["lib", "static"]
40
+
41
+ spec.add_dependency "graphql-client", "0.17.0"
42
+ spec.add_development_dependency "bundler", "~> 1.17"
43
+ spec.add_development_dependency "rake", "~> 10.0"
44
+ spec.add_development_dependency "rspec", "~> 3.0"
45
+ spec.add_development_dependency "pry", "~> 0.14"
46
+ end
@@ -0,0 +1,94 @@
1
+ require 'getoptlong'
2
+ require 'dependagrab'
3
+
4
+ module Dependagrab
5
+ require 'dependagrab/console_writer'
6
+ require 'dependagrab/file_writer'
7
+
8
+ class CLI
9
+ def self.start
10
+ opts = GetoptLong.new(
11
+ [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
12
+ [ '--version', '-v', GetoptLong::NO_ARGUMENT ],
13
+ [ '--output', '-o', GetoptLong::REQUIRED_ARGUMENT ],
14
+ )
15
+
16
+
17
+ options = {}
18
+
19
+ begin
20
+ opts.each do |opt, arg|
21
+ case opt
22
+ when '--help'
23
+ print_help
24
+ exit 0
25
+ when '--version'
26
+ puts "dependagrab #{Dependagrab::VERSION}"
27
+ exit 0
28
+ when '--output'
29
+ options[:output] = arg
30
+ end
31
+ end
32
+ rescue GetoptLong::Error => e
33
+ print_help
34
+ exit 1
35
+ end
36
+
37
+ if ARGV.length != 1
38
+ STDERR.puts "Missing REPO argument (try --help for usage)"
39
+ exit 1
40
+ end
41
+
42
+ repo = ARGV.shift
43
+ _, options[:owner], options[:repo] = repo.split /([\w-]+)\/([\w-]+)$/
44
+ if options[:owner].nil? || options[:repo].nil?
45
+ STDERR.puts "Invalid REPO format"
46
+ exit 1
47
+ end
48
+
49
+ run(options)
50
+ end
51
+
52
+ private
53
+
54
+ def self.run(options)
55
+ result = Dependagrab::GithubClient.new(options).grab
56
+
57
+ if options[:output]
58
+ begin
59
+ FileWriter.new(options[:output]).write!(result[:alerts])
60
+ puts "#{result[:alerts].count} dependency warnings written to '#{options.fetch(:output)}'"
61
+ rescue => e
62
+ STDERR.puts "Failed to write file '#{options.fetch(:output)}'"
63
+ STDERR.puts e.message
64
+ exit 1
65
+ end
66
+ else
67
+ ConsoleWriter.new.write!(result[:alerts])
68
+ end
69
+ end
70
+
71
+ def self.print_usage
72
+ puts "Usage: dependagrab <REPO> [Options]"
73
+ puts
74
+ end
75
+
76
+ def self.print_help
77
+ print_usage
78
+ puts <<-EOF
79
+ <REPO> GitHub Repository (e.g. DDAZZA/dependagrab)
80
+
81
+ Options:
82
+ --output Destination to write JSON file
83
+
84
+ Misc Options:
85
+ -v, --version Prints version
86
+ -h, --help Prints this message
87
+
88
+ For private repositories you will need to set the GITHUB_API_TOKEN environment variable.
89
+ The GitHub documentation provides steps for setup (https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token).
90
+ EOF
91
+ end
92
+ end
93
+ end
94
+
@@ -0,0 +1,23 @@
1
+ module Dependagrab
2
+
3
+ # For writing output in a human readable format in the terminal
4
+ class ConsoleWriter
5
+
6
+ def write!(result)
7
+ puts ["SEVERITY".ljust(8), "PACKAGE".ljust(32), "SUMMARY"].join("\t")
8
+ puts '-' * 120
9
+
10
+ result.each do |line|
11
+ attr = [
12
+ line[:severity].ljust(8),
13
+ "#{line[:package_name]} (#{line[:vulnerable_version_range]})".ljust(32),
14
+ "#{line[:summary]} (#{line[:ghsa_id]})"
15
+ ]
16
+ puts(attr.join("\t"))
17
+ end
18
+
19
+ puts
20
+ puts "Total: #{result.count}"
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,71 @@
1
+ require 'securerandom'
2
+
3
+ module Dependagrab
4
+ # For writing output in to a file in a json format
5
+ # format is aligned to ThreadFix(https://denimgroup.atlassian.net/wiki/spaces/TDOC/pages/496009270/ThreadFix+File+Format)
6
+ #
7
+ class FileWriter
8
+
9
+ # Destination to write file
10
+ attr_accessor :output_file
11
+
12
+ def initialize(output_file)
13
+ @output_file = output_file
14
+ end
15
+
16
+ def write!(result)
17
+ scan = scan_meta_data
18
+
19
+ result.each do |alert|
20
+ scan[:findings].append(
21
+ parse_threadfix_finding(alert)
22
+ )
23
+ end
24
+
25
+ File.open(output_file, "w") do |f|
26
+ f.write(scan.to_json)
27
+ end
28
+ end
29
+
30
+
31
+ private
32
+
33
+ def scan_meta_data
34
+ {
35
+ id: SecureRandom.uuid,
36
+ created: Time.now.strftime('%Y-%m-%dT%H:%M:%SZ'),
37
+ exported: Time.now.strftime('%Y-%m-%dT%H:%M:%SZ'),
38
+ source: "AppSec Team",
39
+ collectionType: "DEPENDENCY",
40
+ findings: [],
41
+ }
42
+ end
43
+
44
+ # Converts an alert into a ThreadFix finding format
45
+ #
46
+ def parse_threadfix_finding(alert)
47
+ {
48
+ nativeId: alert[:id],
49
+ severity: alert[:severity].gsub("MODERATE", "MEDIUM"),
50
+ nativeSeverity: alert[:severity].gsub("MODERATE", "MEDIUM"),
51
+ summary: alert[:summary],
52
+ cvsScore: alert[:cvss],
53
+ description: alert[:description],
54
+ dependencyDetails: {
55
+ library: alert[:package_name],
56
+ description: alert[:description],
57
+ reference: alert[:ghsa_id],
58
+ referenceLink: alert[:permalink],
59
+ version: alert[:vulnerable_version_range],
60
+ issueType: "VULNERABILITY",
61
+ },
62
+ mappings: [
63
+ {
64
+ mappingType: "CWE",
65
+ value: alert[:cwe][4..],
66
+ }
67
+ ]
68
+ }
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,79 @@
1
+ require "graphql/client"
2
+ require "graphql/client/http"
3
+
4
+ module Dependagrab
5
+ module GHAPI
6
+ GRAPHQL_API = "https://api.github.com/graphql"
7
+ SCHEMA_PATH = "static/gh_schema.json"
8
+
9
+ # Configure GraphQL endpoint using the basic HTTP network adapter.
10
+ HTTP = GraphQL::Client::HTTP.new(GRAPHQL_API) do
11
+ def headers(context)
12
+ # Optionally set any HTTP headers
13
+ {
14
+ "User-Agent": "dependagrab #{Dependagrab::VERSION}",
15
+ }.tap do |h|
16
+ if context[:api_token]
17
+ h["Authorization"] = "bearer #{context[:api_token]}"
18
+ end
19
+ end
20
+ end
21
+ end
22
+
23
+ # However, it's smart to dump this to a JSON file and load from disk
24
+ #
25
+ # Run it from a script or rake task
26
+ # GraphQL::Client.dump_schema(GHAPI::HTTP, "gh_schema.json")
27
+ Schema = GraphQL::Client.load_schema(SCHEMA_PATH)
28
+
29
+ Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
30
+
31
+ Query = Client.parse <<-'GRAPHQL'
32
+ query($repo: String!, $owner: String!, $after_cursor: String) {
33
+ repository(name: $repo, owner: $owner) {
34
+ vulnerabilityAlerts(first: 20, after: $after_cursor) {
35
+ pageInfo {
36
+ endCursor
37
+ hasNextPage
38
+ }
39
+ nodes {
40
+
41
+ securityVulnerability {
42
+ package {
43
+ name
44
+ ecosystem
45
+ }
46
+ vulnerableVersionRange
47
+ firstPatchedVersion {
48
+ identifier
49
+ }
50
+ advisory {
51
+ cvss {
52
+ vectorString
53
+ score
54
+ }
55
+ cwes(first:100) {
56
+ edges {
57
+ node {
58
+ cweId
59
+ name
60
+ }
61
+ }
62
+ }
63
+ id
64
+ ghsaId
65
+ severity
66
+ summary
67
+ permalink
68
+ description
69
+ }
70
+
71
+ }
72
+ }
73
+ }
74
+ }
75
+ }
76
+ GRAPHQL
77
+ end
78
+
79
+ end
@@ -0,0 +1,91 @@
1
+ require './lib/dependagrab/gh_api'
2
+
3
+ module Dependagrab
4
+ class GithubClient
5
+
6
+ attr_reader :repo, :owner, :token
7
+
8
+ def initialize(options={})
9
+ @repo = options.fetch(:repo)
10
+ @owner = options.fetch(:owner)
11
+ @token = options[:token] || default_github_token
12
+ end
13
+
14
+ def grab
15
+ result = {
16
+ alerts: []
17
+ }
18
+ query_variables = { repo: repo, owner: owner }
19
+
20
+ has_next_page = true # always run query at least once
21
+ while(has_next_page)
22
+ response = GHAPI::Client.query(GHAPI::Query,
23
+ variables: query_variables,
24
+ context: { api_token: token }
25
+ )
26
+ validate_response!(response)
27
+
28
+ response.original_hash['data']['repository']['vulnerabilityAlerts']['nodes'].each do |alert|
29
+ result[:alerts].append(
30
+ parse_alert(alert)
31
+ )
32
+ end
33
+
34
+ # Sets the last position for pagination
35
+ query_variables[:after_cursor] = response.data.repository.vulnerability_alerts.page_info.end_cursor
36
+
37
+ has_next_page = response.data.repository.vulnerability_alerts.page_info.has_next_page
38
+ end
39
+
40
+ result
41
+ end
42
+
43
+ private
44
+
45
+
46
+ def validate_response!(response)
47
+ if response.errors.messages.any?
48
+ raise GhApiError.new("GitHub API Error(s): " + response.errors.messages.values.join("\n"))
49
+ end
50
+
51
+ if response.original_hash['errors'] && response.original_hash['errors'].any?
52
+ raise Error.new(response.original_hash['errors'].map { |e| e['message'] })
53
+ end
54
+ end
55
+
56
+ # Converts response format to hash
57
+ #
58
+ def parse_alert(alert)
59
+ vuln = alert['securityVulnerability']
60
+
61
+ {}.tap do |finding|
62
+ finding[:id] = vuln['advisory']['id']
63
+ finding[:ghsa_id] = vuln['advisory']['ghsaId']
64
+ finding[:package_name] = vuln['package']['name']
65
+ finding[:ecosystem] = vuln['package']['ecosystem']
66
+ finding[:severity] = vuln['advisory']['severity']
67
+ finding[:cvss_vector] = vuln['advisory']['cvss']['vectorString']
68
+ finding[:cvss] = vuln['advisory']['cvss']['score']
69
+ finding[:permalink] = vuln['advisory']['permalink']
70
+ finding[:summary] = vuln['advisory']['summary']
71
+ finding[:description] = vuln['advisory']['description']
72
+ finding[:vulnerable_version_range] = vuln['vulnerableVersionRange']
73
+ finding[:first_patched_version] = vuln['firstPatchedVersion']
74
+
75
+ if vuln['advisory']['cwes']['edges'].any?
76
+ cwe = vuln['advisory']['cwes']['edges'][0]
77
+ finding[:cwe] = cwe['node']['cweId']
78
+ finding[:cw_name] = cwe['node']['name']
79
+ end
80
+ end
81
+ end
82
+
83
+ def default_github_token
84
+ begin
85
+ ENV.fetch("GITHUB_API_TOKEN")
86
+ rescue
87
+ raise MissingConfigError.new("GitHub API token is not configured")
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,3 @@
1
+ module Dependagrab
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,8 @@
1
+ module Dependagrab
2
+ require "dependagrab/version"
3
+ require "dependagrab/github_client"
4
+
5
+ class Error < StandardError; end
6
+ class MissingConfigError < Dependagrab::Error; end
7
+ class GhApiError < Dependagrab::Error; end
8
+ end