#!/usr/bin/perl -w -T # Main web UI script for DeepNet DNS Administrator ## # $Id: dns.cgi 437 2012-10-30 16:23:30Z 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}; # 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('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 { $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl"); }; if ($@) { warn "Bad page $webvar{page} requested"; $page = HTML::Template->new(filename => "$templatedir/badpage.tmpl"); $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,status FROM users WHERE username=?"); $sth->execute($webvar{username}); if (my ($uid,$gid,$pass,$fname,$lname,$status) = $sth->fetchrow_array) { $webvar{password} = '' if !$webvar{password}; if (!$status) { $webvar{loginfailed} = 1; } elsif ($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}; } # set session bits $session->param('logingroup',$gid); $session->param('curgroup',$gid); $session->param('uid',$uid); $session->param('username',$webvar{username}); changepage(page => "domlist") if !defined($webvar{loginfailed}); } 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. if ($webvar{page} eq 'reclist' && $webvar{defrec} eq 'y') { my %args = (page => $webvar{page}, id => $curgroup, defrec => $webvar{defrec}); $args{errmsg} = $errmsg if $errmsg; changepage(%args); } } } # handle global webvar{action}s initPermissions($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') { # hmm. seeing problems in some possibly-not-so-corner cases. # this currently only handles "domain on", "domain off" if (defined($webvar{domstatus})) { # 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 = domStatus($dbh,$webvar{id},$webvar{domstatus}); ##fixme switch to more consise "Enabled " as with users? logaction($webvar{id}, $session->param("username"), parentID($webvar{id}, 'dom', 'group'), "Changed ".domainName($dbh, $webvar{id})." state to ".($stat ? 'active' : 'inactive')); $page->param(resultmsg => "Changed ".domainName($dbh, $webvar{id})." state to ". ($stat ? 'active' : 'inactive')); } else { $page->param(errmsg => "You are not permitted to view or change the requested domain"); } $uri_self =~ s/\&domstatus=[^&]*//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), (name => $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 { logaction(0, $session->param("username"), $webvar{group}, "Failed adding domain $webvar{domain} ($msg)") if $config{log_failures}; $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($webvar{id}, 'dom', 'group'); my $dom = domainName($dbh, $webvar{id}); my ($code,$msg) = delDomain($dbh, $webvar{id}); if ($code eq 'OK') { logaction($webvar{id}, $session->param("username"), $pargroup, "Deleted domain $dom"); changepage(page => "domlist", resultmsg => "Deleted domain $dom"); } else { logaction($webvar{id}, $session->param("username"), $pargroup, "Failed to delete domain $dom ($msg)") if $config{log_failures}; changepage(page => "domlist", errmsg => "Error deleting domain $dom: $msg"); } } else { # cancelled. whee! changepage(page => "domlist"); } } 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' : 'domain'))) { $page->param(errmsg => "You are not permitted to view or change the requested ". ($webvar{defrec} eq 'y' ? "group's default 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(id => $webvar{id}); $page->param(curpage => $webvar{page}); my $count = getRecCount($dbh, $webvar{defrec}, $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 = ('host', 'type', 'val', 'distance', 'weight', 'port', 'ttl'); my %colheads = (host => 'Name', type => 'Type', val => 'Address', distance => 'Distance', weight => 'Weight', port => 'Port', ttl => 'TTL'); my %custom = (id => $webvar{id}, defrec => $webvar{defrec}); 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}) : domainName($dbh,$webvar{id}))); fill_fpnla($count); # should put some params on this sub... $page->param(defrec => $webvar{defrec}); if ($webvar{defrec} eq 'y') { showdomain('y',$curgroup); } else { showdomain('n',$webvar{id}); ##fixme: permission for viewing logs? $page->param(logdom => 1); } 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'); } } # 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' ? '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' : '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"); $page->param(perm_err => $msg); goto DONEREC; } 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}); $page->param(defrec => $webvar{defrec}); 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}); ##fixme: this should probably go in DNSDB::addRec(), need to ponder what to do about PTR and friends # prevent out-of-domain records from getting added by appending the domain, or DOMAIN for default records my $pname = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid})); $webvar{name} =~ s/\.*$/\.$pname/ if $webvar{name} !~ /$pname$/; my @recargs = ($dbh,$webvar{defrec},$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') { if ($webvar{defrec} eq 'y') { my $restr = "Added default record '$webvar{name} $typemap{$webvar{type}}"; $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX'; $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]" if $typemap{$webvar{type}} eq 'SRV'; $restr .= " $webvar{address}', TTL $webvar{ttl}"; logaction(0, $session->param("username"), $webvar{parentid}, $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } else { my $restr = "Added record '$webvar{name} $typemap{$webvar{type}}"; $restr .= " [distance $webvar{distance}]" if $typemap{$webvar{type}} eq 'MX'; $restr .= " [priority $webvar{distance}] [weight $webvar{weight}] [port $webvar{port}]" if $typemap{$webvar{type}} eq 'SRV'; $restr .= " $webvar{address}', TTL $webvar{ttl}"; logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } } 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(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); # populate the form... er, mostly. $page->param(name => $webvar{name}); if ($config{log_failures}) { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed adding default record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed adding record '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } } 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}); $page->param(defrec => $webvar{defrec}); my $recdata = getRecLine($dbh, $webvar{defrec}, $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}); fill_rectypes($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}); # prevent out-of-domain records from getting added by appending the domain, or DOMAIN for default records my $pname = ($webvar{defrec} eq 'y' ? 'DOMAIN' : domainName($dbh,$webvar{parentid})); $webvar{name} =~ s/\s+$//; $webvar{name} =~ s/\.*$/\.$pname/ if $webvar{name} !~ /$pname$/; # 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{id}); my ($code,$msg) = updateRec($dbh,$webvar{defrec},$webvar{id}, $webvar{name},$webvar{type},$webvar{address},$webvar{ttl}, $webvar{distance},$webvar{weight},$webvar{port}); if ($code eq 'OK') { ##fixme: retrieve old record info for full logging of change if ($webvar{defrec} eq 'y') { my $restr = "Updated default record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n". "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"; logaction(0, $session->param("username"), $webvar{parentid}, $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } else { my $restr = "Updated record from '$oldrec->{host} $typemap{$oldrec->{type}} $oldrec->{val}', TTL $oldrec->{ttl}\n". "to '$webvar{name} $typemap{$webvar{type}} $webvar{address}', TTL $webvar{ttl}"; logaction($webvar{parentid}, $session->param("username"), parentID($webvar{id}, 'rec', 'group'), $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } } 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(defrec => $webvar{defrec}); $page->param(id => $webvar{id}); fill_recdata(); if ($config{log_failures}) { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $webvar{parentid}, "Failed updating default record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } else { logaction($webvar{parentid}, $session->param("username"), parentID($webvar{parentid}, 'dom', 'group'), "Failed updating record '$typemap{$webvar{type}} $webvar{name} $webvar{address}', TTL $webvar{ttl} ($msg)"); } } } } 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})); } # 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}) unless ($permissions{admin} || $permissions{record_delete}); if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? ($webvar{revrec} eq 'y' ? 'defrevrec' : 'defrec') : 'record'))) { changepage(page => 'domlist', 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(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{id}); $page->param(host => $rec->{host}); $page->param(ftype => $typemap{$rec->{type}}); $page->param(recval => $rec->{val}); } elsif ($webvar{del} eq 'ok') { # get rec data before we try to delete it my $rec = getRecLine($dbh,$webvar{defrec},$webvar{id}); my ($code,$msg) = delRec($dbh,$webvar{defrec},$webvar{id}); if ($code eq 'OK') { if ($webvar{defrec} eq 'y') { ##fixme: log distance for MX; log port/weight/distance for SRV my $restr = "Deleted default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}"; logaction(0, $session->param("username"), $rec->{parid}, $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } else { my $restr = "Deleted record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl}"; logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'), $restr); changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, resultmsg => $restr); } } else { ## need to find failure mode if ($config{log_failures}) { if ($webvar{defrec} eq 'y') { logaction(0, $session->param("username"), $rec->{parid}, "Failed deleting default record '$rec->{host} $typemap{$rec->{type}} $rec->{val}',". " TTL $rec->{ttl} ($msg)"); } else { logaction($rec->{parid}, $session->param("username"), parentID($rec->{parid}, 'dom', 'group'), "Failed deleting record '$rec->{host} $typemap{$rec->{type}} $rec->{val}', TTL $rec->{ttl} ($msg)"); } } changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}, errmsg => "Error deleting record: $msg"); } } else { changepage(page => "reclist", id => $webvar{parentid}, defrec => $webvar{defrec}); } } elsif ($webvar{page} eq 'editsoa') { # security check - does the user have permission to view this entity? if (!check_scope(id => $webvar{id}, type => ($webvar{defrec} eq 'y' ? 'group' : '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{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' ? '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' : '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{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}); if ($sth->err) { $page->param(update_failed => 1); $page->param(msg => $DBI::errstr); fillsoa($webvar{defrec},$webvar{id}); ##fixme: faillog } else { # 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($logdomain, 'dom', 'group', $webvar{defrec}); } 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})"); changepage(page => "reclist", id => $webvar{id}, defrec => $webvar{defrec}, resultmsg => "SOA record updated"); } } 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; } } # force inheritance of parent group's default records with inherit flag, # otherwise we end up with the hardcoded defaults from DNSDB.pm. See # https://secure.deepnet.cx/trac/dnsadmin/ticket/8 for the UI enhancement # that will make this variable. my ($code,$msg) = addGroup($dbh, $webvar{newgroup}, $webvar{pargroup}, \%newperms, 1); if ($code eq 'OK') { logaction(0, $session->param("username"), $webvar{pargroup}, "Added group $webvar{newgroup}"); 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 logaction(0, $session->param("username"), $webvar{pargroup}, "Failed to add group $webvar{newgroup}: $msg") if $config{log_failures}; # 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 $deleteme = groupName($dbh,$webvar{id}); # get this before we delete it... my $delparent = parentID($webvar{id}, 'group','group'); my ($code,$msg) = delGroup($dbh, $webvar{id}); if ($code eq 'OK') { ##fixme: need to clean up log when deleting a major container logaction(0, $session->param("username"), $delparent, "Deleted group $deleteme"); changepage(page => "grpman", resultmsg => "Deleted group $deleteme"); } else { # need to find failure mode logaction(0, $session->param("username"), $delparent, "Failed to delete group $deleteme: $msg") if $config{log_failures}; changepage(page => "grpman", errmsg => "Error deleting group $deleteme: $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} 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($webvar{$_}, 'dom', 'group'), "Moved domain ".domainName($dbh, $webvar{$_})." to group $newgname"); $row{domok} = ($code eq 'OK'); } else { logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'), "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 = domStatus($dbh,$webvar{$_},($webvar{bulkaction} eq 'activate' ? 'domon' : 'domoff')); logaction($webvar{$_}, $session->param("username"), parentID($webvar{$_}, 'dom', 'group'), "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($webvar{$_}, 'dom', 'group'); my $dom = domainName($dbh, $webvar{$_}); my ($code, $msg) = delDomain($dbh, $webvar{$_}); 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($webvar{id}, 'user', 'group'), ($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}; fill_rectypes($webvar{type} ? $webvar{type} : '', 1); $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(forcettl => $webvar{forcettl}) if $webvar{forcettl}; $page->param(newttl => $webvar{newttl}) if $webvar{newttl}; $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{domstatus}, $webvar{rwsoa}, $webvar{rwns}, ($webvar{forcettl}); $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)); } 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 } 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; ($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); $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 ($params{$sessme}) { $session->param($sessme, $params{$sessme}); delete $params{$sessme}; } } # handle user check my $newurl = "http://$ENV{HTTP_HOST}$ENV{SCRIPT_NAME}?sid=$sid"; foreach (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 $def = shift; my $id = shift; my $domname = ($def eq 'y' ? '' : "DOMAIN"); $page->param(defrec => $def); # 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 $def eq 'y'; $page->param(parent => ($def eq 'y' ? groupName($dbh, $DNSDB::group) : domainName($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,$def,$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 showdomain { my $def = shift; my $id = shift; # get the SOA first my %soa = getSOA($dbh,$def,$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,$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->{sid} = $webvar{sid}; $rec->{id} = $id; $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); } # fill in record type list on add/update/edit record template sub fill_rectypes { my $type = shift || $reverse_typemap{A}; my $soaflag = shift || 0; my $sth = $dbh->prepare("SELECT val,name FROM rectypes WHERE stdflag=1 ORDER BY listorder"); $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; } if ($soaflag) { my %row = ( recval => $reverse_typemap{SOA}, recname => 'SOA' ); $row{tselect} = 1 if $reverse_typemap{SOA} == $type; push @typelist, \%row; } $page->param(typelist => \@typelist); } # fill_rectypes sub fill_recdata { fill_rectypes($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 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}; # retrieve the right ttl instead of falling (way) back to the hardcoded system default my %soa = getSOA($dbh,$webvar{defrec},$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 { # 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 $sql = "SELECT count(*) FROM domains WHERE group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND domain ~* ?" : ''). ($filter ? " AND domain ~* ?" : ''); 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,"domains",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 = ('domain', 'status', 'group'); my %colheads = (domain => 'Domain', 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? $page->param("start$startwith" => 1) if $startwith && $startwith =~ /^(?:[a-z]|0-9)$/; $page->param(filter => $filter) if $filter; $page->param(searchsubs => $searchsubs) if $searchsubs; ##fixme ##fixme push the SQL and direct database fiddling off into a sub in DNSDB.pm ##fixme $page->param(group => $curgroup); my @domlist; $sql = "SELECT domain_id,domain,status,groups.group_name AS group FROM domains". " INNER JOIN groups ON domains.group_id=groups.group_id". " WHERE domains.group_id IN ($curgroup".($childlist ? ",$childlist" : '').")". ($startwith ? " AND domain ~* ?" : ''). ($filter ? " AND domain ~* ?" : ''). " ORDER BY ".($sortby eq 'group' ? 'groups.group_name' : $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{domainid} = $data[0]; $row{domain} = $data[1]; $row{status} = ($data[2] ? 'Active' : 'Inactive'); $row{group} = $data[3]; $row{bg} = ($rownum++)%2; $row{mkactive} = !$data[2]; $row{sid} = $sid; $row{offset} = $offset; # ACLs $row{domain_edit} = ($permissions{admin} || $permissions{domain_edit}); $row{domain_delete} = ($permissions{admin} || $permissions{domain_delete}); push @domlist, \%row; } $page->param(domtable => \@domlist); } # 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; ##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) ". "VALUES (?,?,?,?,?,?)") or warn $dbh->errstr; $sth->execute($domid,$user_id,$groupid,$username,$fullname,$entry) or warn $sth->errstr; } # end logaction() ##fixme: generalize to return appropriate id on all cases (ie, use $partype) sub parentID { my $id = shift; my $idtype = shift; my $partype = shift; my $defrec = shift || ''; my $sql = ''; if ($idtype eq 'dom') { return $id if $defrec eq 'y'; # "domain" + default records, we're really looking at a group. $sql = "SELECT group_id FROM domains WHERE domain_id=?"; } elsif ($idtype eq 'rec') { if ($defrec eq 'y') { $sql = "SELECT group_id FROM default_records WHERE record_id=?"; } else { $sql = "SELECT d.group_id FROM domains d". " INNER JOIN records r ON d.domain_id=r.domain_id". " WHERE r.record_id=?"; } } elsif ($idtype eq 'group') { $sql = "SELECT parent_group_id FROM groups WHERE group_id=?"; } elsif ($idtype eq 'user') { $sql = "SELECT group_id FROM users WHERE user_id=?"; } else { return "FOO", "BAR"; # can't get here.... we think. } my $sth = $dbh->prepare($sql); $sth->execute($id); my ($retid) = $sth->fetchrow_array; return $retid if $retid; # ahh! fall of the edge of the world if things went sideways ##fixme: really need to do a little more error handling, I think } # end parentID() # 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); } } }