Commit 02cdb61a authored by Ad Schellevis's avatar Ad Schellevis

refacor unboundctlwrapper to python, closes https://github.com/opnsense/core/issues/1505

parent 1a16bfba
#!/usr/local/bin/ruby
=begin
Copyright (C) 2017 Fabian Franz
*
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
*
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
*
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE
=end
require 'json'
require 'optparse'
supported_formats = %w{json}
options = {format: 'json'}
OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} command"
opts.on("-c", "--cache", "Dump cache") do |c|
options[:dump_cache] = c
end
opts.on("-i", "--infra", "Dump infrastructure cache") do |c|
options[:dump_infra] = c
end
opts.on("-f", "--format FORMAT") do |format|
if supported_formats.include? format
options[:format] = format
else
puts "the specified format is not valid"
exit
end
end
opts.on("-s", "--stats") do |stats|
options[:stats] = stats
end
opts.on("-l", "--list-local-zones", "List local Zones") do |llz|
options[:llz] = llz
end
opts.on("-I", "--list-insecure", "List Domain-Insecure Zones") do |i|
options[:insecure] = i
end
opts.on("-d", "--list-local-data", "List local data") do |i|
options[:lld] = i
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
def dump_cache
raw = `unbound-control -c /var/unbound/remotecontrol.conf dump_cache`.split("\n")
raw = raw.select {|x| (x.include? "IN") && (x[0] != ";") && !(x.start_with? "msg ") }
raw.map do |line|
host,ttl, type, rrtype, value = line.scan(/^(\S+)\s+(?:([\d]*)\s+)?(IN)\s+(\S+)\s+(.*)$/).first
{host: host, ttl: ttl, type: type, rrtype: rrtype, value: value}
end
end
def stats
raw = `unbound-control -c /var/unbound/remotecontrol.conf stats`.split("\n")
data = {}
raw.each do |line|
key,value = line.split("=")
key_parts = key.split(".")
if key_parts[0] == 'histogram'
data['histogram'] = [] unless data['histogram']
data['histogram'] << {from: key_parts[1..2].map(&:to_i),
to: key_parts[4..5].map(&:to_i),
value: value.to_i}
else
key = key_parts.pop
origin = data
key_parts.each do |kp|
unless origin[kp]
origin[kp] = {}
end
origin = origin[kp]
end
origin[key] = value.to_i
end
end
data
end
def dump_infra
raw = `unbound-control -c /var/unbound/remotecontrol.conf dump_infra`.split("\n")
raw.map do |line|
elements = line.split(/\s+/)
data = {}
data['ip'] = elements.shift
data['host'] = elements.shift
while elements.count > 2
key = elements.shift
if key == 'lame'
data['lame'] = true
next
end
tmp = elements.shift
data[key] = tmp =~ /^\d+$/ ? tmp.to_i : tmp
end
data
end
end
def insecure
`unbound-control -c /var/unbound/remotecontrol.conf list_insecure`.split("\n")
end
def list_local_zones
raw = `unbound-control -c /var/unbound/remotecontrol.conf list_local_zones`.split("\n")
raw.map do |line|
z, t = line.split(/\s+/)
{zone: z, type: t}
end
end
def list_local_data
raw = `unbound-control -c /var/unbound/remotecontrol.conf list_local_data`.split("\n")
result = []
raw.map do |line|
line.strip!
next if line.length < 10 # not a valid entry
name, ttl, type, rrtype, value = line.split(/\s+/,5)
{name: name, ttl: ttl, type: type, rrtype: rrtype, value: value}
end.select {|x| x }
end
output = nil
if options[:dump_cache]
output = dump_cache
end
if options[:dump_infra]
output = dump_infra
end
if options[:stats]
output = stats
end
if options[:insecure]
output = insecure
end
if options[:llz]
output = list_local_zones
end
if options[:lld]
output = list_local_data
end
puts case options[:format]
when 'json'; then
output.to_json
end
#!/usr/local/bin/python2.7
"""
Copyright (c) 2017 Ad Schellevis
Copyright (C) 2017 Fabian Franz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import os
import sys
import re
import tempfile
import subprocess
import argparse
import json
def unbound_control_reader(action):
with tempfile.NamedTemporaryFile() as output_stream:
subprocess.call(['/usr/sbin/unbound-control', '-c', '/var/unbound/remotecontrol.conf', action],
stdout=output_stream, stderr=open(os.devnull, 'wb'))
output_stream.seek(0)
for line in output_stream:
yield line
# parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--cache', help='Dump cache', action="store_true", default=False)
parser.add_argument('-i', '--infra', help='Dump infrastructure cache', action="store_true", default=False)
parser.add_argument('-s', '--stats', help='Dump stats', action="store_true", default=False)
parser.add_argument('-l', '--list-local-zones', help='List local Zones', action="store_true", default=False)
parser.add_argument('-I', '--list-insecure', help='List Domain-Insecure Zones', action="store_true", default=False)
parser.add_argument('-d', '--list-local-data', help='List local data', action="store_true", default=False)
parser.add_argument('-f', '--format', help='output format', action='store', choices=['json'], default='json')
args = parser.parse_args()
#
output = None
if args.cache:
output = list()
for line in unbound_control_reader('dump_cache'):
parts = re.split('^(\S+)\s+(?:([\d]*)\s+)?(IN)\s+(\S+)\s+(.*)$', line)
if line.find('IN') > -1 and not line.startswith('msg') and len(parts) > 5:
output.append({'host': parts[1], 'ttl': parts[2], 'type': parts[3], 'rrtype': parts[4], 'value': parts[5]})
elif args.infra:
output = list()
for line in unbound_control_reader('dump_infra'):
parts = line.split()
if len(parts) > 2:
record = {'ip': parts.pop(0), 'host': parts.pop(0)}
while len(parts) > 0:
key = parts.pop(0)
if key == 'lame':
record['lame'] = True
continue
record[key] = parts.pop(0)
output.append(record)
elif args.stats:
output = dict()
for line in unbound_control_reader('stats'):
full_key, value = line.split('=')
keys = full_key.split('.')
if keys[0] == 'histogram':
if 'histogram' not in output:
output['histogram'] = list()
output['histogram'].append({
'from': (int(keys[1]), int(keys[2])),
'to': (int(keys[4]), int(keys[5])),
'value': value.strip()
})
else:
ptr = output
while len(keys) > 0 :
key = keys.pop(0)
if len(keys) == 0:
ptr[key] = value.strip()
elif key not in ptr:
ptr[key] = dict()
ptr = ptr[key]
elif args.list_local_zones:
output = list()
for line in unbound_control_reader('list_local_zones'):
parts = line.split()
if len(parts) >= 2:
output.append({'zone': parts[0], 'type': parts[1]})
elif args.list_insecure:
output = list()
for line in unbound_control_reader('list_insecure'):
output.append(line)
elif args.list_local_data:
output = list()
for line in unbound_control_reader('list_local_data'):
parts = line.split()
if len(parts) >= 5:
output.append({'name': parts[0], 'ttl': parts[1], 'type': parts[2], 'rrtype': parts[3], 'value': parts[4]})
else:
parser.print_help()
sys.exit(1)
# flush output
if args.format == 'json':
print (json.dumps(output))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment