index.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. //error_reporting(E_ALL);
  3. //ini_set('display_errors', 1);
  4. define("CONFIG", 1);
  5. // Подключаем конфигурационный файл
  6. $config_file = __DIR__ . '/../admin/config.php';
  7. if (!file_exists($config_file)) {
  8. die("Configuration file not found: $config_file");
  9. }
  10. $servers = require $config_file;
  11. // Проверяем авторизацию Apache
  12. $is_authenticated = false;
  13. $username = '';
  14. // Получаем username из Apache auth или из GET/POST
  15. if (isset($_SERVER['PHP_AUTH_USER'])) {
  16. // Авторизация через Apache Basic Auth
  17. $is_authenticated = true;
  18. $username = $_SERVER['PHP_AUTH_USER'];
  19. } elseif (isset($_SERVER['REMOTE_USER'])) {
  20. // Альтернативный способ получения username
  21. $is_authenticated = true;
  22. $username = $_SERVER['REMOTE_USER'];
  23. } else {
  24. showApacheAuthRequired();
  25. }
  26. $server_name = $_GET['server'] ?? $_POST['server'] ?? 'server1';
  27. // Если авторизованы через Apache - генерируем конфиг
  28. if ($is_authenticated && !empty($username)) {
  29. $server_name = $_GET['server'] ?? $_POST['server'] ?? 'server1';
  30. generateConfig($username, $server_name, $servers);
  31. exit;
  32. }
  33. // Если не авторизованы
  34. showApacheAuthRequired();
  35. function generateConfig($username, $server_name, $servers) {
  36. if (empty($username) || !isset($servers[$server_name])) {
  37. die('Invalid parameters');
  38. }
  39. $server = $servers[$server_name];
  40. $script_path = SHOW_CERT_SCRIPT;
  41. $pki_dir = dirname($server['cert_index']);
  42. $template_path = '../admin/'.$server['cfg_template'] ?? '';
  43. $output = [];
  44. if (!empty($pki_dir)) {
  45. // Безопасное выполнение скрипта
  46. $command = sprintf(
  47. 'sudo %s %s %s 2>&1',
  48. escapeshellcmd($script_path),
  49. escapeshellarg($username),
  50. escapeshellarg($pki_dir)
  51. );
  52. exec($command, $output, $return_var);
  53. if ($return_var !== 0) {
  54. die('Failed to generate config: ' . implode("\n", $output));
  55. }
  56. }
  57. // Формируем контент
  58. $template_content = file_exists($template_path) && is_readable($template_path)
  59. ? file_get_contents($template_path)
  60. : die ('Error: Neither template: '.$template_path);
  61. // Получаем вывод скрипта
  62. $script_output = !empty($output) ? implode("\n", $output) : null;
  63. // Формируем итоговый контент по приоритетам
  64. if ($template_content !== null && $script_output !== null) {
  65. // Оба источника доступны - объединяем
  66. $config_content = $template_content . "\n" . $script_output;
  67. } elseif ($template_content !== null) {
  68. // Только шаблон доступен
  69. $config_content = $template_content;
  70. } elseif ($script_output !== null) {
  71. // Только вывод скрипта доступен
  72. $config_content = $script_output;
  73. } else {
  74. // Ничего не доступно - ошибка
  75. die('Error: Neither template nor script output available');
  76. }
  77. // Прямая отдача контента
  78. header('Content-Type: application/octet-stream');
  79. header('Content-Disposition: attachment; filename="' . $server['name'].'-'.$username . '.ovpn"');
  80. header('Content-Length: ' . strlen($config_content));
  81. echo $config_content;
  82. exit;
  83. }
  84. function showApacheAuthRequired() {
  85. header('WWW-Authenticate: Basic realm="OpenVPN Config Download"');
  86. header('HTTP/1.0 401 Unauthorized');
  87. echo '<!DOCTYPE html>
  88. <html lang="en">
  89. <head>
  90. <meta charset="UTF-8">
  91. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  92. <title>Authentication Required</title>
  93. <style>
  94. body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
  95. .info { background: #f8f9fa; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; }
  96. </style>
  97. </head>
  98. <body>
  99. <h2>Authentication Required</h2>
  100. <div class="info">
  101. <p>This site uses Apache Basic Authentication. Please enter your credentials in the browser authentication dialog.</p>
  102. <p>If you don\'t see the login prompt, try refreshing the page or check your browser settings.</p>
  103. </div>
  104. </body>
  105. </html>';
  106. exit;
  107. }