Class: Zonefile

Inherits:
Object
  • Object
show all
Defined in:
lib/zonefile/zonefile.rb

Overview

Ruby Zonefile - Parse and manipulate DNS Zone Files.

Description

This class can read, manipulate and create DNS zone files. It supports A, AAAA, MX, NS, SOA, TXT, CNAME and SRV records. The data can be accessed by the instance method of the same name. All except SOA return an array of hashes containing the named data. SOA directly returns the hash since there can only be one SOA information.

The following hash keys are returned per record type:

  • SOA

    - :ttl, :primary, :email, :serial, :refresh, :retry, :expire, :minimumTTL
    
  • A

    - :name, :ttl, :class, :host
    
  • MX

    - :name, :ttl, :class, :pri, :host
    
  • NS

    - :name, :ttl, :class, :host
    
  • CNAME

    - :name, :ttl, :class, :host
    
  • TXT

    - :name, :ttl, :class, :text
    
  • A4 (AAAA)

    - :name, :ttl, :class, :host
    
  • SRV

    - :name, :ttl, :class, :pri, :weight, :port, :host
    

Examples

Read a Zonefile

zf = Zonefile.from_file('/path/to/zonefile.db')

# Display MX-Records
zf.mx.each do |mx_record|
   puts "Mail Exchagne with priority: #{mx_record[:pri]} --> #{mx_record[:host]}"
end

# Show SOA TTL
puts "Record Time To Live: #{zf.soa[:ttl]}"

# Show A-Records
zf.a.each do |a_record|
   puts "#{a_record[:name]} --> #{a_record[:host]}"
end

Manipulate a Zonefile

zf = Zonefile.from_file('/path/to/zonefile.db')

# Change TTL and add an A-Record

zf.soa[:ttl] = '123123'	# Change the SOA ttl
zf.a << { :class => 'IN', :name => 'www', :host => '192.168.100.1', :ttl => 3600 }  # add A-Record

# Increase Serial Number
zf.new_serial

# Print new zonefile
puts "New Zonefile: \n#{zf.output}"

Author

Martin Boese, based on Simon Flack Perl library DNS::ZoneParse

Constant Summary collapse

RECORDS =
%w{ mx a a4 ns cname txt ptr srv soa }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(zonefile = '', file_name = nil, origin = nil) ⇒ Zonefile

create a new zonefile object by passing the content of the zonefile



97
98
99
100
101
102
103
104
105
106
# File 'lib/zonefile/zonefile.rb', line 97

def initialize(zonefile = '', file_name= nil, origin= nil)
  @data = zonefile
  @filename = file_name
  @origin = origin
 
  @records = {}
  @soa = {}
  RECORDS.each { |r| @records[r.intern] = [] }
  parse
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m) ⇒ Object



76
77
78
79
# File 'lib/zonefile/zonefile.rb', line 76

def method_missing(m)
  return super unless RECORDS.include?(m.to_s)
  @records[m]
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



74
75
76
# File 'lib/zonefile/zonefile.rb', line 74

def data
  @data
end

#recordsObject (readonly)

Returns the value of attribute records.



72
73
74
# File 'lib/zonefile/zonefile.rb', line 72

def records
  @records
end

#soaObject (readonly)

Returns the value of attribute soa.



73
74
75
# File 'lib/zonefile/zonefile.rb', line 73

def soa
  @soa
end

Class Method Details

.from_file(file_name, origin = nil) ⇒ Object

Create a new object by reading the content of a file



109
110
111
# File 'lib/zonefile/zonefile.rb', line 109

def self.from_file(file_name, origin = nil)
   Zonefile.new(File.read(file_name), file_name.split('/').last, origin)
end

.simplify(zf) ⇒ Object

Compact a zonefile content - removes empty lines, comments, converts tabs into spaces etc…



84
85
86
87
88
89
90
91
92
93
# File 'lib/zonefile/zonefile.rb', line 84

def self.simplify(zf)
   # concatenate everything split over multiple lines in parentheses - remove ;-comments in block
   zf = zf.gsub(/(\([^\)]*?\))/) { |m| m.split(/\n/).map { |l| l.gsub(/\;.*$/, '') }.join("\n").gsub(/[\r\n]/, '') }

   zf.split(/\n/).map do |line|
       r = line.gsub(/\t/, ' ')
       r = r.gsub(/\s+/, ' ')
       r = r.gsub(/\;.*$/, '')
   end.delete_if { |line| line.empty? || line[0].chr == ';'}.join("\n")
end

Instance Method Details

#add_record(type, data = {}) ⇒ Object



113
114
115
# File 'lib/zonefile/zonefile.rb', line 113

def add_record(type, data= {})
   @records[type.downcase.intern] << data
end

#new_serialObject

Generates a new serial number in the format of YYYYMMDDII if possible



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/zonefile/zonefile.rb', line 118

def new_serial
  base = "%04d%02d%02d" % [Time.now.year, Time.now.month, Time.now.day ]

  if ((self.soa[:serial].to_i / 100) > base.to_i) then
      ns = self.soa[:serial].to_i + 1
      self.soa[:serial] = ns.to_s
      return ns.to_s
  end
  
  ii = 0
  while (("#{base}%02d" % ii).to_i <= self.soa[:serial].to_i) do
   ii += 1
  end
  self.soa[:serial] = "#{base}%02d" % ii   
end

#outputObject

Build a new nicely formatted Zonefile



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
# File 'lib/zonefile/zonefile.rb', line 219

def output
   out =<<-ENDH
;
;  Database file #{@filename || 'unknown'} for #{@origin || 'unknown'} zone.
;	Zone version: #{self.soa[:serial]}
;
#{self.soa[:ttl] ? "$TTL #{self.soa[:ttl]}" : ''}
#{self.soa[:origin]}		#{self.soa[:ttl]} IN  SOA  #{self.soa[:primary]} #{self.soa[:email]} (
			#{self.soa[:serial]}	; serial number
			#{self.soa[:refresh]}	; refresh
			#{self.soa[:retry]}	; retry
			#{self.soa[:expire]}	; expire
			#{self.soa[:minimumTTL]}	; minimum TTL
			)
; Zone NS Records
ENDH
  self.ns.each do |ns|
    out <<  "#{ns[:name]}	#{ns[:ttl]}	#{ns[:class]}	NS	#{ns[:host]}\n"
  end
  out << "\n; Zone MX Records\n" unless self.mx.empty?
  self.mx.each do |mx|
    out << "#{mx[:name]}	#{mx[:ttl]}	#{mx[:class]}	MX	#{mx[:pri]} #{mx[:host]}\n"
  end
  
  self.a.each do |a|
       out <<  "#{a[:name]}	#{a[:ttl]}	#{a[:class]}	A	#{a[:host]}\n"
  end   
  self.cname.each do |cn|
    out << "#{cn[:name]}	#{cn[:ttl]}	#{cn[:class]}	CNAME	#{cn[:host]}\n"
  end  
  self.a4.each do |a4|
    out << "#{a4[:name]}	#{a4[:ttl]}	#{a4[:class]}	AAAA	#{a4[:host]}\n"
  end
  self.txt.each do |tx|
    out << "#{tx[:name]}	#{tx[:ttl]}	#{tx[:class]}	TXT	\"#{tx[:text]}\"\n"
  end
  self.srv.each do |srv|
    out << "#{srv[:name]}	#{srv[:ttl]}	#{srv[:class]}	SRV	#{srv[:pri]} #{srv[:weight]} #{srv[:port]}	#{srv[:host]}\n"
  end
  
  out
end

#parseObject



210
211
212
213
214
# File 'lib/zonefile/zonefile.rb', line 210

def parse
   Zonefile.simplify(@data).each_line do |line|
       parse_line(line)      
   end
end

#parse_line(line) ⇒ Object



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
# File 'lib/zonefile/zonefile.rb', line 134

def parse_line(line)
   valid_name = /[\@a-z_\-\.0-9\*]+/i
   valid_ip6  = /[\@a-z_\-\.0-9\*:]+/i
   rr_class   = /\b(?:IN|HS|CH)\b/i
   rr_type    = /\b(?:NS|A|CNAME)\b/i
   rr_ttl     = /(?:\d+[wdhms]?)+/i
   ttl_cls    = Regexp.new("(?:(#{rr_ttl})\s)?(?:(#{rr_class})\s)?")

   data = {}
   if line =~ /^(#{valid_name})? \s*
                #{ttl_cls}
                (#{rr_type}) \s
                (#{valid_name})
              /ix then
             (name, ttl, dclass, type, host) = [$1, $2, $3, $4, $5]
            add_record($4, :name => $1, :ttl => $2, :class => $3, :host => $5)
   elsif line=~/^(#{valid_name})? \s*
               #{ttl_cls}
               AAAA \s
               (#{valid_ip6})               
               /x then
             add_record('a4', :name => $1, :ttl => $2, :class => $3, :host => $4)
   elsif line=~/^(#{valid_name})? \s*
                #{ttl_cls}
                MX \s
                (\d+) \s
                (#{valid_name})
              /ix then
              add_record('mx', :name => $1, :ttl => $2, :class => $3, :pri => $4.to_i, :host => $5)
   elsif line=~/^(#{valid_name})? \s*
                #{ttl_cls}
                SRV \s
                (\d+) \s
                (\d+) \s
                (\d+) \s
                (#{valid_name})
              /ix
       add_record('srv', :name => $1, :ttl => $2, :class => $3, :pri => $4, :weight => $5,
                         :port => $6, :host => $7)
   elsif line=~/^(#{valid_name}) \s+
                #{ttl_cls}
                SOA \s+
                (#{valid_name}) \s+
                (#{valid_name}) \s*
                \(?\s*
                    (#{rr_ttl}) \s+
                    (#{rr_ttl}) \s+
                    (#{rr_ttl}) \s+
                    (#{rr_ttl}) \s+
                    (#{rr_ttl}) \s*
                \)?
              /ix
           ttl = @soa[:ttl] || $2 || ''
           @soa[:origin] = $1
           @soa[:ttl] = ttl
           @soa[:primary] = $4
           @soa[:email] = $5
           @soa[:serial] = $6
           @soa[:refresh] = $7
           @soa[:retry] = $8
           @soa[:expire] = $9
           @soa[:minimumTTL] = $10

   elsif line=~ /^(#{valid_name})? \s*
               #{ttl_cls}
               PTR \s+
               (#{valid_name})
              /ix
           add_record('ptr', :name => $1, :class => $3, :ttl => $2, :host => $4)
   elsif line =~ /(#{valid_name})? \s #{ttl_cls} TXT \s \"([^\"]*)\"/ix
           add_record('txt', :name => $1, :ttl => $2, :class => $3, :text => $4)
   elsif line =~ /\$TTL\s+(#{rr_ttl})/i 
           @soa[:ttl] = $1
   end
end