Here is an example i-rule which uses the tables. This irule counts connections on a per source IP basis. You can change it to count referrers instead.
rule connection_counter {
Irule, written by John Alam, Feb 21st, 2011.
This irule counts the connections from a source IP within a time interval. When the number connections
allowed within specified interval is exceeded, a message is logged and the measurement is restarted.
when RULE_INIT {
maxRate is the maximum number of connection an IP address can initiate in windowSecs interval.
set static::maxRate 10
WindowSec is the length of an interval in seconds.
set static::windowSecs 10
}
when CLIENT_ACCEPTED {
set srcip [IP::remote_addr]
set currtime [clock second]
set count [ table lookup -subtable conns $srcip]
if { $count > 0 } {
set count [incr -subtable Conns $srcip]
If frequency is more than ::maxRate send message to log.
Any existing record cannot have been more than windowSecs old.
Count is the number of connections within windowSecs.
if { $count > $static::maxRate } {
set elapsed_secs [expr $static::windowSecs - [table timeout -subtable conns -remaining $srcip]]
log "IP address <$srcip> Connected $count times within $elapsed_secs seconds"
we must delete and start over otherwise every subsequent new connecton will trigger a log message.
table delete -subtable conns $srcip
return
}
} else {
In this clause, either the user is new
or more than ::maxRate connections were established per windowSec and we issued a log message.
Or the lifetime (windowSec) has expired.
We are creating a new record.
table set -subtables conns $srcip 1 $static::windowSecs $static::windowSecs
log "New or refreshed user <$srcip> <$currtime> Connections $count interval remaining [table timeout -subtable conns -remaining $srcip]"
}
}
}