#!/usr/bin/ruby $LOAD_PATH << File.expand_path(File.dirname(__FILE__)) require 'iptables' require 'time' require 'rubygems' require_gem 'activerecord' # config section dbuser = 'user' dbpass = 'pass' dbhost = 'localhost' database = 'iptablelog' mysqlsocket = '/path/to/socket' # end config # Active Record config ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => dbhost, :username => dbuser, :password => dbpass, :database => database, :socket => mysqlsocket ) class IPTableLog < ActiveRecord::Base set_table_name 'log' end # end active record config begin while line = gets # get rid of some syslog-ng stuff line = line[3..-1] tmp = Hash.new pieces = line.split month = pieces.shift day = pieces.shift hour, min, sec = pieces.shift.split(':') tmp['host'] = pieces.shift tmp['logtime'] = Time.gm(Time.now.year,month,day,hour,min,sec).to_i #next if (IPTableLog.count(["logtime = ? and line = ?", tmp['logtime'], line.strip]) > 0) ipinfo = IPTables.parse(line, 1) tmp['chain'] = ipinfo['chain'] tmp['mac'] = ipinfo['mac'] tmp['in_int'] = ipinfo['in_int'] tmp['out_int'] = ipinfo['out_int'] tmp['line'] = ipinfo['line'] tmp['src'] = ipinfo['ip']['src'] tmp['dst'] = ipinfo['ip']['dst'] tmp['len'] = ipinfo['ip']['len'] tmp['tos'] = ipinfo['ip']['tos'] tmp['prec'] = ipinfo['ip']['prec'] tmp['ttl'] = ipinfo['ip']['ttl'] tmp['ip_id'] = ipinfo['ip']['id'] tmp['fragment_flags'] = ipinfo['ip']['fragment_flags'].join(' ') tmp['type'] = ipinfo['ip']['type'] if (tmp['type'] != 'icmp') tmp['spt'] = ipinfo['ip'][tmp['type']]['spt'] tmp['dpt'] = ipinfo['ip'][tmp['type']]['dpt'] if (tmp['type'] == 'tcp') tmp['window'] = ipinfo['ip']['tcp']['window'] tmp['res'] = ipinfo['ip']['tcp']['res'] tmp['flags'] = ipinfo['ip']['tcp']['flags'].join(' ') tmp['urgp'] = ipinfo['ip']['tcp']['urgp'] else tmp['udp_len'] = ipinfo['ip']['udp']['len'] end else tmp['icmp_type'] = ipinfo['ip']['icmp']['type'] tmp['icmp_code'] = ipinfo['ip']['icmp']['code'] tmp['icmp_error_header'] = ipinfo['ip']['icmp']['error_header'] tmp['icmp_id'] = ipinfo['ip']['icmp']['id'] tmp['icmp_seq'] = ipinfo['ip']['icmp']['seq'] end #print "#{tmp['line']}\n" IPTableLog.create(tmp) end rescue f = File.open("/var/log/iptablelog.log",'a') f.write(Time.now) f.write(": ") f.write($!) f.write(" -> #{line}\n\n") f.close end