index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. define("CONFIG", 1);
  3. // Настройки
  4. $page_title = 'OpenVPN Status';
  5. // Подключаем конфигурационный файл
  6. $config_file = __DIR__ . '/config.php';
  7. if (!file_exists($config_file)) {
  8. die("Configuration file not found: $config_file");
  9. }
  10. $servers = require $config_file;
  11. session_start();
  12. $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
  13. // Проверяем и инициализируем массив, если его нет
  14. if (!isset($_SESSION['last_request_time']) || !is_array($_SESSION['last_request_time'])) {
  15. $_SESSION['last_request_time'] = []; // Создаем пустой массив
  16. }
  17. if (isset($_GET['action']) && $_GET['action'] === 'generate_config') {
  18. session_start();
  19. // Проверка CSRF
  20. // if (empty($_GET['csrf']) || $_GET['csrf'] !== $_SESSION['csrf_token']) {
  21. // header('HTTP/1.0 403 Forbidden');
  22. // die('Invalid CSRF token');
  23. // }
  24. $server_name = $_GET['server'] ?? '';
  25. $username = $_GET['username'] ?? '';
  26. if (empty($username) || !isset($servers[$server_name])) {
  27. die('Invalid parameters');
  28. }
  29. $server = $servers[$server_name];
  30. $script_path = SHOW_CERT_SCRIPT;
  31. $pki_dir = dirname($server['cert_index']);
  32. $template_path = $server['cfg_template'] ?? '';
  33. $output =[];
  34. if (!empty($pki_dir)) {
  35. // Безопасное выполнение скрипта
  36. $command = sprintf(
  37. 'sudo %s %s %s 2>&1',
  38. escapeshellcmd($script_path),
  39. escapeshellarg($username),
  40. escapeshellarg($pki_dir)
  41. );
  42. exec($command, $output, $return_var);
  43. if ($return_var !== 0) {
  44. die('Failed to generate config: ' . implode("\n", $output));
  45. }
  46. }
  47. // Формируем контент
  48. $template_content = file_exists($template_path) && is_readable($template_path)
  49. ? file_get_contents($template_path)
  50. : null;
  51. // Получаем вывод скрипта
  52. $script_output = !empty($output) ? implode("\n", $output) : null;
  53. // Формируем итоговый контент по приоритетам
  54. if ($template_content !== null && $script_output !== null) {
  55. // Оба источника доступны - объединяем
  56. $config_content = $template_content . "\n" . $script_output;
  57. } elseif ($template_content !== null) {
  58. // Только шаблон доступен
  59. $config_content = $template_content;
  60. } elseif ($script_output !== null) {
  61. // Только вывод скрипта доступен
  62. $config_content = $script_output;
  63. } else {
  64. // Ничего не доступно - ошибка
  65. die('Error: Neither template nor script output available');
  66. }
  67. // Прямая отдача контента
  68. header('Content-Type: application/octet-stream');
  69. header('Content-Disposition: attachment; filename="' . $server['name'].'-'.$username . '.ovpn"');
  70. header('Content-Length: ' . strlen($config_content));
  71. echo $config_content;
  72. $clean_url = strtok($_SERVER['REQUEST_URI'], '?');
  73. header("Refresh:0; url=" . $clean_url);
  74. exit;
  75. }
  76. ?>
  77. <!DOCTYPE html>
  78. <html>
  79. <head>
  80. <title><?= htmlspecialchars($page_title) ?></title>
  81. <meta name="csrf_token" content="<?= $_SESSION['csrf_token'] ?>">
  82. <style>
  83. body { font-family: Arial, sans-serif; margin: 20px; }
  84. table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
  85. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  86. th { background-color: #f2f2f2; }
  87. .banned { background-color: #ffeeee; }
  88. .actions { white-space: nowrap; }
  89. .btn { padding: 3px 8px; margin: 2px; cursor: pointer; border: 1px solid #ccc; border-radius: 3px; }
  90. .kick-btn { background-color: #ffcccc; }
  91. .ban-btn { background-color: #ff9999; }
  92. .unban-btn { background-color: #ccffcc; }
  93. .section { margin-bottom: 30px; }
  94. .status-badge { padding: 2px 5px; border-radius: 3px; font-size: 0.8em; }
  95. .status-active { background-color: #ccffcc; }
  96. .status-banned { background-color: #ff9999; }
  97. .server-section { border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; border-radius: 5px; }
  98. .spoiler { margin-top: 10px; }
  99. .spoiler-title {
  100. cursor: pointer;
  101. color: #0066cc;
  102. padding: 5px;
  103. background-color: #f0f0f0;
  104. border: 1px solid #ddd;
  105. border-radius: 3px;
  106. display: inline-block;
  107. margin-bottom: 5px;
  108. }
  109. .spoiler-title:after { content: " ▼"; }
  110. .spoiler-title.collapsed:after { content: " ►"; }
  111. .spoiler-content {
  112. display: none;
  113. padding: 10px;
  114. border: 1px solid #ddd;
  115. margin-top: 5px;
  116. background-color: #f9f9f9;
  117. border-radius: 3px;
  118. }
  119. .loading { color: #666; font-style: italic; }
  120. .last-update { font-size: 0.8em; color: #666; margin-top: 5px; }
  121. .spinner {
  122. position: fixed;
  123. top: 50%;
  124. left: 50%;
  125. transform: translate(-50%, -50%);
  126. width: 40px;
  127. height: 40px;
  128. border: 4px solid rgba(0, 0, 0, 0.1);
  129. border-radius: 50%;
  130. border-left-color: #09f;
  131. animation: spin 1s linear infinite;
  132. z-index: 1000;
  133. }
  134. @keyframes spin {
  135. 0% { transform: translate(-50%, -50%) rotate(0deg); }
  136. 100% { transform: translate(-50%, -50%) rotate(360deg); }
  137. }
  138. </style>
  139. </head>
  140. <body>
  141. <h1><?= htmlspecialchars($page_title) ?></h1>
  142. <div id="server-container">
  143. <?php foreach ($servers as $server_name => $server): ?>
  144. <div class="server-section" id="server-<?= htmlspecialchars($server_name) ?>">
  145. <h2><?= htmlspecialchars($server['title']) ?></h2>
  146. <div class="loading">Loading data...</div>
  147. </div>
  148. <?php endforeach; ?>
  149. </div>
  150. <script>
  151. // Функция для загрузки данных сервера
  152. function loadServerData(serverName) {
  153. const serverElement = document.getElementById(`server-${serverName}`);
  154. fetch(`get_server_data.php?server=${serverName}&csrf=<?= $_SESSION['csrf_token'] ?>`,{
  155. headers: {
  156. 'X-Requested-With': 'XMLHttpRequest'
  157. }
  158. })
  159. .then(response => response.text())
  160. .then(html => {
  161. serverElement.innerHTML = html;
  162. // Обновляем данные каждые 60 секунд
  163. setTimeout(() => loadServerData(serverName), 60000);
  164. })
  165. .catch(error => {
  166. serverElement.querySelector('.loading').textContent = 'Error loading data';
  167. console.error('Error:', error);
  168. // Повторяем попытку через 10 секунд при ошибке
  169. setTimeout(() => loadServerData(serverName), 10000);
  170. });
  171. }
  172. // Загружаем данные для всех серверов
  173. document.addEventListener('DOMContentLoaded', function() {
  174. <?php foreach ($servers as $server_name => $server): ?>
  175. loadServerData('<?= $server_name ?>');
  176. <?php endforeach; ?>
  177. });
  178. // Функция для обработки действий (ban/unban)
  179. function handleAction(serverName, action, clientName) {
  180. const params = new URLSearchParams();
  181. params.append('server', serverName);
  182. params.append('action', action);
  183. params.append('client', clientName);
  184. fetch('handle_action.php', {
  185. method: 'POST',
  186. headers: {
  187. 'Content-Type': 'application/x-www-form-urlencoded',
  188. 'X-Requested-With': 'XMLHttpRequest'
  189. },
  190. body: params
  191. })
  192. .then(response => {
  193. // 2. Проверяем статус ответа
  194. if (!response.ok) {
  195. throw new Error(`Server returned ${response.status} status`);
  196. }
  197. return response.json();
  198. })
  199. .then(data => {
  200. // 3. Проверяем структуру ответа
  201. if (!data || typeof data.success === 'undefined') {
  202. throw new Error('Invalid server response');
  203. }
  204. if (data.success) {
  205. loadServerData(serverName);
  206. } else {
  207. console.error('Server error:', data.message);
  208. alert(`Error: ${data.message || 'Operation failed'}`);
  209. }
  210. })
  211. .catch(error => {
  212. // 4. Правильное отображение ошибки
  213. console.error('Request failed:', error);
  214. alert(`Request failed: ${error.message}`);
  215. });
  216. }
  217. // Функция для переключения спойлера
  218. function toggleSpoiler(button) {
  219. const content = button.nextElementSibling;
  220. if (content.style.display === "block") {
  221. content.style.display = "none";
  222. button.classList.add('collapsed');
  223. } else {
  224. content.style.display = "block";
  225. button.classList.remove('collapsed');
  226. }
  227. }
  228. function generateConfig(server, username, event) {
  229. event.preventDefault();
  230. if (!confirm('Сгенерировать конфигурацию для ' + username + '?')) {
  231. return false;
  232. }
  233. // Индикатор загрузки
  234. const spinner = document.createElement('div');
  235. spinner.className = 'spinner';
  236. document.body.appendChild(spinner);
  237. const csrf = document.querySelector('meta[name="csrf_token"]').content;
  238. const params = new URLSearchParams({
  239. server: server,
  240. action: 'generate_config',
  241. username: username,
  242. csrf: csrf
  243. });
  244. // Вариант 1: Простое открытие (рекомендуется)
  245. window.open(`?${params.toString()}`, '_blank');
  246. document.body.removeChild(spinner);
  247. /*
  248. // Вариант 2: Через fetch (если нужно строго AJAX)
  249. fetch(`?${params.toString()}`, {
  250. headers: {'X-Requested-With': 'XMLHttpRequest'}
  251. })
  252. .then(response => response.blob())
  253. .then(blob => {
  254. const url = URL.createObjectURL(blob);
  255. const a = document.createElement('a');
  256. a.href = url;
  257. a.download = `${username}.ovpn`;
  258. a.click();
  259. URL.revokeObjectURL(url);
  260. })
  261. .catch(console.error)
  262. .finally(() => document.body.removeChild(spinner));
  263. */
  264. return false;
  265. }
  266. </script>
  267. </body>
  268. </html>