passivedns-client 2.1.12 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,146 +0,0 @@
1
- # DESCRIPTION: Module to query PassiveTotal's passive DNS repository
2
-
3
- require 'net/http'
4
- require 'net/https'
5
- require 'openssl'
6
- require 'pp'
7
-
8
- module PassiveDNS #:nodoc: don't document this
9
- # The Provider module contains all the Passive DNS provider client code
10
- module Provider
11
- # Queries RiskIQ's passive DNS database
12
- class RiskIQ < PassiveDB
13
- # Sets the modules self-reported name to "RiskIQ"
14
- def self.name
15
- "RiskIQ"
16
- end
17
- # Sets the configuration section name to "riskiq"
18
- def self.config_section_name
19
- "riskiq"
20
- end
21
- # Sets the command line database argument to "r"
22
- def self.option_letter
23
- "r"
24
- end
25
-
26
- # :debug enables verbose logging to standard output
27
- attr_accessor :debug
28
- # === Options
29
- # * :debug Sets the debug flag for the module
30
- # * "API_TOKEN" REQUIRED: User name associated with your RiskIQ account
31
- # * "API_PRIVATE_KEY" REQUIRED: Password associated with your RiskIQ account
32
- # * "API_SERVER" Alternate server for testing. Defaults to "ws.riskiq.net"
33
- # * "API_VERSION" Alternate version of the API to test. Defaults to "V1"
34
- #
35
- # === Example Instantiation
36
- #
37
- # options = {
38
- # :debug => true,
39
- # "API_TOKEN" => "riskiq_token",
40
- # "API_PRIVATE_KEY" => "riskiq_private_key",
41
- # "API_SERVER" => "ws.riskiq.net",
42
- # "API_VERSION" => "v1"
43
- # }
44
- #
45
- # PassiveDNS::Provider::RiskIQ.new(options)
46
- #
47
- def initialize(options={})
48
- @debug = options[:debug] || false
49
- @timeout = options[:timeout] || 20
50
- @token = options["API_TOKEN"] || raise("#{self.class.name} requires an API_TOKEN")
51
- @privkey = options["API_PRIVATE_KEY"] || raise("#{self.class.name} requires an API_PRIVATE_KEY")
52
- @version = options["API_VERSION"] || "v1"
53
- @server = options["API_SERVER"] || api_settings[@version][:server]
54
- @url = "https://#{@server}/#{@version}"
55
- end
56
-
57
- # Takes a label (either a domain or an IP address) and returns
58
- # an array of PassiveDNS::PDNSResult instances with the answers to the query
59
- def lookup(label, limit=nil)
60
- $stderr.puts "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
61
- Timeout::timeout(@timeout) {
62
- url = nil
63
- params = {"rrType" => "", "maxResults" => limit || 1000}
64
-
65
- if label =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
66
- url = @url+"/dns/data"
67
- params["ip"] = label
68
- else
69
- resource = api_settings[@version][:resource]
70
- param = api_settings[@version][:param]
71
- url = @url+"/dns/#{resource}"
72
- params[param] = label
73
- end
74
- url << "?"
75
- params.each do |k,v|
76
- url << "#{k}=#{v}&"
77
- end
78
- url.gsub!(/\&$/,"")
79
-
80
- $stderr.puts "DEBUG: #{self.class.name} url = #{url}" if @debug
81
- url = URI.parse url
82
- http = Net::HTTP.new(url.host, url.port)
83
- http.use_ssl = (url.scheme == 'https')
84
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
85
- http.verify_depth = 5
86
- request = Net::HTTP::Get.new(url.request_uri)
87
- request.add_field("User-Agent", "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}")
88
- request.add_field('Accept', 'Application/JSON')
89
- request.add_field('Content-Type', 'Application/JSON')
90
- request.basic_auth(@token, @privkey)
91
- t1 = Time.now
92
- response = http.request(request)
93
- t2 = Time.now
94
- recs = parse_json(response.body, label, t2-t1)
95
- if limit
96
- recs[0,limit]
97
- else
98
- recs
99
- end
100
- }
101
- rescue Timeout::Error
102
- $stderr.puts "#{self.class.name} lookup timed out: #{label}"
103
- end
104
-
105
- private
106
-
107
- def api_settings
108
- @api_settings ||= {
109
- 'v1' => { server: "ws.riskiq.net", resource: 'name', param: 'name' },
110
- 'v2' => { server: "api.passivetotal.org", resource: 'passive', param: 'query' }
111
- }
112
- end
113
-
114
- # parses the response of riskiq's JSON reply to generate an array of PDNSResult
115
- def parse_json(page,query,response_time=0)
116
- res = []
117
- data = JSON.parse(page)
118
- if data['message']
119
- if data['message'] =~ /quota_exceeded/
120
- $stderr.puts "ERROR: quota exceeded."
121
- return res
122
- end
123
- end
124
- if data['records']
125
- data['records'].each do |record|
126
- name = record['name'].gsub!(/\.$/,'')
127
- type = record['rrtype']
128
- last_seen = Time.parse(record['lastSeen'])
129
- first_seen = Time.parse(record['firstSeen'])
130
- count = record['count']
131
- record['data'].each do |datum|
132
- datum.gsub!(/\.$/,'')
133
- res << PDNSResult.new(self.class.name,response_time,
134
- name, datum, type, 0, first_seen, last_seen, count, 'yellow')
135
- end
136
- end
137
- end
138
- res
139
- rescue Exception => e
140
- $stderr.puts "#{self.class.name} Exception: #{e}"
141
- raise e
142
- end
143
-
144
- end
145
- end
146
- end
@@ -1,129 +0,0 @@
1
- require 'net/http'
2
- require 'net/https'
3
- require 'openssl'
4
- require 'json'
5
-
6
- # Please read http://www.tcpiputils.com/terms-of-service under automated requests
7
-
8
- module PassiveDNS #:nodoc: don't document this
9
- # The Provider module contains all the Passive DNS provider client code
10
- module Provider
11
- # Queries TCPIPUtils's passive DNS database
12
- class TCPIPUtils < PassiveDB
13
- # Sets the modules self-reported name to "TCPIPUtils"
14
- def self.name
15
- "TCPIPUtils"
16
- end
17
- # Sets the configuration section name to "tcpiputils"
18
- def self.config_section_name
19
- "tcpiputils"
20
- end
21
- # Sets the command line database argument to "t"
22
- def self.option_letter
23
- "t"
24
- end
25
-
26
- # :debug enables verbose logging to standard output
27
- attr_accessor :debug
28
- # === Options
29
- # * :debug Sets the debug flag for the module
30
- # * "APIKEY" REQUIRED: The API key associated with TCPIPUtils
31
- # * "URL" Alternate url for testing. Defaults to "https://www.utlsapi.com/api.php?version=1.0&apikey="
32
- #
33
- # === Example Instantiation
34
- #
35
- # options = {
36
- # :debug => true,
37
- # "APIKEY" => "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
38
- # "URL" => "https://www.utlsapi.com/api.php?version=1.0&apikey="
39
- # }
40
- #
41
- # PassiveDNS::Provider::TCPIPUtils.new(options)
42
- #
43
- def initialize(options={})
44
- @debug = options[:debug] || false
45
- @timeout = options[:timeout] || 20
46
- @apikey = options["APIKEY"] || raise("#{self.class.name} requires an APIKEY. See README.md")
47
- @url = options["URL"] || "https://www.utlsapi.com/api.php?version=1.0&apikey="
48
- end
49
-
50
- # Takes a label (either a domain or an IP address) and returns
51
- # an array of PassiveDNS::PDNSResult instances with the answers to the query
52
- def lookup(label, limit=nil)
53
- $stderr.puts "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
54
- type = (label.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) ? "domainneighbors" : "domainipdnshistory"
55
- url = "#{@url}#{@apikey}&type=#{type}&q=#{label}"
56
- recs = []
57
- Timeout::timeout(@timeout) {
58
- url = URI.parse url
59
- http = Net::HTTP.new(url.host, url.port)
60
- http.use_ssl = (url.scheme == 'https')
61
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
62
- http.verify_depth = 5
63
- request = Net::HTTP::Get.new(url.path+"?"+url.query)
64
- request.add_field("User-Agent", "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}")
65
- t1 = Time.now
66
- response = http.request(request)
67
- delta = (Time.now - t1).to_f
68
- reply = JSON.parse(response.body)
69
- if reply["status"] and reply["status"] == "succeed"
70
- question = reply["data"]["question"]
71
- recs = format_recs(reply["data"], question, delta)
72
- elsif reply["status"] and reply["status"] == "error"
73
- raise "#{self.class.name}: error from web API: #{reply["data"]}"
74
- end
75
- if limit
76
- recs[0,limit]
77
- else
78
- recs
79
- end
80
- }
81
- rescue Timeout::Error
82
- $stderr.puts "#{self.class.name} lookup timed out: #{label}"
83
- end
84
-
85
- private
86
-
87
- # translates the data structure derived from of tcpiputils's JSON reply
88
- def format_recs(reply_data, question, delta)
89
- recs = []
90
- fieldname = nil
91
- rrtype = nil
92
- add_records = false
93
- reply_data.each do |key, data|
94
- case key
95
- when "ipv4"
96
- fieldname = "ip"
97
- rrtype = "A"
98
- add_records = true
99
- when "ipv6"
100
- fieldname = "ip"
101
- rrtype = "AAAA"
102
- add_records = true
103
- when "dns"
104
- fieldname = "dns"
105
- rrtype = "NS"
106
- add_records = true
107
- when "mx"
108
- fieldname = "dns"
109
- rrtype = "MX"
110
- add_records = true
111
- when "domains"
112
- data.each do |rec|
113
- lastseen = (rec["updatedate"]) ? Date.parse(rec["updatedate"]) : nil
114
- recs << PDNSResult.new(self.class.name, delta, rec, question, "A", nil, nil, lastseen, nil, 'yellow')
115
- end
116
- end
117
- if add_records
118
- data.each do |rec|
119
- lastseen = (rec["updatedate"]) ? Date.parse(rec["updatedate"]) : nil
120
- recs << PDNSResult.new(self.class.name, delta, question, rec[fieldname], rrtype, nil, nil, lastseen, nil, 'yellow')
121
- end
122
- end
123
- end
124
- recs
125
- end
126
-
127
- end
128
- end
129
- end
@@ -1,31 +0,0 @@
1
- # coding: utf-8
2
- lib = File.expand_path('../lib', __FILE__)
3
- $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
- require 'passivedns/client/version'
5
-
6
- Gem::Specification.new do |spec|
7
- spec.name = "passivedns-client"
8
- spec.version = PassiveDNS::Client::VERSION
9
- spec.authors = ["chrislee35"]
10
- spec.email = ["rubygems@chrislee.dhs.org"]
11
- spec.description = %q{This provides interfaces to various passive DNS databases to do the query and to normalize the responses. The query tool also allows for recursive queries, using an SQLite3 database to keep state.}
12
- spec.summary = %q{Query passive DNS databases}
13
- spec.homepage = "https://github.com/chrislee35/passivedns-client"
14
- spec.license = "MIT"
15
-
16
- spec.files = `git ls-files`.split($/)
17
- spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
- spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
- spec.require_paths = ["lib"]
20
-
21
- spec.add_runtime_dependency 'json'
22
- spec.add_runtime_dependency 'sqlite3'
23
- spec.add_runtime_dependency 'structformatter'
24
- spec.add_runtime_dependency 'configparser'
25
- spec.add_development_dependency "minitest"
26
- spec.add_development_dependency "bundler"
27
- spec.add_development_dependency "rake"
28
-
29
- #spec.signing_key = "#{File.dirname(__FILE__)}/../gem-private_key.pem"
30
- #spec.cert_chain = ["#{File.dirname(__FILE__)}/../gem-public_cert.pem"]
31
- end
data/test/helper.rb DELETED
@@ -1,6 +0,0 @@
1
- require 'minitest/autorun'
2
- require 'minitest/test'
3
- require 'minitest/unit'
4
- require 'minitest/pride'
5
- include MiniTest::Assertions
6
- require File.expand_path('../../lib/passivedns/client.rb', __FILE__)
data/test/test_cli.rb DELETED
@@ -1,234 +0,0 @@
1
- unless Kernel.respond_to?(:require_relative)
2
- module Kernel
3
- def require_relative(path)
4
- require File.join(File.dirname(caller[0]), path.to_str)
5
- end
6
- end
7
- end
8
-
9
- require_relative 'helper'
10
- require 'configparser'
11
- require_relative '../lib/passivedns/client/cli.rb'
12
-
13
- class TestCLI < Minitest::Test
14
- def test_letter_map
15
- letter_map = PassiveDNS::CLI.get_letter_map
16
- assert_equal("3bcdmprtv", letter_map.keys.sort.join(""))
17
- end
18
-
19
- def test_help_text
20
- helptext = PassiveDNS::CLI.run(["--help"])
21
- helptext.gsub!(/Usage: .*?\[/, "Usage: [")
22
- assert_equal(
23
- "Usage: [-d [3bcdmprtv]] [-g|-v|-m|-c|-x|-y|-j|-t] [-os <sep>] [-f <file>] [-r#|-w#|-v] [-l <count>] [--config <file>] <ip|domain|cidr>
24
- Passive DNS Providers
25
- -d3bcdmprtv uses all of the available passive dns database
26
- -d3 use 360.cn
27
- -db use BFK.de
28
- -dc use CIRCL
29
- -dd use DNSDB
30
- -dm use Mnemonic
31
- -dp use PassiveTotal
32
- -dr use RiskIQ
33
- -dt use TCPIPUtils
34
- -dv use VirusTotal
35
- -dvt uses VirusTotal and TCPIPUtils (for example)
36
-
37
- Output Formatting
38
- -g link-nodal GDF visualization definition
39
- -z link-nodal graphviz visualization definition
40
- -m link-nodal graphml visualization definition
41
- -c CSV
42
- -x XML
43
- -y YAML
44
- -j JSON
45
- -t ASCII text (default)
46
- -s <sep> specifies a field separator for text output, default is tab
47
-
48
- State and Recursion
49
- -f[file] specifies a sqlite3 database used to read the current state - useful for large result sets and generating graphs of previous runs.
50
- -r# specifies the levels of recursion to pull. **WARNING** This is quite taxing on the pDNS servers, so use judiciously (never more than 3 or so) or find yourself blocked!
51
- -w# specifies the amount of time to wait, in seconds, between queries (Default: 0)
52
- -l <count> limits the number of records returned per passive dns database queried.
53
-
54
- Specifying a Configuration File
55
- --config <file> specifies a config file. default: #{ENV['HOME']}/.passivedns-client
56
-
57
- Getting Help
58
- -h hello there. This option produces this helpful help information on how to access help.
59
- -v debugging information
60
- ", helptext)
61
- end
62
-
63
- def test_provider_parsing
64
- options_target = {
65
- :pdnsdbs => ["bfk"],
66
- :format => "text",
67
- :sep => "\t",
68
- :recursedepth => 1,
69
- :wait => 0,
70
- :res => nil,
71
- :debug => false,
72
- :sqlitedb => nil,
73
- :limit => nil,
74
- :help => false,
75
- :configfile => "#{ENV['HOME']}/.passivedns-client"
76
- }
77
-
78
- options, items = PassiveDNS::CLI.parse_command_line([])
79
- assert_equal(options_target, options)
80
- assert_equal([], items)
81
-
82
- options_target[:pdnsdbs] = ["cn360"]
83
- options, items = PassiveDNS::CLI.parse_command_line(["-d3"])
84
- assert_equal(options_target, options)
85
- assert_equal([], items)
86
-
87
- options_target[:pdnsdbs] = ["bfk"]
88
- options, items = PassiveDNS::CLI.parse_command_line(["-db"])
89
- assert_equal(options_target, options)
90
- assert_equal([], items)
91
-
92
- options_target[:pdnsdbs] = ["circl", "dnsdb", "mnemonic", "riskiq"]
93
- options, items = PassiveDNS::CLI.parse_command_line(["-dcdmr"])
94
- assert_equal(options_target, options)
95
- assert_equal([], items)
96
-
97
- options_target[:pdnsdbs] = ["passivetotal", "tcpiputils", "virustotal"]
98
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv"])
99
- assert_equal(options_target, options)
100
- assert_equal([], items)
101
-
102
- end
103
-
104
- def test_output_parsing
105
- options_target = {
106
- :pdnsdbs => ["passivetotal", "tcpiputils", "virustotal"],
107
- :format => "text",
108
- :sep => "\t",
109
- :recursedepth => 1,
110
- :wait => 0,
111
- :res => nil,
112
- :debug => false,
113
- :sqlitedb => nil,
114
- :limit => nil,
115
- :help => false,
116
- :configfile => "#{ENV['HOME']}/.passivedns-client"
117
- }
118
-
119
- options_target[:sep] = ","
120
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-c", "8.8.8.8"])
121
- assert_equal(options_target, options)
122
- assert_equal(["8.8.8.8"], items)
123
-
124
- options_target[:sep] = "|"
125
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-s", "|", "8.8.8.8"])
126
- assert_equal(options_target, options)
127
- assert_equal(["8.8.8.8"], items)
128
-
129
- options_target[:sep] = "\t"
130
-
131
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-t", "8.8.8.8"])
132
- assert_equal(options_target, options)
133
- assert_equal(["8.8.8.8"], items)
134
-
135
- options_target[:format] = "json"
136
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-j", "8.8.8.8"])
137
- assert_equal(options_target, options)
138
- assert_equal(["8.8.8.8"], items)
139
-
140
- options_target[:format] = "xml"
141
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-x", "8.8.8.8"])
142
- assert_equal(options_target, options)
143
- assert_equal(["8.8.8.8"], items)
144
-
145
- options_target[:format] = "yaml"
146
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-y", "8.8.8.8"])
147
- assert_equal(options_target, options)
148
- assert_equal(["8.8.8.8"], items)
149
-
150
- options_target[:format] = "gdf"
151
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-g", "8.8.8.8"])
152
- assert_equal(options_target, options)
153
- assert_equal(["8.8.8.8"], items)
154
-
155
- options_target[:format] = "graphviz"
156
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-z", "8.8.8.8"])
157
- assert_equal(options_target, options)
158
- assert_equal(["8.8.8.8"], items)
159
-
160
- options_target[:format] = "graphml"
161
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-m", "8.8.8.8"])
162
- assert_equal(options_target, options)
163
- assert_equal(["8.8.8.8"], items)
164
-
165
- options_target[:format] = "text"
166
- end
167
-
168
- def test_help_debug_parsing
169
- options_target = {
170
- :pdnsdbs => ["passivetotal", "tcpiputils", "virustotal"],
171
- :format => "text",
172
- :sep => "\t",
173
- :recursedepth => 1,
174
- :wait => 0,
175
- :res => nil,
176
- :debug => false,
177
- :sqlitedb => nil,
178
- :limit => nil,
179
- :help => true,
180
- :configfile => "#{ENV['HOME']}/.passivedns-client"
181
- }
182
-
183
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-h", "8.8.8.8"])
184
- assert_equal(options_target, options)
185
- assert_equal(["8.8.8.8"], items)
186
-
187
- options_target[:debug] = true
188
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-h", "-v", "8.8.8.8"])
189
- assert_equal(options_target, options)
190
- assert_equal(["8.8.8.8"], items)
191
- end
192
-
193
- def test_state_recursion_parsing
194
- options_target = {
195
- :pdnsdbs => ["passivetotal", "tcpiputils", "virustotal"],
196
- :format => "text",
197
- :sep => "\t",
198
- :recursedepth => 5,
199
- :wait => 30,
200
- :res => nil,
201
- :debug => false,
202
- :sqlitedb => "test.db",
203
- :limit => 10,
204
- :help => false,
205
- :configfile => "#{ENV['HOME']}/.passivedns-client"
206
- }
207
-
208
- options, items = PassiveDNS::CLI.parse_command_line(["-dptv", "-f", "test.db", "-r", "5", "-w", "30", "-l", "10", "8.8.8.8"])
209
- assert_equal(options_target, options)
210
- assert_equal(["8.8.8.8"], items)
211
- end
212
-
213
- def test_configuration_file
214
- options_target = {
215
- :pdnsdbs => ["bfk"],
216
- :format => "text",
217
- :sep => "\t",
218
- :recursedepth => 1,
219
- :wait => 0,
220
- :res => nil,
221
- :debug => false,
222
- :sqlitedb => nil,
223
- :limit => nil,
224
- :help => false,
225
- :configfile => "#{ENV['HOME']}/.passivedns-client"
226
- }
227
-
228
-
229
- options, items = PassiveDNS::CLI.parse_command_line(["--config", "#{ENV['HOME']}/.passivedns-client"])
230
- assert_equal(options_target, options)
231
- assert_equal([], items)
232
-
233
- end
234
- end