Skip to content

Instantly share code, notes, and snippets.

@bagf
Created February 27, 2014 12:08
Show Gist options
  • Save bagf/9248880 to your computer and use it in GitHub Desktop.
Save bagf/9248880 to your computer and use it in GitHub Desktop.
OpenVPN common name sync script for bind9 DNS servers
#!/usr/bin/php
<?php
/*
* This script can be passed to --learn-address of the openvpn server, it will
* update the local bind9 server whenever an ip address is passed
*/
// Bind9 server to update
define("NS_ADDR", "127.0.0.1");
// Domain to prepend common name to
define("DOMAIN", "vpn.");
// nsupdate bin
define("NSUPDATE", "/usr/bin/nsupdate");
// Temp path
define("TMP_PATH", "/tmp/");
// Private key path
define("PRIVATE_KEY", "/var/lib/bind/affiwr.key");
// Debug
define("DEBUG", true);
function failWithError($error) {
syslog(LOG_ERR, $error);
exit(1);
}
function addRecordWithIP($record, $ip) {
$domain = $record.".".DOMAIN;
$filepath = TMP_PATH."/". __FUNCTION__."_" .rand(900, 999);
$fh = fopen($filepath, "w");
fwrite($fh, "server ".NS_ADDR."\n");
fwrite($fh, "debug ".(DEBUG?'yes':'no')."\n");
fwrite($fh, "zone ".DOMAIN."\n");
fwrite($fh, "update add {$domain} 60 A {$ip}\n");
fwrite($fh, "send\n");
fclose($fh);
$output = [];
exec(NSUPDATE." -k ".escapeshellarg(PRIVATE_KEY)." -v ".escapeshellarg($filepath).(DEBUG?"":" 2>&1 > /dev/null"), $output);
if (DEBUG) {
syslog(LOG_ERR, print_r($output, true));
}
// clean up
unlink($filepath);
}
function removeRecord($record) {
$domain = $record.".".DOMAIN;
$filepath = TMP_PATH."/". __FUNCTION__."_" .rand(900, 999);
$fh = fopen($filepath, "w");
fwrite($fh, "server ".NS_ADDR."\n");
fwrite($fh, "debug ".(DEBUG?'yes':'no')."\n");
fwrite($fh, "zone ".DOMAIN."\n");
fwrite($fh, "update delete {$domain}\n");
fwrite($fh, "send\n");
fclose($fh);
$output = [];
exec(NSUPDATE." -k ".escapeshellarg(PRIVATE_KEY)." -v ".escapeshellarg($filepath).(DEBUG?"":" 2>&1 > /dev/null"), $output);
if (DEBUG) {
syslog(LOG_ERR, print_r($output, true));
}
// clean up
unlink($filepath);
}
if ($argc < 3) {
failWithError("Incorrect number of params");
}
$slashpos = strpos($argv[2], "/");
if ($slashpos !== false) {
// Remove subnet from ip
$argv[2] = substr($argv[2], $slashpos);
}
if (inet_pton($argv[2]) === false) {
failWithError("{$argv[2]} is not a valid ip address");
}
switch($argv[1]) {
case "update":
case "add":
if (isset($argv[3])) {
removeRecord($argv[3]);
addRecordWithIP($argv[3], $argv[2]);
}
break;
case "remove":
// Since openvpn only provides the ip on this request we cannot remove the
break;
}
// Success
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment