1
0

functions.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. defined('CONFIG') or die('Direct access not allowed');
  3. function canRequestStatus($server) {
  4. if (!isset($_SESSION['last_request_time'][$server['name']])) { return true; }
  5. if (time() - $_SESSION['last_request_time'][$server['name']] >= REQUEST_INTERVAL) { return true; }
  6. return false;
  7. }
  8. function updateLastRequestTime($server) {
  9. $_SESSION['last_request_time'][$server['name']] = time();
  10. }
  11. function openvpnManagementCommand($server, $command) {
  12. $mgmt_host = $server['host'];
  13. $mgmt_port = $server['port'];
  14. $mgmt_pass = $server['password'];
  15. $timeout = 5;
  16. $socket = @fsockopen($mgmt_host, $mgmt_port, $errno, $errstr, $timeout);
  17. if (!$socket) {
  18. error_log("OpenVPN management connection failed to {$server['name']}: $errstr ($errno)");
  19. return false;
  20. }
  21. stream_set_timeout($socket, $timeout);
  22. try {
  23. // Читаем приветственное сообщение
  24. $welcome = '';
  25. while (!feof($socket)) {
  26. $line = fgets($socket);
  27. if ($line === false) break;
  28. $welcome .= $line;
  29. if (strpos($welcome, 'ENTER PASSWORD:') !== false) break;
  30. }
  31. // Отправляем пароль
  32. if (@fwrite($socket, "$mgmt_pass\n") === false) {
  33. throw new Exception("Failed to send password");
  34. }
  35. // Ждем подтверждения аутентификации
  36. $authResponse = '';
  37. while (!feof($socket)) {
  38. $line = fgets($socket);
  39. if ($line === false) break;
  40. $authResponse .= $line;
  41. if (strpos($authResponse, 'SUCCESS:') !== false || strpos($authResponse, '>INFO:') !== false) break;
  42. }
  43. // Отправляем команду
  44. if (@fwrite($socket, "$command\n") === false) {
  45. throw new Exception("Failed to send command");
  46. }
  47. // Читаем ответ
  48. $response = '';
  49. $expectedEnd = strpos($command, 'status') !== false ? "END\r\n" : ">";
  50. while (!feof($socket)) {
  51. $line = fgets($socket);
  52. if ($line === false) break;
  53. $response .= $line;
  54. if (strpos($response, $expectedEnd) !== false) break;
  55. }
  56. return $response;
  57. } catch (Exception $e) {
  58. error_log("OpenVPN management error ({$server['name']}): " . $e->getMessage());
  59. return false;
  60. } finally {
  61. @fwrite($socket, "quit\n");
  62. @fclose($socket);
  63. }
  64. }
  65. function getOpenVPNStatus($server) {
  66. // Проверяем, можно ли делать запрос
  67. if (!canRequestStatus($server)) {
  68. // Возвращаем кэшированные данные или пустой массив
  69. return $_SESSION['cached_status'][$server['name']] ?? [];
  70. }
  71. // Обновляем время последнего запроса
  72. updateLastRequestTime($server);
  73. $response = openvpnManagementCommand($server, "status 2");
  74. if (!$response) return $_SESSION['cached_status'][$server['name']] ?? [];
  75. $banned = getBannedClients($server);
  76. $clients = [];
  77. $lines = explode("\n", $response);
  78. $in_client_list = false;
  79. foreach ($lines as $line) {
  80. $line = trim($line);
  81. if (strpos($line, 'HEADER,CLIENT_LIST') === 0) {
  82. $in_client_list = true;
  83. continue;
  84. }
  85. if (strpos($line, 'HEADER,ROUTING_TABLE') === 0) {
  86. $in_client_list = false;
  87. continue;
  88. }
  89. //CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,Peer ID,Data Channel Cipher
  90. if ($in_client_list && strpos($line, 'CLIENT_LIST') === 0) {
  91. $parts = explode(',', $line);
  92. if (count($parts) >= 9) {
  93. $clients[] = [
  94. 'name' => $parts[1],
  95. 'real_ip' => $parts[2],
  96. 'virtual_ip' => $parts[3],
  97. 'bytes_received' => formatBytes($parts[5]),
  98. 'bytes_sent' => formatBytes($parts[6]),
  99. 'connected_since' => $parts[7],
  100. 'username' => $parts[8] ?? $parts[1],
  101. 'cipher' => end($parts),
  102. 'banned' => isset($banned[$parts[1]]),
  103. ];
  104. }
  105. }
  106. }
  107. // Кэшируем результат
  108. $_SESSION['cached_status'][$server['name']] = $clients;
  109. return $clients;
  110. }
  111. function get_servers_crt($cert_index) {
  112. // Проверка входных параметров
  113. if (empty($cert_index) || !is_string($cert_index)) {
  114. return false;
  115. }
  116. // Проверка существования исполняемого файла
  117. if (empty(SHOW_SERVERS_CRT) || !file_exists(SHOW_SERVERS_CRT) || !is_executable(SHOW_SERVERS_CRT)) {
  118. error_log('SHOW_SERVERS_CRT is not configured properly', 0);
  119. return false;
  120. }
  121. $command = sprintf(
  122. 'sudo %s %s 2>&1',
  123. escapeshellcmd(SHOW_SERVERS_CRT),
  124. escapeshellarg($cert_index)
  125. );
  126. exec($command, $cert_content, $return_var);
  127. if ($return_var !== 0) {
  128. error_log(sprintf(
  129. 'Command failed: %s (return code: %d, output: %s)',
  130. $command,
  131. $return_var,
  132. implode("\n", $cert_content)
  133. ), 0);
  134. return false;
  135. }
  136. if (empty($cert_content)) {
  137. error_log('Empty certificate content for file: '.$cert_index, 0);
  138. return false;
  139. }
  140. $result = array_fill_keys($cert_content, true);
  141. return $result;
  142. }
  143. function getBannedClients($server) {
  144. // Проверка входных параметров
  145. if (empty($server["ccd"]) || !is_string($server["ccd"])) {
  146. return [];
  147. }
  148. // Проверка существования исполняемого файла
  149. if (empty(SHOW_BANNED) || !file_exists(SHOW_BANNED) || !is_executable(SHOW_BANNED)) {
  150. error_log('SHOW_BANNED is not configured properly', 0);
  151. return [];
  152. }
  153. $command = sprintf(
  154. 'sudo %s %s 2>&1',
  155. escapeshellcmd(SHOW_BANNED),
  156. escapeshellarg($server["ccd"])
  157. );
  158. exec($command, $banned_content, $return_var);
  159. if ($return_var !== 0) {
  160. error_log(sprintf(
  161. 'Command failed: %s (return code: %d)',
  162. $command,
  163. $return_var,
  164. ), 0);
  165. return [];
  166. }
  167. if (empty($banned_content)) { return []; }
  168. $result = array_fill_keys($banned_content, true);
  169. return $result;
  170. }
  171. function getClientIPsCCD($server) {
  172. // Проверка входных параметров
  173. if (empty($server["ccd"]) || !is_string($server["ccd"])) {
  174. return [];
  175. }
  176. // Проверка существования исполняемого файла
  177. if (empty(GET_IPS_FROM_CCD) || !file_exists(GET_IPS_FROM_CCD) || !is_executable(GET_IPS_FROM_CCD)) {
  178. error_log('SHOW_BANNED is not configured properly', 0);
  179. return [];
  180. }
  181. $command = sprintf(
  182. 'sudo %s %s 2>&1',
  183. escapeshellcmd(GET_IPS_FROM_CCD),
  184. escapeshellarg($server["ccd"])
  185. );
  186. exec($command, $ccd_content, $return_var);
  187. if ($return_var !== 0) {
  188. error_log(sprintf(
  189. 'Command failed: %s (return code: %d)',
  190. $command,
  191. $return_var,
  192. ), 0);
  193. return [];
  194. }
  195. if (empty($ccd_content)) { return []; }
  196. $result=[];
  197. foreach ($ccd_content as $line) {
  198. if (empty($line)) { continue; }
  199. list($login, $ip) = explode(' ', trim($line), 2);
  200. $result[$login] = $ip;
  201. }
  202. return $result;
  203. }
  204. function getClientIPsIPP($server) {
  205. // Проверка входных параметров
  206. if (empty($server["ipp_file"]) || !is_string($server["ipp_file"])) {
  207. return [];
  208. }
  209. // Проверка существования исполняемого файла
  210. if (empty(GET_IPS_FROM_IPP) || !file_exists(GET_IPS_FROM_IPP) || !is_executable(GET_IPS_FROM_IPP)) {
  211. error_log('SHOW_BANNED is not configured properly', 0);
  212. return [];
  213. }
  214. $command = sprintf(
  215. 'sudo %s %s 2>&1',
  216. escapeshellcmd(GET_IPS_FROM_IPP),
  217. escapeshellarg($server["ipp_file"])
  218. );
  219. exec($command, $ipp_content, $return_var);
  220. if ($return_var !== 0) {
  221. error_log(sprintf(
  222. 'Command failed: %s (return code: %d)',
  223. $command,
  224. $return_var,
  225. ), 0);
  226. return [];
  227. }
  228. if (empty($ipp_content)) { return []; }
  229. $result=[];
  230. foreach ($ipp_content as $line) {
  231. if (empty($line)) { continue; }
  232. list($login, $ip) = explode(',', trim($line), 2);
  233. $result[$login] = $ip;
  234. }
  235. return $result;
  236. }
  237. function getAccountList($server) {
  238. $accounts = [];
  239. $banned = getBannedClients($server);
  240. // Получаем список из index.txt (неотозванные сертификаты)
  241. if (!empty($server['cert_index']) && !empty(SHOW_PKI_INDEX) && file_exists(SHOW_PKI_INDEX)) {
  242. $servers_list = get_servers_crt($server['cert_index']);
  243. // Безопасное выполнение скрипта
  244. $command = sprintf(
  245. 'sudo %s %s 2>&1',
  246. escapeshellcmd(SHOW_PKI_INDEX),
  247. escapeshellarg($server['cert_index']),
  248. );
  249. exec($command, $index_content, $return_var);
  250. if ($return_var == 0) {
  251. foreach ($index_content as $line) {
  252. if (empty(trim($line))) { continue; }
  253. if (preg_match('/\/CN=([^\/]+)/', $line, $matches)) {
  254. $username = trim($matches[1]);
  255. }
  256. if (empty($username)) { continue; }
  257. $revoked = false;
  258. if (preg_match('/^R\s+/',$line)) { $revoked = true; }
  259. if (isset($servers_list[$username])) { continue; }
  260. $accounts[$username] = [
  261. "username" => $username,
  262. "ip" => null,
  263. "banned" => isset($banned[$username]) || $revoked,
  264. "revoked" => $revoked
  265. ];
  266. }
  267. }
  268. }
  269. // Получаем список выданных IP из ipp.txt
  270. if (!empty($server['ipp_file']) && file_exists($server['ipp_file'])) {
  271. $ipps = getClientIPsIPP($server);
  272. foreach ($ipps as $username => $ip) {
  273. if (!isset($accounts[$username]) && empty($server['cert_index'])) {
  274. $accounts[$username] = [
  275. "username" => $username,
  276. "banned" => isset($banned[$username]),
  277. "ip" => $ip,
  278. "revoked" => false,
  279. ];
  280. }
  281. if (isset($accounts[$username]) and !empty($server['cert_index'])) {
  282. $accounts[$username]["ip"] = $ip;
  283. }
  284. }
  285. }
  286. // Ищем IP-адреса в CCD файлах
  287. if (!empty($server['ccd']) && is_dir($server['ccd'])) {
  288. $ccds = getClientIPsCCD($server);
  289. foreach ($ccds as $username => $ip) {
  290. if (!isset($accounts[$username]) && empty($server['cert_index'])) {
  291. $accounts[$username] = [
  292. "username" => $username,
  293. "banned" => isset($banned[$username]),
  294. "ip" => $ip,
  295. "revoked" => false,
  296. ];
  297. }
  298. if (isset($accounts[$username]) and !empty($server['cert_index'])) {
  299. $accounts[$username]["ip"] = $ip;
  300. }
  301. }
  302. }
  303. return $accounts;
  304. }
  305. function kickClient($server, $client_name) {
  306. return openvpnManagementCommand($server, "kill $client_name");
  307. }
  308. function removeCCD($server, $client_name) {
  309. if (empty($server["ccd"]) || empty($client_name) || empty(REMOVE_CCD) || !file_exists(REMOVE_CCD)) { return false; }
  310. $script_path = REMOVE_CCD;
  311. $ccd_file = "{$server['ccd']}/$client_name";
  312. $command = sprintf(
  313. 'sudo %s %s 2>&1',
  314. escapeshellcmd($script_path),
  315. escapeshellarg($ccd_file)
  316. );
  317. exec($command, $output, $return_var);
  318. $_SESSION['last_request_time'] = [];
  319. if ($return_var === 0) {
  320. return true;
  321. } else {
  322. return false;
  323. }
  324. }
  325. function unbanClient($server, $client_name) {
  326. if (empty($server["ccd"]) || empty($client_name) || empty(BAN_CLIENT) || !file_exists(BAN_CLIENT)) { return false; }
  327. $script_path = BAN_CLIENT;
  328. $ccd_file = "{$server['ccd']}/$client_name";
  329. $command = sprintf(
  330. 'sudo %s %s unban 2>&1',
  331. escapeshellcmd($script_path),
  332. escapeshellarg($ccd_file)
  333. );
  334. exec($command, $output, $return_var);
  335. $_SESSION['last_request_time'] = [];
  336. if ($return_var === 0) {
  337. return true;
  338. } else {
  339. return false;
  340. }
  341. }
  342. function banClient($server, $client_name) {
  343. if (empty($server["ccd"]) || empty($client_name) || empty(BAN_CLIENT) || !file_exists(BAN_CLIENT)) { return false; }
  344. $script_path = BAN_CLIENT;
  345. $ccd_file = "{$server['ccd']}/$client_name";
  346. $command = sprintf(
  347. 'sudo %s %s ban 2>&1',
  348. escapeshellcmd($script_path),
  349. escapeshellarg($ccd_file)
  350. );
  351. exec($command, $output, $return_var);
  352. $_SESSION['last_request_time'] = [];
  353. if ($return_var === 0) {
  354. // Кикаем клиента
  355. kickClient($server, $client_name);
  356. return true;
  357. } else {
  358. return false;
  359. }
  360. }
  361. function revokeClient($server, $client_name) {
  362. if (empty(REVOKE_CRT) || !file_exists(REVOKE_CRT)) {
  363. return banClient($server, $client_name);
  364. }
  365. $script_path = REVOKE_CRT;
  366. $rsa_dir = dirname(dirname($server['cert_index']));
  367. $command = sprintf(
  368. 'sudo %s %s %s %s 2>&1',
  369. escapeshellcmd($script_path),
  370. escapeshellarg('openvpn-server@'.$server['name']),
  371. escapeshellarg($rsa_dir),
  372. escapeshellarg($client_name)
  373. );
  374. exec($command, $output, $return_var);
  375. if ($return_var === 0) {
  376. return true;
  377. } else {
  378. return false;
  379. }
  380. }
  381. function formatBytes($bytes) {
  382. $bytes = (int)$bytes;
  383. if ($bytes <= 0) return '0 B';
  384. $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  385. $pow = floor(log($bytes)/log(1024));
  386. return round($bytes/pow(1024,$pow),2).' '.$units[$pow];
  387. }
  388. function isClientActive($active_clients,$username) {
  389. $active_names = array_column($active_clients, 'name');
  390. if (in_array($username,$active_names)) { return true; }
  391. return false;
  392. }