#!/usr/local/bin/perl -- -*-Perl-*-
#
# $Id$
# $Source$
# Paul Traina & Mark Baushke (Feburary 1994)
#
# Generate fast acl's based upon time parameters
# (this is intended to restrict vty access on terminal servers)
#
require 'netsec-data.pl';
require 'getopts.pl';

$data_file = "cs-access.policy";

&Getopts("f:n");

$data_file = $opt_f if $opt_f;
$data_file = ""     if $opt_n;

########################################################################
#####
#####	Begin ACL Policy Section
#####
########################################################################

&header_prelude;
&start_list(51);

print "! cisco networks\n";
&fast_entry("deny",   @cisco_insecure_networks);
&fast_entry("permit", @cisco_networks);

&read_policy($data_file) if ($data_file ne "");

print "end\n";

########################################################################
#####
#####	Subroutines
#####
########################################################################

#
# read_policy
#
# Read time based access policy information from a data file
# and produce access list entries suitable for terminal server
# vty access lines.
#
# policy lines look like this:
# user:source:start:end[:comment]

sub read_policy {
    local($file) = @_[0];

    local($user,$source,$start,$end,$today);
    local($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
	localtime(time);
    $today = sprintf("%d-%-2.2d-%-2.2d", 1900 + $year, $mon+1, $mday);

    open(POLICY, $file) || die "no data file $file found";

    print "! reading policy from $file\n";
    print "!\n";

    while(<POLICY>) {
	chop;
	next if (/^\#/ || /^\!/ || /^$/); # skip comment lines
	($user,$source,$start,$end,$comment) = split(':', $_, 5);
	if ((&validdate($start) != 1) ||
	    (&validdate($end) != 1)) {
	    print STDERR "ignoring line $. \'$_\'\n";
	    next;
	}

	# do we need to worry about this time yet?
	if ((&comparedate($today,$start) < 0) ||
	    (&comparedate($today,$end) > 0)) {
	    next;
	}
	print "! $user from $start to $end\n";
	print "! $comment\n" if ($comment ne '');
	&fast_entry("permit", $source);
    }

    close(POLICY);
}

sub comparedate {
    local($date1, $date2) = @_;
    local($result) = 0;

    ($y1, $m1, $d1) = split('-',$date1);
    ($y2, $m2, $d2) = split('-',$date2);

    if ($y1 < $y2) {
	$result = -1;
    }
    elsif ($y1 > $y2) {
	$result = 1;
    }
    elsif ($m1 < $m2) {
	$result = -1;
    }
    elsif ($m1 > $m2) {
	$result = 1;
    }
    elsif ($d1 < $d2) {
	$result = -1;
    }
    elsif ($d1 > $d2) {
	$result = 1;
    }
    $result;
}

sub validdate {
    local($date) = @_;
    local($y, $m, $d) = split('-',$date);

    if (($y < 1900) ||
	($m < 1) || ($m > 12) ||
	($d < 1) || ($d > 31)) {
	print STDERR "bogus date $y-$m-$d\n";
	return 0;
    }
    return 1;
}

# -------------------------------------------------------------------------
#  $Log$
# -------------------------------------------------------------------------
