summaryrefslogtreecommitdiff
path: root/lib/custodian/protocoltest/dnsbl.rb
blob: 7f967683f7b149a1aab4bfdf1c298601b759793b (plain)
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
require 'resolv'




#
#  The DNSBL test.
#
#  This object is instantiated if the parser sees a line such as:
#
###
### 1.2.3.4 must not run dnsbl via zen.spamhaus.org otherwise 'The IP is blacklisted in spamhaus'.
###
#
#

module Custodian

  module ProtocolTest

    class DNSBLTest < TestFactory


      #
      # Save away state from the configuration line.
      #
      def initialize( line )
        @line = line
        @host = line.split( /\s+/)[0]

        #
        # Ensure the host is an IP address.
        #
        raise ArgumentError, "The target must be an IP address" unless( @host =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/ )

        #
        # See which blacklist(s) we're testing against.
        #
        if ( line =~ /via\s+([^\s]+)\s+/ )
          @zones = $1.dup
        else
          @zones = "zen.spamhaus.org"
        end

        #
        # Is this test inverted?
        #
        if ( line =~ /must\s+not\s+run\s+/ )
          @inverted = true
        else
          @inverted = false
        end
      end



      #
      # Allow this test to be serialized.
      #
      def to_s
          @line
      end



      #
      # Run the test.
      #
      # Return "true" on success - if the IP is listed.  False if not.
      #
      def run_test

        # The error is empty.
        @error  = nil

        @zones.split( "," ).each do |zone|

          #
          #  Convert the IP to be looked up.
          #
          #  Given IP 1.2.3.4 we lookup the address of the name
          # 4.3.2.1.$zone
          #
          if ( @host =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/ )

            name = "#{$4}.#{$3}.#{$2}.#{$1}.#{zone}"

            result = Custodian::Util::DNS.hostname_to_ip( name )

            if ( ( !result.nil? ) && ( result.length > 0 ) )
              @error = "IP #{@host} listed in blacklist #{zone}.  Lookup of #{name} lead to result: #{result}"
              return true
            end

          else
             @error = "#{@host} wasn't an IP address"
             return true
          end
        end

        return false
      end


      #
      # If the test failed here we will return a suitable error message.
      #
      def error
        @error
      end

      # register ourselves with the class-factory
      register_test_type "dnsbl"
    end
  end
end