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,30 +1,37 @@
1
+ # frozen_string_literal: true
2
+
1
3
  # DESCRIPTION: Module to query PassiveTotal's passive DNS repository
2
4
 
5
+ require 'json'
3
6
  require 'net/http'
4
- require 'net/https'
5
7
  require 'openssl'
6
- require 'pp'
8
+ require 'time'
9
+ require 'timeout'
10
+ require 'uri'
7
11
 
8
- module PassiveDNS #:nodoc: don't document this
12
+ module PassiveDNS # :nodoc: don't document this
9
13
  # The Provider module contains all the Passive DNS provider client code
10
14
  module Provider
11
15
  # Queries PassiveTotal's passive DNS database
12
16
  class PassiveTotal < PassiveDB
13
17
  # Sets the modules self-reported name to "PassiveTotal"
14
18
  def self.name
15
- "PassiveTotal"
19
+ 'PassiveTotal'
16
20
  end
21
+
17
22
  # Sets the configuration section name to "passivetotal"
18
23
  def self.config_section_name
19
- "passivetotal"
24
+ 'passivetotal'
20
25
  end
26
+
21
27
  # Sets the command line database argument to "p"
22
28
  def self.option_letter
23
- "p"
29
+ 'p'
24
30
  end
25
-
31
+
26
32
  # :debug enables verbose logging to standard output
27
33
  attr_accessor :debug
34
+
28
35
  # === Options
29
36
  # * :debug Sets the debug flag for the module
30
37
  # * "USERNAME" REQUIRED: The username for the associated API key
@@ -39,7 +46,7 @@ module PassiveDNS #:nodoc: don't document this
39
46
  # "APIKEY" => "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
40
47
  # "URL" => "https://api.passivetotal.org/v2/dns/passive"
41
48
  # }
42
-
49
+
43
50
  # or
44
51
  #
45
52
  # options = {
@@ -52,68 +59,65 @@ module PassiveDNS #:nodoc: don't document this
52
59
  #
53
60
  # PassiveDNS::Provider::PassiveTotal.new(options)
54
61
  #
55
- def initialize(options={})
56
- @debug = options[:debug] || false
57
- @timeout = options[:timeout] || 20
58
- @username = options["USERNAME"] || raise("#{self.class.name} requires a USERNAME")
59
- @apikey = options["APIKEY"] || raise("#{self.class.name} requires an APIKEY")
60
- @url = options["URL"] || "https://api.passivetotal.org/v2/dns/passive"
62
+ def initialize(config = {})
63
+ super()
64
+ @debug = config[:debug] || false
65
+ @timeout = config[:timeout] || 20
66
+ @username = config['USERNAME'] || raise("#{self.class.name} requires a USERNAME")
67
+ @apikey = config['APIKEY'] || raise("#{self.class.name} requires an APIKEY")
68
+ @url = config['URL'] || 'https://api.passivetotal.org/v2/dns/passive'
61
69
  end
62
70
 
63
71
  # Takes a label (either a domain or an IP address) and returns
64
72
  # an array of PassiveDNS::PDNSResult instances with the answers to the query
65
- def lookup(label, limit=nil)
66
- $stderr.puts "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
67
- Timeout::timeout(@timeout) {
68
- url = @url+"?query=#{label}"
69
- $stderr.puts "DEBUG: #{self.class.name} url = #{url}" if @debug
73
+ def lookup(label, limit = nil)
74
+ warn "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
75
+ Timeout.timeout @timeout do
76
+ url = @url + "?query=#{label}"
77
+ warn "DEBUG: #{self.class.name} url = #{url}" if @debug
70
78
  url = URI.parse url
71
- http = Net::HTTP.new(url.host, url.port)
79
+ http = Net::HTTP.new url.host, url.port
72
80
  http.use_ssl = (url.scheme == 'https')
73
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
74
81
  http.verify_depth = 5
75
- request = Net::HTTP::Get.new(url.request_uri)
76
- request.basic_auth(@username, @apikey)
77
- request.add_field("User-Agent", "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}")
78
- #request.set_form_data({"api_key" => @apikey, "query" => label})
82
+ request = Net::HTTP::Get.new url.request_uri
83
+ request.basic_auth @username, @apikey
84
+ request.add_field 'User-Agent', "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}"
85
+ # request.set_form_data({"api_key" => @apikey, "query" => label})
79
86
  t1 = Time.now
80
- response = http.request(request)
87
+ response = http.request request
81
88
  t2 = Time.now
82
- recs = parse_json(response.body, label, t2-t1)
89
+ check_response response
90
+ recs = parse_json response.body, label, t2 - t1
83
91
  if limit
84
- recs[0,limit]
92
+ recs[0, limit]
85
93
  else
86
94
  recs
87
95
  end
88
- }
96
+ end
89
97
  rescue Timeout::Error
90
- $stderr.puts "#{self.class.name} lookup timed out: #{label}"
98
+ warn "#{self.class.name} lookup timed out: #{label}"
91
99
  end
92
-
100
+
93
101
  private
94
-
102
+
95
103
  # parses the response of passivetotals's JSON reply to generate an array of PDNSResult
96
- def parse_json(page,query,response_time=0)
104
+ def parse_json(page, query, response_time = 0)
97
105
  res = []
98
- data = JSON.parse(page)
99
- pp data
100
- if data['message']
101
- raise "#{self.class.name} Error: #{data['message']}"
102
- end
106
+ data = JSON.parse page
107
+ raise "#{self.class.name} Error: #{data['message']}" if data['message']
108
+
103
109
  query = data['queryValue']
104
- if data['results']
105
- data['results'].each do |row|
106
- first_seen = (row['firstSeen'] == "None") ? nil : Time.parse(row['firstSeen']+" +0000")
107
- last_seen = (row['lastSeen'] == "None") ? nil : Time.parse(row['lastSeen']+" +0000")
108
- value = row['resolve']
109
- source = row['source'].join(",")
110
- res << PDNSResult.new(self.class.name+"/"+source,response_time,
111
- query, value, "A", 0, first_seen, last_seen, 'yellow')
112
- end
110
+ data['results']&.each do |row|
111
+ first_seen = row['firstSeen'] == 'None' ? nil : Time.parse("#{row['firstSeen']} +0000")
112
+ last_seen = row['lastSeen'] == 'None' ? nil : Time.parse("#{row['lastSeen']} +0000")
113
+ value = row['resolve']
114
+ source = row['source'].join ','
115
+ res << PDNSResult.new("#{self.class.name}/#{source}", response_time,
116
+ query, value, 'A', 0, first_seen, last_seen, nil, 'yellow')
113
117
  end
114
118
  res
115
- rescue Exception => e
116
- $stderr.puts "#{self.class.name} Exception: #{e}"
119
+ rescue StandardError => e
120
+ warn "#{self.class.name} Exception: #{e}"
117
121
  raise e
118
122
  end
119
123
  end
@@ -1,119 +1,125 @@
1
+ # frozen_string_literal: true
2
+
1
3
  # DESCRIPTION: this is a module for pdns.rb, primarily used by pdnstool.rb, to query VirusTotal's passive DNS database
4
+ require 'json'
2
5
  require 'net/http'
3
- require 'net/https'
4
6
  require 'openssl'
7
+ require 'time'
8
+ require 'timeout'
9
+ require 'uri'
5
10
 
6
- module PassiveDNS #:nodoc: don't document this
11
+ module PassiveDNS # :nodoc: don't document this
7
12
  # The Provider module contains all the Passive DNS provider client code
8
13
  module Provider
9
14
  # Queries VirusTotal's passive DNS database
10
15
  class VirusTotal < PassiveDB
11
16
  # Sets the modules self-reported name to "VirusTotal"
12
17
  def self.name
13
- "VirusTotal"
18
+ 'VirusTotal'
14
19
  end
20
+
15
21
  # Sets the configuration section name to "virustotal"
16
22
  def self.config_section_name
17
- "virustotal"
23
+ 'virustotal'
18
24
  end
25
+
19
26
  # Sets the command line database argument to "v"
20
27
  def self.option_letter
21
- "v"
28
+ 'v'
22
29
  end
23
-
30
+
24
31
  # :debug enables verbose logging to standard output
25
32
  attr_accessor :debug
26
-
33
+
27
34
  # === Options
28
35
  # * :debug Sets the debug flag for the module
29
36
  # * "APIKEY" Mandatory. API Key associated with your VirusTotal account
30
- # * "URL" Alternate url for testing. Defaults to https://www.virustotal.com/vtapi/v2/
37
+ # * "URL" Alternate url for testing. Defaults to https://www.virustotal.com/api/v3/
31
38
  #
32
39
  # === Example Instantiation
33
40
  #
34
41
  # options = {
35
42
  # :debug => true,
36
43
  # "APIKEY" => "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
37
- # "URL" => "https://www.virustotal.com/vtapi/v2/"
44
+ # "URL" => "https://www.virustotal.com/api/v3/"
38
45
  # }
39
46
  #
40
47
  # PassiveDNS::Provider::VirusTotal.new(options)
41
48
  #
42
- def initialize(options={})
43
- @debug = options[:debug] || false
44
- @timeout = options[:timeout] || 20
45
- @apikey = options["APIKEY"] || raise("#{self.class.name} requires an APIKEY. See README.md")
46
- @url = options["URL"] || "https://www.virustotal.com/vtapi/v2/"
49
+ def initialize(config = {})
50
+ super()
51
+ @debug = config[:debug] || false
52
+ @timeout = config[:timeout] || 20
53
+ @apikey = config['APIKEY'] || raise("#{self.class.name} requires an APIKEY. See README.md")
54
+ @url = config['URL'] || 'https://www.virustotal.com/api/v3/'
55
+ @url += '/' unless @url.end_with? '/'
47
56
  end
48
57
 
58
+ # the most resolutions that VirusTotal returns in one response
59
+ MAX_LIMIT = 40
60
+
49
61
  # Takes a label (either a domain or an IP address) and returns
50
- # an array of PassiveDNS::PDNSResult instances with the answers to the query
51
- def lookup(label, limit=nil)
52
- $stderr.puts "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
53
- Timeout::timeout(@timeout) {
54
- url = nil
55
- if label =~ /^[\d\.]+$/
56
- url = "#{@url}ip-address/report?ip=#{label}&apikey=#{@apikey}"
57
- else
58
- url = "#{@url}domain/report?domain=#{label}&apikey=#{@apikey}"
59
- end
60
- $stderr.puts "DEBUG: #{self.class.name} url = #{url}" if @debug
62
+ # an array of PassiveDNS::PDNSResult instances with the answers to the query.
63
+ # VirusTotal returns at most MAX_LIMIT resolutions per query.
64
+ def lookup(label, limit = nil)
65
+ warn "DEBUG: #{self.class.name}.lookup(#{label})" if @debug
66
+ Timeout.timeout @timeout do
67
+ kind = /^[\d.]+$|:/.match?(label) ? 'ip_addresses' : 'domains'
68
+ count = [limit || MAX_LIMIT, MAX_LIMIT].min
69
+ url = "#{@url}#{kind}/#{URI.encode_uri_component label}/resolutions?limit=#{count}"
70
+ warn "DEBUG: #{self.class.name} url = #{url}" if @debug
61
71
  begin
62
72
  url = URI.parse url
63
73
  rescue URI::InvalidURIError
64
- $stderr.puts "ERROR: Invalid address: #{url}"
74
+ warn "ERROR: Invalid address: #{url}"
65
75
  return
66
76
  end
67
- http = Net::HTTP.new(url.host, url.port)
77
+ http = Net::HTTP.new url.host, url.port
68
78
  http.use_ssl = (url.scheme == 'https')
69
- http.verify_mode = OpenSSL::SSL::VERIFY_NONE
70
79
  http.verify_depth = 5
71
- request = Net::HTTP::Get.new(url.path+"?"+url.query)
72
- request.add_field("User-Agent", "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}")
80
+ request = Net::HTTP::Get.new url.request_uri
81
+ request.add_field 'User-Agent', "Ruby/#{RUBY_VERSION} passivedns-client rubygem v#{PassiveDNS::Client::VERSION}"
82
+ request.add_field 'Accept', 'application/json'
83
+ request.add_field 'x-apikey', @apikey
73
84
  t1 = Time.now
74
- response = http.request(request)
75
- if response.code.to_i == 204
76
- $stderr.puts "DEBUG: empty response from server" if @debug
77
- return
78
- end
85
+ response = http.request request
79
86
  t2 = Time.now
80
- recs = parse_json(response.body, label, t2-t1)
81
- if limit
82
- recs[0,limit]
83
- else
84
- recs
87
+ if response.code.to_i == 404
88
+ warn 'DEBUG: empty response from server' if @debug
89
+ return
85
90
  end
86
- }
91
+ check_response response
92
+ recs = parse_json response.body, label, t2 - t1
93
+ limit ? recs[0, limit] : recs
94
+ end
87
95
  rescue Timeout::Error
88
- $stderr.puts "#{self.class.name} lookup timed out: #{label}"
96
+ warn "#{self.class.name} lookup timed out: #{label}"
89
97
  end
90
-
98
+
91
99
  private
92
-
93
- # parses the response of virustotal's JSON reply to generate an array of PDNSResult
94
- def parse_json(page,query,response_time=0)
100
+
101
+ # parses the response of virustotal's v3 JSON reply to generate an array of PDNSResult
102
+ def parse_json(page, query, response_time = 0)
95
103
  res = []
96
- return res if !page
97
- data = JSON.parse(page)
98
- if data['resolutions']
99
- data['resolutions'].each do |row|
100
- lastseen = Time.parse(row['last_resolved']+" +0000")
101
- if row['ip_address']
102
- res << PDNSResult.new(self.class.name,response_time,query,row['ip_address'],'A',nil,nil,lastseen, 'yellow')
103
- elsif row['hostname']
104
- res << PDNSResult.new(self.class.name,response_time,row['hostname'],query,'A',nil,nil,lastseen, 'yellow')
105
- end
104
+ return res unless page
105
+
106
+ data = JSON.parse page
107
+ raise "#{self.class.name} Error: #{data['error']['message']}" if data['error']
108
+
109
+ data['data']&.each do |row|
110
+ attributes = row['attributes'] || {}
111
+ lastseen = Time.at attributes['date'].to_i
112
+ if attributes['ip_address']
113
+ res << PDNSResult.new(self.class.name, response_time, query, attributes['ip_address'], 'A', nil, nil, lastseen, nil, 'yellow')
114
+ elsif attributes['host_name']
115
+ res << PDNSResult.new(self.class.name, response_time, attributes['host_name'], query, 'A', nil, nil, lastseen, nil, 'yellow')
106
116
  end
107
117
  end
108
- if data['response_code'] == 0
109
- $stderr.puts "DEBUG: server returned error: #{data['verbose_msg']}" if @debug
110
- end
111
118
  res
112
- rescue Exception => e
113
- $stderr.puts "VirusTotal Exception: #{e}"
119
+ rescue StandardError => e
120
+ warn "VirusTotal Exception: #{e}"
114
121
  raise e
115
122
  end
116
-
117
123
  end
118
124
  end
119
125
  end