#!/usr/bin/perl -w -T # Main web UI script for DeepNet DNS Administrator ## # $Id: dns.cgi 293 2012-03-27 21:11:59Z kdeugau $ # Copyright 2008-2011 Kris Deugau # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . ## use strict; use warnings; use CGI::Carp qw (fatalsToBrowser); use CGI::Simple; use HTML::Template; use CGI::Session; use Crypt::PasswdMD5; use Digest::MD5 qw(md5_hex); use Net::DNS; use DBI; use Data::Dumper; #sub is_tainted { # # from perldoc perlsec # return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 }; #} #use Cwd 'abs_path'; #use File::Basename; #use lib dirname( abs_path $0 ); #die "argh! tainted!" if is_tainted($0); #die "argh! \@INC got tainted!" if is_tainted(@INC); # don't remove! required for GNU/FHS-ish install from tarball use lib '.'; ##uselib## use DNSDB qw(:ALL); my @debugbits; # temp, to be spit out near the end of processing my $debugenv = 0; # Let's do these templates right... my $templatedir = "templates"; # Set up the CGI object... my $q = new CGI::Simple; # ... and get query-string params as well as POST params if necessary $q->parse_query_string; # This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about... my %webvar = $q->Vars; # shut up some warnings, in case we arrive somewhere we forgot to set this $webvar{defrec} = 'n' if !$webvar{defrec}; # non-default records $webvar{revrec} = 'n' if !$webvar{revrec}; # non-reverse (domain) records # load some local system defaults (mainly DB connect info) # note this is not *absolutely* fatal, since there's a default dbname/user/pass in DNSDB.pm # we'll catch a bad DB connect string once we get to trying that ##fixme: pass params to loadConfig, and use them there, to allow one codebase to support multiple sites if (!loadConfig()) { warn "Using default configuration; unable to load custom settings: $DNSDB::errstr"; } # persistent stuff needed on most/all pages my $sid = ($webvar{sid} ? $webvar{sid} : undef); my $session = new CGI::Session("driver:File", $sid, {Directory => $config{sessiondir}}) or die CGI::Session->errstr(); #$sid = $session->id() if !$sid; if (!$sid) { # init stuff. can probably axe this down to just above if'n'when user manipulation happens $sid = $session->id(); $session->expire($config{timeout}); # need to know the "upper" group the user can deal with; may as well # stick this in the session rather than calling out to the DB every time. $session->param('logingroup',1); $session->param('curgroup',1); # yes, we *do* need to track this too. er, probably. $session->param('domlistsortby','domain'); $session->param('domlistorder','ASC'); $session->param('revzonessortby','revnet'); $session->param('revzonesorder','ASC'); $session->param('useradminsortby','user'); $session->param('useradminorder','ASC'); $session->param('grpmansortby','group'); $session->param('grpmanorder','ASC'); $session->param('reclistsortby','host'); $session->param('reclistorder','ASC'); } # Just In Case. Stale sessions should not be resurrectable. if ($sid ne $session->id()) { $sid = ''; changepage(page=> "login", sessexpired => 1); } # normal expiry, more or less if ($session->is_expired) { $sid = ''; changepage(page=> "login", sessexpired => 1); } my $logingroup = ($session->param('logingroup') ? $session->param('logingroup') : 1); my $curgroup = ($session->param('curgroup') ? $session->param('curgroup') : $logingroup); # decide which page to spit out... # also set $webvar{page} before we try to use it. $webvar{page} = 'login' if !$webvar{page}; # per-page startwith, filter, searchsubs ##fixme: complain-munge-and-continue with non-"[a-z0-9-.]" filter and startwith $webvar{startwith} =~ s/^(0-9|[a-z]).*/$1/ if $webvar{startwith}; # not much call for chars not allowed in domain names $webvar{filter} =~ s/[^a-zA-Z0-9_.:@-]//g if $webvar{filter}; ## only set 'y' if box is checked, no other values legal ## however, see https://secure.deepnet.cx/trac/dnsadmin/ticket/31 # first, drop obvious fakes delete $webvar{searchsubs} if $webvar{searchsubs} && $webvar{searchsubs} !~ /^[ny]/; # strip the known "turn me off!" bit. $webvar{searchsubs} =~ s/^n\s?// if $webvar{searchsubs}; # strip non-y/n - note this legitimately allows {searchsubs} to go empty $webvar{searchsubs} =~ s/[^yn]//g if $webvar{searchsubs}; $session->param($webvar{page}.'startwith', $webvar{startwith}) if defined($webvar{startwith}); $session->param($webvar{page}.'filter', $webvar{filter}) if defined($webvar{filter}); $session->param($webvar{page}.'searchsubs', $webvar{searchsubs}) if defined($webvar{searchsubs}); my $startwith = $session->param($webvar{page}.'startwith'); my $filter = $session->param($webvar{page}.'filter'); my $searchsubs = $session->param($webvar{page}.'searchsubs'); # ... and assemble the args my @filterargs; push @filterargs, "^[$startwith]" if $startwith; push @filterargs, $filter if $filter; # nrgh, can't handle login here because we don't have a database handle to check the user/pass with yet my $header = HTML::Template->new(filename => "$templatedir/header.tmpl"); my $footer = HTML::Template->new(filename => "$templatedir/footer.tmpl"); $header->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp'; $footer->param(version => $DNSDB::VERSION); ## set up "URL to self" # @#$%@%@#% XHTML - & in a URL must be escaped. >:( my $uri_self = $ENV{REQUEST_URI}; $uri_self =~ s/\&([a-z])/\&\;$1/g; # le sigh. and we need to strip any previous action $uri_self =~ s/\&action=[^&]+//g; # and search filter options. these get stored in the session, but discarded # as soon as you switch to a different page. ##fixme: think about retaining these on a per-page basis, as well as offset; same as the sort-order bits no warnings qw(uninitialized); $uri_self =~ s/\&startwith=[a-z09-]*(\&)?/$1/g; $uri_self =~ s/\&searchsubs=[a-z09-]*(\&)?/$1/g; $uri_self =~ s/\&filter=[a-z09-]*(\&)?/$1/g; use warnings qw(uninitialized); # Fix up $uri_self so we don't lose the session/page $uri_self .= "?sid=$sid&page=$webvar{page}" if $uri_self =~ m{/dns.cgi$}; $uri_self = "$ENV{SCRIPT_NAME}?sid=$sid&page=$webvar{page}$1" if $uri_self =~ m{/dns.cgi\&(.+)$}; # pagination my $perpage = 15; $perpage = $config{perpage} if $config{perpage}; my $offset = ($webvar{offset} ? $webvar{offset} : 0); # NB: these must match the field name and SQL ascend/descend syntax respectively my $sortby = "domain"; my $sortorder = "ASC"; ##fixme: quit throwing the database handle around, and put all the SQL and direct DB fiddling into DNSDB.pm # dbname, user, pass, host (optional) my ($dbh,$msg) = connectDB($config{dbname}, $config{dbuser}, $config{dbpass}, $config{dbhost}); if (!$dbh) { print "Content-type: text/html\n\n"; print $header->output; my $errpage = HTML::Template->new(filename => "$templatedir/dberr.tmpl"); $errpage->param(errmsg => $msg); print $errpage->output; print $footer->output; exit; } # Load config pieces from the database. Ideally all but the DB user/pass/etc should be loaded here. initGlobals($dbh); # security check - does the user have permission to view this entity? # this is a prep step used "many" places my @viewablegroups; getChildren($dbh, $logingroup, \@viewablegroups, 'all'); push @viewablegroups, $logingroup; my $page; eval { # sigh. can't set loop_context_vars or global_vars once instantiated. $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl", loop_context_vars => 1, global_vars => 1); }; if ($@) { my $msg = $@; $page = HTML::Template->new(filename => "$templatedir/badpage.tmpl"); if (-e "$templatedir/$webvar{page}.tmpl") { $page->param(badtemplate => $q->escapeHTML($msg)); } else { warn "Bad page $webvar{page} requested"; $page->param(badpage => $q->escapeHTML($webvar{page})); } $webvar{page} = 'badpage'; } # handle login redirect if ($webvar{action}) { if ($webvar{action} eq 'login') { # Snag ACL/permissions here too # my $sth = $dbh->prepare("SELECT user_id,group_id,password,firstname,lastname FROM users WHERE username=?"); # $sth->execute($webvar{username}); # # if (my ($uid,$gid,$pass,$fname,$lname) = $sth->fetchrow_array) { # $webvar{password} = '' if !$webvar{password}; # # if ($pass =~ m|^\$1\$([A-Za-z0-9/.]+)\$|) { # # native passwords (crypt-md5) # $webvar{loginfailed} = 1 if $pass ne unix_md5_crypt($webvar{password},$1); # } elsif ($pass =~ /^[0-9a-f]{32}$/) { # # VegaDNS import (hex-coded MD5) # $webvar{loginfailed} = 1 if $pass ne md5_hex($webvar{password}); # } else { # # plaintext (convenient now and then) # $webvar{loginfailed} = 1 if $pass ne $webvar{password}; # } my $userdata = login($dbh, $webvar{username}, $webvar{password}); if ($userdata) { # set session bits $session->param('logingroup',$userdata->{group_id}); $session->param('curgroup',$userdata->{group_id}); $session->param('uid',$userdata->{user_id}); $session->param('username',$webvar{username}); changepage(page => "domlist"); } else { $webvar{loginfailed} = 1; } # user data fetch check } elsif ($webvar{action} eq 'logout') { # delete the session $session->delete(); $session->flush(); my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}"; $newurl =~ s|/[^/]+$|/|; print "Status: 302\nLocation: $newurl\n\n"; exit; } elsif ($webvar{action} eq 'chgroup') { # fiddle session-stored group data # magic incantation to... uhhh... # ... and the "change group" bits... $uri_self =~ s/\&group=[^&]*//g; # security check - does the user have permission to view this entity? my $errmsg; if (!(grep /^$webvar{group}$/, @viewablegroups)) { # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere. $session->param('curgroup',$logingroup); $webvar{group} = $logingroup; $curgroup = $logingroup; $errmsg = "You are not permitted to view or make changes in the requested group"; $page->param(errmsg => $errmsg); } $session->param('curgroup', $webvar{group}); $curgroup = ($webvar{group} ? $webvar{group} : $session->param('curgroup')); # I hate special cases. ##fixme: probably need to handle webvar{revrec}=='y' too if ($webvar{page} eq 'reclist' && $webvar{defrec} eq 'y') { my %args = (page => $webvar{page}, id => $curgroup, defrec => $webvar{defrec}, revrec => $webvar{revrec}); $args{errmsg} = $errmsg if $errmsg; changepage(%args); } } } # handle global webvar{action}s # Misc Things To Do on most pages initPermissions($dbh, $session->param('uid')); initActionLog($dbh, $session->param('uid')); $page->param(sid => $sid) unless $webvar{page} eq 'login'; # no session ID on the login page if ($webvar{page} eq 'login') { $page->param(loginfailed => 1) if $webvar{loginfailed}; $page->param(sessexpired => 1) if $webvar{sessexpired}; # $page->param(orgname => $config{orgname}) if $config{orgname} ne 'Example Corp'; $page->param(version => $DNSDB::VERSION); } elsif ($webvar{page} eq 'domlist' or $webvar{page} eq 'index') { $page->param(domlist => 1); # hmm. seeing problems in some possibly-not-so-corner cases. # this currently only handles "domain on", "domain off" if (defined($webvar{zonestatus})) { # security check - does the user have permission to access this entity? my $flag = 0; foreach (@viewablegroups) { $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'domain'); } if ($flag && ($permissions{admin} || $permissions{domain_edit})) { my $stat = zoneStatus($dbh,$webvar{id},'n',$webvar{zonestatus}); $page->param(resultmsg => $DNSDB::resultstr); } else { $page->param(errmsg => "You are not permitted to view or change the requested domain"); } $uri_self =~ s/\&zonestatus=[^&]*//g; # clean up URL for stuffing into templates } if ($session->param('resultmsg')) { $page->param(resultmsg => $session->param('resultmsg')); $session->clear('resultmsg'); } if ($session->param('errmsg')) { $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); } $page->param(curpage => $webvar{page}); listdomains(); } elsif ($webvar{page} eq 'newdomain') { changepage(page => "domlist", errmsg => "You are not permitted to add domains") unless ($permissions{admin} || $permissions{domain_create}); fill_grouplist("grouplist"); if ($session->param('add_failed')) { $session->clear('add_failed'); $page->param(add_failed => 1); $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); $page->param(domain => $webvar{domain}); } } elsif ($webvar{page} eq 'adddomain') { changepage(page => "domlist", errmsg => "You are not permitted to add domains") unless ($permissions{admin} || $permissions{domain_create}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{group}, type => 'group')) { $session->param('add_failed', 1); ##fixme: domain a security risk for XSS? changepage(page => "newdomain", domain => $webvar{domain}, errmsg => "You do not have permission to add a domain to the requested group"); } $webvar{makeactive} = 0 if !defined($webvar{makeactive}); my ($code,$msg) = addDomain($dbh,$webvar{domain},$webvar{group},($webvar{makeactive} eq 'on' ? 1 : 0), (username => $session->param("username"), id => $session->param("uid"))); if ($code eq 'OK') { mailNotify($dbh, "New ".($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive')." Domain Created", ($webvar{makeactive} eq 'on' ? 'Active' : 'Inactive').qq( domain "$webvar{domain}" added by ). $session->param("username")); changepage(page => "reclist", id => $msg); } else { $session->param('add_failed', 1); ##fixme: domain a security risk for XSS? ##fixme: keep active/inactive state, group selection changepage(page => "newdomain", domain => $webvar{domain}, errmsg => $msg); } } elsif ($webvar{page} eq 'deldom') { changepage(page => "domlist", errmsg => "You are not permitted to delete domains") unless ($permissions{admin} || $permissions{domain_delete}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{id}, type => 'domain')) { changepage(page => "domlist", errmsg => "You do not have permission to delete the requested domain"); } $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(domain => domainName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { my $pargroup = parentID($dbh, (id => $webvar{id}, type => 'domain', revrec => $webvar{revrec})); my ($code,$msg) = delZone($dbh, $webvar{id}, $webvar{revrec}); if ($code eq 'OK') { changepage(page => "domlist", resultmsg => $msg); } else { changepage(page => "domlist", errmsg => $msg); } } else { # cancelled. whee! changepage(page => "domlist"); } } elsif ($webvar{page} eq 'revzones') { $webvar{revrec} = 'y'; if (defined($webvar{zonestatus})) { # security check - does the user have permission to access this entity? my $flag = 0; foreach (@viewablegroups) { $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'revzone'); } if ($flag && ($permissions{admin} || $permissions{domain_edit})) { my $stat = zoneStatus($dbh,$webvar{id},'y',$webvar{zonestatus}); $page->param(resultmsg => $DNSDB::resultstr); } else { $page->param(errmsg => "You are not permitted to view or change the requested reverse zone"); } $uri_self =~ s/\&zonestatus=[^&]*//g; # clean up URL for stuffing into templates } if ($session->param('resultmsg')) { $page->param(resultmsg => $session->param('resultmsg')); $session->clear('resultmsg'); } if ($session->param('errmsg')) { $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); } $page->param(curpage => $webvar{page}); listzones(); } elsif ($webvar{page} eq 'newrevzone') { ## scope/access check - use domain settings? invent new (bleh) changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones") unless ($permissions{admin} || $permissions{domain_create}); fill_grouplist("grouplist"); # prepopulate revpatt with the matching default record # getRecByName($dbh, (revrec => $webvar{revrec}, defrec => $webvar{defrec}, host => 'string')); if ($session->param('add_failed')) { $session->clear('add_failed'); $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); $page->param(revzone => $webvar{revzone}); $page->param(revpatt => $webvar{revpatt}); } } elsif ($webvar{page} eq 'addrevzone') { changepage(page => "revzones", errmsg => "You are not permitted to add reverse zones") unless ($permissions{admin} || $permissions{domain_create}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{group}, type => 'group')) { changepage(page => "newrevzone", add_failed => 1, revzone => $webvar{revzone}, revpatt => $webvar{revpatt}, errmsg => "You do not have permission to add a reverse zone to the requested group"); } my ($code,$msg) = addRDNS($dbh, $webvar{revzone}, $webvar{revpatt}, $webvar{group}, ($webvar{makeactive} eq 'on' ? 1 : 0)); if ($code eq 'OK') { changepage(page => "reclist", id => $msg, revrec => 'y'); } elsif ($code eq 'WARN') { changepage(page => "reclist", id => $msg, revrec => 'y', warnmsg => $DNSDB::resultstr); } else { $session->param('add_failed', 1); changepage(page => "newrevzone", revzone => $webvar{revzone}, revpatt => $webvar{revpatt}, errmsg => $msg); } } elsif ($webvar{page} eq 'delrevzone') { changepage(page => "revzones", errmsg => "You are not permitted to delete reverse zones") unless ($permissions{admin} || $permissions{domain_delete}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{id}, type => 'revzone')) { changepage(page => "revzones", errmsg => "You do not have permission to delete the requested reverse zone"); } $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(revzone => revName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { my $pargroup = parentID($dbh, (id => $webvar{id}, type => 'revzone', revrec => $webvar{revrec})); my $zone = revName($dbh, $webvar{id}); my ($code,$msg) = delZone($dbh, $webvar{id}, 'y'); if ($code eq 'OK') { changepage(page => "revzones", resultmsg => $msg); } else { changepage(page => "revzones", errmsg => $msg); } } else { # cancelled. whee! changepage(page => "revzones"); } } elsif ($webvar{page} eq 'reclist') { # security check - does the user have permission to view this entity? if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) { $page->param(errmsg => "You are not permitted to view or change the requested ". ($webvar{defrec} eq 'y' ? "group's default records" : ($webvar{revrec} eq 'y' ? "reverse zone's records" : "domain's records"))); $page->param(perm_err => 1); # this causes the template to skip the record listing output. goto DONERECLIST; # and now we skip filling in the content which is not printed due to perm_err above } # hmm. where do we send them? if ($webvar{defrec} eq 'y' && !$permissions{admin}) { $page->param(errmsg => "You are not permitted to edit default records"); $page->param(perm_err => 1); } else { $page->param(mayeditsoa => $permissions{admin} || $permissions{domain_edit}); ##fixme: ACL needs pondering. Does "edit domain" interact with record add/remove/etc? # Note this seems to be answered "no" in Vega. # ACLs $page->param(record_create => ($permissions{admin} || $permissions{record_create}) ); # we don't have any general edit links on the page; they're all embedded in the TMPL_LOOP # $page->param(record_edit => ($permissions{admin} || $permissions{record_edit}) ); $page->param(record_delete => ($permissions{admin} || $permissions{record_delete}) ); # Handle record list for both default records (per-group) and live domain records $page->param(defrec => $webvar{defrec}); $page->param(revrec => $webvar{revrec}); $page->param(id => $webvar{id}); $page->param(curpage => $webvar{page}); my $count = getRecCount($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}, $filter); $sortby = 'host'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols; my %colheads; if ($webvar{revrec} eq 'n') { @cols = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl'); %colheads = (host => 'Name', type => 'Type', val => 'Address', distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL'); } else { @cols = ('val', 'type', 'host', 'ttl'); %colheads = (val => 'IP Address', type => 'Type', host => 'Hostname', ttl => 'TTL'); } my %custom = (id => $webvar{id}, defrec => $webvar{defrec}, revrec => $webvar{revrec}); fill_colheads($sortby, $sortorder, \@cols, \%colheads, \%custom); # fill the page-count and first-previous-next-last-all details fill_pgcount($count,"records", ($webvar{defrec} eq 'y' ? "group ".groupName($dbh,$webvar{id}) : ($webvar{revrec} eq 'y' ? revName($dbh,$webvar{id}) : domainName($dbh,$webvar{id})) )); fill_fpnla($count); # should put some params on this sub... $page->param(defrec => $webvar{defrec}); showzone($webvar{defrec}, $webvar{revrec}, $webvar{id}); if ($webvar{defrec} eq 'n') { if ($webvar{revrec} eq 'n') { $page->param(logdom => 1); } else { $page->param(logrdns => 1); } } if ($session->param('resultmsg')) { $page->param(resultmsg => $session->param('resultmsg')); $session->clear('resultmsg'); } if ($session->param('warnmsg')) { $page->param(warnmsg => $session->param('warnmsg')); $session->clear('warnmsg'); } if ($session->param('errmsg')) { $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); } } # close "you can't edit default records" check # Yes, this is a GOTO target. PTBHTTT. DONERECLIST: ; } elsif ($webvar{page} eq 'record') { # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) { $page->param(perm_err => "You are not permitted to edit the requested record"); goto DONEREC; } # round 2, check the parent. if (!check_scope(id => $webvar{parentid}, type => ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) { my $msg = ($webvar{defrec} eq 'y' ? "You are not permitted to add or edit default records in the requested group" : "You are not permitted to add or edit records in the requested domain/zone"); $page->param(perm_err => $msg); goto DONEREC; } $page->param(defrec => $webvar{defrec}); $page->param(revrec => $webvar{revrec}); $page->param(fwdzone => $webvar{revrec} eq 'n'); if ($webvar{recact} eq 'new') { changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_create}); $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); fill_recdata(); } elsif ($webvar{recact} eq 'add') { changepage(page => "reclist", errmsg => "You are not permitted to add records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_create}); my @recargs = ($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid}, \$webvar{name},\$webvar{type},\$webvar{address},$webvar{ttl}); if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{distance}; if ($webvar{type} == $reverse_typemap{SRV}) { push @recargs, $webvar{weight}; push @recargs, $webvar{port}; } } my ($code,$msg) = addRec(@recargs); if ($code eq 'OK' || $code eq 'WARN') { my %pageparams = (page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}); $pageparams{warnmsg} = $msg."

\n".$DNSDB::resultstr if $code eq 'WARN'; $pageparams{resultmsg} = $DNSDB::resultstr if $code eq 'OK'; changepage(%pageparams); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "adding"); $page->param(todo => "Add record"); $page->param(recact => "add"); $page->param(parentid => $webvar{parentid}); $page->param(id => $webvar{id}); fill_recdata(); # populate the form... er, mostly. } } elsif ($webvar{recact} eq 'edit') { changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_edit}); $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(id => $webvar{id}); my $recdata = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}); $page->param(name => $recdata->{host}); $page->param(address => $recdata->{val}); $page->param(distance => $recdata->{distance}); $page->param(weight => $recdata->{weight}); $page->param(port => $recdata->{port}); $page->param(ttl => $recdata->{ttl}); $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $recdata->{type})); } elsif ($webvar{recact} eq 'update') { changepage(page => "reclist", errmsg => "You are not permitted to edit records", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{record_edit}); # get current/previous record info so we can log "updated 'foo A 1.2.3.4' to 'foo A 2.3.4.5'" my $oldrec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}); my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{revrec},$webvar{id},$webvar{parentid}, \$webvar{name},\$webvar{type},\$webvar{address},$webvar{ttl}, $webvar{distance},$webvar{weight},$webvar{port}); if ($code eq 'OK' || $code eq 'WARN') { my %pageparams = (page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}); $pageparams{warnmsg} = $msg."

\n".$DNSDB::resultstr if $code eq 'WARN'; $pageparams{resultmsg} = $DNSDB::resultstr if $code eq 'OK'; changepage(%pageparams); } else { $page->param(failed => 1); $page->param(errmsg => $msg); $page->param(wastrying => "updating"); $page->param(todo => "Update record"); $page->param(recact => "update"); $page->param(parentid => $webvar{parentid}); $page->param(id => $webvar{id}); fill_recdata(); } } if ($webvar{defrec} eq 'y') { $page->param(dohere => "default records in group ".groupName($dbh,$webvar{parentid})); } else { $page->param(parentid => $webvar{parentid}); $page->param(dohere => domainName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'n'; $page->param(dohere => revName($dbh,$webvar{parentid})) if $webvar{revrec} eq 'y'; } # Yes, this is a GOTO target. PTBHTTT. DONEREC: ; } elsif ($webvar{page} eq 'delrec') { # This is a complete separate segment since it uses a different template from add/edit records above changepage(page => "reclist", errmsg => "You are not permitted to delete records", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}) unless ($permissions{admin} || $permissions{record_delete}); if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) { # redirect to domlist because we don't have permission for the entity requested changepage(page => 'domlist', revrec => $webvar{revrec}, errmsg => "You do not have permission to delete records in the requested ". ($webvar{defrec} eq 'y' ? 'group' : 'domain')); } $page->param(id => $webvar{id}); $page->param(defrec => $webvar{defrec}); $page->param(revrec => $webvar{revrec}); $page->param(parentid => $webvar{parentid}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); my $rec = getRecLine($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}); $page->param(host => $rec->{host}); $page->param(ftype => $typemap{$rec->{type}}); $page->param(recval => $rec->{val}); } elsif ($webvar{del} eq 'ok') { my ($code,$msg) = delRec($dbh, $webvar{defrec}, $webvar{revrec}, $webvar{id}); if ($code eq 'OK') { changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}, resultmsg => $msg); } else { ## need to find failure mode changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}, errmsg => $msg); } } else { changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, revrec => $webvar{revrec}); } } elsif ($webvar{page} eq 'editsoa') { # security check - does the user have permission to view this entity? # id is domain/revzone/group id if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) { changepage(page => 'domlist', errmsg => "You do not have permission to edit the ". ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ". ($webvar{defrec} eq 'y' ? 'group' : 'domain')); } if ($webvar{defrec} eq 'y') { changepage(page => "domlist", errmsg => "You are not permitted to edit default records") unless $permissions{admin}; } else { changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id}) unless ($permissions{admin} || $permissions{domain_edit}); } fillsoa($webvar{defrec},$webvar{revrec},$webvar{id}); } elsif ($webvar{page} eq 'updatesoa') { # security check - does the user have permission to view this entity? # pass 1, record ID if (!check_scope(id => $webvar{recid}, type => ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) { changepage(page => 'domlist', errmsg => "You do not have permission to edit the requested SOA record"); } # pass 2, parent (group or domain) ID if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : ($webvar{revrec} eq 'y' ? 'revzone' : 'domain')))) { changepage(page => 'domlist', errmsg => "You do not have permission to edit the ". ($webvar{defrec} eq 'y' ? 'default ' : '')."SOA record for the requested ". ($webvar{defrec} eq 'y' ? 'group' : 'domain')); } changepage(page => "reclist", errmsg => "You are not permitted to edit domain SOA records", id => $webvar{id}) unless ($permissions{admin} || $permissions{domain_edit}); # get old SOA for log my %soa = getSOA($dbh,$webvar{defrec},$webvar{revrec},$webvar{id}); # my $sth; ###fixme: push SQL into DNSDB.pm ###fixme: data validation: make sure {recid} is really the SOA for {id} # # no domain ID, so we're editing the default SOA for a group (we don't care which one here) # # plus a bit of magic to update the appropriate table # my $sql = "UPDATE ".($webvar{defrec} eq 'y' ? "default_records" : "records"). # " SET host=?, val=?, ttl=? WHERE record_id=?"; # $sth = $dbh->prepare($sql); # $sth->execute("$webvar{contact}:$webvar{prins}", # "$webvar{refresh}:$webvar{retry}:$webvar{expire}:$webvar{minttl}", # $webvar{ttl}, # $webvar{recid}); my ($code, $msg) = updateSOA($dbh, $webvar{defrec}, $webvar{revrec}, (contact => $webvar{contact}, prins => $webvar{prins}, refresh => $webvar{refresh}, retry => $webvar{retry}, expire => $webvar{expire}, minttl => $soa{minttl}, ttl => $webvar{ttl}, recid => $webvar{recid}) ); if ($code eq 'OK') { changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec}, revrec => $webvar{revrec}, resultmsg => "SOA record updated"); } else { $page->param(update_failed => 1); $page->param(msg => $DNSDB::errstr); fillsoa($webvar{defrec},$webvar{revrec},$webvar{id}); } ##fixme: faillog # } else { if (0) { # do this in the order of "default to most common case" my $loggroup; my $logdomain = $webvar{id}; if ($webvar{defrec} eq 'y') { $loggroup = $webvar{id}; $logdomain = 0; } else { $loggroup = parentID($dbh, (id => $logdomain, type => 'domain', revrec => $webvar{revrec})); } logaction($logdomain, $session->param("username"), $loggroup, "Updated ".($webvar{defrec} eq 'y' ? 'default ' : '')."SOA for ". ($webvar{defrec} eq 'y' ? groupName($dbh, $webvar{id}) : domainName($dbh, $webvar{id}) ). ": (ns $soa{prins}, contact $soa{contact}, refresh $soa{refresh},". " retry $soa{retry}, expire $soa{expire}, minTTL $soa{minttl}, TTL $soa{ttl}) to ". "(ns $webvar{prins}, contact $webvar{contact}, refresh $webvar{refresh},". " retry $webvar{retry}, expire $webvar{expire}, minTTL $webvar{minttl}, TTL $webvar{ttl})"); } # if (0) } elsif ($webvar{page} eq 'grpman') { listgroups(); # Permissions! $page->param(addgrp => $permissions{admin} || $permissions{group_create}); $page->param(edgrp => $permissions{admin} || $permissions{group_edit}); $page->param(delgrp => $permissions{admin} || $permissions{group_delete}); if ($session->param('resultmsg')) { $page->param(resultmsg => $session->param('resultmsg')); $session->clear('resultmsg'); } if ($session->param('warnmsg')) { $page->param(warnmsg => $session->param('warnmsg')); $session->clear('warnmsg'); } if ($session->param('errmsg')) { $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); } $page->param(curpage => $webvar{page}); } elsif ($webvar{page} eq 'newgrp') { changepage(page => "grpman", errmsg => "You are not permitted to add groups") unless ($permissions{admin} || $permissions{group_create}); # do.. uhh.. stuff.. if we have no webvar{grpaction} if ($webvar{grpaction} && $webvar{grpaction} eq 'add') { # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{pargroup}, type => 'group')) { changepage(page => "grpman", errmsg => "You are not permitted to add a group to the requested parent group"); } my %newperms; my $alterperms = 0; foreach (@permtypes) { $newperms{$_} = 0; if ($permissions{admin} || $permissions{$_}) { $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0); } else { $alterperms = 1; } } # not gonna provide the 4th param: template-or-clone flag, just yet my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms); if ($code eq 'OK') { if ($alterperms) { changepage(page => "grpman", warnmsg => "You can only grant permissions you hold. New group $webvar{newgroup} added with reduced access."); } else { changepage(page => "grpman", resultmsg => "Added group $webvar{newgroup}"); } } # fallthrough else # no point in doing extra work fill_permissions($page, \%newperms); $page->param(add_failed => 1); $page->param(errmsg => $msg); $page->param(newgroup => $webvar{newgroup}); fill_grouplist('pargroup',$webvar{pargroup}); } else { fill_grouplist('pargroup',$curgroup); # fill default permissions with immediate parent's current ones my %parperms; getPermissions($dbh, 'group', $curgroup, \%parperms); fill_permissions($page, \%parperms); } } elsif ($webvar{page} eq 'delgrp') { changepage(page => "grpman", errmsg => "You are not permitted to delete groups", id => $webvar{parentid}) unless ($permissions{admin} || $permissions{group_delete}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{id}, type => 'group')) { changepage(page => "grpman", errmsg => "You are not permitted to delete the requested group"); } $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); ##fixme # do a check for "group has stuff in it", and splatter a big warning # up along with an unchecked-by-default check box to YES DAMMIT DELETE THE WHOLE THING } elsif ($webvar{del} eq 'ok') { my ($code,$msg) = delGroup($dbh, $webvar{id}); if ($code eq 'OK') { ##fixme: need to clean up log when deleting a major container changepage(page => "grpman", resultmsg => $msg); } else { # need to find failure mode changepage(page => "grpman", errmsg => $msg); } } else { # cancelled. whee! changepage(page => "grpman"); } $page->param(delgroupname => groupName($dbh, $webvar{id})); } elsif ($webvar{page} eq 'edgroup') { changepage(page => "grpman", errmsg => "You are not permitted to edit groups") unless ($permissions{admin} || $permissions{group_edit}); # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{gid}, type => 'group')) { changepage(page => "grpman", errmsg => "You are not permitted to edit the requested group"); } if ($webvar{grpaction} && $webvar{grpaction} eq 'updperms') { # extra safety check; make sure user can't construct a URL to bypass ACLs my %curperms; getPermissions($dbh, 'group', $webvar{gid}, \%curperms); my %chperms; my $alterperms = 0; foreach (@permtypes) { $webvar{$_} = 0 if !defined($webvar{$_}); $webvar{$_} = 1 if $webvar{$_} eq 'on'; if ($permissions{admin} || $permissions{$_}) { $chperms{$_} = $webvar{$_} if $curperms{$_} ne $webvar{$_}; } else { $alterperms = 1; $chperms{$_} = 0; } } my ($code,$msg) = changePermissions($dbh, 'group', $webvar{gid}, \%chperms); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{gid}, "Updated default permissions in group $webvar{gid} (".groupName($dbh, $webvar{gid}).")"); if ($alterperms) { changepage(page => "grpman", warnmsg => "You can only grant permissions you hold. Default permissions in group ". groupName($dbh, $webvar{gid})." updated with reduced access"); } else { changepage(page => "grpman", resultmsg => "Updated default permissions in group ".groupName($dbh, $webvar{gid})); } } # fallthrough else logaction(0, $session->param("username"), $webvar{gid}, "Failed to update default permissions in group ". groupName($dbh, $webvar{gid}).": $msg") if $config{log_failures}; # no point in doing extra work fill_permissions($page, \%chperms); $page->param(errmsg => $msg); } $page->param(gid => $webvar{gid}); $page->param(grpmeddle => groupName($dbh, $webvar{gid})); my %grpperms; getPermissions($dbh, 'group', $webvar{gid}, \%grpperms); fill_permissions($page, \%grpperms); } elsif ($webvar{page} eq 'bulkdomain') { # Bulk operations on domains. Note all but group move are available on the domain list. changepage(page => "domlist", errmsg => "You are not permitted to make bulk domain changes") unless ($permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete}); fill_grouplist("grouplist"); ##fixme ##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm ##fixme my $sth = $dbh->prepare("SELECT count(*) FROM domains WHERE group_id=?"); $sth->execute($curgroup); my ($count) = ($sth->fetchrow_array); $page->param(curpage => $webvar{page}); fill_pgcount($count,'domains',groupName($dbh,$curgroup)); fill_fpnla($count); $page->param(perpage => $perpage); my @domlist; my $sql = "SELECT domain_id,domain FROM domains". " WHERE group_id=?". " ORDER BY domain". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute($curgroup); my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{domid} = $data[0]; $row{domain} = $data[1]; $rownum++; # putting this in the expression below causes failures. *eyeroll* $row{newrow} = $rownum % 5 == 0; push @domlist, \%row; } $page->param(domtable => \@domlist); # ACLs $page->param(maymove => ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete}))); $page->param(maystatus => $permissions{admin} || $permissions{domain_edit}); $page->param(maydelete => $permissions{admin} || $permissions{domain_delete}); } elsif ($webvar{page} eq 'bulkchange') { # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{destgroup}, type => 'group')) { $page->param(errmsg => "You are not permitted to make bulk changes in the requested group"); goto DONEBULK; } if ($webvar{bulkaction} eq 'move') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-move domains") unless ($permissions{admin} || ($permissions{domain_edit} && $permissions{domain_create} && $permissions{domain_delete})); my $newgname = groupName($dbh,$webvar{destgroup}); $page->param(action => "Move to group $newgname"); my @bulkresults; # nngh. due to alpha-sorting on the previous page, we can't use domid-numeric # order here, and since we don't have the domain names until we go around this # loop, we can't alpha-sort them here. :( foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; # second security check - does the user have permission to meddle with this domain? if (!check_scope(id => $webvar{$_}, type => 'domain')) { $row{domerr} = "You are not permitted to make changes to the requested domain"; $row{domain} = $webvar{$_}; push @bulkresults, \%row; next; } $row{domain} = domainName($dbh,$webvar{$_}); my ($code, $msg) = changeGroup($dbh, 'domain', $webvar{$_}, $webvar{destgroup}); if ($code eq 'OK') { logaction($webvar{$_}, $session->param("username"), parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})), "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname"); $row{domok} = ($code eq 'OK'); } else { logaction($webvar{$_}, $session->param("username"), parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})), "Failed to move domain ".domainName($dbh, $webvar{$_})." to group $newgname: $msg") if $config{log_failures}; } $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } elsif ($webvar{bulkaction} eq 'deactivate' || $webvar{bulkaction} eq 'activate') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-$webvar{bulkaction} domains") unless ($permissions{admin} || $permissions{domain_edit}); $page->param(action => "$webvar{bulkaction} domains"); my @bulkresults; foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; # second security check - does the user have permission to meddle with this domain? if (!check_scope(id => $webvar{$_}, type => 'domain')) { $row{domerr} = "You are not permitted to make changes to the requested domain"; $row{domain} = $webvar{$_}; push @bulkresults, \%row; next; } $row{domain} = domainName($dbh,$webvar{$_}); ##fixme: error handling on status change my $stat = zoneStatus($dbh,$webvar{$_},($webvar{bulkaction} eq 'activate' ? 'domon' : 'domoff')); logaction($webvar{$_}, $session->param("username"), parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})), "Changed domain ".domainName($dbh, $webvar{$_})." state to ".($stat ? 'active' : 'inactive')); $row{domok} = 1; # $row{domok} = ($code eq 'OK'); # $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } elsif ($webvar{bulkaction} eq 'delete') { changepage(page => "domlist", errmsg => "You are not permitted to bulk-delete domains") unless ($permissions{admin} || $permissions{domain_delete}); $page->param(action => "$webvar{bulkaction} domains"); my @bulkresults; foreach (keys %webvar) { my %row; next unless $_ =~ /^dom_\d+$/; # second security check - does the user have permission to meddle with this domain? if (!check_scope(id => $webvar{$_}, type => 'domain')) { $row{domerr} = "You are not permitted to make changes to the requested domain"; $row{domain} = $webvar{$_}; push @bulkresults, \%row; next; } $row{domain} = domainName($dbh,$webvar{$_}); my $pargroup = parentID($dbh, (id => $webvar{$_}, type => 'domain', revrec => $webvar{revrec})); my $dom = domainName($dbh, $webvar{$_}); my ($code, $msg) = delZone($dbh, $webvar{$_}, 'n'); if ($code eq 'OK') { logaction($webvar{$_}, $session->param("username"), $pargroup, "Deleted domain $dom"); $row{domok} = ($code eq 'OK'); } else { logaction($webvar{$_}, $session->param("username"), $pargroup, "Failed to delete domain $dom: $msg") if $config{log_failures}; } $row{domerr} = $msg; push @bulkresults, \%row; } $page->param(bulkresults => \@bulkresults); } # move/(de)activate/delete if() # not going to handle the unknown $webvar{action} else; it should not be possible in normal # operations, and anyone who meddles with the URL gets what they deserve. # Yes, this is a GOTO target. PTHBTTT. DONEBULK: ; } elsif ($webvar{page} eq 'useradmin') { if (defined($webvar{userstatus})) { # security check - does the user have permission to access this entity? my $flag = 0; foreach (@viewablegroups) { $flag = 1 if isParent($dbh, $_, 'group', $webvar{id}, 'user'); } if ($flag && ($permissions{admin} || $permissions{user_edit})) { my $stat = userStatus($dbh,$webvar{id},$webvar{userstatus}); logaction(0, $session->param("username"), parentID($dbh, (id => $webvar{id}, type => 'user')), ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u')); $page->param(resultmsg => ($stat ? 'Enabled' : 'Disabled')." ".userFullName($dbh, $webvar{id}, '%u')); } else { $page->param(errmsg => "You are not permitted to view or change the requested user"); } $uri_self =~ s/\&userstatus=[^&]*//g; # clean up URL for stuffing into templates } list_users(); # Permissions! $page->param(adduser => $permissions{admin} || $permissions{user_create}); # should we block viewing other users? Vega blocks "editing"... # NB: no "edit self" link as with groups here. maybe there should be? # $page->param(eduser => $permissions{admin} || $permissions{user_edit}); $page->param(deluser => $permissions{admin} || $permissions{user_delete}); if ($session->param('resultmsg')) { $page->param(resultmsg => $session->param('resultmsg')); $session->clear('resultmsg'); } if ($session->param('warnmsg')) { $page->param(warnmsg => $session->param('warnmsg')); $session->clear('warnmsg'); } if ($session->param('errmsg')) { $page->param(errmsg => $session->param('errmsg')); $session->clear('errmsg'); } $page->param(curpage => $webvar{page}); } elsif ($webvar{page} eq 'user') { # All user add/edit actions fall through the same page, since there aren't # really any hard differences between the templates #fill_actypelist($webvar{accttype}); fill_clonemelist(); my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $grppermlist = new HTML::Template(filename => "$templatedir/permlist.tmpl"); my %noaccess; fill_permissions($grppermlist, \%grpperms, \%noaccess); $grppermlist->param(info => 1); $page->param(grpperms => $grppermlist->output); $page->param(is_admin => $permissions{admin}); $webvar{useraction} = '' if !$webvar{useraction}; if ($webvar{useraction} eq 'add' or $webvar{useraction} eq 'update') { $page->param(add => 1) if $webvar{useraction} eq 'add'; my ($code,$msg); my $alterperms = 0; # flag iff we need to force custom permissions due to user's current access limits my %newperms; # we're going to prefill the existing permissions, so we can change them. getPermissions($dbh, 'user', $webvar{uid}, \%newperms); if ($webvar{pass1} ne $webvar{pass2}) { $code = 'FAIL'; $msg = "Passwords don't match"; } else { # assemble a permission string - far simpler than trying to pass an # indeterminate set of permission flags individually # But first, we have to see if the user can add any particular # permissions; otherwise we have a priviledge escalation. Whee. if (!$permissions{admin}) { my %grpperms; getPermissions($dbh, 'group', $curgroup, \%grpperms); my $ret = comparePermissions(\%permissions, \%grpperms); if ($ret eq '<' || $ret eq '!') { # User's permissions are not a superset or equivalent to group. Can't inherit # (and include access user doesn't currently have), so we force custom. $webvar{perms_type} = 'custom'; $alterperms = 1; } } my $permstring; if ($webvar{perms_type} eq 'custom') { $permstring = 'C:'; foreach (@permtypes) { if ($permissions{admin} || $permissions{$_}) { $permstring .= ",$_" if defined($webvar{$_}) && $webvar{$_} eq 'on'; $newperms{$_} = (defined($webvar{$_}) && $webvar{$_} eq 'on' ? 1 : 0); } } $page->param(perm_custom => 1); } elsif ($permissions{admin} && $webvar{perms_type} eq 'clone') { $permstring = "c:$webvar{clonesrc}"; getPermissions($dbh, 'user', $webvar{clonesrc}, \%newperms); $page->param(perm_clone => 1); } else { $permstring = 'i'; } if ($webvar{useraction} eq 'add') { changepage(page => "useradmin", errmsg => "You do not have permission to add new users") unless $permissions{admin} || $permissions{user_create}; # no scope check; user is created in the current group ($code,$msg) = addUser($dbh, $webvar{uname}, $curgroup, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $permstring, $webvar{fname}, $webvar{lname}, $webvar{phone}); logaction(0, $session->param("username"), $curgroup, "Added user $webvar{uname} (uid $msg)") if $code eq 'OK'; } else { changepage(page => "useradmin", errmsg => "You do not have permission to edit users") unless $permissions{admin} || $permissions{user_edit}; # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{user}, type => 'user')) { changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user"); } # User update is icky. I'd really like to do this in one atomic # operation, but that would duplicate a **lot** of code in DNSDB.pm # Allowing for changing group, but not coding web support just yet. ($code,$msg) = updateUser($dbh, $webvar{uid}, $webvar{uname}, $webvar{gid}, $webvar{pass1}, ($webvar{makeactive} eq 'on' ? 1 : 0), $webvar{accttype}, $webvar{fname}, $webvar{lname}, $webvar{phone}); if ($code eq 'OK') { $newperms{admin} = 1 if $webvar{accttype} eq 'S'; ($code,$msg) = changePermissions($dbh, 'user', $webvar{uid}, \%newperms, ($permstring eq 'i')); logaction(0, $session->param("username"), $curgroup, "Updated uid $webvar{uid}, user $webvar{uname} ($webvar{fname} $webvar{lname})"); } } } if ($code eq 'OK') { if ($alterperms) { changepage(page => "useradmin", warnmsg => "You can only grant permissions you hold. $webvar{uname} ". ($webvar{useraction} eq 'add' ? 'added' : 'updated')." with reduced access."); } else { changepage(page => "useradmin", resultmsg => "Successfully ". ($webvar{useraction} eq 'add' ? 'added' : 'updated')." user $webvar{uname}"); } # add/update failed: } else { $page->param(add_failed => 1); $page->param(action => $webvar{useraction}); $page->param(set_permgroup => 1); if ($webvar{perms_type} eq 'inherit') { # set permission class radio $page->param(perm_inherit => 1); } elsif ($webvar{perms_type} eq 'clone') { $page->param(perm_clone => 1); } else { $page->param(perm_custom => 1); } $page->param(uname => $webvar{uname}); $page->param(fname => $webvar{fname}); $page->param(lname => $webvar{lname}); $page->param(pass1 => $webvar{pass1}); $page->param(pass2 => $webvar{pass2}); $page->param(errmsg => $msg); fill_permissions($page, \%newperms); fill_actypelist($webvar{accttype}); fill_clonemelist(); logaction(0, $session->param("username"), $curgroup, "Failed to $webvar{useraction} user ". "$webvar{uname}: $msg") if $config{log_failures}; } } elsif ($webvar{useraction} eq 'edit') { changepage(page => "useradmin", errmsg => "You do not have permission to edit users") unless $permissions{admin} || $permissions{user_edit}; # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{user}, type => 'user')) { changepage(page => "useradmin", errmsg => "You do not have permission to edit the requested user"); } $page->param(set_permgroup => 1); $page->param(action => 'update'); $page->param(uid => $webvar{user}); fill_clonemelist(); my $userinfo = getUserData($dbh,$webvar{user}); fill_actypelist($userinfo->{type}); # not using this yet, but adding it now means we can *much* more easily do so later. $page->param(gid => $webvar{group_id}); my %curperms; getPermissions($dbh, 'user', $webvar{user}, \%curperms); fill_permissions($page, \%curperms); $page->param(uname => $userinfo->{username}); $page->param(fname => $userinfo->{firstname}); $page->param(lname => $userinfo->{lastname}); $page->param(set_permgroup => 1); if ($userinfo->{inherit_perm}) { $page->param(perm_inherit => 1); } else { $page->param(perm_custom => 1); } } else { changepage(page => "useradmin", errmsg => "You are not allowed to add new users") unless $permissions{admin} || $permissions{user_create}; # default is "new" $page->param(add => 1); $page->param(action => 'add'); fill_permissions($page, \%grpperms); fill_actypelist(); } } elsif ($webvar{page} eq 'deluser') { changepage(page=> "useradmin", errmsg => "You are not allowed to delete users") unless $permissions{admin} || $permissions{user_delete}; # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{id}, type => 'user')) { changepage(page => "useradmin", errmsg => "You are not permitted to delete the requested user"); } $page->param(id => $webvar{id}); # first pass = confirm y/n (sorta) if (!defined($webvar{del})) { $page->param(del_getconf => 1); $page->param(user => userFullName($dbh,$webvar{id})); } elsif ($webvar{del} eq 'ok') { ##fixme: find group id user is in (for logging) *before* we delete the user ##fixme: get other user data too for log my $userref = getUserData($dbh, $webvar{id}); my ($code,$msg) = delUser($dbh, $webvar{id}); if ($code eq 'OK') { # success. go back to the user list, do not pass "GO" # actions on users have a domain id of 0, always logaction(0, $session->param("username"), $curgroup, "Deleted user $webvar{id}/".$userref->{username}. " (".$userref->{lastname}.", ".$userref->{firstname}.")"); changepage(page => "useradmin", resultmsg => "Deleted user ".$userref->{username}. " (".$userref->{lastname}.", ".$userref->{firstname}.")"); } else { # need to find failure mode $page->param(del_failed => 1); $page->param(errmsg => $msg); list_users($curgroup); logaction(0, $session->param("username"), $curgroup, "Failed to delete user ". "$webvar{id}/".$userref->{username}.": $msg") if $config{log_failures}; } } else { # cancelled. whee! changepage(page => "useradmin"); } } elsif ($webvar{page} eq 'dnsq') { $page->param(qfor => $webvar{qfor}) if $webvar{qfor}; $page->param(typelist => getTypelist($dbh, 'l', ($webvar{type} ? $webvar{type} : undef))); $page->param(nrecurse => $webvar{nrecurse}) if $webvar{nrecurse}; $page->param(resolver => $webvar{resolver}) if $webvar{resolver}; if ($webvar{qfor}) { my $resolv = Net::DNS::Resolver->new; $resolv->tcp_timeout(5); # make me adjustable! $resolv->udp_timeout(5); # make me adjustable! $resolv->recurse(0) if $webvar{nrecurse}; $resolv->nameservers($webvar{resolver}) if $webvar{resolver}; my $query = $resolv->query($webvar{qfor}, $typemap{$webvar{type}}); if ($query) { $page->param(showresults => 1); my @answer; foreach my $rr ($query->answer) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/s); $row{host} = $host; $row{ftype} = $type; $row{rdata} = ($type eq 'SOA' ? "
$data
" : $data); push @answer, \%row; } $page->param(answer => \@answer); my @additional; foreach my $rr ($query->additional) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @additional, \%row; } $page->param(additional => \@additional); my @authority; foreach my $rr ($query->authority) { # next unless $rr->type eq "A" or $rr->type eq 'NS'; my %row; my ($host,$ttl,$class,$type,$data) = ($rr->string =~ /^([0-9a-zA-Z_.-]+)\s+(\d+)\s+([A-Za-z]+)\s+([A-Za-z]+)\s+(.+)$/); $row{host} = $host; $row{ftype} = $type; $row{rdata} = $data; push @authority, \%row; } $page->param(authority => \@authority); $page->param(usedresolver => $resolv->answerfrom); $page->param(frtype => $typemap{$webvar{type}}); } else { $page->param(errmsg => $resolv->errorstring); } } ## done DNS query } elsif ($webvar{page} eq 'axfr') { changepage(page => "domlist", errmsg => "You are not permitted to import domains") unless ($permissions{admin} || $permissions{domain_create}); # don't need this while we've got the dropdown in the menu. hmm. fill_grouplist("grouplist"); $page->param(ifrom => $webvar{ifrom}) if $webvar{ifrom}; $page->param(rwsoa => $webvar{rwsoa}) if $webvar{rwsoa}; $page->param(rwns => $webvar{rwns}) if $webvar{rwns}; $page->param(dominactive => 1) if (!$webvar{domactive} && $webvar{doit}); # eww. $page->param(importdoms => $webvar{importdoms}) if $webvar{importdoms}; # shut up warning about uninitialized variable $webvar{doit} = '' if !defined($webvar{doit}); if ($webvar{doit} eq 'y' && !$webvar{ifrom}) { $page->param(errmsg => "Need to set host to import from"); } elsif ($webvar{doit} eq 'y' && !$webvar{importdoms}) { $page->param(errmsg => "Need domains to import"); } elsif ($webvar{doit} eq 'y') { # security check - does the user have permission to access this entity? if (!check_scope(id => $webvar{group}, type => 'group')) { $page->param(errmsg => "You are not permitted to import domains into the requested group"); goto DONEAXFR; } my @domlist = split /\s+/, $webvar{importdoms}; my @results; foreach my $domain (@domlist) { my %row; my ($code,$msg) = importAXFR($dbh, $webvar{ifrom}, $domain, $webvar{group}, $webvar{zonestatus}, $webvar{rwsoa}, $webvar{rwns}); $row{domok} = $msg if $code eq 'OK'; if ($code eq 'WARN') { $msg =~ s|\n|
|g; $row{domwarn} = $msg; } if ($code eq 'FAIL') { $msg =~ s|\n|
\n|g; $row{domerr} = $msg; } $msg = "
\n".$msg if $msg =~ m|
|; logaction(domainID($dbh, $domain), $session->param("username"), $webvar{group}, "AXFR import $domain from $webvar{ifrom} ($code): $msg"); $row{domain} = $domain; push @results, \%row; } $page->param(axfrresults => \@results); } # Yes, this is a GOTO target. PTBHTTT. DONEAXFR: ; } elsif ($webvar{page} eq 'whoisq') { if ($webvar{qfor}) { use Net::Whois::Raw; use Text::Wrap; # caching useful? #$Net::Whois::Raw::CACHE_DIR = "/var/spool/pwhois/"; #$Net::Whois::Raw::CACHE_TIME = 60; my ($dominfo, $whois_server) = whois($webvar{qfor}); ##fixme: if we're given an IP, try rwhois as well as whois so we get the real final data # le sigh. idjits spit out data without linefeeds... $Text::Wrap::columns = 88; # &%$@%@# high-bit crap. We should probably find a way to properly recode these # instead of one-by-one. Note CGI::Simple's escapeHTML() doesn't do more than # the bare minimum. :/ # Mainly an XHTML validation thing. $dominfo = $q->escapeHTML($dominfo); $dominfo =~ s/\xa9/\©/g; $dominfo =~ s/\xae/\®/g; $page->param(qfor => $webvar{qfor}); $page->param(dominfo => wrap('','',$dominfo)); $page->param(whois_server => $whois_server); } else { $page->param(errmsg => "Missing host or domain to query in WHOIS") if $webvar{askaway}; } } elsif ($webvar{page} eq 'log') { ##fixme put in some real log-munching stuff my $sql = "SELECT user_id, email, name, entry, date_trunc('second',stamp) FROM log WHERE "; my $id = $curgroup; # we do this because the group log may be called from (almost) any page, # but the others are much more limited. this is probably non-optimal. if ($webvar{ltype} && $webvar{ltype} eq 'user') { $sql .= "user_id=?"; $id = $webvar{id}; if (!check_scope(id => $id, type => 'user')) { $page->param(errmsg => "You are not permitted to view log entries for the requested user"); goto DONELOG; } $page->param(logfor => 'user '.userFullName($dbh,$id)); } elsif ($webvar{ltype} && $webvar{ltype} eq 'dom') { $sql .= "domain_id=?"; $id = $webvar{id}; if (!check_scope(id => $id, type => 'domain')) { $page->param(errmsg => "You are not permitted to view log entries for the requested domain"); goto DONELOG; } $page->param(logfor => 'domain '.domainName($dbh,$id)); } elsif ($webvar{ltype} && $webvar{ltype} eq 'rdns') { $sql .= "rdns_id=?"; $id = $webvar{id}; if (!check_scope(id => $id, type => 'revzone')) { $page->param(errmsg => "You are not permitted to view log entries for the requested reverse zone"); goto DONELOG; } $page->param(logfor => 'reverse zone '.revName($dbh,$id)); } else { # Default to listing curgroup log $sql .= "group_id=?"; $page->param(logfor => 'group '.groupName($dbh,$id)); # note that scope limitations are applied via the change-group check; # group log is always for the "current" group } ##fixme: # - filtering # - show reverse zone column? # - pagination/limiting number of records - put newest-first so user # doesn't always need to go to the last page for recent activity? my $sth = $dbh->prepare($sql); $sth->execute($id); my @logbits; while (my ($uid, $email, $name, $entry, $stamp) = $sth->fetchrow_array) { my %row; $row{userfname} = $name; $row{userid} = $uid; $row{useremail} = $email; ($row{logentry} = $entry) =~ s/\n/
\n/g; ($row{logtime}) = ($stamp =~ /^(.+)-\d\d$/); push @logbits, \%row; } $page->param(logentries => \@logbits); # scope check fail target DONELOG: ; } # end $webvar{page} dance # start output here so we can redirect pages. print "Content-type: text/html\n\n", $header->output; ##common bits if ($webvar{page} ne 'login' && $webvar{page} ne 'badpage') { $page->param(username => $session->param("username")); $page->param(group => $curgroup); $page->param(groupname => groupName($dbh,$curgroup)); $page->param(logingrp => groupName($dbh,$logingroup)); $page->param(logingrp_num => $logingroup); ##fixme $page->param(mayrdns => 1); $page->param(maydefrec => $permissions{admin}); $page->param(mayimport => $permissions{admin} || $permissions{domain_create}); $page->param(maybulk => $permissions{admin} || $permissions{domain_edit} || $permissions{domain_create} || $permissions{domain_delete}); $page->param(chggrps => ($permissions{admin} || $permissions{group_create} || $permissions{group_edit} || $permissions{group_delete})); # group tree. should go elsewhere, probably my $tmpgrplist = fill_grptree($logingroup,$curgroup); $page->param(grptree => $tmpgrplist); $page->param(subs => ($tmpgrplist ? 1 : 0)); # probably not useful to pass gobs of data in for a boolean $page->param(inlogingrp => $curgroup == $logingroup); # fill in the URL-to-self $page->param(whereami => $uri_self); } if (@debugbits) { print "
\n";
  foreach (@debugbits) { print; }
  print "
\n"; } # spit it out print $page->output; if ($debugenv) { print "
webvar keys:
\n";
  foreach my $key (keys %webvar) {
    print "key: $key\tval: $webvar{$key}\n";
  }
  print "
\nsession:\n
\n";
  my $sesdata = $session->dataref();
  foreach my $key (keys %$sesdata) {
    print "key: $key\tval: ".$sesdata->{$key}."\n";
  }
  print "
\nENV:\n
\n";
  foreach my $key (keys %ENV) {
    print "key: $key\tval: $ENV{$key}\n";
  }
  print "
\n"; } print $footer->output; # as per the docs, Just In Case $session->flush(); exit 0; sub fill_grptree { my $root = shift; my $cur = shift; my $indent = shift || ' '; my @childlist; my $grptree = HTML::Template->new(filename => 'templates/grptree.tmpl'); getChildren($dbh,$root,\@childlist,'immediate'); return if $#childlist == -1; my @grouplist; foreach (@childlist) { my %row; $row{grpname} = groupName($dbh,$_); $row{grpnum} = $_; $row{whereami} = $uri_self; $row{curgrp} = ($_ == $cur); $row{expanded} = isParent($dbh, $_, 'group', $cur, 'group'); $row{expanded} = 1 if $_ == $cur; $row{subs} = fill_grptree($_,$cur,$indent.' '); $row{indent} = $indent; push @grouplist, \%row; } $grptree->param(indent => $indent); $grptree->param(treelvl => \@grouplist); return $grptree->output; } sub changepage { my %params = @_; # think this works the way I want... # cross-site scripting fixup. instead of passing error messages by URL/form # variable, put them in the session where the nasty user can't meddle. # these are done here since it's far simpler to pass them in from wherever # than set them locally everywhere. foreach my $sessme ('resultmsg','warnmsg','errmsg') { if (my $tmp = $params{$sessme}) { $tmp =~ s/^\n//; $tmp =~ s|\n|
\n|g; $session->param($sessme, $tmp); delete $params{$sessme}; } } # handle user check my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid"; foreach (sort keys %params) { $newurl .= "&$_=".$q->url_encode($params{$_}); } # Just In Case $session->flush(); print "Status: 302\nLocation: $newurl\n\n"; exit; } # end changepage sub fillsoa { my $defrec = shift; my $revrec = shift; my $id = shift; my $domname = ($defrec eq 'y' ? '' : "DOMAIN"); $page->param(defrec => $defrec); $page->param(revrec => $revrec); # i had a good reason to do this when I wrote it... # $page->param(domain => $domname); # $page->param(group => $DNSDB::group); $page->param(isgrp => 1) if $defrec eq 'y'; $page->param(parent => ($defrec eq 'y' ? groupName($dbh, $id) : ($revrec eq 'n' ? domainName($dbh, $id) : revName($dbh, $id)) ) ); # defaults $page->param(defcontact => $DNSDB::def{contact}); $page->param(defns => $DNSDB::def{prins}); $page->param(defsoattl => $DNSDB::def{soattl}); $page->param(defrefresh => $DNSDB::def{refresh}); $page->param(defretry => $DNSDB::def{retry}); $page->param(defexpire => $DNSDB::def{expire}); $page->param(defminttl => $DNSDB::def{minttl}); # there are probably better ways to do this. TMTOWTDI. my %soa = getSOA($dbh,$defrec,$revrec,$id); $page->param(id => $id); $page->param(recid => $soa{recid}); $page->param(prins => ($soa{prins} ? $soa{prins} : $DNSDB::def{prins})); $page->param(contact => ($soa{contact} ? $soa{contact} : $DNSDB::def{contact})); $page->param(refresh => ($soa{refresh} ? $soa{refresh} : $DNSDB::def{refresh})); $page->param(retry => ($soa{retry} ? $soa{retry} : $DNSDB::def{retry})); $page->param(expire => ($soa{expire} ? $soa{expire} : $DNSDB::def{expire})); $page->param(minttl => ($soa{minttl} ? $soa{minttl} : $DNSDB::def{minttl})); $page->param(ttl => ($soa{ttl} ? $soa{ttl} : $DNSDB::def{soattl})); } sub showzone { my $def = shift; my $rev = shift; my $id = shift; # get the SOA first my %soa = getSOA($dbh,$def,$rev,$id); $page->param(contact => $soa{contact}); $page->param(prins => $soa{prins}); $page->param(refresh => $soa{refresh}); $page->param(retry => $soa{retry}); $page->param(expire => $soa{expire}); $page->param(minttl => $soa{minttl}); $page->param(ttl => $soa{ttl}); my $foo2 = getDomRecs($dbh,$def,$rev,$id,$perpage,$webvar{offset},$sortby,$sortorder,$filter); my $row = 0; foreach my $rec (@$foo2) { $rec->{type} = $typemap{$rec->{type}}; $rec->{row} = $row % 2; $rec->{defrec} = $def; $rec->{revrec} = $rev; $rec->{sid} = $webvar{sid}; $rec->{id} = $id; $rec->{fwdzone} = $rev eq 'n'; $rec->{distance} = 'n/a' unless ($rec->{type} eq 'MX' || $rec->{type} eq 'SRV'); $rec->{weight} = 'n/a' unless ($rec->{type} eq 'SRV'); $rec->{port} = 'n/a' unless ($rec->{type} eq 'SRV'); $row++; # ACLs $rec->{record_edit} = ($permissions{admin} || $permissions{record_edit}); $rec->{record_delete} = ($permissions{admin} || $permissions{record_delete}); } $page->param(reclist => $foo2); } sub fill_recdata { $page->param(typelist => getTypelist($dbh, $webvar{revrec}, $webvar{type})); # le sigh. we may get called with many empty %webvar keys no warnings qw( uninitialized ); ##todo: allow BIND-style bare names, ASS-U-ME that the name is within the domain? # prefill or DOMAIN in "Host" space for new records if ($webvar{revrec} eq 'n') { my $domroot = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid})); $page->param(name => $domroot); $page->param(address => $webvar{address}); $page->param(distance => $webvar{distance}) if ($webvar{type} == $reverse_typemap{MX} or $webvar{type} == $reverse_typemap{SRV}); $page->param(weight => $webvar{weight}) if $webvar{type} == $reverse_typemap{SRV}; $page->param(port => $webvar{port}) if $webvar{type} == $reverse_typemap{SRV}; } else { my $domroot = ($webvar{defrec} eq 'y' ? 'ADMINDOMAIN' : ".$config{domain}"); $page->param(name => ($webvar{name} ? $webvar{name} : $domroot)); my $zname = ($webvar{defrec} eq 'y' ? 'ZONE' : revName($dbh,$webvar{parentid})); $zname =~ s|\d*/\d+$||; $page->param(address => ($webvar{address} ? $webvar{address} : $zname)); } # retrieve the right ttl instead of falling (way) back to the hardcoded system default my %soa = getSOA($dbh,$webvar{defrec},$webvar{revrec},$webvar{parentid}); $page->param(ttl => ($webvar{ttl} ? $webvar{ttl} : $soa{minttl})); } sub fill_actypelist { my $curtype = shift || 'u'; my @actypes; my %row1 = (actypeval => 'u', actypename => 'user'); $row1{typesel} = 1 if $curtype eq 'u'; push @actypes, \%row1; my %row2 = (actypeval => 'S', actypename => 'superuser'); $row2{typesel} = 1 if $curtype eq 'S'; push @actypes, \%row2; $page->param(actypelist => \@actypes); } sub fill_clonemelist { my $sth = $dbh->prepare("SELECT username,user_id FROM users WHERE group_id=$curgroup"); $sth->execute; # shut up some warnings, but don't stomp on caller's state local $webvar{clonesrc} = 0 if !defined($webvar{clonesrc}); my @clonesrc; while (my ($username,$uid) = $sth->fetchrow_array) { my %row = ( username => $username, uid => $uid, selected => ($webvar{clonesrc} == $uid ? 1 : 0) ); push @clonesrc, \%row; } $page->param(clonesrc => \@clonesrc); } sub fill_fpnla { my $count = shift; if ($offset eq 'all') { $page->param(perpage => $perpage); # uhm.... } else { # all these bits only have sensible behaviour if offset is numeric. err, probably. if ($count > $perpage) { # if there are more results than the default, always show the "all" link $page->param(navall => 1); if ($offset > 0) { $page->param(navfirst => 1); $page->param(navprev => 1); $page->param(prevoffs => $offset-1); } # show "next" and "last" links if we're not on the last page of results if ( (($offset+1) * $perpage - $count) < 0 ) { $page->param(navnext => 1); $page->param(nextoffs => $offset+1); $page->param(navlast => 1); $page->param(lastoffs => int (($count-1)/$perpage)); } } else { $page->param(onepage => 1); } } } # end fill_fpnla() sub fill_pgcount { my $pgcount = shift; my $pgtype = shift; my $parent = shift; # Fix display/UI bug where if you are not on the first page of the list, and # you add a search term or click one of the "starts with" links, you end up # on a page showing nothing. # For bonus points, this reverts to the original offset on clicking the "All" link (mostly) if ($offset ne 'all') { $offset-- while ($offset * $perpage) >= $pgcount; } $page->param(ntot => $pgcount); $page->param(nfirst => (($offset eq 'all' ? 0 : $offset)*$perpage+1)); $page->param(npglast => ($offset eq 'all' ? $pgcount : ( (($offset+1)*$perpage) > $pgcount ? $pgcount : (($offset+1)*$perpage) ) )); $page->param(pgtype => $pgtype); $page->param(parent => $parent); $page->param(filter => $filter); } # end fill_pgcount() sub listdomains { listzones(); } # temp sub listzones { # ACLs $page->param(domain_create => ($permissions{admin} || $permissions{domain_create}) ); $page->param(domain_edit => ($permissions{admin} || $permissions{domain_edit}) ); $page->param(domain_delete => ($permissions{admin} || $permissions{domain_delete}) ); my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $count = getZoneCount($dbh, (childlist => $childlist, curgroup => $curgroup, revrec => $webvar{revrec}, filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef) ) ); # fill page count and first-previous-next-last-all bits fill_pgcount($count,($webvar{revrec} eq 'n' ? 'domains' : 'revzones'),groupName($dbh,$curgroup)); fill_fpnla($count); # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = (($webvar{revrec} eq 'n' ? 'domain' : 'revnet'), 'status', 'group'); my %colheads = (domain => 'Domain', revnet => 'Reverse Zone', status => 'Status', group => 'Group'); fill_colheads($sortby, $sortorder, \@cols, \%colheads); # hack! hack! pthbttt. have to rethink the status column storage, # or inactive comes "before" active. *sigh* $sortorder = ($sortorder eq 'ASC' ? 'DESC' : 'ASC') if $sortby eq 'status'; # waffle, waffle - keep state on these as well as sortby, sortorder? ##fixme: put this higher so the count doesn't get munched? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; $page->param(group => $curgroup); my $zonelist = getZoneList($dbh, (childlist => $childlist, curgroup => $curgroup, revrec => $webvar{revrec}, filter => ($filter ? $filter : undef), startwith => ($startwith ? $startwith : undef), offset => $webvar{offset}, sortby => $sortby, sortorder => $sortorder ) ); # probably don't need this, keeping for reference for now # foreach (@$zonelist) { # } $page->param(domtable => $zonelist); } # end listdomains() sub listgroups { # security check - does the user have permission to view this entity? if (!(grep /^$curgroup$/, @viewablegroups)) { # hmm. Reset the current group to the login group? Yes. Prevents confusing behaviour elsewhere. $session->param('curgroup',$logingroup); $page->param(errmsg => "You are not permitted to view the requested group"); $curgroup = $logingroup; } my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM groups WHERE parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND group_name ~* ?" : ''). ($filter ? " AND group_name ~* ?" : ''); my $sth = $dbh->prepare($sql); $sth->execute(@filterargs); my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits fill_pgcount($count,"groups",''); fill_fpnla($count); $page->param(gid => $curgroup); $sortby = 'group'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('group','parent','nusers','ndomains'); my %colnames = (group => 'Group', parent => 'Parent Group', nusers => 'Users', ndomains => 'Domains'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'g2.group_name' if $sortby eq 'parent'; my @grouplist; $sql = "SELECT g.group_id, g.group_name, g2.group_name, ". "count(distinct(u.username)) AS nusers, count(distinct(d.domain)) AS ndomains ". "FROM groups g ". "INNER JOIN groups g2 ON g2.group_id=g.parent_group_id ". "LEFT OUTER JOIN users u ON u.group_id=g.group_id ". "LEFT OUTER JOIN domains d ON d.group_id=g.group_id ". "WHERE g.parent_group_id IN ($curgroup".($childlist ? ",$childlist" : '').") ". ($startwith ? " AND g.group_name ~* ?" : ''). ($filter ? " AND g.group_name ~* ?" : ''). " GROUP BY g.group_id, g.group_name, g2.group_name ". " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute(@filterargs); my $rownum = 0; while (my @data = $sth->fetchrow_array) { my %row; $row{groupid} = $data[0]; $row{groupname} = $data[1]; $row{pgroup} = $data[2]; $row{nusers} = $data[3]; $row{ndomains} = $data[4]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; $row{edgrp} = ($permissions{admin} || $permissions{group_edit}); $row{delgrp} = ($permissions{admin} || $permissions{group_delete}); push @grouplist, \%row; } $page->param(grouptable => \@grouplist); } # end listgroups() sub fill_grouplist { my $template_var = shift; my $cur = shift || $curgroup; my @childgroups; getChildren($dbh, $logingroup, \@childgroups, 'all'); my $childlist = join(',',@childgroups); ##fixme: need to reorder list so that we can display a pseudotree in group dropdowns # weesa gonna discard parent_group_id for now my $sth = $dbh->prepare("SELECT group_id,parent_group_id,group_name FROM groups ". "WHERE group_id IN ($logingroup".($childlist ? ",$childlist" : '').")". "ORDER BY group_id"); $sth->execute; my @grouplist; while (my ($groupid,$pargroup,$groupname) = $sth->fetchrow_array()) { my %row; $row{groupname} = $groupname; $row{groupval} = $groupid; ##fixme: need magic ## ... WTF? # $row{defgroup} = ''; $row{groupactive} = 1 if $groupid == $cur; push @grouplist, \%row; } $page->param("$template_var" => \@grouplist); } # end fill_grouplist() sub list_users { my @childgroups; getChildren($dbh, $curgroup, \@childgroups, 'all') if $searchsubs; my $childlist = join(',',@childgroups); my $sql = "SELECT count(*) FROM users WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND username ~* ?" : ''). ($filter ? " AND username ~* ?" : ''); my $sth = $dbh->prepare($sql); $sth->execute(@filterargs); my ($count) = ($sth->fetchrow_array); # fill page count and first-previous-next-last-all bits fill_pgcount($count,"users",''); fill_fpnla($count); $sortby = 'user'; # sort/order $session->param($webvar{page}.'sortby', $webvar{sortby}) if $webvar{sortby}; $session->param($webvar{page}.'order', $webvar{order}) if $webvar{order}; $sortby = $session->param($webvar{page}.'sortby') if $session->param($webvar{page}.'sortby'); $sortorder = $session->param($webvar{page}.'order') if $session->param($webvar{page}.'order'); # set up the headers my @cols = ('user','fname','type','group','status'); my %colnames = (user => 'Username', fname => 'Full Name', type => 'Type', group => 'Group', status => 'Status'); fill_colheads($sortby, $sortorder, \@cols, \%colnames); # waffle, waffle - keep state on these as well as sortby, sortorder? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; # munge sortby for columns in database $sortby = 'u.username' if $sortby eq 'user'; $sortby = 'u.type' if $sortby eq 'type'; $sortby = 'g.group_name' if $sortby eq 'group'; $sortby = 'u.status' if $sortby eq 'status'; my @userlist; $sql = "SELECT u.user_id, u.username, u.firstname || ' ' || u.lastname AS fname, u.type, g.group_name, u.status ". "FROM users u ". "INNER JOIN groups g ON u.group_id=g.group_id ". "WHERE u.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND u.username ~* ?" : ''). ($filter ? " AND u.username ~* ?" : ''). " ORDER BY $sortby $sortorder ". ($offset eq 'all' ? '' : " LIMIT $perpage OFFSET ".$offset*$perpage); $sth = $dbh->prepare($sql); $sth->execute(@filterargs); my $rownum = 0; while (my @data = $sth->fetchrow_array) { no warnings "uninitialized"; # Just In Case something stupid happens and a user gets no first or last name my %row; $row{userid} = $data[0]; $row{username} = $data[1]; $row{userfull} = $data[2]; $row{usertype} = ($data[3] eq 'S' ? 'superuser' : "user"); $row{usergroup} = $data[4]; $row{active} = $data[5]; $row{bg} = ($rownum++)%2; $row{sid} = $sid; $row{eduser} = ($permissions{admin} || $permissions{user_edit}); $row{deluser} = ($permissions{admin} || $permissions{user_delete}); push @userlist, \%row; } $page->param(usertable => \@userlist); } # end list_users() # Generate all of the glop necessary to add or not the appropriate marker/flag for # the sort order and column in domain, user, group, and record lists # Takes an array ref and hash ref sub fill_colheads { my $sortby = shift; my $sortorder = shift; my $cols = shift; my $colnames = shift; my $custom = shift; my @headings; foreach my $col (@$cols) { my %coldata; $coldata{firstcol} = 1 if $col eq $cols->[0]; $coldata{sid} = $sid; $coldata{page} = $webvar{page}; $coldata{offset} = $webvar{offset} if $webvar{offset}; $coldata{sortby} = $col; $coldata{colname} = $colnames->{$col}; if ($col eq $sortby) { $coldata{order} = ($sortorder eq 'ASC' ? 'DESC' : 'ASC'); $coldata{sortorder} = $sortorder; } else { $coldata{order} = 'ASC'; } if ($custom) { foreach my $ckey (keys %$custom) { $coldata{$ckey} = $custom->{$ckey}; } } push @headings, \%coldata; } $page->param(colheads => \@headings); } # end fill_colheads() sub logaction { my $domid = shift; my $username = shift; my $groupid = shift; my $entry = shift; my $revid = shift || 0; ##fixme: push SQL into DNSDB.pm ##fixme: add bits to retrieve group/domain name info to retain after entity is deleted? my $sth = $dbh->prepare("SELECT user_id, firstname || ' ' || lastname FROM users WHERE username=?"); $sth->execute($username); my ($user_id, $fullname) = $sth->fetchrow_array; $sth = $dbh->prepare("INSERT INTO log (domain_id,user_id,group_id,email,name,entry,rdns_id) ". "VALUES (?,?,?,?,?,?,?)") or warn $dbh->errstr; $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry,$revid) or warn $sth->errstr; } # end logaction() # we have to do this in a variety of places; let's make it consistent sub fill_permissions { my $template = shift; # may need to do several sets on a single page my $permset = shift; # hashref to permissions on object my $usercan = shift || \%permissions; # allow alternate user-is-allowed permission block foreach (@permtypes) { $template->param("may_$_" => ($usercan->{admin} || $usercan->{$_})); $template->param($_ => $permset->{$_}); } } # so simple when defined as a sub instead of inline. O_o sub check_scope { my %args = @_; my $entity = $args{id} || 0; # prevent the shooting of feet with SQL "... intcolumn = '' ..." my $entype = $args{type} || ''; if ($entype eq 'group') { return 1 if grep /^$entity$/, @viewablegroups; } else { foreach (@viewablegroups) { return 1 if isParent($dbh, $_, 'group', $entity, $entype); } } }