Skip to content

Instantly share code, notes, and snippets.

@hgaibor
Last active June 11, 2020 00:41
Show Gist options
  • Save hgaibor/002f11424c6eec7ed0416e9d245d753e to your computer and use it in GitHub Desktop.
Save hgaibor/002f11424c6eec7ed0416e9d245d753e to your computer and use it in GitHub Desktop.
VPN for D-phones
#!/usr/bin/php -q
<?php
echo "
------------------------------------------------------------------------------------------
| |
| Script: vpnize-phones.php |
| Script used to modify extension files and allow D phones to connect using |
| VPN connectivity from Sysadmin PRO VPN clients module |
| |
| Latest version: https://gist.github.com/hgaibor/002f11424c6eec7ed0416e9d245d753e |
| |
| Usage: Put this file on /home/asterisk and run as Asterisk user to keep files |
| permissions untouched. |
| Tested this using FreePBX 15 version and sysadmin_pro module installed |
| (required to use the VPN clients module). |
| |
| This module takes into account that the default directories are used and the |
| VPN client description has the format: EXTENSION_number - Any text here |
| |
| It will get the list of VPN clients and generate the ovpn files required for |
| the D phones to be able to get the VPN set up |
| |
| USAGE: |
| # php vpnize-Dphones.php |
| |
| Commands: |
| No commands at the momment... may get upgraded |
| |
| License: GNU/GPL3+ |
| |
| History: |
| 2020-06-08 Initial commit |
| |
------------------------------------------------------------------------------------------
";
// include FreePBX bootstrap environment
include '/etc/freepbx.conf';
$FreePBX = FreePBX::Create();
// Variables for general operation, do not touch this unless you have changed directories or want to test before using this command
$oVpnServerCaFile = '/etc/openvpn/sysadmin_ca.crt'; // Default VPN server certificate file path if using FPBX/PBXact distros
$oVpnSourceFileFolder = '/etc/openvpn/clients/'; // Default VPN clients file paths if using FPBX/PBXact distros
// Same folder as where phones will take their extension config files
// $oVpnOutFileFolder = '/home/asterisk/ovpntest/'; // For debug only
$oVpnOutFileFolder = '/tftpboot/'; // Production use
// Variables used during phone extension configuration files
$extConfigStringReplace = '-----oVpn_MD5_hash-----'; //Space filler for template file, so it gets replaced on each ext.cfg file when running this script
// Folder where phones will take their extension config files
// $extConfigFileFolder = '/home/asterisk/tftptest/'; // For debug only
$extConfigFileFolder = '/tftpboot/'; // Production use
$fullExtConfigFilePath = '';
// In case file extension changes, we can modify it here
// $extConfigFileExtension = '-test.cfg'; // For debug only
$extConfigFileExtension = '.cfg'; // Production use
$vpnFileAddParams = "setenv FORWARD_COMPATIBLE 1
setenv PUSH_PEER_INFO
redirect-gateway def1\n"; // If you know openVPN, you may add additional stuff here, end with a line break...
// BEGIN!
echo "Getting list of VPN clients from sysadmin..."."\n";
$VpnClients = getVpnClients($FreePBX);
// print_r($VpnClients); // For debug only
echo "Creating ovpn files for each client extension..."."\n";
foreach($VpnClients as $vpnClientId => $clientData) {
// echo $vpnClientId."\n"; // For debug only
// echo $clientData['description']; // For debug only
// Get the extension number from the VPN client description field, given that the first part of the description is the extension number.
preg_match('/^(\d+)/', $clientData['description'], $parsedString);
$oVpnOutFileName = $parsedString[0].'.ovpn';
// echo $oVpnOutFileName; // For debug only
if (($parsedString[0] != '') and $clientData['enabled']==1) // Check only for enabled VPN clients
{
echo " - Found extension ".$parsedString[0]."\n";
createOvpnFile($vpnClientId, $oVpnServerCaFile, $oVpnSourceFileFolder, $oVpnOutFileFolder, $oVpnOutFileName, $vpnFileAddParams);
// echo $VpnClient['description'] ;
// break; // For debug only
echo " - Creating ovpn file... ".$oVpnOutFileFolder.$oVpnOutFileName."\n";
// Saving file path for extension config file generation based on vpn client description
$fullExtConfigFilePath = $extConfigFileFolder.$parsedString[0].$extConfigFileExtension;
// echo $fullExtConfigFilePath."\n"; // For debug only
echo " - Rewriting Cfg file... ".$fullExtConfigFilePath."\n";
$oVpnOutFile = $oVpnOutFileFolder.$oVpnOutFileName;
$oVpnOutFileMd5 = md5_file($oVpnOutFile);
// echo $oVpnOutFileMd5."\n"; // For debug only
// Edit files generated by EPM to replace the ovpn hash with the filler name
insertExtConfigHash($fullExtConfigFilePath, $extConfigStringReplace, $oVpnOutFileMd5);
}
}
function getVpnClients(&$FreePBX)
{
// Requires the FreePBX bootstrap, passed by reference
// $sql = "select * from sysadmin_options where `key` like '%vpn%';"; // For debug only
$sql = "select * from sysadmin_options where `key`='vpnclients';";
$sth = $FreePBX->database->prepare($sql);
$sth->execute();
$rows = $sth->fetchAll(\PDO::FETCH_ASSOC);
foreach($rows as $row) {
$results = array( $row['key'] => $row['value']);
// print_r($results); // For debug only
}
// return $results;
$VpnArray = json_decode($results['vpnclients'], true);
// echo $results['vpnclients'];
// var_dump($VpnArray); // For debug only
return $VpnArray;
}
function createOvpnFile($clientId, $saCaFilePath, $sourceFilePath, $destinationPath, $clientFileName, $ovpnAddParams)
{
$ovpnFileContent = '';
// $ovpnAddParams - ''; // Use this variable to send additional parameters to the openvpn file, updated it to receive it from called function
$confFilePath = $sourceFilePath.'sysadmin_client'.$clientId.'.conf';
$crtFilePath = $sourceFilePath.'sysadmin_client'.$clientId.'.crt';
$keyFilePath = $sourceFilePath.'sysadmin_client'.$clientId.'.key';
if (file_exists($saCaFilePath) and file_exists($confFilePath) and file_exists($crtFilePath) and file_exists($keyFilePath)){
//Check if the directory exists.
if(!is_dir($destinationPath)){
//Create directory if not exists
mkdir($destinationPath, 0655, true);
}
//Get contents from conf file
$confFileContent = file_get_contents($confFilePath);
//Removing ca sysadmin_ca.crt for ovpn file
$confFileContent = preg_replace('/ca sysadmin.*crt\n/', '', $confFileContent);
//Removing cert sysadmin_client1.crt for ovpn file
$confFileContent = preg_replace('/cert sysadmin.*crt\n/', '', $confFileContent);
//Removing key sysadmin_client1.key for ovpn file
$confFileContent = preg_replace('/key sysadmin.*key\n/', '', $confFileContent);
// echo $ovpnFileContent; // For debug only
$ovpnFileContent = $confFileContent.$ovpnAddParams;
// echo $ovpnFileContent; // For debug only
//Get contents from sysadmin CA file
$saCaFileContent = file_get_contents($saCaFilePath);
preg_match('#(-----BEGIN CERTIFICATE-----).*(-----END CERTIFICATE-----)#s',$saCaFileContent,$parsedString);
$ovpnFileContent .= "<ca>\n".$parsedString[0]."\n</ca>\n";
//Get contents from client crt file
$crtFileContent = file_get_contents($crtFilePath);
preg_match('#(-----BEGIN CERTIFICATE-----).*(-----END CERTIFICATE-----)#s',$crtFileContent,$parsedString);
// echo $parsedString[0]; // For debug only
$ovpnFileContent .= "<cert>\n".$parsedString[0]."\n</cert>\n";
//Get contents from client key file
$keyFileContent = file_get_contents($keyFilePath);
preg_match('#(-----BEGIN PRIVATE KEY-----).*(-----END PRIVATE KEY-----)#s',$keyFileContent,$parsedString);
// echo $parsedString[0]; // For debug only
$ovpnFileContent .= "<key>\n".$parsedString[0]."\n</key>\n";
// echo $ovpnFileContent; // For debug only
//Write file contents
$destOvpnFile = $destinationPath.$clientFileName;
$openVpnFile = fopen($destOvpnFile, 'w+');
fputs($openVpnFile, $ovpnFileContent."\r\n");
fclose($openVpnFile);
}
}
function insertExtConfigHash($configFile, $stringReplace, $fileMd5)
{
if (file_exists($configFile))
{
$configFileContent = file_get_contents($configFile);
// echo $fileMd5;
$configFileContentNew = str_replace($stringReplace, $fileMd5, $configFileContent);
// echo "FILE \n\n".$configFileContentNew."\n\n";
//Write file contents
$openConfigFile = fopen($configFile, 'w+');
fputs($openConfigFile, $configFileContentNew);
fclose($openConfigFile);
}
else
{
echo " - Warning, file ".$configFile." does not exist, could not rewrite .cfg file"."\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment