From dc03d9ea002557f1c28a20b6849bb52437e25f6f Mon Sep 17 00:00:00 2001 From: billz Date: Sat, 6 Feb 2021 11:03:30 +0000 Subject: [PATCH] Prepend .ovpn filename to client + login --- includes/functions.php | 37 +++++++++++++++++++++++++++++++++++++ includes/openvpn.php | 14 +++++++++++--- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/includes/functions.php b/includes/functions.php index f1dec2c0..923ff007 100755 --- a/includes/functions.php +++ b/includes/functions.php @@ -224,6 +224,43 @@ function safefilerewrite($fileName, $dataToSave) } } +/** + * Prepends data to a file if not exists + * + * @param string $filename + * @param string $dataToSave + * @return boolean + */ +function file_prepend_data($filename, $dataToSave) +{ + $context = stream_context_create(); + $file = fopen($filename, 'r', 1, $context); + $file_data = readfile($file); + + if (!preg_match('/^'.$dataToSave.'/', $file_data)) { + $tmp_file = tempnam(sys_get_temp_dir(), 'php_prepend_'); + file_put_contents($tmp_file, $dataToSave); + file_put_contents($tmp_file, $file, FILE_APPEND); + fclose($file); + unlink($filename); + rename($tmp_file, $filename); + return true; + } else { + return false; + } +} + +/** + * Callback function for array_filter + * + * @param string $var + * @return filtered value + */ +function filter_comments($var) +{ + return $var[0] != '#'; +} + /** * Saves a CSRF token in the session */ diff --git a/includes/openvpn.php b/includes/openvpn.php index 6f9e40b5..d337f04d 100755 --- a/includes/openvpn.php +++ b/includes/openvpn.php @@ -47,8 +47,9 @@ function DisplayOpenVPNConfig() // parse client auth credentials if (!empty($auth)) { - $authUser = $auth[0]; - $authPassword = $auth[1]; + $auth = array_filter($auth, 'filter_comments'); + $authUser = current($auth); + $authPassword = next($auth); } echo renderTemplate( @@ -136,18 +137,25 @@ function SaveOpenVPNConfig($status, $file, $authUser, $authPassword) ) { throw new RuntimeException('Unable to move uploaded file'); } + + // Good file upload, update auth credentials if present + $prepend = '# filename '.pathinfo($file['name'], PATHINFO_FILENAME) .PHP_EOL; if (!empty($authUser) && !empty($authPassword)) { $auth_flag = 1; // Move tmp authdata to /etc/openvpn/login.conf - $auth = $authUser .PHP_EOL . $authPassword .PHP_EOL; + $auth.= $authUser .PHP_EOL . $authPassword .PHP_EOL; file_put_contents($tmp_authdata, $auth); + file_prepend_data($tmp_authdata, $prepend); system("sudo cp $tmp_authdata " . RASPI_OPENVPN_CLIENT_LOGIN, $return); if ($return !=0) { $status->addMessage('Unable to save client auth credentials', 'danger'); } } + // Prepend filname tag to .ovpn client config + file_prepend_data($tmp_ovpnclient, $prepend); + // Set iptables rules and, optionally, auth-user-pass exec("sudo /etc/raspap/openvpn/configauth.sh $tmp_ovpnclient $auth_flag " .$_SESSION['ap_interface'], $return); foreach ($return as $line) {