fast_DNS_2

Problem this snippet solves:

This iRule replys to query for "www.f5.com" (offload this query from server) and leave other queries as is.

The 2nd version shows how to add 2 answers - first, we change number of answer section in DNS header to "2" - second, we create another answer resource record (RR)

Code :

#
# LTM DNS offload sample
# This iRule replys to query for "www.f5.com" (offload this query from server) and leave other queries as is.
# It can be applied to DNS security, such as, to filter out invalid/bad domain, etc.
#
when RULE_INIT priority 1 {
    # Domain Name = www f5 com
    set static::domain "www.f5.com"    
    # IP address in answer section (type A)
    set static::answer_string "65.197.145.23 65.61.115.222"
}
when RULE_INIT {
    # Header generation (in hexadecimal)
    # qr(1) opcode(0000) AA(1) TC(0) RD(1) RA(1) Z(000) RCODE(0000)
    set static::header "8580"
    
    # 1 question, X answer, 0 NS, 0 Addition
    set static::answer_record [format %04x [llength $static::answer_string]]
    set static::header "${static::header}0001${static::answer_record}00000000"
    
    # generate domain binary string
    set static::domainhex ""
    foreach static::d [split $static::domain "."] {
        set static::l [string length $static::d]
        scan $static::l %d static::h
        append static::domainhex [format %02x $static::h]
        foreach static::n [split $static::d ""] {
            scan $static::n %c static::h
            append static::domainhex [format %02x $static::h]
        }
    }
    set static::domainbin [binary format H* $static::domainhex]
    append static::domainhex 00

    set static::answerhead $static::domainhex
    # Type = A
    set static::answerhead "${static::answerhead}0001"
    # Class = IN
    set static::answerhead "${static::answerhead}0001"
    # TTL = 1 day
    set static::answerhead "${static::answerhead}00015180"
    # Data length = 4
    set static::answerhead "${static::answerhead}0004"

    set static::answer ""
    foreach static::a $static::answer_string {
        scan $static::a "%d.%d.%d.%d" a b c d
        append static::answer "${static::answerhead}[format %02x%02x%02x%02x $a $b $c $d]"
    }
}
when CLIENT_DATA {
    binary scan [UDP::payload] H4@12A*@12H* id dname question
    set dname [string tolower [getfield $dname \x00 1 ] ]
    
    switch -glob $dname \
        $static::domainbin {
            #log local0. "match"
            set hex ${id}${static::header}${question}${static::answer}
            set payload [binary format H* $hex ]
            # to drop only a packet and keep UDP connection, use UDP::drop
            drop
            UDP::respond $payload
        } \
        default {
            #log local0. "does not match"
        }
}
Published Mar 17, 2015
Version 1.0

Was this article helpful?

No CommentsBe the first to comment