/*
 * Copyright (c) 2001-2007, OpenFWTK Development Group
 * All rights reserved. See LICENSE.
 */

/*
 *  netacl.c, a generic tcpwrapper program for OpenFWTK
 * (C) Copyright 2001-2002 by ArkanoiD <ark@eltex.ru>
 */

#include	<syslog.h>
#include	<stdio.h>
#include	<string.h>
#include	<unistd.h>
#include	<stdlib.h>
#include	<sys/types.h>
#include	<sys/file.h>
#include	<pwd.h>
#include	<time.h>
#include	<errno.h>

#include	"firewall.h"
#include	"firewall2.h"
#include	"fwfunc.h"

static	char*	moduleId ATTR_UNUSED = "$Id: netacl.c,v 1.6 2007/09/10 02:49:13 arkenoi Exp $";
static	char	*service;

/*
 * We cannot use our generic proxy_parse_options here because of
 * -exec parameters which may start with dash
 */


static	void
parse_options(cf)
Cfg	*cf;
{
	int	x;


	for(x = 0; x < cf->argc; x++) {
		if(!strcmp(cf->argv[x],"-klaxon")) {
			syslog(LLEV,"securityalert: host=%.128s/%.128s accessing service %.32s",
				proxy_stats.rladdr,proxy_stats.riaddr,service);
			continue;
		}
		if ((cf->argv[x][0] == '-') && !((x+1) >= cf->argc)) {
			syslog(LLEV,"fwtkcfgerr: missing parameter, line %d",cf->ln);
			exit(1);
		}
		if(!strcmp(cf->argv[x],"-user")) {
			if((proxy_uid  = mapuid(cf->argv[x+1])) == -1) {
				syslog(LLEV,"fwtkcfgerr: cannot map uid %.100s",cf->argv[x+1]);
				exit(1);
			}
			x++;
			continue;
		}
		if(!strcmp(cf->argv[x],"-group")) {
			if((proxy_gid  = mapgid(cf->argv[x+1])) == -1) {
				syslog(LLEV,"fwtkcfgerr: cannot map gid %.100s",cf->argv[x+1]);
				exit(1);
			}
			x++;
			continue;
		}
		if(!strcmp(cf->argv[x],"-chroot")) {
			strncpy(proxy_chroot,cf->argv[x+1],sizeof(proxy_chroot));
			x++;
			continue;
		}
		if(!strcmp(cf->argv[x],"-exec")) {
			proxy_chroot_setugid();
			syslog(LLEV,"permit host=%.512s/%.20s service=%.100s execute=%.512s",proxy_stats.rladdr,proxy_stats.riaddr,service,cf->argv[x+1]);
			execv(cf->argv[x + 1],&(cf->argv[x +1]));
			syslog(LLEV,"fwtksyserr: exec: %.512s : %s",cf->argv[x+1], strerror(errno));
			exit(1);
		}
	}
	exit(0);	/* Nothing to do */
}

int
main(argc,argv)
int	argc;
char	*argv[];
{
	Cfg	*cf;
	char	buf[512];

	proxy_init(argc,argv);

	if((argc == 1) || !(argv[1])) {
		service = proxy_name;
	} else
		service = argv[1];

	if(strlen(service) + 9 > sizeof(buf)) {
		syslog(LLEV,"fwtkcfgerr: name of av[](%.100s) too long",service);
		exit(1);
	}

	snprintf(buf,sizeof(buf)-1,"netacl-%s",service);
	cfg_free(proxy_confp);
	if((proxy_confp = cfg_read(buf)) == (Cfg *)-1) {
		syslog(LLEV,"fwtkcfgerr: %.512s exiting - cannot read configuration",service);
		exit(1);
	}

	if ((cf = proxy_conf_hosts(proxy_confp,proxy_stats.rladdr,
					proxy_stats.riaddr)))
		parse_options(cf);
	else {
		syslog(LLEV,"deny host=%.512s/%.20ss service=%.100s",
				proxy_stats.rladdr,proxy_stats.riaddr,service);
		exit(1);
	}
	exit(1);	/* Unreached */
}
