#!/usr/bin/env php
<?php
// vim: :set filetype=php tabstop=4 shiftwidth=4 autoindent smartindent:

// This adds all the RFC1918 addressess to the 'trusted' zone.

// If the firewall hasn't started yet, don't do anything.
if (file_exists("/var/run/firewalld.safemode")) {
	print "Firewall not started. Ignoring\n";
	exit;
}

// ///////////////////////////////////// //
// BOILERPLATE SECURITY VALIDATION CODE: // 
// ------------------------------------- //
// Ensure this is run before including   //
// any files from the module. If you're  //
// including a file IN the module, check //
// to see if the class exists...         //
// ///////////////////////////////////// //

// Now we've passed the first checks, we can load the fake (root-owned-file) FreePBX and GPG objects
require '/usr/lib/sysadmin/includes.php';
$g = new \Sysadmin\GPG();
$sigfile = \Sysadmin\FreePBX::Config()->get('AMPWEBROOT')."/admin/modules/firewall/module.sig";
$sig = $g->checkSig($sigfile);
if (!isset($sig['config']['hash']) || $sig['config']['hash'] !== "sha256") {
	throw new \Exception("Invalid sig file.. Hash is not sha256 - check $sigfile");
}

// Check the hash of the validator, before we include it
if (empty($sig['hashes']['hooks/validator.php'])) {
	throw new \Exception("Validator not part of module.sig");
}

$vhash = hash_file('sha256', __DIR__."/validator.php");
if ($vhash !== $sig['hashes']['hooks/validator.php']) {
	throw new \Exception("Validator tampered");
} else {
	include __DIR__."/validator.php";
}

// Yay! We instantiate it now so that the Driver loader
// knows we're running as root, and we have our hashes
// preloaded.
$v = new \FreePBX\modules\Firewall\Validator($sig);

// /////////////////////////////////// //
// END BOILERPLATE SECURITY VALIDATION //
// /////////////////////////////////// //

$v->secureInclude('Zones.class.php');
$v->secureInclude('Driver.class.php');
$d = new \FreePBX\modules\Firewall\Driver;
$driver = $d->getDriver();

$needsreload = false;

$known = $driver->getKnownNetworks();

// Note: If you update this (.. why would you, though?), make sure you update
// them in the Firewall class, too.
if (!isset($known['192.168.0.0/16'])) {
	$driver->addNetworkToZone("trusted", "192.168.0.0", 16);
	$needsreload = true;
}

if (!isset($known['172.16.0.0/12'])) {
	$driver->addNetworkToZone("trusted", "172.16.0.0", 12);
	$needsreload = true;
}

if (!isset($known['10.0.0.0/8'])) {
	$driver->addNetworkToZone("trusted", "10.0.0.0", 8);
	$needsreload = true;
}

if (!isset($known['fc00::/8'])) {
	$driver->addNetworkToZone("trusted", "fc00::", 8);
	$needsreload = true;
}

if (!isset($known['fd00::/8'])) {
	$driver->addNetworkToZone("trusted", "fd00::", 8);
	$needsreload = true;
}

if ($needsreload) {
	$driver->commit();
}

