Class: Wmap::UrlCrawler::AdwareTag

Inherits:
Wmap::UrlCrawler show all
Defined in:
lib/wmap/url_crawler/adware_tag.rb

Constant Summary

Constants inherited from Wmap::UrlCrawler

Crawl_timeout, Max_http_timeout

Constants included from Wmap::Utils::DomainRoot

Wmap::Utils::DomainRoot::File_ccsld, Wmap::Utils::DomainRoot::File_cctld, Wmap::Utils::DomainRoot::File_gtld, Wmap::Utils::DomainRoot::File_tld

Instance Attribute Summary

Attributes inherited from Wmap::UrlCrawler

#crawl_depth, #crawl_done, #crawl_page_limit, #crawl_start, #data_dir, #data_store, #discovered_urls_by_crawler, #http_timeout, #max_parallel, #signature_file, #tag_file, #tag_signatures, #tag_store, #verbose, #visited_urls_by_crawler

Instance Method Summary collapse

Methods inherited from Wmap::UrlCrawler

#crawl, #crawl_worker, #crawl_workers, #crawl_workers_on_file, #get_discovered_sites_by_crawler, #pre_crawl, #print_discovered_urls_by_crawler, #save_discovered_urls

Methods included from Wmap::Utils

#cidr_2_ips, #file_2_hash, #file_2_list, #get_nameserver, #get_nameservers, #host_2_ip, #host_2_ips, #is_cidr?, #is_fqdn?, #is_ip?, #list_2_file, #reverse_dns_lookup, #sort_ips, #valid_dns_record?, #zone_transferable?

Methods included from Wmap::Utils::Logger

#wlog

Methods included from Wmap::Utils::UrlMagic

#create_absolute_url_from_base, #create_absolute_url_from_context, #host_2_url, #is_site?, #is_ssl?, #is_url?, #make_absolute, #normalize_url, #url_2_host, #url_2_path, #url_2_port, #url_2_site, #urls_on_same_domain?

Methods included from Wmap::Utils::DomainRoot

#get_domain_root, #get_sub_domain, #is_domain_root?, #print_ccsld, #print_cctld, #print_gtld

Constructor Details

#initialize(params = {}) ⇒ AdwareTag

Initialize the instance variables



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/wmap/url_crawler/adware_tag.rb', line 22

def initialize (params = {})
  @verbose=params.fetch(:verbose, false)
    @data_dir=params.fetch(:data_dir, File.dirname(__FILE__)+'/../../../data/')
    @tag_file=@data_dir + 'tag_sites'
  # Set default instance variables
  @signature_file=File.dirname(__FILE__) + '/../../../settings/' + 'tag_signatures'
  file=params.fetch(:signature_file, @signature_file)
  @tag_signatures=load_from_file(file)
    file2=params.fetch(:tag_file, @tag_file)
    File.write(file2, "") unless File.exist?(@tag_file)
    # load the known tag store
    @tag_store=load_tag_from_file(file2)
end

Instance Method Details

#check_adware(site, use_cache = true) ⇒ Object

Give a site, locate the landing page, then sift out the adware tag if found



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/wmap/url_crawler/adware_tag.rb', line 144

def check_adware(site,use_cache=true)
   #begin
    puts "Check the site for known Adware tags: #{site}" if @verbose
     record = Hash.new
    if use_cache && @tag_store.key?(site)
    puts "Site entry already exist. Skipping: #{site}" if @verbose
    else
       url = fast_landing(site)
       tags = find_tags(url)
       return record if tags.size==0
       tag_vers=tags.map do |tag|
         get_ver(url,tag)
       end
       tag_descs=tags.map do |tag|
         Base64.urlsafe_encode64(get_desc(url,tag))
       end
      if tags
         record[site]=[url, tags.join("|"), tag_vers.join("|"), tag_descs.join("|")]
         @tag_store.merge!(record)
         puts "Tag entry loaded: #{record}" if @verbose
       else
         puts "No tag found. Skip site #{site}" if @verbose
       end
    end
     return record
   #rescue => ee
  #  puts "Exception on method #{__method__}: #{ee}: #{site}" if @verbose
  #end
end

#fast_landing(site) ⇒ Object

Given a site, determine the landing url



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/wmap/url_crawler/adware_tag.rb', line 175

def fast_landing(site)
  puts "Locate the landing url for: #{site}" if @verbose
  my_tracker=Wmap::SiteTracker.instance
  if my_tracker.known_sites.key?(site)
    # looking into the cache first
    if my_tracker.known_sites[site]['code'] >= 300 && my_tracker.known_sites[site]['code'] < 400
      url = my_tracker.known_sites[site]['redirection']
    else
      url = site
    end
    my_tracker = nil
  else
    # no cache, then need to do it fresh
    my_checker = Wmap::UrlChecker.new
    url = my_checker.landing_location(site)
    my_checker = nil
  end
  puts "Landing url found: #{url}" if @verbose
  return url
end

#find_tags(url) ⇒ Object

Search the page for known tag signatures. If found return them in an array



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/wmap/url_crawler/adware_tag.rb', line 197

def find_tags(url)
begin
  puts "Search and return tags within the url payload: #{url}" if @verbose
  tag_list = []
    doc = Nokogiri::HTML(open(url))
    doc.text.each_line do |line|
      my_line = line.downcase
      @tag_signatures.keys.map do |tag|
        tag_list.push(tag) if my_line.include?(tag)
      end
    end
    doc = nil
    return tag_list
  rescue => ee
    puts "Exception on method #{__method__}: #{ee}" if @verbose
    return []
end
end

#get_desc(url, tag) ⇒ Object

Search the url payload for known tag. If found return the base64 encode whole script snippet.



262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/wmap/url_crawler/adware_tag.rb', line 262

def get_desc(url,tag)
  puts "Search and return tag script in url payload: #{url}, #{tag}" if @verbose
  recording=false
  tag_found=false
  tag_desc=""
  doc = Nokogiri::HTML(open(url))
  doc.search('script').map do |script|
    if script.text.include?(tag)
      return script.text
    end
  end
  doc = nil
  return tag_desc
end

#get_ver(url, tag) ⇒ Object

Search the url payload for known tag version identifier. If found return a string, else empty string.



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/wmap/url_crawler/adware_tag.rb', line 217

def get_ver(url,tag)
  puts "Search and return tag version within the url payload: #{url}, #{tag}" if @verbose
  tag_ver=""
  doc = Nokogiri::HTML(open(url))
  case tag
  when "utag.js"          # sample: ...,"code_release_version":"cb20190312032612",...
    doc.text.each_line do |line|
      my_line = line.downcase
      if my_line.include?("code_release_version")
        puts "Extract tag version from line: #{my_line}" if @verbose
        m = my_line.match(/\"code\_release\_version\"\:\"(?<ver>[a-z]+\d+)\"/)
        tag_ver = m[:ver]
        break
      end
    end
  when "analytics.js"          # sample:   ga('create', 'UA-19175804-2', 'knopfdoubleday.com');
    doc.text.each_line do |line|
      my_line = line.downcase
      if my_line.include?("ga(") && my_line.include?("create")
        puts "Extract tag version from line: #{my_line}" if @verbose
        m = my_line.match(/[\'|\"]create[\'|\"]\s*\,\s*[\'|\"](?<ver>\w+\-\d+\-\d+)[\'|\"]\s*\,/)
        tag_ver = m[:ver]
        break
      end
    end
  when "all.js"          # sample:    appId      : '749936668352954',
    doc.text.each_line do |line|
      my_line = line.downcase
      if my_line.include?("appid") && my_line.include?(":")
        puts "Extract tag version from line: #{my_line}" if @verbose
        m = my_line.match(/appid\s+\:\s+[\'|\"](?<ver>\d+)[\'|\"]\s*\,/)
        tag_ver = m[:ver]
        break
      end
    end

  else
    puts "Unknown Adware Tag: #{tag}"
    # do nothing
  end
  doc = nil
  return tag_ver
end

#load_from_file(file, lc = true) ⇒ Object

load the known tag signatures into an instance variable



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/wmap/url_crawler/adware_tag.rb', line 38

def load_from_file (file, lc=true)
  begin
     puts "Loading data file: #{file}"  if @verbose
    data_store=Hash.new
    f = File.open(file, 'r')
    f.each_line do |line|
      puts "Processing line: #{line}" if @verbose
      line=line.chomp.strip
      next if line.nil?
      next if line.empty?
      next if line =~ /^\s*#/
      line=line.downcase if lc==true
      entry=line.split(',')
      if data_store.key?(entry[0])
        next
      else
        data_store[entry[0]]=entry[1].strip
      end

    end
    f.close
    return data_store
  rescue => ee
    puts "Exception on method #{__method__}: #{ee}" if @verbose
    return nil
  end
end

#load_tag_from_file(file, lc = true) ⇒ Object

load the known tag store cache into an instance variable



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/wmap/url_crawler/adware_tag.rb', line 67

def load_tag_from_file (file, lc=true)
  begin
     puts "Loading tag data file: #{file}"  if @verbose
    data_store=Hash.new
    f = File.open(file, 'r')
    f.each_line do |line|
      puts "Processing line: #{line}" if @verbose
      line=line.chomp.strip
      next if line.nil?
      next if line.empty?
      next if line =~ /^\s*#/
      line=line.downcase if lc==true
      entry=line.split(',')
      if data_store.key?(entry[0])
        next
      else
        data_store[entry[0]]=[entry[1].strip, entry[2].strip, entry[3]]
      end
    end
    f.close
    return data_store
  rescue => ee
    puts "Exception on method #{__method__}: #{ee}" if @verbose
    return nil
  end
end

#refresh(num = @max_parallel, use_cache = true) ⇒ Object

add tag entries (from the sitetracker list)



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/wmap/url_crawler/adware_tag.rb', line 114

def refresh (num=@max_parallel,use_cache=true)
   #begin
    puts "Add entries to the local cache table from site tracker: " if @verbose
    results=Hash.new
    tags=Wmap::SiteTracker.instance.known_sites.keys
    if tags.size > 0
      Parallel.map(tags, :in_processes => num) { |target|
        check_adware(target,use_cache)
      }.each do |process|
        if !process
          next
        else
          results.merge!(process)
        end
      end
      @tag_store.merge!(results)
      puts "Done loading entries."
       tags=nil
      return results
    else
      puts "Error: no entry is loaded. Please check your list and try again."
    end
     tags=nil
    return results
  #rescue => ee
  #  puts "Exception on method #{__method__}: #{ee}" if @verbose
  #end
end

#save_to_file!(file_tag = @tag_file, tags = @tag_store) ⇒ Object Also known as: save!

Save the current tag store hash table into a file



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/wmap/url_crawler/adware_tag.rb', line 95

def save_to_file!(file_tag=@tag_file, tags=@tag_store)
   begin
     puts "Saving the current wordpress site table from memory to file: #{file_tag} ..." if @verbose
    timestamp=Time.now
    f=File.open(file_tag, 'w')
    f.write "# Local tag file created by class #{self.class} method #{__method__} at: #{timestamp}\n"
    f.write "# Site, Landing URL, Detected Adware Tag, Tag Version, Tag Description\n"
    tags.each do |key, val|
      f.write "#{key}, #{val[0]}, #{val[1]}, #{val[2]}, #{val[3]}\n"
    end
    f.close
    puts "Tag store cache table is successfully saved: #{file_tag}"
  rescue => ee
    puts "Exception on method #{__method__}: #{ee}" if @verbose
  end
end