# dns/trunk/DNSDB.pm # Abstraction functions for DNS administration ### # SVN revision info # $Date: 2012-02-09 19:43:08 +0000 (Thu, 09 Feb 2012) $ # SVN revision $Rev: 230 $ # Last update by $Author: kdeugau $ ### # Copyright (C) 2008-2011 - Kris Deugau package DNSDB; use strict; use warnings; use Exporter; use DBI; use Net::DNS; use Crypt::PasswdMD5; use Net::SMTP; use NetAddr::IP qw(:lower); use POSIX; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 0.1; ##VERSION## @ISA = qw(Exporter); @EXPORT_OK = qw( &initGlobals &initPermissions &getPermissions &changePermissions &comparePermissions &changeGroup &loadConfig &connectDB &finish &addDomain &delDomain &domainName &domainID &addGroup &delGroup &getChildren &groupName &addUser &updateUser &delUser &userFullName &userStatus &getUserData &getSOA &getRecLine &getDomRecs &getRecCount &addRec &updateRec &delRec &getTypelist &getParents &isParent &domStatus &importAXFR &export &mailNotify %typemap %reverse_typemap %config %permissions @permtypes $permlist ); @EXPORT = (); # Export nothing by default. %EXPORT_TAGS = ( ALL => [qw( &initGlobals &initPermissions &getPermissions &changePermissions &comparePermissions &changeGroup &loadConfig &connectDB &finish &addDomain &delDomain &domainName &domainID &addGroup &delGroup &getChildren &groupName &addUser &updateUser &delUser &userFullName &userStatus &getUserData &getSOA &getRecLine &getDomRecs &getRecCount &addRec &updateRec &delRec &getTypelist &getParents &isParent &domStatus &importAXFR &export &mailNotify %typemap %reverse_typemap %config %permissions @permtypes $permlist )] ); our $group = 1; our $errstr = ''; # Halfway sane defaults for SOA, TTL, etc. # serial defaults to 0 for convenience. # value will be either YYYYMMDDNN for BIND/etc, or auto-internal for tinydns our %def = qw ( contact hostmaster.DOMAIN prins ns1.myserver.com serial 0 soattl 86400 refresh 10800 retry 3600 expire 604800 minttl 10800 ttl 10800 ); # Arguably defined wholly in the db, but little reason to change without supporting code changes our @permtypes = qw ( group_edit group_create group_delete user_edit user_create user_delete domain_edit domain_create domain_delete record_edit record_create record_delete self_edit admin ); our $permlist = join(',',@permtypes); # DNS record type map and reverse map. # loaded from the database, from http://www.iana.org/assignments/dns-parameters our %typemap; our %reverse_typemap; our %permissions; # Prepopulate a basic config. Note some of these *will* cause errors if left unset. # note: add appropriate stanzas in loadConfig to parse these our %config = ( # Database connection info dbname => 'dnsdb', dbuser => 'dnsdb', dbpass => 'secret', dbhost => '', # Email notice settings mailhost => 'smtp.example.com', mailnotify => 'dnsdb@example.com', # to mailsender => 'dnsdb@example.com', # from mailname => 'DNS Administration', orgname => 'Example Corp', domain => 'example.com', # Template directory templatedir => 'templates/', # fmeh. this is a real web path, not a logical internal one. hm.. # cssdir => 'templates/', sessiondir => 'session/', # Session params timeout => '3600', # 1 hour default # Other miscellanea log_failures => 1, # log all evarthing by default perpage => 15, ); ## (Semi)private variables # Hash of functions for validating record types. Filled in initGlobals() since # it relies on visibility flags from the rectypes table in the DB my %validators; ## ## utility functions # _rectable() # Takes default+rdns flags, returns appropriate table name sub _rectable { my $def = shift; my $rev = shift; return 'records' if $def ne 'y'; return 'default_records' if $rev ne 'y'; return 'default_rev_records'; } # end _rectable() # _recparent() # Takes default+rdns flags, returns appropriate parent-id column name sub _recparent { my $def = shift; my $rev = shift; return 'group_id' if $def eq 'y'; return 'rdns_id' if $rev eq 'y'; return 'domain_id'; } # end _recparent() # Check an IP to be added in a reverse zone to see if it's really in the requested parent. # Takes a database handle, default and reverse flags, IP (fragment) to check, parent zone ID, # and a reference to a NetAddr::IP object (also used to pass back a fully-reconstructed IP for # database insertion) sub _ipparent { my $dbh = shift; my $defrec = shift; my $revrec = shift; my $val = shift; my $id = shift; my $addr = shift; # subsub to split, reverse, and overlay an IP fragment on a netblock sub __rev_overlay { my $splitme = shift; # ':' or '.', m'lud? my $parnet = shift; my $val = shift; my $addr = shift; my $joinme = $splitme; $splitme = '\.' if $splitme eq '.'; my @working = reverse(split($splitme, $parnet->addr)) or warn $!; my @parts = reverse(split($splitme, $val)); for (my $i = 0; $i <= $#parts; $i++) { $working[$i] = $parts[$i]; } my $checkme = NetAddr::IP->new(join($joinme, reverse(@working))) or return; return unless $checkme->within($parnet); $$addr = $checkme; # force "correct" IP to be recorded. return 1; } my ($parstr) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id = ?", undef, ($id)); my $parnet = NetAddr::IP->new($parstr); # Fail early on v6-in-v4 or v4-in-v6. We're not accepting these ATM. return if $parnet->addr =~ /\./ && $val =~ /:/; return if $parnet->addr =~ /:/ && $val =~ /\./; # Arguably this is incorrect, but... if ($val =~ /^::/) { $val =~ s/^:+//; # gotta strip'em all... return __rev_overlay(':', $parnet, $val, $addr); } if ($val =~ /^\./) { $val =~ s/^\.+//; return __rev_overlay('.', $parnet, $val, $addr); } if ($revrec eq 'y') { if ($$addr && !$$addr->{isv6}) { # argh. 12.1 == 12.0.0.1 (WTF?) # so we do this The Hard Way, because of the stupid if ($val =~ /^(?:\d{1,3}\.){3}\d{1,3}$/) { # we really have a real IP. return $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE revnet >> ?", undef, ($val)); } else { return __rev_overlay('.', $parnet, $val, $addr); } } elsif ($$addr && $$addr->{isv6}) { # real v6 address. return $dbh->selectrow_array("SELECT count(*) FROM revzones WHERE revnet >> ?", undef, ($val)); } else { # v6 tail return __rev_overlay(':', $parnet, $val, $addr); } # should be impossible to get here... } # ... and here. # can't do nuttin' in forward zones } # end _ipparent() ## ## Record validation subs. ## # A record sub _validate_1 { my $dbh = shift; my %args = @_; return ('FAIL', 'Reverse zones cannot contain A records') if $args{revrec} eq 'y'; # Coerce all hostnames to end in ".DOMAIN" for group/default records, # or the intended parent domain for live records. my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id})); ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; # Check IP is well-formed, and that it's a v4 address return ('FAIL',"A record must be a valid IPv4 address") unless $args{addr} && !$args{addr}->{isv6}; # coerce IP/value to normalized form for storage ${$args{val}} = $args{addr}->addr; return ('OK','OK'); } # done A record # NS record sub _validate_2 { my $dbh = shift; my %args = @_; # Coerce the hostname to "DOMAIN" for forward default records, "ZONE" for reverse default records, # or the intended parent zone for live records. ##fixme: allow for delegating .DOMAIN? if ($args{revrec} eq 'y') { my $pname = ($args{defrec} eq 'y' ? 'ZONE' : revName($dbh,$args{id})); ${$args{host}} = $pname if ${$args{host}} ne $pname; } else { my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id})); ${$args{host}} = $pname if ${$args{host}} ne $pname; } # Let this lie for now. Needs more magic. # # Check IP is well-formed, and that it's a v4 address # return ('FAIL',"A record must be a valid IPv4 address") # unless $addr && !$addr->{isv6}; # # coerce IP/value to normalized form for storage # $$val = $addr->addr; return ('OK','OK'); } # done NS record # CNAME record sub _validate_5 { my $dbh = shift; my %args = @_; # Not really true, but these are only useful for delegating smaller-than-/24 IP blocks. # This is fundamentally a messy operation and should really just be taken care of by the # export process, not manual maintenance of the necessary records. return ('FAIL', 'Reverse zones cannot contain CNAME records') if $args{revrec} eq 'y'; # Coerce all hostnames to end in ".DOMAIN" for group/default records, # or the intended parent domain for live records. my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id})); ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; return ('OK','OK'); } # done CNAME record # SOA record sub _validate_6 { # Smart monkeys won't stick their fingers in here; we have # separate dedicated routines to deal with SOA records. return ('OK','OK'); } # done SOA record # PTR record sub _validate_12 { return ('OK','OK'); } # done PTR record # MX record sub _validate_15 { my $dbh = shift; my %args = @_; # Not absolutely true but WTF use is an MX record for a reverse zone? return ('FAIL', 'Reverse zones cannot contain MX records') if $args{revrec} eq 'y'; return ('FAIL', "Distance is required for MX records") unless defined(${$args{dist}}); ${$args{dist}} =~ s/\s*//g; return ('FAIL',"Distance is required, and must be numeric") unless ${$args{dist}} =~ /^\d+$/; ${$args{fields}} = "distance,"; push @{$args{vallist}}, ${$args{dist}}; # Coerce all hostnames to end in ".DOMAIN" for group/default records, # or the intended parent domain for live records. my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id})); ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; return ('OK','OK'); } # done MX record # TXT record sub _validate_16 { return ('OK','OK'); } # done TXT record # RP record sub _validate_17 { return ('OK','OK'); } # done RP record # AAAA record sub _validate_28 { my $dbh = shift; my %args = @_; return ('FAIL', 'Reverse zones cannot contain AAAA records') if $args{revrec} eq 'y'; # Coerce all hostnames to end in ".DOMAIN" for group/default records, # or the intended parent domain for live records. my $pname = ($args{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$args{id})); ${$args{host}} =~ s/\.*$/\.$pname/ if ${$args{host}} !~ /$pname$/; # Check IP is well-formed, and that it's a v6 address return ('FAIL',"AAAA record must be a valid IPv6 address") unless $args{addr} && $args{addr}->{isv6}; # coerce IP/value to normalized form for storage ${$args{val}} = $args{addr}->addr; return ('OK','OK'); } # done AAAA record # SRV record sub _validate_33 { return ('OK','OK'); } # done SRV record # Now the custom types # A+PTR record sub _validate_65280 { return ('OK','OK'); } # done A+PTR record # AAAA+PTR record sub _validate_65281 { return ('OK','OK'); } # done AAAA+PTR record # PTR template record sub _validate_65282 { return ('OK','OK'); } # done PTR template record # A+PTR template record sub _validate_65283 { return ('OK','OK'); } # done AAAA+PTR template record # AAAA+PTR template record sub _validate_65284 { return ('OK','OK'); } # done AAAA+PTR template record ## ## Initialization and cleanup subs ## ## DNSDB::loadConfig() # Load the minimum required initial state (DB connect info) from a config file # Load misc other bits while we're at it. # Takes an optional basename and config path to look for # Populates the %config and %def hashes sub loadConfig { my $basename = shift || ''; # this will work OK ##fixme $basename isn't doing what I think I thought I was trying to do. my $deferr = ''; # place to put error from default config file in case we can't find either one my $configroot = "/etc/dnsdb"; ##CFG_LEAF## $configroot = '' if $basename =~ m|^/|; $basename .= ".conf" if $basename !~ /\.conf$/; my $defconfig = "$configroot/dnsdb.conf"; my $siteconfig = "$configroot/$basename"; # System defaults __cfgload("$defconfig") or $deferr = $errstr; # Per-site-ish settings. if ($basename ne '.conf') { unless (__cfgload("$siteconfig")) { $errstr = ($deferr ? "Error opening default config file $defconfig: $deferr\n" : ''). "Error opening site config file $siteconfig"; return; } } # Munge log_failures. if ($config{log_failures} ne '1' && $config{log_failures} ne '0') { # true/false, on/off, yes/no all valid. if ($config{log_failures} =~ /^(?:true|false|on|off|yes|no)$/) { if ($config{log_failures} =~ /(?:true|on|yes)/) { $config{log_failures} = 1; } else { $config{log_failures} = 0; } } else { $errstr = "Bad log_failures setting $config{log_failures}"; $config{log_failures} = 1; # Bad setting shouldn't be fatal. # return 2; } } # All good, clear the error and go home. $errstr = ''; return 1; } # end loadConfig() ## DNSDB::__cfgload() # Private sub to parse a config file and load it into %config # Takes a file handle on an open config file sub __cfgload { $errstr = ''; my $cfgfile = shift; if (open CFG, "<$cfgfile") { while () { chomp; s/^\s*//; next if /^#/; next if /^$/; # hmm. more complex bits in this file might require [heading] headers, maybe? # $mode = $1 if /^\[(a-z)+]/; # DB connect info $config{dbname} = $1 if /^dbname\s*=\s*([a-z0-9_.-]+)/i; $config{dbuser} = $1 if /^dbuser\s*=\s*([a-z0-9_.-]+)/i; $config{dbpass} = $1 if /^dbpass\s*=\s*([a-z0-9_.-]+)/i; $config{dbhost} = $1 if /^dbhost\s*=\s*([a-z0-9_.-]+)/i; # SOA defaults $def{contact} = $1 if /^contact\s*=\s*([a-z0-9_.-]+)/i; $def{prins} = $1 if /^prins\s*=\s*([a-z0-9_.-]+)/i; $def{soattl} = $1 if /^soattl\s*=\s*(\d+)/i; $def{refresh} = $1 if /^refresh\s*=\s*(\d+)/i; $def{retry} = $1 if /^retry\s*=\s*(\d+)/i; $def{expire} = $1 if /^expire\s*=\s*(\d+)/i; $def{minttl} = $1 if /^minttl\s*=\s*(\d+)/i; $def{ttl} = $1 if /^ttl\s*=\s*(\d+)/i; # Mail settings $config{mailhost} = $1 if /^mailhost\s*=\s*([a-z0-9_.-]+)/i; $config{mailnotify} = $1 if /^mailnotify\s*=\s*([a-z0-9_.\@-]+)/i; $config{mailsender} = $1 if /^mailsender\s*=\s*([a-z0-9_.\@-]+)/i; $config{mailname} = $1 if /^mailname\s*=\s*([a-z0-9\s_.-]+)/i; $config{orgname} = $1 if /^orgname\s*=\s*([a-z0-9\s_.,'-]+)/i; $config{domain} = $1 if /^domain\s*=\s*([a-z0-9_.-]+)/i; # session - note this is fed directly to CGI::Session $config{timeout} = $1 if /^[tT][iI][mM][eE][oO][uU][tT]\s*=\s*(\d+[smhdwMy]?)/; $config{sessiondir} = $1 if m{^sessiondir\s*=\s*([a-z0-9/_.-]+)}i; # misc $config{log_failures} = $1 if /^log_failures\s*=\s*([a-z01]+)/i; $config{perpage} = $1 if /^perpage\s*=\s*(\d+)/i; } close CFG; } else { $errstr = $!; return; } return 1; } # end __cfgload() ## DNSDB::connectDB() # Creates connection to DNS database. # Requires the database name, username, and password. # Returns a handle to the db. # Set up for a PostgreSQL db; could be any transactional DBMS with the # right changes. sub connectDB { $errstr = ''; my $dbname = shift; my $user = shift; my $pass = shift; my $dbh; my $DSN = "DBI:Pg:dbname=$dbname"; my $host = shift; $DSN .= ";host=$host" if $host; # Note that we want to autocommit by default, and we will turn it off locally as necessary. # We may not want to print gobbledygook errors; YMMV. Have to ponder that further. $dbh = DBI->connect($DSN, $user, $pass, { AutoCommit => 1, PrintError => 0 }) or return (undef, $DBI::errstr) if(!$dbh); ##fixme: initialize the DB if we can't find the table (since, by definition, there's # nothing there if we can't select from it...) my $tblsth = $dbh->prepare("SELECT count(*) FROM pg_catalog.pg_class WHERE relkind='r' AND relname=?"); my ($tblcount) = $dbh->selectrow_array($tblsth, undef, ('misc')); return (undef,$DBI::errstr) if $dbh->err; #if ($tblcount == 0) { # # create tables one at a time, checking for each. # return (undef, "check table misc missing"); #} # Return here if we can't select. # This should retrieve the dbversion key. my $sth = $dbh->prepare("SELECT key,value FROM misc WHERE misc_id=1"); $sth->execute(); return (undef,$DBI::errstr) if ($sth->err); ##fixme: do stuff to the DB on version mismatch # x.y series should upgrade on $DNSDB::VERSION > misc(key=>version) # DB should be downward-compatible; column defaults should give sane (if possibly # useless-and-needs-help) values in columns an older software stack doesn't know about. # See if the select returned anything (or null data). This should # succeed if the select executed, but... $sth->fetchrow(); return (undef,$DBI::errstr) if ($sth->err); $sth->finish; # If we get here, we should be OK. return ($dbh,"DB connection OK"); } # end connectDB ## DNSDB::finish() # Cleans up after database handles and so on. # Requires a database handle sub finish { my $dbh = $_[0]; $dbh->disconnect; } # end finish ## DNSDB::initGlobals() # Initialize global variables # NB: this does NOT include web-specific session variables! # Requires a database handle sub initGlobals { my $dbh = shift; # load record types from database my $sth = $dbh->prepare("SELECT val,name,stdflag FROM rectypes"); $sth->execute; while (my ($recval,$recname,$stdflag) = $sth->fetchrow_array()) { $typemap{$recval} = $recname; $reverse_typemap{$recname} = $recval; # now we fill the record validation function hash if ($stdflag < 5) { my $fn = "_validate_$recval"; $validators{$recval} = \&$fn; } else { my $fn = "sub { return ('FAIL','Type $recval ($recname) not supported'); }"; $validators{$recval} = eval $fn; } } } # end initGlobals ## DNSDB::initPermissions() # Set up permissions global # Takes database handle and UID sub initPermissions { my $dbh = shift; my $uid = shift; # %permissions = $(getPermissions($dbh,'user',$uid)); getPermissions($dbh, 'user', $uid, \%permissions); } # end initPermissions() ## DNSDB::getPermissions() # Get permissions from DB # Requires DB handle, group or user flag, ID, and hashref. sub getPermissions { my $dbh = shift; my $type = shift; my $id = shift; my $hash = shift; my $sql = qq( SELECT p.admin,p.self_edit, p.group_create,p.group_edit,p.group_delete, p.user_create,p.user_edit,p.user_delete, p.domain_create,p.domain_edit,p.domain_delete, p.record_create,p.record_edit,p.record_delete FROM permissions p ); if ($type eq 'group') { $sql .= qq( JOIN groups g ON g.permission_id=p.permission_id WHERE g.group_id=? ); } else { $sql .= qq( JOIN users u ON u.permission_id=p.permission_id WHERE u.user_id=? ); } my $sth = $dbh->prepare($sql); $sth->execute($id) or die "argh: ".$sth->errstr; # my $permref = $sth->fetchrow_hashref; # return $permref; # $hash = $permref; # Eww. Need to learn how to forcibly drop a hashref onto an existing hash. ($hash->{admin},$hash->{self_edit}, $hash->{group_create},$hash->{group_edit},$hash->{group_delete}, $hash->{user_create},$hash->{user_edit},$hash->{user_delete}, $hash->{domain_create},$hash->{domain_edit},$hash->{domain_delete}, $hash->{record_create},$hash->{record_edit},$hash->{record_delete}) = $sth->fetchrow_array; } # end getPermissions() ## DNSDB::changePermissions() # Update an ACL entry # Takes a db handle, type, owner-id, and hashref for the changed permissions. sub changePermissions { my $dbh = shift; my $type = shift; my $id = shift; my $newperms = shift; my $inherit = shift || 0; my $failmsg = ''; # see if we're switching from inherited to custom. for bonus points, # snag the permid and parent permid anyway, since we'll need the permid # to set/alter custom perms, and both if we're switching from custom to # inherited. my $sth = $dbh->prepare("SELECT (u.permission_id=g.permission_id) AS was_inherited,u.permission_id,g.permission_id". " FROM ".($type eq 'user' ? 'users' : 'groups')." u ". " JOIN groups g ON u.".($type eq 'user' ? '' : 'parent_')."group_id=g.group_id ". " WHERE u.".($type eq 'user' ? 'user' : 'group')."_id=?"); $sth->execute($id); my ($wasinherited,$permid,$parpermid) = $sth->fetchrow_array; # hack phtoui # group id 1 is "special" in that it's it's own parent (err... possibly.) # may make its parent id 0 which doesn't exist, and as a bonus is Perl-false. $wasinherited = 0 if ($type eq 'group' && $id == 1); local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; # Wrap all the SQL in a transaction eval { if ($inherit) { $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='t',permission_id=? ". "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($parpermid, $id) ); $dbh->do("DELETE FROM permissions WHERE permission_id=?", undef, ($permid) ); } else { if ($wasinherited) { # munge new permission entry in if we're switching from inherited perms ##fixme: need to add semirecursive bit to properly munge inherited permission ID on subgroups and users # ... if'n'when we have groups with fully inherited permissions. # SQL is coo $dbh->do("INSERT INTO permissions ($permlist,".($type eq 'user' ? 'user' : 'group')."_id) ". "SELECT $permlist,? FROM permissions WHERE permission_id=?", undef, ($id,$permid) ); ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions ". "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($id) ); $dbh->do("UPDATE ".($type eq 'user' ? 'users' : 'groups')." SET inherit_perm='f',permission_id=? ". "WHERE ".($type eq 'user' ? 'user' : 'group')."_id=?", undef, ($permid, $id) ); } # and now set the permissions we were passed foreach (@permtypes) { if (defined ($newperms->{$_})) { $dbh->do("UPDATE permissions SET $_=? WHERE permission_id=?", undef, ($newperms->{$_},$permid) ); } } } # (inherited->)? custom $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg ($permid)"); } else { return ('OK',$permid); } } # end changePermissions() ## DNSDB::comparePermissions() # Compare two permission hashes # Returns '>', '<', '=', '!' sub comparePermissions { my $p1 = shift; my $p2 = shift; my $retval = '='; # assume equality until proven otherwise no warnings "uninitialized"; foreach (@permtypes) { next if $p1->{$_} == $p2->{$_}; # equal is good if ($p1->{$_} && !$p2->{$_}) { if ($retval eq '<') { # if we've already found an unequal pair where $retval = '!'; # $p2 has more access, and we now find a pair last; # where $p1 has more access, the overall access } # is neither greater or lesser, it's unequal. $retval = '>'; } if (!$p1->{$_} && $p2->{$_}) { if ($retval eq '>') { # if we've already found an unequal pair where $retval = '!'; # $p1 has more access, and we now find a pair last; # where $p2 has more access, the overall access } # is neither greater or lesser, it's unequal. $retval = '<'; } } return $retval; } # end comparePermissions() ## DNSDB::changeGroup() # Change group ID of an entity # Takes a database handle, entity type, entity ID, and new group ID sub changeGroup { my $dbh = shift; my $type = shift; my $id = shift; my $newgrp = shift; ##fixme: fail on not enough args #return ('FAIL', "Missing if ($type eq 'domain') { $dbh->do("UPDATE domains SET group_id=? WHERE domain_id=?", undef, ($newgrp, $id)) or return ('FAIL','Group change failed: '.$dbh->errstr); } elsif ($type eq 'user') { $dbh->do("UPDATE users SET group_id=? WHERE user_id=?", undef, ($newgrp, $id)) or return ('FAIL','Group change failed: '.$dbh->errstr); } elsif ($type eq 'group') { $dbh->do("UPDATE groups SET parent_group_id=? WHERE group_id=?", undef, ($newgrp, $id)) or return ('FAIL','Group change failed: '.$dbh->errstr); } return ('OK','OK'); } # end changeGroup() ## DNSDB::_log() # Log an action # Internal sub # Takes a database handle, domain_id, user_id, group_id, email, name and log entry ##fixme: convert to trailing hash for user info # User info must contain a (user ID OR username)+fullname sub _log { my $dbh = shift; my ($domain_id,$user_id,$group_id,$username,$name,$entry) = @_; ##fixme: need better way(s?) to snag userinfo for log entries. don't want to have # to pass around yet *another* constant (already passing $dbh, shouldn't need to) my $fullname; if (!$user_id) { ($user_id, $fullname) = $dbh->selectrow_array("SELECT user_id, firstname || ' ' || lastname FROM users". " WHERE username=?", undef, ($username)); } elsif (!$username) { ($username, $fullname) = $dbh->selectrow_array("SELECT username, firstname || ' ' || lastname FROM users". " WHERE user_id=?", undef, ($user_id)); } else { ($fullname) = $dbh->selectrow_array("SELECT firstname || ' ' || lastname FROM users". " WHERE user_id=?", undef, ($user_id)); } $name = $fullname if !$name; ##fixme: farm out the actual logging to different subs for file, syslog, internal, etc based on config $dbh->do("INSERT INTO log (domain_id,user_id,group_id,email,name,entry) VALUES (?,?,?,?,?,?)", undef, ($domain_id,$user_id,$group_id,$username,$name,$entry)); # 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 # 1 2 3 4 5 6 7 } # end _log ## ## Processing subs ## ## DNSDB::addDomain() # Add a domain # Takes a database handle, domain name, numeric group, boolean(ish) state (active/inactive), # and user info hash (for logging). # Returns a status code and message sub addDomain { $errstr = ''; my $dbh = shift; return ('FAIL',"Need database handle") if !$dbh; my $domain = shift; return ('FAIL',"Domain must not be blank") if !$domain; my $group = shift; return ('FAIL',"Need group") if !defined($group); my $state = shift; return ('FAIL',"Need domain status") if !defined($state); my %userinfo = @_; # remaining bits. # user ID, username, user full name $state = 1 if $state =~ /^active$/; $state = 1 if $state =~ /^on$/; $state = 0 if $state =~ /^inactive$/; $state = 0 if $state =~ /^off$/; return ('FAIL',"Invalid domain status") if $state !~ /^\d+$/; return ('FAIL', "Invalid characters in domain") if $domain !~ /^[a-zA-Z0-9_.-]+$/; my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); my $dom_id; # quick check to start to see if we've already got one $sth->execute($domain); ($dom_id) = $sth->fetchrow_array; return ('FAIL', "Domain already exists") if $dom_id; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; # Wrap all the SQL in a transaction eval { # insert the domain... $dbh->do("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)", undef, ($domain, $group, $state)); # get the ID... ($dom_id) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain)); _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname}, "Added ".($state ? 'active' : 'inactive')." domain $domain"); # ... and now we construct the standard records from the default set. NB: group should be variable. my $sth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); my $sth_in = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,distance,weight,port,ttl)". " VALUES ($dom_id,?,?,?,?,?,?,?)"); $sth->execute($group); while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $sth->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sth_in->execute($host,$type,$val,$dist,$weight,$port,$ttl); if ($typemap{$type} eq 'SOA') { my @tmp1 = split /:/, $host; my @tmp2 = split /:/, $val; _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname}, "[new $domain] Added SOA record [contact $tmp1[0]] [master $tmp1[1]] ". "[refresh $tmp2[0]] [retry $tmp2[1]] [expire $tmp2[2]] [minttl $tmp2[3]], TTL $ttl"); } else { my $logentry = "[new $domain] Added record '$host $typemap{$type}"; $logentry .= " [distance $dist]" if $typemap{$type} eq 'MX'; $logentry .= " [priority $dist] [weight $weight] [port $port]" if $typemap{$type} eq 'SRV'; _log($dbh, $dom_id, $userinfo{id}, $group, $userinfo{name}, $userinfo{fullname}, $logentry." $val', TTL $ttl"); } } # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } else { return ('OK',$dom_id); } } # end addDomain ## DNSDB::delDomain() # Delete a domain. # for now, just delete the records, then the domain. # later we may want to archive it in some way instead (status code 2, for example?) sub delDomain { my $dbh = shift; my $domid = shift; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $failmsg = ''; # Wrap all the SQL in a transaction eval { my $sth = $dbh->prepare("delete from records where domain_id=?"); $failmsg = "Failure removing domain records"; $sth->execute($domid); $sth = $dbh->prepare("delete from domains where domain_id=?"); $failmsg = "Failure removing domain"; $sth->execute($domid); # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg"); } else { return ('OK','OK'); } } # end delDomain() ## DNSDB::domainName() # Return the domain name based on a domain ID # Takes a database handle and the domain ID # Returns the domain name or undef on failure sub domainName { $errstr = ''; my $dbh = shift; my $domid = shift; my ($domname) = $dbh->selectrow_array("SELECT domain FROM domains WHERE domain_id=?", undef, ($domid) ); $errstr = $DBI::errstr if !$domname; return $domname if $domname; } # end domainName() ## DNSDB::revName() # Return the reverse zone name based on an rDNS ID # Takes a database handle and the rDNS ID # Returns the reverse zone name or undef on failure sub revName { $errstr = ''; my $dbh = shift; my $revid = shift; my ($revname) = $dbh->selectrow_array("SELECT revnet FROM revzones WHERE rdns_id=?", undef, ($revid) ); $errstr = $DBI::errstr if !$revname; return $revname if $revname; } # end revName() ## DNSDB::domainID() # Takes a database handle and domain name # Returns the domain ID number sub domainID { $errstr = ''; my $dbh = shift; my $domain = shift; my ($domid) = $dbh->selectrow_array("SELECT domain_id FROM domains WHERE domain=?", undef, ($domain) ); $errstr = $DBI::errstr if !$domid; return $domid if $domid; } # end domainID() ## DNSDB::addGroup() # Add a group # Takes a database handle, group name, parent group, hashref for permissions, # and optional template-vs-cloneme flag # Returns a status code and message sub addGroup { $errstr = ''; my $dbh = shift; my $groupname = shift; my $pargroup = shift; my $permissions = shift; # 0 indicates "custom", hardcoded. # Any other value clones that group's default records, if it exists. my $inherit = shift || 0; ##fixme: need a flag to indicate clone records or ? # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?"); my $group_id; # quick check to start to see if we've already got one $sth->execute($groupname); ($group_id) = $sth->fetchrow_array; return ('FAIL', "Group already exists") if $group_id; # Wrap all the SQL in a transaction eval { $sth = $dbh->prepare("INSERT INTO groups (parent_group_id,group_name) VALUES (?,?)"); $sth->execute($pargroup,$groupname); $sth = $dbh->prepare("SELECT group_id FROM groups WHERE group_name=?"); $sth->execute($groupname); my ($groupid) = $sth->fetchrow_array(); # Permissions if ($inherit) { } else { my @permvals; foreach (@permtypes) { if (!defined ($permissions->{$_})) { push @permvals, 0; } else { push @permvals, $permissions->{$_}; } } $sth = $dbh->prepare("INSERT INTO permissions (group_id,$permlist) values (?".',?'x($#permtypes+1).")"); $sth->execute($groupid,@permvals); $sth = $dbh->prepare("SELECT permission_id FROM permissions WHERE group_id=?"); $sth->execute($groupid); my ($permid) = $sth->fetchrow_array(); $dbh->do("UPDATE groups SET permission_id=$permid WHERE group_id=$groupid"); } # done permission fiddling # Default records $sth = $dbh->prepare("INSERT INTO default_records (group_id,host,type,val,distance,weight,port,ttl) ". "VALUES ($groupid,?,?,?,?,?,?,?)"); if ($inherit) { # Duplicate records from parent. Actually relying on inherited records feels # very fragile, and it would be problematic to roll over at a later time. my $sth2 = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl FROM default_records WHERE group_id=?"); $sth2->execute($pargroup); while (my @clonedata = $sth2->fetchrow_array) { $sth->execute(@clonedata); } } else { ##fixme: Hardcoding is Bad, mmmmkaaaay? # reasonable basic defaults for SOA, MX, NS, and minimal hosting # could load from a config file, but somewhere along the line we need hardcoded bits. $sth->execute('ns1.example.com:hostmaster.example.com', 6, '10800:3600:604800:10800', 0, 0, 0, 86400); $sth->execute('DOMAIN', 1, '192.168.4.2', 0, 0, 0, 7200); $sth->execute('DOMAIN', 15, 'mx.example.com', 10, 0, 0, 7200); $sth->execute('DOMAIN', 2, 'ns1.example.com', 0, 0, 0, 7200); $sth->execute('DOMAIN', 2, 'ns2.example.com', 0, 0, 0, 7200); $sth->execute('www.DOMAIN', 5, 'DOMAIN', 0, 0, 0, 7200); } # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } else { return ('OK','OK'); } } # end addGroup() ## DNSDB::delGroup() # Delete a group. # Takes a group ID # Returns a status code and message sub delGroup { my $dbh = shift; my $groupid = shift; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; ##fixme: locate "knowable" error conditions and deal with them before the eval # ... or inside, whatever. # -> domains still exist in group # -> ... my $failmsg = ''; # Wrap all the SQL in a transaction eval { my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); $sth->execute($groupid); my ($domcnt) = $sth->fetchrow_array; $failmsg = "Can't remove group ".groupName($dbh,$groupid); die "$domcnt domains still in group\n" if $domcnt; $sth = $dbh->prepare("delete from default_records where group_id=?"); $failmsg = "Failed to delete default records for ".groupName($dbh,$groupid); $sth->execute($groupid); $sth = $dbh->prepare("delete from groups where group_id=?"); $failmsg = "Failed to remove group ".groupName($dbh,$groupid); $sth->execute($groupid); # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg"); } else { return ('OK','OK'); } } # end delGroup() ## DNSDB::getChildren() # Get a list of all groups whose parent^n is group # Takes a database handle, group ID, reference to an array to put the group IDs in, # and an optional flag to return only immediate children or all children-of-children # default to returning all children # Calls itself sub getChildren { $errstr = ''; my $dbh = shift; my $rootgroup = shift; my $groupdest = shift; my $immed = shift || 'all'; # special break for default group; otherwise we get stuck. if ($rootgroup == 1) { # by definition, group 1 is the Root Of All Groups my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE NOT (group_id=1)". ($immed ne 'all' ? " AND parent_group_id=1" : '')); $sth->execute; while (my @this = $sth->fetchrow_array) { push @$groupdest, @this; } } else { my $sth = $dbh->prepare("SELECT group_id FROM groups WHERE parent_group_id=?"); $sth->execute($rootgroup); return if $sth->rows == 0; my @grouplist; while (my ($group) = $sth->fetchrow_array) { push @$groupdest, $group; getChildren($dbh,$group,$groupdest) if $immed eq 'all'; } } } # end getChildren() ## DNSDB::groupName() # Return the group name based on a group ID # Takes a database handle and the group ID # Returns the group name or undef on failure sub groupName { $errstr = ''; my $dbh = shift; my $groupid = shift; my $sth = $dbh->prepare("SELECT group_name FROM groups WHERE group_id=?"); $sth->execute($groupid); my ($groupname) = $sth->fetchrow_array(); $errstr = $DBI::errstr if !$groupname; return $groupname if $groupname; } # end groupName ## DNSDB::groupID() # Return the group ID based on the group name # Takes a database handle and the group name # Returns the group ID or undef on failure sub groupID { $errstr = ''; my $dbh = shift; my $group = shift; my ($grpid) = $dbh->selectrow_array("SELECT group_id FROM groups WHERE group=?", undef, ($group) ); $errstr = $DBI::errstr if !$grpid; return $grpid if $grpid; } # end groupID() ## DNSDB::addUser() # Add a user. # Takes a DB handle, username, group ID, password, state (active/inactive). # Optionally accepts: # user type (user/admin) - defaults to user # permissions string - defaults to inherit from group # three valid forms: # i - Inherit permissions # c: - Clone permissions from # C: - Set these specific permissions # first name - defaults to username # last name - defaults to blank # phone - defaults to blank (could put other data within column def) # Returns (OK,) on success, (FAIL,) on failure sub addUser { $errstr = ''; my $dbh = shift; my $username = shift; my $group = shift; my $pass = shift; my $state = shift; return ('FAIL', "Missing one or more required entries") if !defined($state); return ('FAIL', "Username must not be blank") if !$username; my $type = shift || 'u'; # create limited users by default - fwiw, not sure yet how this will interact with ACLs my $permstring = shift || 'i'; # default is to inhert permissions from group my $fname = shift || $username; my $lname = shift || ''; my $phone = shift || ''; # not going format-check my $sth = $dbh->prepare("SELECT user_id FROM users WHERE username=?"); my $user_id; # quick check to start to see if we've already got one $sth->execute($username); ($user_id) = $sth->fetchrow_array; return ('FAIL', "User already exists") if $user_id; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $failmsg = ''; # Wrap all the SQL in a transaction eval { # insert the user... note we set inherited perms by default since # it's simple and cleans up some other bits of state my $sth = $dbh->prepare("INSERT INTO users ". "(group_id,username,password,firstname,lastname,phone,type,status,permission_id,inherit_perm) ". "VALUES (?,?,?,?,?,?,?,?,(SELECT permission_id FROM permissions WHERE group_id=?),'t')"); $sth->execute($group,$username,unix_md5_crypt($pass),$fname,$lname,$phone,$type,$state,$group); # get the ID... ($user_id) = $dbh->selectrow_array("SELECT currval('users_user_id_seq')"); # Permissions! Gotta set'em all! die "Invalid permission string $permstring" if $permstring !~ /^(?: i # inherit |c:\d+ # clone # custom. no, the leading , is not a typo |C:(?:,(?:group|user|domain|record|self)_(?:edit|create|delete))* )$/x; # bleh. I'd call another function to do my dirty work, but we're in the middle of a transaction already. if ($permstring ne 'i') { # for cloned or custom permissions, we have to create a new permissions entry. my $clonesrc = $group; if ($permstring =~ /^c:(\d+)/) { $clonesrc = $1; } $dbh->do("INSERT INTO permissions ($permlist,user_id) ". "SELECT $permlist,? FROM permissions WHERE permission_id=". "(SELECT permission_id FROM permissions WHERE ".($permstring =~ /^c:/ ? 'user' : 'group')."_id=?)", undef, ($user_id,$clonesrc) ); $dbh->do("UPDATE users SET permission_id=". "(SELECT permission_id FROM permissions WHERE user_id=?) ". "WHERE user_id=?", undef, ($user_id, $user_id) ); } if ($permstring =~ /^C:/) { # finally for custom permissions, we set the passed-in permissions (and unset # any that might have been brought in by the clone operation above) my ($permid) = $dbh->selectrow_array("SELECT permission_id FROM permissions WHERE user_id=?", undef, ($user_id) ); foreach (@permtypes) { if ($permstring =~ /,$_/) { $dbh->do("UPDATE permissions SET $_='t' WHERE permission_id=?", undef, ($permid) ); } else { $dbh->do("UPDATE permissions SET $_='f' WHERE permission_id=?", undef, ($permid) ); } } } $dbh->do("UPDATE users SET inherit_perm='n' WHERE user_id=?", undef, ($user_id) ); ##fixme: add another table to hold name/email for log table? # once we get here, we should have suceeded. $dbh->commit; }; # end eval if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg." $failmsg"); } else { return ('OK',$user_id); } } # end addUser ## DNSDB::checkUser() # Check user/pass combo on login sub checkUser { my $dbh = shift; my $user = shift; my $inpass = shift; my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?"); $sth->execute($user); my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array; my $loginfailed = 1 if !defined($uid); if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { $loginfailed = 1 if $pass ne unix_md5_crypt($inpass,$1); } else { $loginfailed = 1 if $pass ne $inpass; } # nnnngggg return ($uid, $gid); } # end checkUser ## DNSDB:: updateUser() # Update general data about user sub updateUser { my $dbh = shift; ##fixme: tweak calling convention so that we can update any given bit of data my $uid = shift; my $username = shift; my $group = shift; my $pass = shift; my $state = shift; my $type = shift || 'u'; my $fname = shift || $username; my $lname = shift || ''; my $phone = shift || ''; # not going format-check my $failmsg = ''; # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $sth; # Password can be left blank; if so we assume there's one on file. # Actual blank passwords are bad, mm'kay? if (!$pass) { $sth = $dbh->prepare("SELECT password FROM users WHERE user_id=?"); $sth->execute($uid); ($pass) = $sth->fetchrow_array; } else { $pass = unix_md5_crypt($pass); } eval { my $sth = $dbh->prepare(q( UPDATE users SET username=?, password=?, firstname=?, lastname=?, phone=?, type=?, status=? WHERE user_id=? ) ); $sth->execute($username, $pass, $fname, $lname, $phone, $type, $state, $uid); $dbh->commit; }; if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',"$failmsg: $msg"); } else { return ('OK','OK'); } } # end updateUser() ## DNSDB::delUser() # sub delUser { my $dbh = shift; return ('FAIL',"Need database handle") if !$dbh; my $userid = shift; return ('FAIL',"Missing userid") if !defined($userid); my $sth = $dbh->prepare("delete from users where user_id=?"); $sth->execute($userid); return ('FAIL',"Couldn't remove user: ".$sth->errstr) if $sth->err; return ('OK','OK'); } # end delUser ## DNSDB::userFullName() # Return a pretty string! # Takes a user_id and optional printf-ish string to indicate which pieces where: # %u for the username # %f for the first name # %l for the last name # All other text in the passed string will be left as-is. ##fixme: need a "smart" option too, so that missing/null/blank first/last names don't give funky output sub userFullName { $errstr = ''; my $dbh = shift; my $userid = shift; my $fullformat = shift || '%f %l (%u)'; my $sth = $dbh->prepare("select username,firstname,lastname from users where user_id=?"); $sth->execute($userid); my ($uname,$fname,$lname) = $sth->fetchrow_array(); $errstr = $DBI::errstr if !$uname; $fullformat =~ s/\%u/$uname/g; $fullformat =~ s/\%f/$fname/g; $fullformat =~ s/\%l/$lname/g; return $fullformat; } # end userFullName ## DNSDB::userStatus() # Sets and/or returns a user's status # Takes a database handle, user ID and optionally a status argument # Returns undef on errors. sub userStatus { my $dbh = shift; my $id = shift; my $newstatus = shift; return undef if $id !~ /^\d+$/; my $sth; # ooo, fun! let's see what we were passed for status if ($newstatus) { $sth = $dbh->prepare("update users set status=? where user_id=?"); # ass-u-me caller knows what's going on in full if ($newstatus =~ /^[01]$/) { # only two valid for now. $sth->execute($newstatus,$id); } elsif ($newstatus =~ /^usero(?:n|ff)$/) { $sth->execute(($newstatus eq 'useron' ? 1 : 0),$id); } } $sth = $dbh->prepare("select status from users where user_id=?"); $sth->execute($id); my ($status) = $sth->fetchrow_array; return $status; } # end userStatus() ## DNSDB::getUserData() # Get misc user data for display sub getUserData { my $dbh = shift; my $uid = shift; my $sth = $dbh->prepare("SELECT group_id,username,firstname,lastname,phone,type,status,inherit_perm ". "FROM users WHERE user_id=?"); $sth->execute($uid); return $sth->fetchrow_hashref(); } # end getUserData() ## DNSDB::getSOA() # Return all suitable fields from an SOA record in separate elements of a hash # Takes a database handle, default/live flag, domain/reverse flag, and parent ID sub getSOA { $errstr = ''; my $dbh = shift; my $def = shift; my $rev = shift; my $id = shift; my %ret; # (ab)use distance and weight columns to store SOA data? can't for default_rev_records... # - should really attach serial to the zone parent somewhere my $sql = "SELECT record_id,host,val,ttl from "._rectable($def,$rev). " WHERE "._recparent($def,$rev)." = ? AND type=$reverse_typemap{SOA}"; my $sth = $dbh->prepare($sql); $sth->execute($id); my ($recid,$host,$val,$ttl) = $sth->fetchrow_array() or return; my ($contact,$prins) = split /:/, $host; my ($refresh,$retry,$expire,$minttl) = split /:/, $val; $ret{recid} = $recid; $ret{ttl} = $ttl; # $ret{serial} = $serial; # ca't use distance for serial with default_rev_records $ret{prins} = $prins; $ret{contact} = $contact; $ret{refresh} = $refresh; $ret{retry} = $retry; $ret{expire} = $expire; $ret{minttl} = $minttl; return %ret; } # end getSOA() ## DNSDB::getRecLine() # Return all data fields for a zone record in separate elements of a hash # Takes a database handle, default/live flag, and record ID sub getRecLine { $errstr = ''; my $dbh = shift; my $def = shift; my $id = shift; my $sql = "SELECT record_id,host,type,val,distance,weight,port,ttl". (($def eq 'def' or $def eq 'y') ? ',group_id FROM default_' : ',domain_id FROM '). "records WHERE record_id=?"; my $ret = $dbh->selectrow_hashref($sql, undef, ($id) ); if ($dbh->err) { $errstr = $DBI::errstr; return undef; } if (!$ret) { $errstr = "No such record"; return undef; } $ret->{parid} = (($def eq 'def' or $def eq 'y') ? $ret->{group_id} : $ret->{domain_id}); return $ret; } ##fixme: should use above (getRecLine()) to get lines for below? ## DNSDB::getDomRecs() # Return records for a domain # Takes a database handle, default/live flag, group/domain ID, start, # number of records, sort field, and sort order # Returns a reference to an array of hashes sub getDomRecs { $errstr = ''; my $dbh = shift; my $def = shift; my $rev = shift; my $id = shift; my $nrecs = shift || 'all'; my $nstart = shift || 0; ## for order, need to map input to column names my $order = shift || 'host'; my $direction = shift || 'ASC'; my $filter = shift || ''; my $sql = "SELECT r.record_id,r.host,r.type,r.val,r.ttl"; $sql .= ",r.distance,r.weight,r.port" if $rev eq 'n'; $sql .= " FROM "._rectable($def,$rev)." r "; $sql .= "INNER JOIN rectypes t ON r.type=t.val "; # for sorting by type alphabetically $sql .= "WHERE "._recparent($def,$rev)." = ?"; $sql .= " AND NOT r.type=$reverse_typemap{SOA}"; $sql .= " AND host ~* ?" if $filter; # use alphaorder column for "correct" ordering of sort-by-type instead of DNS RR type number $sql .= " ORDER BY ".($order eq 'type' ? 't.alphaorder' : "r.$order")." $direction"; my @bindvars = ($id); push @bindvars, $filter if $filter; # just to be ultraparanoid about SQL injection vectors if ($nstart ne 'all') { $sql .= " LIMIT ? OFFSET ?"; push @bindvars, $nrecs; push @bindvars, ($nstart*$nrecs); } my $sth = $dbh->prepare($sql) or warn $dbh->errstr; $sth->execute(@bindvars) or warn "$sql: ".$sth->errstr; my @retbase; while (my $ref = $sth->fetchrow_hashref()) { push @retbase, $ref; } my $ret = \@retbase; return $ret; } # end getDomRecs() ## DNSDB::getRecCount() # Return count of non-SOA records in zone (or default records in a group) # Takes a database handle, default/live flag, reverse/forward flag, group/domain ID, # and optional filtering modifier # Returns the count sub getRecCount { my $dbh = shift; my $defrec = shift; my $revrec = shift; my $id = shift; my $filter = shift || ''; # keep the nasties down, since we can't ?-sub this bit. :/ # note this is chars allowed in DNS hostnames $filter =~ s/[^a-zA-Z0-9_.:-]//g; my @bindvars = ($id); push @bindvars, $filter if $filter; my $sql = "SELECT count(*) FROM ". _rectable($defrec,$revrec). " WHERE "._recparent($defrec,$revrec)."=? ". "AND NOT type=$reverse_typemap{SOA}". ($filter ? " AND host ~* ?" : ''); my ($count) = $dbh->selectrow_array($sql, undef, (@bindvars) ); return $count; } # end getRecCount() ## DNSDB::addRec() # Add a new record to a domain or a group's default records # Takes a database handle, default/live flag, group/domain ID, # host, type, value, and TTL # Some types require additional detail: "distance" for MX and SRV, # and weight/port for SRV # Returns a status code and detail message in case of error sub addRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $revrec = shift; my $id = shift; # parent (group_id for defrecs, rdns_id for reverse records, # domain_id for domain records) my $host = shift; my $rectype = shift; my $val = shift; my $ttl = shift; # prep for validation my $addr = NetAddr::IP->new($val); $host =~ s/\.+$//; # FQDNs ending in . are an internal detail, and really shouldn't be exposed in the UI. my $domid = 0; my $revid = 0; my $retcode = 'OK'; # assume everything will go OK my $retmsg = ''; # do simple validation first return ('FAIL', "TTL must be numeric") unless $ttl =~ /^\d+$/; ## possible contents for record types # (A/AAAA+)PTR: IP + (FQDN or bare hostname to have ADMINDOMAIN appended?) # (A/AAAA+)PTR template: IP or netblock + (fully-qualified hostname pattern or bare hostname pattern to have # ADMINDOMAIN appended?) # A/AAAA: append parent domain if not included, validate IP # NS,MX,CNAME,SRV,TXT: append parent domain if not included # ickypoo. can't see a handy way to really avoid hardcoding these here... otoh, these aren't # really mutable, it's just handy to have them in a DB table for reordering # 65280 | A+PTR # 65281 | AAAA+PTR # 65282 | PTR template # 65283 | A+PTR template # 65284 | AAAA+PTR template # can only validate parenthood on IPs in live zones; group default records are likely to contain "ZONE" if ($revrec eq 'y' && $defrec eq 'n') { if ($rectype == $reverse_typemap{PTR} || $rectype == 65280 || $rectype == 65281) { return ('FAIL', "IP or IP fragment $val is not within ".revName($dbh, $id)) unless _ipparent($dbh, $defrec, $revrec, $val, $id, \$addr); $revid = $id; } if ($rectype == 65280 || $rectype == 65281) { # check host to see if it's managed here. coerce down to PTR if not. # Split $host and work our way up the hierarchy until we run out of parts to add, or we find a match # Note we do not do '$checkdom = shift @hostbits' right away, since we want to be able to support # private TLDs. my @hostbits = reverse(split(/\./, $host)); my $checkdom = ''; my $sth = $dbh->prepare("SELECT count(*),domain_id FROM domains WHERE domain = ? GROUP BY domain_id"); foreach (@hostbits) { $checkdom = "$_.$checkdom"; $checkdom =~ s/\.$//; $sth->execute($checkdom); my ($found, $parid) = $sth->fetchrow_array; if ($found) { $domid = $parid; last; } } if (!$domid) { # no domain found; set the return code and message, then coerce type down to PTR $retcode = 'WARN'; $retmsg = "Record added as PTR instead of $typemap{$rectype}; domain not found for $host"; $rectype = $reverse_typemap{PTR}; } } # types 65282, 65283, 65284 left } elsif ($revrec eq 'n' && $defrec eq 'n') { # Forward zone. Validate IPs where we know they *MUST* be correct, # check to see if we manage the reverse zone on A(AAA)+PTR, # append the domain on hostnames without it. if ($rectype == $reverse_typemap{A} || $rectype == 65280) { return ('FAIL',$typemap{$rectype}." record must be a valid IPv4 address") unless $addr && !$addr->{isv6}; $val = $addr->addr; } if ($rectype == $reverse_typemap{AAAA} || $rectype == 65281) { return ('FAIL',$typemap{$rectype}." record must be a valid IPv6 address") unless $addr && $addr->{isv6}; $val = $addr->addr; } if ($rectype == 65280 || $rectype == 65281) { # The ORDER BY here makes sure we pick the *smallest* revzone parent. Just In Case. ($revid) = $dbh->selectrow_array("SELECT rdns_id FROM revzones WHERE revnet >> ?". " ORDER BY masklen(revnet) DESC", undef, ($val)); if (!$revid) { $retcode = 'WARN'; $retmsg = "Record added as ".($rectype == 65280 ? 'A' : 'AAAA')." instead of $typemap{$rectype}; ". "reverse zone not found for $val"; $rectype = $reverse_typemap{A} if $rectype == 65280; $rectype = $reverse_typemap{AAAA} if $rectype == 65281; $revid = 0; # Just In Case } } my $parstr = domainName($dbh,$id); $host .= ".$parstr" if $host !~ /$parstr$/; } # Validate IPs in MX, NS, SRV records? # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) { # if ($val =~ /^\s*[\da-f:.]+\s*$/) { # return ('FAIL',"$val is not a valid IP address") if !$addr; # } # } # basic fields: immediate parent ID, host, type, val, ttl my $fields = _recparent($defrec,$revrec).",host,type,val,ttl"; my $vallen = "?,?,?,?,?"; my @vallist = ($id,$host,$rectype,$val,$ttl); if ($defrec eq 'n' && ($rectype == 65280 || $rectype == 65281)) { $fields .= ",".($revrec eq 'n' ? 'rdns_id' : 'domain_id'); $vallen .= ",?"; push @vallist, ($revrec eq 'n' ? $revid : $domid); } # MX and SRV specials my $dist; if ($rectype == $reverse_typemap{MX} or $rectype == $reverse_typemap{SRV}) { $dist = shift; return ('FAIL',"Distance is required for $typemap{$rectype} records") unless defined($dist); $dist =~ s/\s*//g; return ('FAIL',"Distance is required, and must be numeric") unless $dist =~ /^\d+$/; $fields .= ",distance"; $vallen .= ",?"; push @vallist, $dist; } my $weight; my $port; if ($rectype == $reverse_typemap{SRV}) { # check for _service._protocol. NB: RFC2782 does not say "MUST"... nor "SHOULD"... # it just says (paraphrased) "... is prepended with _ to prevent DNS collisions" return ('FAIL',"SRV records must begin with _service._protocol [$host]") unless $host =~ /^_[A-Za-z]+\._[A-Za-z]+\.[a-zA-Z0-9-]+/; $weight = shift; $port = shift; return ('FAIL',"Port and weight are required for SRV records") unless defined($weight) && defined($port); $weight =~ s/\s*//g; $port =~ s/\s*//g; return ('FAIL',"Port and weight are required, and must be numeric") unless $weight =~ /^\d+$/ && $port =~ /^\d+$/; $fields .= ",weight,port"; $vallen .= ",?,?"; push @vallist, ($weight,$port); } # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; eval { $dbh->do("INSERT INTO ".($defrec eq 'y' ? 'default_' : '')."records ($fields) VALUES ($vallen)", undef, @vallist); $dbh->commit; }; if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg); } return ($retcode, $retmsg); } # end addRec() ## DNSDB::updateRec() # Update a record sub updateRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $id = shift; # all records have these my $host = shift; my $type = shift; my $val = shift; my $ttl = shift; return('FAIL',"Missing standard argument(s)") if !defined($ttl); # only MX and SRV will use these my $dist = 0; my $weight = 0; my $port = 0; if ($type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) { $dist = shift; $dist =~ s/\s+//g; return ('FAIL',"MX or SRV requires distance") if !defined($dist); return ('FAIL', "Distance must be numeric") unless $dist =~ /^\d+$/; if ($type == $reverse_typemap{SRV}) { $weight = shift; $weight =~ s/\s+//g; return ('FAIL',"SRV requires weight") if !defined($weight); return ('FAIL',"Weight must be numeric") unless $weight =~ /^\d+$/; $port = shift; $port =~ s/\s+//g; return ('FAIL',"SRV requires port") if !defined($port); return ('FAIL',"Port must be numeric") unless $port =~ /^\d+$/; } } # Enforce IP addresses on A and AAAA types my $addr = NetAddr::IP->new($val); if ($type == $reverse_typemap{A}) { return ('FAIL',$typemap{$type}." record must be a valid IPv4 address") unless $addr && !$addr->{isv6}; } if ($type == $reverse_typemap{AAAA}) { return ('FAIL',$typemap{$type}." record must be a valid IPv6 address") unless $addr && $addr->{isv6}; } # hmm.. this might work. except possibly for something pointing to "deadbeef.ca". # if ($type == $reverse_typemap{NS} || $type == $reverse_typemap{MX} || $type == $reverse_typemap{SRV}) { # if ($val =~ /^\s*[\da-f:.]+\s*$/) { # return ('FAIL',"$val is not a valid IP address") if !$addr; # } # } local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; eval { $dbh->do("UPDATE ".($defrec eq 'y' ? 'default_' : '')."records ". "SET host=?,val=?,type=?,ttl=?,distance=?,weight=?,port=? ". "WHERE record_id=?", undef, ($host, $val, $type, $ttl, $dist, $weight, $port, $id) ); $dbh->commit; }; if ($@) { my $msg = $@; $dbh->rollback; return ('FAIL', $msg); } return ('OK','OK'); } # end updateRec() ## DNSDB::delRec() # Delete a record. sub delRec { $errstr = ''; my $dbh = shift; my $defrec = shift; my $id = shift; my $sth = $dbh->prepare("DELETE FROM ".($defrec eq 'y' ? 'default_' : '')."records WHERE record_id=?"); $sth->execute($id); return ('FAIL',"Couldn't remove record: ".$sth->errstr) if $sth->err; return ('OK','OK'); } # end delRec() # Reference hashes. my %par_tbl = ( group => 'groups', user => 'users', defrec => 'default_records', domain => 'domains', record => 'records' ); my %id_col = ( group => 'group_id', user => 'user_id', defrec => 'record_id', domain => 'domain_id', record => 'record_id' ); my %par_col = ( group => 'parent_group_id', user => 'group_id', defrec => 'group_id', domain => 'group_id', record => 'domain_id' ); my %par_type = ( group => 'group', user => 'group', defrec => 'group', domain => 'group', record => 'domain' ); ## DNSDB::getTypelist() # Get a list of record types for various UI dropdowns # Takes database handle, forward/reverse/lookup flag, and optional "tag as selected" indicator (defaults to A) # Returns an arrayref to list of hashrefs perfect for HTML::Template sub getTypelist { my $dbh = shift; my $recgroup = shift; my $type = shift || $reverse_typemap{A}; # also accepting $webvar{revrec}! $recgroup = 'f' if $recgroup eq 'n'; $recgroup = 'r' if $recgroup eq 'y'; my $sql = "SELECT val,name FROM rectypes WHERE "; if ($recgroup eq 'r') { # reverse zone types $sql .= "stdflag=2 OR stdflag=3"; } elsif ($recgroup eq 'l') { # DNS lookup types. Note we avoid our custom types >= 65280, since those are entirely internal. $sql .= "(stdflag=1 OR stdflag=2 OR stdflag=3) AND val < 65280"; } else { # default; forward zone types. technically $type eq 'f' but not worth the error message. $sql .= "stdflag=1 OR stdflag=2"; } $sql .= " ORDER BY listorder"; my $sth = $dbh->prepare($sql); $sth->execute; my @typelist; while (my ($rval,$rname) = $sth->fetchrow_array()) { my %row = ( recval => $rval, recname => $rname ); $row{tselect} = 1 if $rval == $type; push @typelist, \%row; } # Add SOA on lookups since it's not listed in other dropdowns. if ($recgroup eq 'l') { my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); $row{tselect} = 1 if $reverse_typemap{SOA} == $type; push @typelist, \%row; } return \@typelist; } # end getTypelist() ## DNSDB::getParents() # Find out which entities are parent to the requested id # Returns arrayref containing hash pairs of id/type sub getParents { my $dbh = shift; my $id = shift; my $type = shift; my $depth = shift || 'all'; # valid values: 'all', 'immed', (stop at this group ID) my @parlist; while (1) { my $result = $dbh->selectrow_hashref("SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?", undef, ($id) ); my %tmp = ($result->{$par_col{$type}} => $par_type{$type}); unshift @parlist, \%tmp; last if $result->{$par_col{$type}} == 1; # group 1 is its own parent $id = $result->{$par_col{$type}}; $type = $par_type{$type}; } return \@parlist; } # end getParents() ## DNSDB::isParent() # Returns true if $id1 is a parent of $id2, false otherwise sub isParent { my $dbh = shift; my $id1 = shift; my $type1 = shift; my $id2 = shift; my $type2 = shift; ##todo: immediate, secondary, full (default) # Return false on invalid types return 0 if !grep /^$type1$/, ('record','defrec','user','domain','group'); return 0 if !grep /^$type2$/, ('record','defrec','user','domain','group'); # Return false on impossible relations return 0 if $type1 eq 'record'; # nothing may be a child of a record return 0 if $type1 eq 'defrec'; # nothing may be a child of a record return 0 if $type1 eq 'user'; # nothing may be child of a user return 0 if $type1 eq 'domain' && $type2 ne 'record'; # domain may not be a parent of anything other than a record # ennnhhhh.... if we're passed an id of 0, it will never be found. usual # case would be the UI creating a new , and so we don't have an ID for # to look up yet. in that case the UI should check the parent as well. # argument for returning 1 is return 0 if $id1 == 0; # nothing can have a parent id of 0 return 1 if $id2 == 0; # anything could have a child id of 0 (or "unknown") # group 1 is the ultimate root parent return 1 if $type1 eq 'group' && $id1 == 1; # groups are always (a) parent of themselves return 1 if $type1 eq 'group' && $type2 eq 'group' && $id1 == $id2; # almost the same loop as getParents() above my $id = $id2; my $type = $type2; my $foundparent = 0; my $limiter = 0; while (1) { my $sql = "SELECT $par_col{$type} FROM $par_tbl{$type} WHERE $id_col{$type} = ?"; my $result = $dbh->selectrow_hashref($sql, undef, ($id) ); if (!$result) { $limiter++; ##fixme: how often will this happen on a live site? warn "no results looking for $sql with id $id (depth $limiter)\n"; last; } if ($result && $result->{$par_col{$type}} == $id1) { $foundparent = 1; last; } else { ##fixme: do we care about trying to return a "no such record/domain/user/group" error? warn $dbh->errstr." $sql, $id" if $dbh->errstr; } # group 1 is its own parent. need this here more to break strange loops than for detecting a parent last if $result->{$par_col{$type}} == 1; $id = $result->{$par_col{$type}}; $type = $par_type{$type}; } return $foundparent; } # end isParent() ## DNSDB::domStatus() # Sets and/or returns a domain's status # Takes a database handle, domain ID and optionally a status argument # Returns undef on errors. sub domStatus { my $dbh = shift; my $id = shift; my $newstatus = shift; return undef if $id !~ /^\d+$/; my $sth; # ooo, fun! let's see what we were passed for status if ($newstatus) { $sth = $dbh->prepare("update domains set status=? where domain_id=?"); # ass-u-me caller knows what's going on in full if ($newstatus =~ /^[01]$/) { # only two valid for now. $sth->execute($newstatus,$id); } elsif ($newstatus =~ /^domo(?:n|ff)$/) { $sth->execute(($newstatus eq 'domon' ? 1 : 0),$id); } } $sth = $dbh->prepare("select status from domains where domain_id=?"); $sth->execute($id); my ($status) = $sth->fetchrow_array; return $status; } # end domStatus() ## DNSDB::importAXFR # Import a domain via AXFR # Takes AXFR host, domain to transfer, group to put the domain in, # and optionally: # - active/inactive state flag (defaults to active) # - overwrite-SOA flag (defaults to off) # - overwrite-NS flag (defaults to off, doesn't affect subdomain NS records) # Returns a status code (OK, WARN, or FAIL) and message - message should be blank # if status is OK, but WARN includes conditions that are not fatal but should # really be reported. sub importAXFR { my $dbh = shift; my $ifrom_in = shift; my $domain = shift; my $group = shift; my $status = shift || 1; my $rwsoa = shift || 0; my $rwns = shift || 0; ##fixme: add mode to delete&replace, merge+overwrite, merge new? my $nrecs = 0; my $soaflag = 0; my $nsflag = 0; my $warnmsg = ''; my $ifrom; # choke on possible bad setting in ifrom # IPv4 and v6, and valid hostnames! ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); return ('FAIL', "Bad AXFR source host $ifrom") unless ($ifrom) = ($ifrom_in =~ /^([0-9a-f\:.]+|[0-9a-z_.-]+)$/i); # Allow transactions, and raise an exception on errors so we can catch it later. # Use local to make sure these get "reset" properly on exiting this block local $dbh->{AutoCommit} = 0; local $dbh->{RaiseError} = 1; my $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); my $dom_id; # quick check to start to see if we've already got one $sth->execute($domain); ($dom_id) = $sth->fetchrow_array; return ('FAIL', "Domain already exists") if $dom_id; eval { # can't do this, can't nest transactions. sigh. #my ($dcode, $dmsg) = addDomain(dbh, domain, group, status); ##fixme: serial my $sth = $dbh->prepare("INSERT INTO domains (domain,group_id,status) VALUES (?,?,?)"); $sth->execute($domain,$group,$status); ## bizarre DBI<->Net::DNS interaction bug: ## sometimes a zone will cause an immediate commit-and-exit (sort of) of the while() ## fixed, apparently I was doing *something* odd, but not certain what it was that ## caused a commit instead of barfing # get domain id so we can do the records $sth = $dbh->prepare("SELECT domain_id FROM domains WHERE domain=?"); $sth->execute($domain); ($dom_id) = $sth->fetchrow_array(); my $res = Net::DNS::Resolver->new; $res->nameservers($ifrom); $res->axfr_start($domain) or die "Couldn't begin AXFR\n"; while (my $rr = $res->axfr_next()) { my $type = $rr->type; my $sql = "INSERT INTO records (domain_id,host,type,ttl,val"; my $vallen = "?,?,?,?,?"; $soaflag = 1 if $type eq 'SOA'; $nsflag = 1 if $type eq 'NS'; my @vallist = ($dom_id, $rr->name, $reverse_typemap{$type}, $rr->ttl); # "Primary" types: # A, NS, CNAME, SOA, PTR(warn in forward), MX, TXT, AAAA, SRV, A6(ob), SPF # maybe KEY # nasty big ugly case-like thing here, since we have to do *some* different # processing depending on the record. le sigh. ##fixme: what record types other than TXT can/will have >255-byte payloads? if ($type eq 'A') { push @vallist, $rr->address; } elsif ($type eq 'NS') { # hmm. should we warn here if subdomain NS'es are left alone? next if ($rwns && ($rr->name eq $domain)); push @vallist, $rr->nsdname; $nsflag = 1; } elsif ($type eq 'CNAME') { push @vallist, $rr->cname; } elsif ($type eq 'SOA') { next if $rwsoa; $vallist[1] = $rr->mname.":".$rr->rname; push @vallist, ($rr->refresh.":".$rr->retry.":".$rr->expire.":".$rr->minimum); $soaflag = 1; } elsif ($type eq 'PTR') { push @vallist, $rr->ptrdname; # hmm. PTR records should not be in forward zones. } elsif ($type eq 'MX') { $sql .= ",distance"; $vallen .= ",?"; push @vallist, $rr->exchange; push @vallist, $rr->preference; } elsif ($type eq 'TXT') { ##fixme: Net::DNS docs say this should be deprecated for rdatastr() or char_str_list(), ## but don't really seem enthusiastic about it. my $rrdata = $rr->txtdata; push @vallist, $rrdata; } elsif ($type eq 'SPF') { ##fixme: and the same caveat here, since it is apparently a clone of ::TXT my $rrdata = $rr->txtdata; push @vallist, $rrdata; } elsif ($type eq 'AAAA') { push @vallist, $rr->address; } elsif ($type eq 'SRV') { $sql .= ",distance,weight,port" if $type eq 'SRV'; $vallen .= ",?,?,?" if $type eq 'SRV'; push @vallist, $rr->target; push @vallist, $rr->priority; push @vallist, $rr->weight; push @vallist, $rr->port; } elsif ($type eq 'KEY') { # we don't actually know what to do with these... push @vallist, ($rr->flags.":".$rr->protocol.":".$rr->algorithm.":".$rr->key.":".$rr->keytag.":".$rr->privatekeyname); } else { my $rrdata = $rr->rdatastr; push @vallist, $rrdata; # Finding a different record type is not fatal.... just problematic. # We may not be able to export it correctly. $warnmsg .= "Unusual record ".$rr->name." ($type) found\n"; } # BIND supports: # A CNAME HINFO MB(ex) MD(ob) MF(ob) MG(ex) MINFO(ex) MR(ex) MX NS NULL # PTR SOA TXT WKS AFSDB(ex) ISDN(ex) RP(ex) RT(ex) X25(ex) PX # ... if one can ever find the right magic to format them correctly # Net::DNS supports: # RRSIG SIG NSAP NS NIMLOC NAPTR MX MR MINFO MG MB LOC ISDN IPSECKEY HINFO # EID DNAME CNAME CERT APL AFSDB AAAA A DS NXT NSEC3PARAM NSEC3 NSEC KEY # DNSKEY DLV X25 TXT TSIG TKEY SSHFP SRV SPF SOA RT RP PX PTR NULL APL::AplItem $sth = $dbh->prepare($sql.") VALUES (".$vallen.")") or die "problem preparing record insert SQL\n"; $sth->execute(@vallist) or die "failed to insert ".$rr->string.": ".$sth->errstr."\n"; $nrecs++; } # while axfr_next # Overwrite SOA record if ($rwsoa) { $soaflag = 1; my $sthgetsoa = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); my $sthputsoa = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); $sthgetsoa->execute($group,$reverse_typemap{SOA}); while (my ($host,$val,$ttl) = $sthgetsoa->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sthputsoa->execute($dom_id,$host,$reverse_typemap{SOA},$val,$ttl); } } # Overwrite NS records if ($rwns) { $nsflag = 1; my $sthgetns = $dbh->prepare("SELECT host,val,ttl FROM default_records WHERE group_id=? AND type=?"); my $sthputns = $dbh->prepare("INSERT INTO records (domain_id,host,type,val,ttl) VALUES (?,?,?,?,?)"); $sthgetns->execute($group,$reverse_typemap{NS}); while (my ($host,$val,$ttl) = $sthgetns->fetchrow_array()) { $host =~ s/DOMAIN/$domain/g; $val =~ s/DOMAIN/$domain/g; $sthputns->execute($dom_id,$host,$reverse_typemap{NS},$val,$ttl); } } die "No records found; either $ifrom is not authoritative or doesn't allow transfers\n" if !$nrecs; die "Bad zone: No SOA record!\n" if !$soaflag; die "Bad zone: No NS records!\n" if !$nsflag; $dbh->commit; }; if ($@) { my $msg = $@; eval { $dbh->rollback; }; return ('FAIL',$msg." $warnmsg"); } else { return ('WARN', $warnmsg) if $warnmsg; return ('OK',"Imported OK"); } # it should be impossible to get here. return ('WARN',"OOOK!"); } # end importAXFR() ## DNSDB::export() # Export the DNS database, or a part of it # Takes database handle, export type, optional arguments depending on type # Writes zone data to targets as appropriate for type sub export { my $dbh = shift; my $target = shift; if ($target eq 'tiny') { __export_tiny($dbh,@_); } # elsif ($target eq 'foo') { # __export_foo($dbh,@_); #} # etc } # end export() ## DNSDB::__export_tiny # Internal sub to implement tinyDNS (compatible) export # Takes database handle, filehandle to write export to, optional argument(s) # to determine which data gets exported sub __export_tiny { my $dbh = shift; my $datafile = shift; ##fixme: slurp up further options to specify particular zone(s) to export ## Convert a bare number into an octal-coded pair of octets. # Take optional arg to indicate a decimal or hex input. Defaults to hex. sub octalize { my $tmp = shift; my $srctype = shift || 'h'; # default assumes hex string $tmp = sprintf "%0.4x", hex($tmp) if $srctype eq 'h'; # 0-pad hex to 4 digits $tmp = sprintf "%0.4x", $tmp if $srctype eq 'd'; # 0-pad decimal to 4 hex digits my @o = ($tmp =~ /^(..)(..)$/); # split into octets return sprintf "\\%0.3o\\%0.3o", hex($o[0]), hex($o[1]);; } ##fixme: fail if $datafile isn't an open, writable file # easy case - export all evarything # not-so-easy case - export item(s) specified # todo: figure out what kind of list we use to export items my $domsth = $dbh->prepare("SELECT domain_id,domain,status FROM domains WHERE status=1"); my $recsth = $dbh->prepare("SELECT host,type,val,distance,weight,port,ttl ". "FROM records WHERE domain_id=?"); $domsth->execute(); while (my ($domid,$dom,$domstat) = $domsth->fetchrow_array) { $recsth->execute($domid); while (my ($host,$type,$val,$dist,$weight,$port,$ttl) = $recsth->fetchrow_array) { ##fixme: need to store location in the db, and retrieve it here. # temporarily hardcoded to empty so we can include it further down. my $loc = ''; ##fixme: record validity timestamp. tinydns supports fiddling with timestamps. # note $ttl must be set to 0 if we want to use tinydns's auto-expiring timestamps. # timestamps are TAI64 # ~~ 2^62 + time() my $stamp = ''; # raw packet in unknown format: first byte indicates length # of remaining data, allows up to 255 raw bytes ##fixme? append . to all host/val hostnames if ($typemap{$type} eq 'SOA') { # host contains pri-ns:responsible # val is abused to contain refresh:retry:expire:minttl ##fixme: "manual" serial vs tinydns-autoserial # let's be explicit about abusing $host and $val my ($email, $primary) = (split /:/, $host)[0,1]; my ($refresh, $retry, $expire, $min_ttl) = (split /:/, $val)[0,1,2,3]; print $datafile "Z$dom:$primary:$email"."::$refresh:$retry:$expire:$min_ttl:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'A') { print $datafile "+$host:$val:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'NS') { print $datafile "\&$host"."::$val:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'AAAA') { print $datafile ":$host:28:"; my $altgrp = 0; my @altconv; # Split in to up to 8 groups of hex digits (allows for IPv6 :: 0-collapsing) foreach (split /:/, $val) { if (/^$/) { # flag blank entry; this is a series of 0's of (currently) unknown length $altconv[$altgrp++] = 's'; } else { # call sub to convert 1-4 hex digits to 2 string-rep octal bytes $altconv[$altgrp++] = octalize($_) } } foreach my $octet (@altconv) { # if not 's', output print $datafile $octet unless $octet =~ /^s$/; # if 's', output (9-array length)x literal '\000\000' print $datafile '\000\000'x(9-$altgrp) if $octet =~ /^s$/; } print $datafile ":$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'MX') { print $datafile "\@$host"."::$val:$dist:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'TXT') { ##fixme: split v-e-r-y long TXT strings? will need to do so for BIND export, at least $val =~ s/:/\\072/g; # may need to replace other symbols print $datafile "'$host:$val:$ttl:$stamp:$loc\n"; # by-hand TXT #:deepnet.cx:16:2v\075spf1\040a\040a\072bacon.deepnet.cx\040a\072home.deepnet.cx\040-all:3600 #@ IN TXT "v=spf1 a a:bacon.deepnet.cx a:home.deepnet.cx -all" #'deepnet.cx:v=spf1 a a\072bacon.deepnet.cx a\072home.deepnet.cx -all:3600 #txttest IN TXT "v=foo bar:bob kn;ob' \" !@#$%^&*()-=_+[]{}<>?" #:txttest.deepnet.cx:16:\054v\075foo\040bar\072bob\040kn\073ob\047\040\042\040\041\100\043\044\045\136\046\052\050\051-\075\137\053\133\135\173\175\074\076\077:3600 # very long TXT record as brought in by axfr-get # note tinydns does not support >512-byte RR data, need axfr-dns (for TCP support) for that # also note, tinydns does not seem to support <512, >256-byte RRdata from axfr-get either. :/ #:longtxt.deepnet.cx:16: #\170this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. #\263 it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. #\351 it is really long. long. very long. really very long.this is a very long txt record. it is really long. long. very long. really very long. this is a very long txt record. it is really long. long. very long. really very long. #:3600 } elsif ($typemap{$type} eq 'CNAME') { print $datafile "C$host:$val:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'SRV') { # data is two-byte values for priority, weight, port, in that order, # followed by length/string data print $datafile ":$host:33:".octalize($dist,'d').octalize($weight,'d').octalize($port,'d'); $val .= '.' if $val !~ /\.$/; foreach (split /\./, $val) { printf $datafile "\\%0.3o%s", length($_), $_; } print $datafile "\\000:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'RP') { # RP consists of two mostly free-form strings. # The first is supposed to be an email address with @ replaced by . (as with the SOA contact) # The second is the "hostname" of a TXT record with more info. print $datafile ":$host:17:"; my ($who,$what) = split /\s/, $val; foreach (split /\./, $who) { printf $datafile "\\%0.3o%s", length($_), $_; } print $datafile '\000'; foreach (split /\./, $what) { printf $datafile "\\%0.3o%s", length($_), $_; } print $datafile "\\000:$ttl:$stamp:$loc\n"; } elsif ($typemap{$type} eq 'PTR') { # must handle both IPv4 and IPv6 ##work # data should already be in suitable reverse order. print $datafile "^$host:$val:$ttl:$stamp:$loc\n"; } else { # raw record. we don't know what's in here, so we ASS-U-ME the user has # put it in correctly, since either the user is messing directly with the # database, or the record was imported via AXFR # # convert anything not a-zA-Z0-9.- to octal coding ##fixme: add flag to export "unknown" record types - note we'll probably end up # mangling them since they were written to the DB from Net::DNS::RR::->rdatastr. #print $datafile ":$host:$type:$val:$ttl:$stamp:$loc\n"; } # record type if-else } # while ($recsth) } # while ($domsth) } # end __export_tiny() ## DNSDB::mailNotify() # Sends notification mail to recipients regarding an IPDB operation sub mailNotify { my $dbh = shift; my ($subj,$message) = @_; return if $config{mailhost} eq 'smtp.example.com'; # do nothing if still using default SMTP host. my $mailer = Net::SMTP->new($config{mailhost}, Hello => "dnsadmin.$config{domain}"); my $mailsender = ($config{mailsender} ? $config{mailsender} : $config{mailnotify}); $mailer->mail($mailsender); $mailer->to($config{mailnotify}); $mailer->data("From: \"$config{mailname}\" <$mailsender>\n", "To: <$config{mailnotify}>\n", "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n", "Subject: $subj\n", "X-Mailer: DNSAdmin Notify v".sprintf("%.1d",$DNSDB::VERSION)."\n", "Organization: $config{orgname}\n", "\n$message\n"); $mailer->quit; } # shut Perl up 1;