Search code examples
phpconfigphp-7dnssec

Edit BIND config file using PHP


I have a file called named.conf, which is the configuration file for BIND. It has entries enclosed in curly braces. I want to edit and enter a new zone entry into both the internal and external views using PHP. How can I do this. Is there any library available for editing this type of config files?

view "internal"
{

match-clients { localnets; };
match-destinations { localnets; };
recursion yes;

include "/etc/named.root.hints";
    
zone "my.internal.zone" {
type master;
file "my.internal.zone.db";
};

};


view "external"
{

match-clients { !localnets; !localhost; };
match-destinations { !localnets; !localhost; };

recursion no;
    
include "/etc/named.root.hints";
    
zone "my.external.zone" {
type master;
file "my.external.zone.db";
};
};

Solution

  • I was able to do it using the below code. The code accepts arguments using PHP CLI and creates a new file with the values.

    $file = file('named.conf');
    
    $arg =  getopt("", array('zone:', 'type:', 'file:'));
    
    $internal_end = 0;
    $external_end = 0;
    $flag = false;
    $count = 0;
    foreach ($file as $index => $line) {
        if (preg_match('/view\s*"internal"\s*{/i', $line) !== 1 && !$flag) {
            continue;
        }
        $flag = true;
    
        $ob =  substr_count($line, '{');
        $count += $ob;
        $cb =  substr_count($line, '}');
        $count -= $cb;
        if ($count == 0) {
            $internal_end = $index;
            break;
        }
    }
    
    
    
    array_splice($file, $internal_end, 0, array(
        "\n",
        "zone \"".$arg['zone']."\" {\n",
        "\ttype ".$arg['type'].";\n",
        "\tfile \"".$arg['file']."\";\n",
        "};\n",
        "\n"
    ));
    
    $flag = false;
    $count = 0;
    foreach ($file as $index => $line) {
        if (preg_match('/view\s*"external"\s*{/i', $line) !== 1 && !$flag) {
            continue;
        }
        $flag = true;
    
        $ob =  substr_count($line, '{');
        $count += $ob;
        $cb =  substr_count($line, '}');
        $count -= $cb;
        if ($count == 0) {
            $external_end = $index;
            break;
        }
    }
    
    
    array_splice($file, $external_end, 0, array(
        "\n",
        "zone \"".$arg['zone']."\" {\n",
        "\ttype ".$arg['type'].";\n",
        "\tfile \"".$arg['file']."\";\n",
        "};\n",
        "\n"
    ));
    
    
    file_put_contents('named_new.conf', implode('', $file));
    

    To execute the code call php script.php --zone=my.new.external.zone --type=master --file=my.new.external.zone.db