#!/usr/bin/perl # ipdb/cgi-bin/main.cgi ### # SVN revision info # $Date: 2010-08-25 20:12:50 +0000 (Wed, 25 Aug 2010) $ # SVN revision $Rev: 477 $ # Last update by $Author: kdeugau $ ### # Copyright (C) 2004-2010 - Kris Deugau use strict; use warnings; use CGI::Carp qw(fatalsToBrowser); use CGI::Simple; use HTML::Template; use DBI; use CommonWeb qw(:ALL); use CustIDCK; use POSIX qw(ceil); use NetAddr::IP; use Sys::Syslog; # don't remove! required for GNU/FHS-ish install from tarball ##uselib## use MyIPDB; openlog "IPDB","pid","$IPDB::syslog_facility"; # Collect the username from HTTP auth. If undefined, we're in # a test environment, or called without a username. my $authuser; if (!defined($ENV{'REMOTE_USER'})) { $authuser = '__temptest'; } else { $authuser = $ENV{'REMOTE_USER'}; } syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}"; # Why not a global DB handle? (And a global statement handle, as well...) # Use the connectDB function, otherwise we end up confusing ourselves my $ip_dbh; my $sth; my $errstr; ($ip_dbh,$errstr) = connectDB_My; if (!$ip_dbh) { exitError("Database error: $errstr\n"); } initIPDBGlobals($ip_dbh); # Set up some globals ##fixme - need to autofill this somehow $ENV{HTML_TEMPLATE_ROOT} = '/home/kdeugau/dev/ipdb/trunk/templates'; my $header = HTML::Template->new(filename => "header.tmpl"); my $footer = HTML::Template->new(filename => "footer.tmpl"); $header->param(version => $IPDB::VERSION); $header->param(addperm => $IPDBacl{$authuser} =~ /a/); print "Content-type: text/html\n\n", $header->output; # 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; # Convenience; saves changing all references to %webvar ##fixme: tweak for handling value have either encoded or bare newlines. # Also applies to privdata. $page->param(notes => $q->escapeHTML($webvar{notes},'y')); # Check to see if user is allowed to do anything with sensitive data my $privdata = ''; $page->param(privdata => $q->escapeHTML($webvar{privdata},'y')) if $IPDBacl{$authuser} =~ /s/; # Yay! This now has it's very own little home. $page->param(billinguser => $webvar{userid}) if $webvar{userid}; ##fixme: this is only needed iff confirm.tmpl/confirm.html and # confirmRemove.html/confirmRemove.tmpl are merged (quite possible, just # a little tedious) $page->param(action => "insert"); } # end confirmAssign # Do the work of actually inserting a block in the database. sub insertAssign { if ($IPDBacl{$authuser} !~ /a/) { printError("You shouldn't have been able to get here. Access denied."); return; } # Some things are done more than once. return if !validateInput(); if (!defined($webvar{privdata})) { $webvar{privdata} = ''; } # $code is "success" vs "failure", $msg contains OK for a # successful netblock allocation, the IP allocated for static # IP, or the error message if an error occurred. my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from}, $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes}, $webvar{circid}, $webvar{privdata}, $webvar{node}); if ($code eq 'OK') { if ($webvar{alloctype} =~ /^.i$/) { $msg =~ s|/32||; $page->param(staticip => $msg); $page->param(custid => $webvar{custid}); $page->param(billinguser => $webvar{billinguser}); mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation", "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n". "Description: $webvar{desc}\n\nAllocated by: $authuser\n"); } else { my $netblock = new NetAddr::IP $webvar{fullcidr}; $page->param(fullcidr => $webvar{fullcidr}); $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}}); $page->param(custid => $webvar{custid}); if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) { $page->param(billinguser => $webvar{billinguser}); $page->param(custid => $webvar{custid}); $page->param(netaddr => $netblock->addr); $page->param(masklen => $netblock->masklen); } mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation", "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n". "Description: $webvar{desc}\n\nAllocated by: $authuser\n"); } syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ". "'$webvar{alloctype}' ($msg)"; } else { syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ". "'$webvar{alloctype}' by $authuser failed: '$msg'"; $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'". " failed:
\n$msg\n"); } } # end insertAssign() # Does some basic checks on common input data to make sure nothing # *really* weird gets in to the database through this script. # Does NOT do complete input validation!!! sub validateInput { if ($webvar{city} eq '-') { printError("Please choose a city."); return; } # Alloctype check. chomp $webvar{alloctype}; if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) { # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone # managing to call things in such a way as to cause this deserves a cryptic error. printError("Invalid alloctype"); return; } # CustID check # We have different handling for customer allocations and "internal" or "our" allocations if ($def_custids{$webvar{alloctype}} eq '') { if (!$webvar{custid}) { printError("Please enter a customer ID."); return; } if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) { # Force uppercase for now... $webvar{custid} =~ tr/a-z/A-Z/; # Crosscheck with billing. my $status = CustIDCK->custid_exist($webvar{custid}); if ($CustIDCK::Error) { printError("Error verifying customer ID: ".$CustIDCK::ErrMsg); return; } if (!$status) { printError("Customer ID not valid. Make sure the Customer ID ". "is correct.
\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ". "non-customer assignments."); return; } } # print "\n"; } else { # New! Improved! And now Loaded From The Database!! if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) { $webvar{custid} = $def_custids{$webvar{alloctype}}; } } # Check POP location my $flag; if ($webvar{alloctype} eq 'rm') { $flag = 'for a routed netblock'; foreach (@poplist) { if (/^$webvar{city}$/) { $flag = 'n'; last; } } } else { $flag = 'n'; ##fixme: hook to force-set POP or city on certain alloctypes # if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; } if ($webvar{pop} =~ /^-$/) { $flag = 'to route the block from/through'; } } if ($flag ne 'n') { printError("Please choose a valid POP location $flag. Valid ". "POP locations are currently:
\n".join (" - ", @poplist)); return; } return 'OK'; } # end validateInput # Displays details of a specific allocation in a form # Allows update/delete # action=edit sub edit { my $sql; # Two cases: block is a netblock, or block is a static IP from a pool # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data ##fixme: allow "SWIP" (publication to rWHOIS) of static IP data if ($webvar{block} =~ /\/32$/) { $sql = "select ip,custid,type,city,circuitid,description,notes,modifystamp,privdata from poolips where ip='$webvar{block}'"; } else { $sql = "select cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip from allocations where cidr='$webvar{block}'" } # gotta snag block info from db $sth = $ip_dbh->prepare($sql); $sth->execute; my @data = $sth->fetchrow_array; # Clean up extra whitespace on alloc type $data[2] =~ s/\s//; # We can't let the city be changed here; this block is a part of # a larger routed allocation and therefore by definition can't be moved. # block and city are static. ##fixme # Needs thinking. Have to allow changes to city to correct errors, no? # Also have areas where a routed block at a POP serves "many" cities/towns/named crossroads # @data: cidr,custid,type,city,circuitid,description,notes,modifystamp,privdata,swip $page->param(block => $webvar{block}); $page->param(custid => $data[1]); $page->param(city => $data[3]); $page->param(circid => $data[4]); $page->param(desc => $data[5]); $page->param(notes => $data[6]); ##fixme The check here should be built from the database # Need to expand to support pool types too if ($data[2] =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) { $page->param(changetype => 1); $page->param(alloctype => [ { selme => ($data[2] eq 'me'), type => "me", disptype => "Dialup netblock" }, { selme => ($data[2] eq 'de'), type => "de", disptype => "Dynamic DSL netblock" }, { selme => ($data[2] eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" }, { selme => ($data[2] eq 'we'), type => "we", disptype => "Dynamic wireless netblock" }, { selme => ($data[2] eq 'cn'), type => "cn", disptype => "Customer netblock" }, { selme => ($data[2] eq 'en'), type => "en", disptype => "End-use netblock" }, { selme => ($data[2] eq 'in'), type => "in", disptype => "Internal netblock" }, ] ); } else { $page->param(disptype => $disp_alloctypes{$data[2]}); $page->param(type => $data[2]); } ## node hack $sth = $ip_dbh->prepare("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef". " ON nodes.node_id=noderef.node_id WHERE noderef.block='$webvar{block}'"); $sth->execute; my ($nodeid,$nodename) = $sth->fetchrow_array(); $page->param(havenodeid => $nodeid); if ($data[2] eq 'fr' || $data[2] eq 'bi') { $page->param(typesupportsnodes => 1); $page->param(nodename => $nodename); ##fixme: this whole hack needs cleanup and generalization for all alloctypes ##fixme: arguably a bug that presence of a nodeid implies it can be changed.. # but except for manual database changes, only the two types fr and bi can # (currently) have a nodeid set in the first place. if ($IPDBacl{$authuser} =~ /c/) { $sth = $ip_dbh->prepare("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id"); $sth->execute; my @nodelist; while (my ($nid,$nname) = $sth->fetchrow_array()) { my %row = ( selme => ($nodeid == $nid), nodeid => $nid, nodename => $nname, ); push (@nodelist, \%row); } $page->param(nodelist => \@nodelist); } } ## end node hack my ($lastmod,undef) = split /\s+/, $data[7]; $page->param(lastmod => $lastmod); # not happy with the upside-down logic, but... $page->param(swipable => $data[2] !~ /.i/); $page->param(swip => $data[10] ne 'n'); # Check to see if we can display sensitive data $page->param(nocling => $IPDBacl{$authuser} =~ /s/); $page->param(privdata => $data[8]); # ACL trickery - these two template booleans control the presence of all form/input tags $page->param(maychange => $IPDBacl{$authuser} =~ /c/); $page->param(maydel => $IPDBacl{$authuser} =~ /d/); } # edit() # Stuff new info about a block into the db # action=update sub update { if ($IPDBacl{$authuser} !~ /c/) { printError("You shouldn't have been able to get here. Access denied."); return; } # Check to see if we can update restricted data my $privdata = ''; if ($IPDBacl{$authuser} =~ /s/) { $privdata = ",privdata='$webvar{privdata}'"; } # Make sure incoming data is in correct format - custID among other things. return if !validateInput; # SQL transaction wrapper eval { # Relatively simple SQL transaction here. my $sql; if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) { $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',". "circuitid='$webvar{circid}',description='$webvar{desc}',city='$webvar{city}'". "$privdata where ip='$webvar{block}'"; } else { $sql = "update allocations set custid='$webvar{custid}',". "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',". "type='$webvar{alloctype}',circuitid='$webvar{circid}'$privdata,". "swip='".($webvar{swip} eq 'on' ? 'y' : 'n')."' ". "where cidr='$webvar{block}'"; } # Log the details of the change. syslog "debug", $sql; $sth = $ip_dbh->prepare($sql); $sth->execute; ## node hack if ($webvar{node}) { $ip_dbh->do("DELETE FROM noderef WHERE block='$webvar{block}'"); $sth = $ip_dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)"); $sth->execute($webvar{block},$webvar{node}); } ## end node hack $ip_dbh->commit; }; if ($@) { my $msg = $@; carp "Transaction aborted because $msg"; eval { $ip_dbh->rollback; }; syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'"; printError("Could not update block/IP $webvar{block}: $msg"); return; } # If we get here, the operation succeeded. syslog "notice", "$authuser updated $webvar{block}"; ##fixme: need to wedge something in to allow "update:field" notifications ## hmm. how to tell what changed? O_o mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}", "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on'; ## node hack if ($webvar{node} && $webvar{node} ne '-') { $sth = $ip_dbh->prepare("SELECT node_name FROM nodes WHERE node_id=?"); $sth->execute($webvar{node}); my ($nodename) = $sth->fetchrow_array(); $page->param(nodename => $nodename); } ## end node hack # Link back to browse-routed or list-pool page on "Update complete" page. my $cblock; # to contain the CIDR of the container block we're retrieving. my $sql; if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) { $page->param(backpool => 1); $sql = "select pool from poolips where ip='$webvar{block}'"; } else { $sql = "select cidr from routed where cidr >>= '$webvar{block}'"; } # I define there to be no errors on this operation... so we don't need to check for them. $sth = $ip_dbh->prepare($sql); $sth->execute; $sth->bind_columns(\$cblock); $sth->fetch(); $sth->finish; $page->param(backblock => $cblock); $page->param(cidr => $webvar{block}); $page->param(city => $webvar{city}); $page->param(disptype => $disp_alloctypes{$webvar{alloctype}}); $page->param(custid => $webvar{custid}); $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No'); $page->param(circid => $q->escapeHTML($webvar{circid})); $page->param(desc => $q->escapeHTML($webvar{desc})); $page->param(notes => $q->escapeHTML($webvar{notes})); $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : " "); $page->param(privdata => $webvar{privdata}) if $IPDBacl{$authuser} =~ /s/; } # update() # Delete an allocation. sub remove { if ($IPDBacl{$authuser} !~ /d/) { printError("You shouldn't have been able to get here. Access denied."); return; } # Serves'em right for getting here... if (!defined($webvar{block})) { printError("Error 332"); return; } my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype, $privdata); if ($webvar{alloctype} eq 'rm') { $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'"); $sth->execute(); # This feels... extreme. croak $sth->errstr() if($sth->errstr()); $sth->bind_columns(\$cidr,\$city); $sth->execute(); $sth->fetch || croak $sth->errstr(); $custid = "N/A"; $alloctype = $webvar{alloctype}; $circid = "N/A"; $desc = "N/A"; $notes = "N/A"; $privdata = "N/A"; } elsif ($webvar{alloctype} eq 'mm') { $cidr = $webvar{block}; $city = "N/A"; $custid = "N/A"; $alloctype = $webvar{alloctype}; $circid = "N/A"; $desc = "N/A"; $notes = "N/A"; $privdata = "N/A"; } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m # Unassigning a static IP my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid,privdata". " from poolips where ip='$webvar{block}'"); $sth->execute(); # croak $sth->errstr() if($sth->errstr()); $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid, \$privdata); $sth->fetch() || croak $sth->errstr; } else { # done with alloctype=~ /^.i$/ my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes,privdata". " from allocations where cidr='$webvar{block}'"); $sth->execute(); # croak $sth->errstr() if($sth->errstr()); $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes, \$privdata); $sth->fetch() || carp $sth->errstr; } # end cases for different alloctypes $page->param(block => $cidr); $page->param(disptype => $disp_alloctypes{$alloctype}); $page->param(type => $alloctype); $page->param(city => $city); $page->param(custid => $custid); $page->param(circid => $circid); $page->param(desc => $desc); $page->param(notes => $notes); $privdata = ' ' if $privdata eq ''; $page->param(privdata => $privdata) if $IPDBacl{$authuser} =~ /s/; $page->param(delpool => $alloctype =~ /^.[pd]$/); } # end remove() # Delete an allocation. Return it to the freeblocks table; munge # data as necessary to keep as few records as possible in freeblocks # to prevent weirdness when allocating blocks later. # Remove IPs from pool listing if necessary sub finalDelete { if ($IPDBacl{$authuser} !~ /d/) { $page->param(aclerr => 1); return; } # need to retrieve block data before deleting so we can notify on that my ($cidr,$custid,$type,$city,$description) = getBlockData($ip_dbh, $webvar{block}); my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype}); $page->param(block => $webvar{block}); if ($code eq 'OK') { syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}". " $custid, $city, desc='$description'"; mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}", "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n". "CustID: $custid\nCity: $city\nDescription: $description\n"); } else { $page->param(failmsg => $msg); if ($webvar{alloctype} =~ /^.i$/) { syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'"; } else { syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'"; $page->param(netblock => 1); } } } # finalDelete # going, going, gone... this sub to be removed Any Day Real Soon Now(TM) sub exitError { my $errStr = $_[0]; printHeader('',''); print qq(

$errStr

); # We print the footer here, so we don't have to do it elsewhere. # include the admin tools link in the output? $footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/)); print $footer->output; exit; } # errorExit # Just in case we manage to get here. exit 0;