a fairly big rewrite of add/delete record that actually works!

This commit is contained in:
Jeffrey Forman 2012-10-27 18:03:45 -04:00
parent 00b22acba7
commit 4565e93d93
8 changed files with 217 additions and 136 deletions

View File

@ -1,6 +1,6 @@
from django import forms from django import forms
from bcommon.models import BindServer, Key from bcommon.models import Key
RECORD_TYPE_CHOICES = (("A", "A"), ("AAAA", "AAAA"), ("CNAME", "CNAME")) RECORD_TYPE_CHOICES = (("A", "A"), ("AAAA", "AAAA"), ("CNAME", "CNAME"))
TTL_CHOICES = ((300, "5 minutes"), TTL_CHOICES = ((300, "5 minutes"),
@ -10,13 +10,14 @@ TTL_CHOICES = ((300, "5 minutes"),
(86400, "1 day")) (86400, "1 day"))
class FormAddRecord(forms.Form): class FormAddRecord(forms.Form):
dns_server = forms.CharField(max_length=100, label="Hostname of DNS Server", widget=forms.TextInput(attrs={'readonly':'readonly'})) dns_server = forms.CharField(max_length=100)
name = forms.CharField(max_length=100, label="Record Name (FQDN)") record_name = forms.RegexField(max_length=100, regex="^[a-zA-Z0-9-_]+$", required=False)
record_type = forms.ChoiceField(choices=RECORD_TYPE_CHOICES, label="Record Type") record_type = forms.CharField(max_length=10)
ttl = forms.ChoiceField(choices=TTL_CHOICES, label="TTL", initial=86400) zone_name = forms.CharField(max_length=100)
create_reverse = forms.BooleanField(label="Create Reverse Record (PTR)?", required=False) record_data = forms.GenericIPAddressField()
data = forms.CharField(max_length=256, label="Record Data (IP/Hostname)") ttl = forms.IntegerField(min_value=1)
key_name = forms.ModelChoiceField(queryset=Key.objects.all(), empty_label=None, label="TSIG Key", required=False) create_reverse = forms.BooleanField(required=False)
key_name = forms.ModelChoiceField(queryset=Key.objects.all(), empty_label=None, required=False)
class FormAddCnameRecord(forms.Form): class FormAddCnameRecord(forms.Form):

View File

@ -5,8 +5,13 @@ import dns.query
import dns.reversename import dns.reversename
import dns.update import dns.update
import keyutils
re_IPADDRESS = re.compile(r"\d+.\d+.\d+.\d+") re_IPADDRESS = re.compile(r"\d+.\d+.\d+.\d+")
class BinderException(Exception):
pass
def list_zone_records(dns_server, zone_name): def list_zone_records(dns_server, zone_name):
"""Take a DNS server and a zone name, """Take a DNS server and a zone name,
and return an array of its records.""" and return an array of its records."""
@ -34,39 +39,29 @@ def list_zone_records(dns_server, zone_name):
'rr_data' : split_record.split(" ")[4]}) 'rr_data' : split_record.split(" ")[4]})
return record_array return record_array
def add_forward_record(form_data, zone_keyring): def add_forward_record(dns_server, zone_name, record_name, record_type, record_data, ttl, keyring):
"""Take in data from FormAddRecord and a keyring object, """Take in data from FormAddRecord and a keyring object,
return a response from the DNS server about adding the record.""" return a response from the DNS server about adding the record."""
re_form_data = re.search(r"(\w+).(.*)", form_data["name"]) dns_update = dns.update.Update(zone_name, keyring = keyring)
hostname = re_form_data.group(1) dns_update.replace(record_name, ttl, record_type, record_data)
domain = re_form_data.group(2)
dns_update = dns.update.Update(domain, keyring = zone_keyring)
if str(form_data["record_type"]) == "CNAME":
data_suffix = "."
else:
data_suffix = ""
dns_update.replace(hostname, int(form_data["ttl"]), str(form_data["record_type"]), str(form_data["data"]) + data_suffix)
try: try:
response = dns.query.tcp(dns_update, form_data["dns_server"]) response = dns.query.tcp(dns_update, dns_server)
except dns.tsig.BadPeerKey: except dns.tsig.BadPeerKey:
raise Exception("There was a problem adding your forward record due to a TSIG key issue.") raise BinderException("There was a problem adding your forward record due to a TSIG key issue.")
return response return response
def add_reverse_record(form_data, zone_keyring): def add_reverse_record(dns_server, zone_name, record_name, record_data, ttl, keyring):
""" Given a FormAddRecord dict and zone_keyring, """ Given passed arguments, add/update a reverse PTR record."""
add/update a reverse PTR record.""" reverse_ip_fqdn = str(dns.reversename.from_address(record_data))
reverse_ip_fqdn = str(dns.reversename.from_address(form_data["data"]))
reverse_ip = re.search(r"([0-9]+).(.*).$", reverse_ip_fqdn).group(1) reverse_ip = re.search(r"([0-9]+).(.*).$", reverse_ip_fqdn).group(1)
reverse_domain = re.search(r"([0-9]+).(.*).$", reverse_ip_fqdn).group(2) reverse_domain = re.search(r"([0-9]+).(.*).$", reverse_ip_fqdn).group(2)
dns_update = dns.update.Update(reverse_domain, keyring = zone_keyring) dns_update = dns.update.Update(reverse_domain, keyring = keyring)
dns_update.replace(reverse_ip, int(form_data["ttl"]), "PTR", str(form_data["name"]) + ".") dns_update.replace(reverse_ip, ttl, "PTR", "%s.%s." % (record_name, zone_name))
output = dns.query.tcp(dns_update, form_data["dns_server"]) output = dns.query.tcp(dns_update, dns_server)
return output return output
@ -75,23 +70,50 @@ def add_record(form_data):
If a reverse PTR record is requested, this will be added too.""" If a reverse PTR record is requested, this will be added too."""
if form_data["key_name"]: if form_data["key_name"]:
keyring = create_keyring(form_data["key_name"]) keyring = keyutils.create_keyring(form_data["key_name"])
else: else:
keyring = None keyring = None
response = {} response = []
forward_response = add_forward_record(form_data, keyring) response.append({ "type" : "Forward Record: %s.%s" % (str(form_data["record_name"]),
response["forward_response"] = forward_response str(form_data["zone_name"])),
"output" : add_forward_record(str(form_data["dns_server"]),
str(form_data["zone_name"]),
str(form_data["record_name"]),
str(form_data["record_type"]),
str(form_data["record_data"]),
form_data["ttl"],
keyring)})
if form_data["create_reverse"]: if form_data["create_reverse"]:
reverse_response = add_reverse_record(form_data, keyring) response.append({ "type" : "Reverse Record: %s" % form_data["record_data"],
response["reverse_response"] = reverse_response "output" : add_reverse_record(str(form_data["dns_server"]),
str(form_data["zone_name"]),
str(form_data["record_name"]),
str(form_data["record_data"]),
form_data["ttl"],
keyring)})
return response
def add_cname_record(dns_server, zone_name, originating_record, cname, ttl, key_name):
"""Add a Cname record."""
if key_name is None:
keyring = create_keyring(key_name)
else:
keyring = None
update = dns.update.Update(zone_name, keyring = keyring)
update.replace(cname, int(ttl), 'CNAME', originating_record + ".")
response = dns.query.tcp(update, dns_server)
return response return response
def delete_record(form_data, rr_items): def delete_record(form_data, rr_items):
"""Delete a list of DNS records passed as strings in rr_items.""" """Delete a list of DNS records passed as strings in rr_items."""
if ("key_name" in form_data and form_data["key_name"]):
if form_data["key_name"]:
keyring = create_keyring(form_data["key_name"]) keyring = create_keyring(form_data["key_name"])
else: else:
keyring = None keyring = None
@ -102,7 +124,6 @@ def delete_record(form_data, rr_items):
re_record = re.search(r"(\w+)\.(.*)$", current_rr_item) re_record = re.search(r"(\w+)\.(.*)$", current_rr_item)
record = re_record.group(1) record = re_record.group(1)
domain = re_record.group(2) domain = re_record.group(2)
dns_update = dns.update.Update(domain, keyring = keyring) dns_update = dns.update.Update(domain, keyring = keyring)
dns_update.delete(record) dns_update.delete(record)
output = dns.query.tcp(dns_update, dns_server) output = dns.query.tcp(dns_update, dns_server)

View File

@ -2,7 +2,7 @@
from bcommon.models import BindServer, Key from bcommon.models import BindServer, Key
from django.template import Context from django.template import Context
from django.shortcuts import render_to_response, redirect from django.shortcuts import render_to_response, redirect, render
from bcommon.helpers import add_record, delete_record, add_cname_record from bcommon.helpers import add_record, delete_record, add_cname_record
from bcommon.forms import FormAddRecord, FormAddCnameRecord from bcommon.forms import FormAddRecord, FormAddCnameRecord
@ -49,6 +49,7 @@ def view_zone_records(request, dns_server, zone_name):
this_server = BindServer.objects.get(hostname=dns_server) this_server = BindServer.objects.get(hostname=dns_server)
zone_array = this_server.list_zone_records(zone_name) zone_array = this_server.list_zone_records(zone_name)
except Exception, err: except Exception, err:
# TODO: Use a custom exception here.
return render_to_response('bcommon/list_zone.htm', return render_to_response('bcommon/list_zone.htm',
{ 'errors' : err}, { 'errors' : err},
context_instance=RequestContext(request)) context_instance=RequestContext(request))
@ -59,41 +60,35 @@ def view_zone_records(request, dns_server, zone_name):
'zone_name' : zone_name}, 'zone_name' : zone_name},
context_instance=RequestContext(request)) context_instance=RequestContext(request))
def view_add_record(request, dns_server, zone): def view_add_record(request, dns_server, zone_name):
""" View to provide form to add a DNS record. """ """ View to provide form to add a DNS record. """
form = FormAddRecord(initial={ 'dns_server' : dns_server, return render(request, 'bcommon/add_record_form.htm',
'zone' : zone }) { "dns_server" : dns_server,
return render_to_response('bcommon/add_record_form.htm', "zone_name" : zone_name })
{ 'form' : form },
context_instance=RequestContext(request))
def view_add_record_result(request): def view_add_record_result(request):
""" Process the input given to add a DNS record. """ """ Process the input given to add a DNS record. """
errors = None
if request.method == "GET": if request.method == "GET":
# Return home. You shouldn't be accessing this url via a GET.
return redirect('/') return redirect('/')
form = FormAddRecord(request.POST) form = FormAddRecord(request.POST)
if form.is_valid(): if form.is_valid():
cd = form.cleaned_data cd = form.cleaned_data
else:
form = FormAddRecord(request.POST)
return render_to_response('bcommon/add_record_form.htm',
{ 'form' : form },
context_instance=RequestContext(request))
try: try:
add_record_response = add_record(cd) add_record_response = add_record(cd)
except Exception, err: except BinderException, errors:
pass
return render_to_response('bcommon/add_record_result.htm', return render_to_response('bcommon/add_record_result.htm',
{ "errors" : err }, { "errors" : errors,
context_instance=RequestContext(request)) "response" : add_record_response },
return render_to_response('bcommon/add_record_result.htm',
{ 'response' : add_record_response,
'rr_data' : cd },
context_instance=RequestContext(request)) context_instance=RequestContext(request))
return render(request, 'bcommon/add_record_form.htm',
{ "dns_server" : request.POST["dns_server"],
"zone_name" : request.POST["zone_name"],
"form_errors" : form.errors,
"form_data" : request.POST })
def view_add_cname_record(request, dns_server, zone_name, record_name): def view_add_cname_record(request, dns_server, zone_name, record_name):
""" Process given input to add a CNAME pointer.""" """ Process given input to add a CNAME pointer."""
@ -172,7 +167,6 @@ def view_delete_result(request):
{ "errors" : err }, { "errors" : err },
context_instance=RequestContext(request)) context_instance=RequestContext(request))
return render_to_response('bcommon/delete_record_result.htm', return render_to_response('bcommon/delete_record_result.htm',
{ 'delete_result' : delete_result }, { 'delete_result' : delete_result },
context_instance=RequestContext(request)) context_instance=RequestContext(request))

View File

@ -9,35 +9,33 @@
<div class="row-fluid"> <div class="row-fluid">
<div class="span2"> <div class="span2">
{% block navigation %} {% block navigation %}
<ul class="nav nav-list"> <ul class="nav nav-list">
<li class="nav-header">Actions</li> <li class="nav-header">Actions</li>
<li><a href="/">Home</a></li> <li><a href="/">Home</a></li>
<li><a href="/info">Server List</a></li> <li><a href="/server_list">Server List</a></li>
</ul> </ul>
{% endblock navigation %} {% endblock navigation %}
</div> </div>
<div class="span10"> <div class="span10">
<body>
<body>
<script src="http://code.jquery.com/jquery.js"></script> <script src="http://code.jquery.com/jquery.js"></script>
<script src="/files/static/bootstrap/js/bootstrap.min.js"></script> <script src="/files/static/bootstrap/js/bootstrap.min.js"></script>
<div class="navbar"> <div class="navbar">
<div class="navbar-inner"> <div class="navbar-inner">
<a class="brand" href="#"> <a class="brand" href="#">
{% block pageheader %} {% block pageheader %}
{% endblock pageheader %} {% endblock pageheader %}
</a> </a>
</div> </div>
</div> </div>
{% block errors %} {% block errors %}
{% if errors %} {% if errors %}
<div class="alert alert-error"> <div class="alert alert-error">
Errors were encountered: Errors were encountered:
<br> <br>
@ -46,16 +44,16 @@
{{ error_context }} {{ error_context }}
{% endif %} {% endif %}
</div> </div>
{% endif %} {% endif %}
{% endblock errors %} {% endblock errors %}
{% block body %} {% block body %}
{% endblock body %} {% endblock body %}
</body> </body>
</div>
</div>
</div>
</div>
{% block footer %} {% block footer %}
{% endblock footer %} {% endblock footer %}
</html> </html>

View File

@ -1,15 +1,91 @@
{% extends "base.htm" %} {% extends "base.htm" %}
{% block pageheader %} {% block pageheader %}
Add record in {{ dns_server }} Add record in {{ zone_name }}
{% endblock pageheader %} {% endblock pageheader %}
{% block body %} {% block body %}
<form action="/add_record/result/" method="post">{% csrf_token %} <form class="form-horizontal" action="/add_record/result/" method="post">{% csrf_token %}
<table class="table"> <legend>Create Foward Record</legend>
{{ form.as_table }} <input type="hidden" name="zone_name" value="{{zone_name}}"/>
</table>
<input type="submit" value="Submit" />
<div class="control-group">
<label class="control-label">DNS Server: </label>
<div class="controls">
<span class="input-xlarge uneditable-input">{{dns_server}}</span>
<input type="hidden" name="dns_server" value="{{dns_server}}"/>
</div>
</div>
<div class="control-group">
<label class="control-label">Record Name: </label>
<div class="controls">
<div class="input-append">
<input class="span2" size="100" name="record_name" type="text"/><span class="add-on">.{{zone_name}}</span>
</div>
{% if form_errors.record_name %}
<div class="alert alert-error">
Record Name: {{ form_errors.record_name|stringformat:"s"|striptags }} Previous Value: {{ form_data.record_name }}
</div>
{% endif %}
</div>
</div>
<div class="control-group">
<label class="control-label">Record Type: </label>
<div class="controls">
<select name="record_type">
<option value="A" selected="selected">A</option>
<option value="AAAA">AAAA</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Record Data: </label>
<div class="controls">
<div class="input-append">
<input class="input-large" size="100" name="record_data" type="text"/>
</div>
{% if form_errors.record_data %}
<div class="alert alert-error">
Record Name: {{ form_errors.record_data|stringformat:"s"|striptags }} Previous Value: {{ form_data.record_data }}
</div>
{% endif %}
</div>
</div>
<div class="control-group">
<label class="control-label">TTL: </label>
<div class="controls">
<select name="ttl">
<option value="86400">86400 (1 day)</option>
</select>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="create_reverse" value="True">Create Reverse Record
</label>
</div>
</div>
<div class="control-group">
<label class="control-label">TSIG Key: </label>
<div class="controls">
<select name="key_name">
<option selected="selected" value=""/>
{% for key in tsig_keys %}
<option value="{{key}}">{{key}}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn">Save Changes</button>
</form> </form>
{% endblock body %} {% endblock body %}

View File

@ -7,24 +7,15 @@ Add Record Result
{% block body %} {% block body %}
<table class="table"> <table class="table">
{% if response.forward_response %} {% for current_response in response %}
<tr> <tr>
<th>Record: {{ response.name }}</th> <th>Record:</th>
<th>Add Result</th> <th>Output</th>
</tr> </tr>
<tr> <tr>
<td>Forward: {{ rr_data.name }}</td> <td>{{ current_response.type }}</td>
<td><pre>{{ response.forward_response }}</pre></td> <td><pre>{{ current_response.output }}</pre></td>
</tr> </tr>
{% endif %} {% endfor %}
{% if response.reverse_response %}
<tr>
<td>Reverse: {{ rr_data.data }}</td>
<td><pre>{{ response.reverse_response }}</pre></td>
</tr>
{% endif %}
</table> </table>
{% endblock body %} {% endblock body %}

View File

@ -31,6 +31,7 @@ Delete record(s) in {{ zone_name }}
<tr> <tr>
<td>Key</td> <td>Key</td>
<td> <select name="key_name"> <td> <select name="key_name">
<option selected="selected" value=""/>
{% for current_key in tsig_keys %} {% for current_key in tsig_keys %}
<option value="{{current_key}}">{{current_key}}</option> <option value="{{current_key}}">{{current_key}}</option>
{% endfor %}</td> {% endfor %}</td>

View File

@ -7,21 +7,20 @@ admin.autodiscover()
urlpatterns = patterns('', urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)), (r'^admin/', include(admin.site.urls)),
(r'^$', 'bcommon.views.home_index'), url(r'^$', 'bcommon.views.home_index', name="index"),
(r'^info/$', 'bcommon.views.view_server_list'), url(r'^server_list/$', 'bcommon.views.view_server_list', name="server_list"),
(r'^info/(?P<dns_server>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_server_zones'), url(r'^info/(?P<dns_server>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_server_zones', name="server_zones"),
(r'^info/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone_name>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_zone_records'), url(r'^info/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone_name>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_zone_records', name="zone_records"),
(r'^add_record/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_add_record'), url(r'^add_record/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone_name>[a-zA-Z0-9.-]+)/$', 'bcommon.views.view_add_record', name="add_record"),
(r'^add_record/result/$', 'bcommon.views.view_add_record_result'), url(r'^add_record/result/$', 'bcommon.views.view_add_record_result'),
(r'^delete_record/$', 'bcommon.views.view_delete_record'), url(r'^delete_record/$', 'bcommon.views.view_delete_record', name="delete_record"),
(r'^delete_record/result/$', 'bcommon.views.view_delete_result'), url(r'^delete_record/result/$', 'bcommon.views.view_delete_result'),
(r'^add_cname/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone_name>[a-zA-Z0-9.-]+)/(?P<record_name>[a-zA-Z0-9-]+)/$', 'bcommon.views.view_add_cname_record'),
(r'^add_cname_record/result/$', 'bcommon.views.view_add_cname_result'),
url(r'^add_cname/(?P<dns_server>[a-zA-Z0-9.-]+)/(?P<zone_name>[a-zA-Z0-9.-]+)/(?P<record_name>[a-zA-Z0-9-]+)/$', 'bcommon.views.view_add_cname_record'),
url(r'^add_cname_record/result/$', 'bcommon.views.view_add_cname_result'),
) )
if settings.DEBUG: if settings.DEBUG: