-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdetect_http_attack.rb
executable file
·415 lines (309 loc) · 7.8 KB
/
detect_http_attack.rb
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
#!/usr/bin/env ruby
#
# Detect HTTP attack
#
# A tool to detect attacks to HTTP server (Apache, Nginx),
# by analyzing the sequential access parsing combined log or LTSV log.
#
# Author:: Toshimitsu Takahashi (mailto:tilfin@gmail.com)
# Copyright:: (c) 2013 Toshimitsu Takahashi
# License:: MIT License
#
require 'date'
require 'optparse'
module DetectHttpAttack
class LogParser
def parse(line)
end
end
class CombinedLogParser < LogParser
def parse(line)
row = line.to_s.chomp
row.strip!
m = parse_line(row)
return nil if m.length == 0
host, ident, user, time, req, status, size, referer, ua = m
method, path = req.split(' ')
{ :host => host,
:time => time,
:date => parse_datetime(time),
:req => req,
:method => method,
:path => path,
:status => status,
:size => size,
:referer => referer,
:ua => ua }
end
def parse_datetime(dt_str)
DateTime.strptime(dt_str, '%d/%b/%Y:%T %z')
end
def parse_line(line)
str = line
values = Array.new
while str
first_char = str[0]
if first_char == '"'
# in double quotes
start_pos = 1
end_pos = 1
begin
end_pos = str.index('"', end_pos+1)
end while end_pos and str[end_pos-1] == '\\'
elsif first_char == '['
# in square brackets
start_pos = 1
end_pos = str.index(']', 1)
else
start_pos = 0
end_pos = str.index(' ', 1)
end
unless end_pos
# Last field
values.push str[start_pos..-1]
break
end
values.push str[start_pos..end_pos-1]
end_pos += start_pos
str = str[end_pos+1 .. -1]
end
values
end
end
class LtsvLogParser < LogParser
def parse(line)
row = line.to_s.chomp
row.strip!
return nil if row.length == 0
values = Hash.new
row.split("\t").map { |field|
name, value = field.split(":", 2)
values[name.to_sym] = value
}
method, path, version = values[:req].split(' ')
values[:method] = method
values[:path] = path
values[:version] = version
values[:date] = parse_datetime(values[:time])
values
end
def parse_datetime(dt_str)
DateTime.strptime(dt_str, '[%d/%b/%Y:%T %z]')
end
end
class Configuration
def initialize(file_path=nil)
conf_file = file_path || File.dirname(__FILE__) + "/detect_http_attack.conf"
return unless File.exists?(conf_file)
@sets = Hash.new
open(conf_file, "r") do |f|
f.each {|line|
next if line.start_with?("#")
name, value = line.split("=", 2)
next unless value
value.chomp!
@sets[name.to_sym] = eval %Q{"#{value}"}
}
end
end
def get(field)
@sets[field]
end
end
class Template
def initialize(head, body, foot, serr, date_format)
@re_field = Regexp.new("\\$[a-z]+")
h = head || "$host\t$count\t$ua\n"
b = body || "$date\t$path\t$referer\n"
f = foot || "\n"
s = serr || "$host\t$count\t$ua\n$date\t$path\t$referer\n"
@head = parse_value(h)
@body = parse_value(b)
@foot = parse_value(f)
@serr = parse_value(s)
@date_format = date_format
end
def parse_value(value)
vals = Array.new
str = value
begin
pos = @re_field =~ str
if pos
if pos > 0
vals.push(str[0, pos])
end
fld = Regexp.last_match(0)
vals.push(fld[1..-1].to_sym)
pos += fld.length
str = str[pos..-1]
end
end while pos
if str
vals.push(str)
end
vals
end
def print_head(count, row)
if @head
print_row(@head, $stdout, count, row)
end
end
def print_body(row)
print_row(@body, $stdout, "", row)
end
def print_foot(count, row)
if @foot
print_row(@foot, $stdout, count, row)
end
end
def print_serr(count, row)
print_row(@serr, $stderr, count, row)
end
def print_row(templ, ops, count, row)
templ.each do |val|
if val.instance_of?(String)
ops.print val
next
end
if val == :count
ops.print count.to_s
else
v = row[val]
next unless v
if val == :date and @date_format
ops.print v.strftime(@date_format)
else
ops.print v.to_s
end
end
end
end
end
class DetectionProcessor
attr :interval_threshold, true
attr :sequence_threshold, true
attr :notify, true
attr :exc_hosts, true
attr :exc_ua, true
attr :exc_path, true
def initialize(template)
@template = template
@interval_threshold = 3
@sequence_threshold = 8
@exc_hosts = []
@exc_ua = nil
@exc_path = nil
@realtime_notify = false
@pre_access_map = Hash.new
@ops = $stdout
end
def proc(row)
host = row[:host]
return if @exc_hosts.index(host)
return if @exc_ua and @exc_ua.match(row[:ua])
path = row[:path]
if path
path, query = path.split("?")
return if @exc_path and @exc_path.match(path)
end
date_ts = row[:date].to_time.to_i
if @pre_access_map.include?(host)
ts, al = @pre_access_map[host]
if (date_ts - ts) <= @interval_threshold
al.push(row)
@pre_access_map.store(host, [date_ts, al])
if @notify and al.count >= @sequence_threshold
@template.print_serr(al.count, row)
end
else
if al.count >= @sequence_threshold
print_access(host, al)
end
@pre_access_map.store(host, [date_ts, [row]])
end
else
@pre_access_map.store(host, [date_ts, [row]])
end
end
def finalize
@pre_access_map.each_pair do |host, values|
al = values[1]
next if al.count < @sequence_threshold
print_access(host, al)
end
end
def print_access(host, al)
fl = al[0]
@template.print_head(al.count, fl)
al.each do |row|
@template.print_body(row)
end
@template.print_foot(al.count, fl)
end
end
def self.get_opts(argv)
# Settting from Arguments
opts = { :parser => 'combined', :max_interval => 3, :min_seq => 8, :notify => false }
opt = OptionParser.new
opt.on('-ltsv', 'Log type is LTSV') { |v| opts[:parser] = "ltsv" }
opt.on('-n', 'notify when detecting attack') { |v| opts[:notify] = true }
opt.on('-s COUNT', 'Specify minimum sequential count') do |count|
opts[:min_seq] = count.to_i
end
opt.on('-i SECONDS', 'Specify maximum interval seconds') do |sec|
opts[:max_interval] = sec.to_i
end
opt.on('-f CONFFILE',
'Specify configuration file') do |path|
opts[:conf_file] = path
end
opt.parse!(argv)
opts
end
def self.main(argv)
opts = get_opts(argv)
if opts[:parser] == "ltsv"
parser = LtsvLogParser.new
else
parser = CombinedLogParser.new
end
conf = Configuration.new(opts[:conf_file])
template = Template.new(conf.get(:head), conf.get(:body), conf.get(:foot), conf.get(:serr),
conf.get(:date_format))
processor = DetectionProcessor.new(template)
processor.interval_threshold = opts[:max_interval]
processor.sequence_threshold = opts[:min_seq]
processor.notify = opts[:notify]
exc_hosts = conf.get(:exc_hosts)
if exc_hosts
processor.exc_hosts = exc_hosts.split(",")
end
exc_ua = conf.get(:exc_ua_match)
if exc_ua
processor.exc_ua = Regexp.new(exc_ua, Regexp::IGNORECASE)
end
exc_path = conf.get(:exc_path_match)
if exc_path
processor.exc_path = Regexp.new(exc_path)
end
#
# Parsing log line, detect attacks
#
begin
while line = $stdin.gets
File.open("/tmp/filelog", "w+") do |f|
f.write("LINE: #{line}")
end
row = parser.parse(line)
next unless row
processor.proc(row)
end
rescue Interrupt
end
processor.finalize
end
end
case $0
when __FILE__
DetectHttpAttack.main ARGV
end