File: plugins.rb

package info (click to toggle)
whatweb 0.4.8~git20141014-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 8,456 kB
  • ctags: 706
  • sloc: ruby: 31,354; sh: 614; makefile: 39
file content (552 lines) | stat: -rw-r--r-- 13,905 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
65
66
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
142
143
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
module PluginSugar
  def def_field(*names)
    class_eval do 
      names.each do |name|
        define_method(name) do |*args|
          case args.size
          when 0 then instance_variable_get("@#{name}")
          else    instance_variable_set("@#{name}", *args)
          end
        end
      end
    end
  end
end


class Plugin
  @registered_plugins = {}
  
  class << self
    attr_reader :registered_plugins
    private :new
    attr_reader :locked
    attr_reader :plugin_name
    @locked=false
  end

  def self.define(name, &block)
    p = new
    p.set_plugin_name(name)
    p.instance_eval(&block)
    p.startup
    Plugin.registered_plugins[name] = p
  end
 
  def set_plugin_name(s)
     @plugin_name = s
  end

  def version_detection?
	r=false
	if @matches and !@matches.empty?
		if !@matches.map {|m| m[:version] }.compact.empty?
			r=true
		end
	end
	r
  end

  def startup
	# individual plugins can override this
  end

  def shutdown
	# individual plugins can override this
  end

  def lock
  	@locked=true
  end
  
  def unlock
  	@locked=false
  end
  
  def locked?
  	@locked
  end

  def init (target)
        @target=target
  	@body=target.body
  	@headers=target.headers
  	@status=target.status
  	@base_uri=target.uri
	@md5sum=target.md5sum
	@tagpattern=target.tag_pattern
	@ip=target.ip
	@raw_response = target.raw_response
	@raw_headers = target.raw_headers
  end

  def make_matches(target,match)
      r=[]
                        search_context = target.body # by default
			search_context = target.raw_response if match[:search] == "all"
			search_context = target.raw_headers if match[:search] == "headers"

			if match[:search] =~ /headers\[(.*)\]/
				if target.headers[$1]
					search_context = target.headers[$1]
				else
					return []
				end
			end

			unless match[:ghdb].nil?
				r << match if match_ghdb(match[:ghdb], target.body, target.headers, target.status, target.uri)
			end
			
			unless match[:text].nil?
				r << match if match[:regexp_compiled] =~ search_context
			end

			unless match[:md5].nil?
				r << match if target.md5sum == match[:md5]
			end

			unless match[:tagpattern].nil?
				r << match if target.tag_pattern == match[:tagpattern]
			end

			unless match[:regexp_compiled].nil?
				[:regexp,:account,:version,:os,:module,:model,:string,:firmware,:filepath].each do |symbol|
					if match[symbol] and match[symbol].class==Regexp
						regexpmatch = search_context.scan(match[:regexp_compiled])
				                unless regexpmatch.empty?
				                        m = match.dup
				                        m[symbol] = regexpmatch.map {|eachmatch|

									if eachmatch.is_a?(Array) and match[:offset]
										eachmatch[match[:offset]]
									elsif eachmatch.is_a?(Array)
										eachmatch.first
									elsif eachmatch.is_a?(String)
										eachmatch
									end
								}.flatten.compact.sort.uniq
				                        r << m
				                end
					end
				end
			end

			# all previous matches are OR
			# these are ARE. e.g. required if present

			if match[:status]
				# status cannot match by itself. it needs friends
				unless r.empty?
					# this match is discarded unless it matches the status
					if match[:status] == target.status
						r << match 
					else
						r=[]
					end
				end
			end

			if match[:url]
				# url cannot match by itself. it needs friends
				unless r.empty?		
					target_url = target.uri.path
					target_url += "?" + target.uri.query unless target.uri.query.nil?
					if match[:url] == target_url
						r << match
					else
						r=[]
					end
				end
			end

			if match[:status] and match[:url]
				unless match[:status] == target.status and match[:url] == target.uri.path
					r=[]
				else
					r << match
				end
			end
	  r
  end

# execute plugin
  def x
        results=[]

  	unless @matches.nil?
	  	@matches.each do |match|
		        results+=make_matches(@target,match)
		end
	end

	# if the plugin has a passive method, use it
   	results += self.passive if defined? self.passive

	# if the plugin has an aggressive method and we're in aggressive mode, use it
	# or if we're guessing all URLs
	if ($AGGRESSION == 3 and !results.empty?) or ($AGGRESSION == 4)
		results += self.aggressive if defined? self.aggressive
		
		# if any of our matches have a url then fetch it
		# and check the matches[]
		# later we can do some caching

		# we have no caching, so we sort the URLs to fetch and only get 1 unique url per plugin. not great..
		unless @matches.nil?
			lastbase_uri=nil
			thisstatus,thisurl,thisbody,thisheaders=nil # this shouldn't be necessary but ruby thinks its a local variable to the if end statement
			
			@matches.map {|x| x if x[:url]}.compact.sort_by {|x| x[:url] }.map do |match|			
				r=[] # temp results

                                newbase_uri=URI.join(@base_uri.to_s, match[:url]).to_s
				
                                aggressivetarget=Target.new(newbase_uri)
			        aggressivetarget.open
				
				if $verbose >1
#				  puts "#{@plugin_name} Aggressive: #{aggressivetarget.uri.to_s} [#{aggressivetarget.status}]"
				end

				results += make_matches(aggressivetarget,match)
			end
		end

	end
	
	# clean up results
	unless results.empty?
		results.each do |r|
			r [:certainty]=100 if r[:certainty].nil?
		end
	end

	results
  end

  extend PluginSugar
  def_field  :author, :version, :description, :website, :matches, :cve, :dorks
  # deprecated fields
  def_field :examples
#, :category

end



# this class contains stuff related to plugins but not necessary to repeat in each plugin we create
class PluginSupport

	# this is used by load_plugins
	def PluginSupport.load_plugin(f)
		begin
			load f
		rescue => err
			error("Error: failed to load - #{err}")
		rescue SyntaxError => err
			error("Error: Failed to load - #{err}")
		rescue SystemExit, Interrupt
			error("ERROR: Failed to load plugins: Interrupted")
			if $WWDEBUG==true or $verbose > 1
				raise
			end
			exit 1
		end
	end


	# precompile regular expressions in plugins for performance
	def PluginSupport.precompile_regular_expressions
		Plugin.registered_plugins.each do |thisplugin|
			matches=thisplugin[1].matches
			unless matches.nil?
				matches.each do |thismatch|
					unless thismatch[:regexp].nil?
						#pp thismatch
						thismatch[:regexp_compiled]=Regexp.new(thismatch[:regexp])
					end

					[:version, :os, :string, :account, :model, :firmware, :module, :filepath].each do |label|
						if !thismatch[label].nil? and thismatch[label].class==Regexp
							thismatch[:regexp_compiled]=Regexp.new(thismatch[label])
							#pp thismatch
						end
					end

					unless thismatch[:text].nil?
						thismatch[:regexp_compiled]=Regexp.new(Regexp.escape(thismatch[:text]))
					end
				end
			end		
		end
	end


=begin
for adding/removing sets of plugins.

--plugins +plugins-disabled,-foobar (+ adds to the full set, -removes from the fullset. items can be directories, files or plugin names)
--plugins +/tmp/moo.rb
--plugins foobar (only select foobar)
--plugins ./plugins-disabled,-md5 (select only plugins from the plugins-disabled folder, remove the md5 plugin from the selected list)
=end

	def PluginSupport.load_plugins(list=nil)
		# separate l into a and b
		#	a = make list of dir & filenames
		#	b = make list of assumed pluginnames
		a=[];b=[]

		plugin_dirs=PLUGIN_DIRS.clone
		plugin_dirs.map {|p| p=File.expand_path(p) }

		if list
			list=list.split(",")

			plugins_disabled_location = ["plugins-disabled"].map {|x|
					$LOAD_PATH.map {|y| y+"/"+x if File.exists?(y+"/"+x) } 
				}.flatten.compact.first

			list.each {|x| x.gsub!(/^\+$/,"+#{plugins_disabled_location}") } # + is short for +plugins-disabled

			list.each do |p|
				choice=PluginChoice.new
				choice.fill(p)
				a << choice if choice.type == "file"
				b << choice if choice.type == "plugin"
			end
  
			# sort by neither, add, minus
			a=a.sort

			if a.map {|c| c.modifier }.include?(nil)
				plugin_dirs=[]
			end

			minus_files = [] # make list of files not to load
			a.map {|c|
				plugin_dirs << c.name if c.modifier.nil? or c.modifier == "+"
				plugin_dirs -= [c.name] if c.modifier == "-" # for Dirs
				minus_files << c.name if c.modifier == "-"    # for files
			}
		
			# load files from plugin_dirs unless a file is minused
			plugin_dirs.each do |d|
				# if a folder, then load all files
				if File.directory?(d)
					(Dir.glob("#{d}/*.rb")-minus_files).each {|x| PluginSupport.load_plugin(x) }
				elsif File.exists?(d)
					PluginSupport.load_plugin(d)
				else
					error("Error: #{d} is not Dir or File")
				end
			end
		
			# make list of plugins to run
			# go through all plugins, remove from list any that match b minus
			selected_plugin_names=[]

			if b.map {|c| c.modifier }.include?(nil)
				selected_plugin_names=[]
			else
				selected_plugin_names = Plugin.registered_plugins.map {|n,p| n.downcase }
			end

			b.map {|c| 
				selected_plugin_names << c.name if c.modifier.nil? or c.modifier=="+"
				selected_plugin_names -= [c.name] if c.modifier == "-"
			}
			plugins_to_use = Plugin.registered_plugins.map {|n,p| [n,p] if selected_plugin_names.include?(n.downcase) }.compact

			# report on plugins that couldn't be found
			unfound_plugins = selected_plugin_names - plugins_to_use.map {|n,p| n.downcase }
			unless unfound_plugins.empty?
				puts "Error: The following plugins were not found: " + unfound_plugins.join(",")
			end

		else
			# no selection, so it's default
			plugin_dirs.each do |d|
				Dir.glob("#{d}/*.rb").each {|x|
					PluginSupport.load_plugin(x)
				}
			end
			plugins_to_use = Plugin.registered_plugins
		end

		plugins_to_use
	end






	def PluginSupport.custom_plugin(c,*option)

		if option == ["grep"]
			matches="matches [:text=>\"#{c}\"]"

			custom="# coding: ascii-8bit
			Plugin.define \"Grep\" do
			author \"Unknown\"
			description \"User defined\"
			website \"User defined\"
			#{matches}
			end
			"
		else
			# define a custom plugin on the cmdline
			# ":text=>'powered by abc'" or
			# "{:text=>'powered by abc'},{:regexp=>/abc [ ]?1/i}"

			# then it's ok..
			if c =~ /:(text|ghdb|md5|regexp|tagpattern)=>[\/'"].*/
				matches="matches [\{#{c}\}]"
			end

			# this isn't checked for sanity... loading plugins = cmd exec anyway
			if c =~ /\{.*\}/
				matches="matches [#{c}]"
			end

			abort("Invalid custom plugin syntax: #{c}") if matches.nil?

			custom="# coding: ascii-8bit
			Plugin.define \"Custom-Plugin\" do
			author \"Unknown\"
			description \"User defined\"
			website \"User defined\"
			#{matches}
			end
			"
		end

		begin
			# open tmp file
			f=Tempfile.new('whatweb-custom-plugin')
			# write
			f.write(custom)
			f.close
			# load
			load f.path
			f.unlink
			true
		rescue SyntaxError
			error("Error: Cannot load custom plugin")
			false
		end
	end


	### some UI stuff


	def PluginSupport.plugin_list
		puts "WhatWeb Plugin List"
		puts
		puts ["Plugin Name".ljust(25),"Description"].join(" ")
		puts "-" * 79
		Plugin.registered_plugins.delete_if {|n,p| n == "\302\277" }.sort_by {|a,b| a.downcase }.each do |n,p|
			puts [n.ljust(25), (p.description.delete("\n\r") unless p.description.nil?)].join(" ")[0..78]
		end
		puts "-" * 30
		puts "#{Plugin.registered_plugins.size} Plugins Loaded"
		puts
	end



	# Show Google Dorks
	def PluginSupport.plugin_dorks(plugin_name)
		dorks=[]

		# Loop through plugins
		Plugin.registered_plugins.delete_if {|n,p| n == "\302\277" }.each do |n,p|
			if n.downcase == plugin_name.downcase
				pp "Google Dorks for #{n}:" if $verbose > 2
				dorks << p.dorks unless p.dorks.nil?
			end
		end

		# Show results if present, else show error message
		dorks.size > 0 ? puts(dorks) : error("Google dork lookup failed: Invalid plugin name or no dorks available")
	end

	# Show plugin information
	def PluginSupport.plugin_info(keywords= nil)
		puts "WhatWeb Plugin Information"
		puts "Searching for " + keywords.join(",") unless keywords.nil?
		puts "-" * 80

		puts ["Plugin Name".ljust(25),"Details"].join(" ")
		count=0
		Plugin.registered_plugins.delete_if {|n,p| n == "\302\277" }.sort_by {|a,b| a.downcase }.each do |name,plugin|
			dump=[name,plugin.author,plugin.description,plugin.website,plugin.matches].flatten.compact.to_a.join.downcase
			if keywords.empty? or keywords.map {|k| dump.include?(k.downcase) }.compact.include?(true)
				puts name
				puts "\tAuthor:".ljust(22) + plugin.author
				puts "\tVersion:".ljust(22) + plugin.version
	#			puts "\tCategory:".ljust(22) + plugin.category.to_s unless plugin.category.nil?
				puts "\tMatches:".ljust(22) + plugin.matches.size.to_s if plugin.matches
				puts "\tDorks:".ljust(22) + plugin.dorks.size.to_s if plugin.dorks
				puts "\tPassive function: ".ljust(22) + (defined?(plugin.passive) ? "Yes" : "No")
				puts "\tAggressive function: ".ljust(22) + (defined?(plugin.aggressive) ? "Yes" : "No")
				puts "\tVersion detection: ".ljust(22) + (plugin.version_detection? ? "Yes" : "No")

				if plugin.description
					puts "\tDescription: "
					word_wrap(plugin.description,72).each {|line| puts "\t" + line }
				end

				if plugin.website
					puts "\tWebsite: ".ljust(22) + plugin.website
				end

				puts
				puts "-" * 80
				count+=1
			end
		end
		puts "#{count} plugins found"
		puts
	end


end


# This is used in plugin selection by load_plugins
class PluginChoice
	attr_accessor :modifier, :type, :name

	def <=>(s)
		x = -1 if self.modifier.nil?
		x = 0 if self.modifier=="+"
		x = 1 if self.modifier=="-"
		x
	end

	def fill(s)
		self.modifier = nil
		self.modifier=s[0].chr if ["+","-"].include?(s[0].chr)

		if self.modifier
			self.name=s[1..-1]
		else
			self.name=s
		end

		# figure out and store the filename or pluginname
		if File.exists?(File.expand_path(self.name))
			self.type = "file"
			self.name = File.expand_path(self.name)
		else
			self.name.downcase!
			self.type = "plugin"
		end
	end
end