api.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. require_once ($_SERVER['DOCUMENT_ROOT']."/inc/auth.utils.php");
  3. login($db_link);
  4. // Получаем параметры через безопасные функции
  5. $action_get = getParam('get', null, null);
  6. $action_send = getParam('send', null, null);
  7. $ip = getParam('ip', null, null, FILTER_VALIDATE_IP, ['flags' => FILTER_FLAG_IPV4]);
  8. $mac_raw = getParam('mac', null, null);
  9. $rec_id = getParam('id', null, null, FILTER_VALIDATE_INT);
  10. $f_subnet = getParam('subnet', null, null);
  11. // Преобразуем IP в BIGINT
  12. $ip_aton = null;
  13. if (!empty($ip)) {
  14. $ip_aton = sprintf('%u', ip2long($ip));
  15. }
  16. // Новые параметры для универсальных методов
  17. $table = getParam('table', null, null);
  18. $filter = getParam('filter', null, null); // JSON-строка для кастомного фильтра
  19. $update_data = null;
  20. $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
  21. if (stripos($content_type, 'application/json') !== false) {
  22. $raw_input = file_get_contents('php://input');
  23. if ($raw_input) {
  24. $json_data = json_decode($raw_input, true);
  25. if (json_last_error() === JSON_ERROR_NONE) {
  26. $update_data = $raw_input; // Передаём как строку для дальнейшей обработки
  27. }
  28. }
  29. }
  30. // Если не получили из тела запроса, пытаемся получить из параметров
  31. if ($update_data === null) {
  32. $update_data = getParam('data', null, null);
  33. }
  34. // Параметры пагинации
  35. $limit_param = getParam('limit', null, null, FILTER_VALIDATE_INT);
  36. $offset_param = getParam('offset', null, null, FILTER_VALIDATE_INT);
  37. $limit = ($limit_param !== null && $limit_param > 0) ? min((int)$limit_param, 1000) : 1000;
  38. $offset = ($offset_param !== null && $offset_param >= 0) ? (int)$offset_param : 0;
  39. // Обработка MAC-адреса
  40. $mac = '';
  41. if (!empty($mac_raw) && checkValidMac($mac_raw)) {
  42. $mac = mac_dotted(trim($mac_raw));
  43. }
  44. // Определяем действие
  45. $action = '';
  46. if (!empty($action_get)) { $action = 'get_' . $action_get; }
  47. if (!empty($action_send)) { $action = 'send_' . $action_send; }
  48. // Дополнительные параметры для send_dhcp
  49. $dhcp_hostname = getParam('hostname', null, '');
  50. $dhcp_action = getParam('action', null, 1, FILTER_VALIDATE_INT);
  51. // === Список разрешённых таблиц ===
  52. $allowed_tables = [
  53. 'building',
  54. 'devices',
  55. 'device_models',
  56. 'device_ports',
  57. 'connections',
  58. 'ou',
  59. 'queue_list',
  60. 'group_list',
  61. 'subnets',
  62. 'config',
  63. 'user_auth',
  64. 'user_list',
  65. 'vendors'
  66. ];
  67. function do_exit() {
  68. exit;
  69. }
  70. // === Валидация таблицы ===
  71. function validate_table($table_name, $allowed) {
  72. return in_array($table_name, $allowed) ? $table_name : null;
  73. }
  74. // === Безопасное получение данных из таблицы ===
  75. function safe_get_records($db, $table, $filter = null, $limit = 1000, $offset = 0) {
  76. global $allowed_tables;
  77. if (!validate_table($table, $allowed_tables)) {
  78. return ['error' => 'Invalid table name'];
  79. }
  80. $sql = "SELECT * FROM " . $table;
  81. $params = [];
  82. if ($filter) {
  83. // Фильтр в формате: {"field":"value","field2":"value2"}
  84. $filter_arr = json_decode($filter, true);
  85. if (is_array($filter_arr) && !empty($filter_arr)) {
  86. $conditions = [];
  87. foreach ($filter_arr as $field => $value) {
  88. // Защита от SQL-инъекции: проверяем имя поля
  89. if (!preg_match('/^[a-z_][a-z0-9_]*$/i', $field)) {
  90. continue;
  91. }
  92. $conditions[] = "$field = ?";
  93. $params[] = $value;
  94. }
  95. if (!empty($conditions)) {
  96. $sql .= " WHERE " . implode(" AND ", $conditions);
  97. }
  98. }
  99. }
  100. $sql .= " LIMIT " . (int)$limit;
  101. if ($offset > 0) {
  102. $sql .= " OFFSET " . (int)$offset;
  103. }
  104. $result = get_records_sql($db, $sql, $params);
  105. return $result;
  106. }
  107. // === Безопасное получение одной записи ===
  108. function safe_get_record($db, $table, $id) {
  109. global $allowed_tables;
  110. if (!validate_table($table, $allowed_tables)) {
  111. return ['error' => 'Invalid table name'];
  112. }
  113. if (!is_numeric($id) || $id <= 0) {
  114. return ['error' => 'Invalid ID'];
  115. }
  116. $pk_field = 'id'; // Все таблицы используют 'id' как первичный ключ
  117. $result = get_record_sql($db, "SELECT * FROM $table WHERE $pk_field = ?", [(int)$id]);
  118. # error_log("SELECT * FROM $table WHERE $pk_field = $id ::". $result);
  119. return $result;
  120. }
  121. if (!empty($action)) {
  122. // === УНИВЕРСАЛЬНЫЙ МЕТОД: get_table_record ===
  123. if ($action === 'get_table_record' && !empty($table)) {
  124. if ($rec_id>0) {
  125. $result = safe_get_record($db_link, $table, $rec_id);
  126. } elseif (!empty($filter)) {
  127. $result_arr = safe_get_records($db_link, $table, $filter, 1);
  128. if (!empty($result_arr)) { $result = $result_arr[0]; }
  129. } else {
  130. do_exit();
  131. }
  132. if (isset($result['error'])) {
  133. http_response_code(400);
  134. echo json_encode($result);
  135. do_exit();
  136. }
  137. if ($result) {
  138. header('Content-Type: application/json; charset=utf-8');
  139. echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  140. } else {
  141. http_response_code(404);
  142. echo json_encode(['error' => 'Record not found']);
  143. }
  144. do_exit();
  145. }
  146. // === УНИВЕРСАЛЬНЫЙ МЕТОД: get_table_list ===
  147. if ($action === 'get_table_list' && !empty($table)) {
  148. $result = safe_get_records($db_link, $table, $filter, $limit, $offset);
  149. if (isset($result['error'])) {
  150. http_response_code(400);
  151. echo json_encode($result);
  152. do_exit();
  153. }
  154. header('Content-Type: application/json; charset=utf-8');
  155. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  156. do_exit();
  157. }
  158. // === ОБНОВЛЕНИЕ USER_LIST ===
  159. if ($action === 'send_update_user' && $rec_id > 0 && !empty($update_data)) {
  160. $data = json_decode($update_data, true);
  161. if (!is_array($data)) {
  162. http_response_code(400);
  163. echo json_encode(['error' => 'Invalid data format']);
  164. do_exit();
  165. }
  166. // Разрешённые поля для обновления
  167. $allowed_fields = [
  168. 'login', 'description', 'enabled', 'blocked', 'ou_id',
  169. 'filter_group_id', 'queue_id', 'day_quota', 'month_quota', 'permanent'
  170. ];
  171. $update_fields = [];
  172. foreach ($data as $key => $value) {
  173. if (in_array($key, $allowed_fields)) {
  174. $update_fields[$key] = $value;
  175. }
  176. }
  177. if (empty($update_fields)) {
  178. http_response_code(400);
  179. echo json_encode(['error' => 'No valid fields to update']);
  180. do_exit();
  181. }
  182. // Проверяем существование пользователя
  183. $existing = get_record_sql($db_link, "SELECT id FROM user_list WHERE id = ?", [$rec_id]);
  184. if (!$existing) {
  185. http_response_code(404);
  186. echo json_encode(['error' => 'User not found']);
  187. do_exit();
  188. }
  189. // Выполняем обновление
  190. if (update_record($db_link, 'user_list', 'id = ?', $update_fields, [$rec_id])) {
  191. LOG_VERBOSE($db_link, "API: User $rec_id updated successfully");
  192. http_response_code(200);
  193. echo json_encode(['status' => 'updated', 'id' => $rec_id]);
  194. } else {
  195. LOG_ERROR($db_link, "API: Failed to update user $rec_id");
  196. http_response_code(500);
  197. echo json_encode(['error' => 'Update failed']);
  198. }
  199. do_exit();
  200. }
  201. // === ОБНОВЛЕНИЕ USER_AUTH ===
  202. if ($action === 'send_update_user_auth' && $rec_id > 0 && !empty($update_data)) {
  203. $data = json_decode($update_data, true);
  204. if (!is_array($data)) {
  205. http_response_code(400);
  206. echo json_encode(['error' => 'Invalid data format']);
  207. do_exit();
  208. }
  209. // Разрешённые поля для обновления
  210. $allowed_fields = ['mac', 'ip', 'ip_int', 'wikiname', 'description', 'dns_name'];
  211. $update_fields = [];
  212. foreach ($data as $key => $value) {
  213. $db_key = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $key)); // WikiName -> wiki_name
  214. if (in_array($db_key, $allowed_fields)) {
  215. $update_fields[$db_key] = $value;
  216. }
  217. }
  218. if (empty($update_fields)) {
  219. http_response_code(400);
  220. echo json_encode(['error' => 'No valid fields to update']);
  221. do_exit();
  222. }
  223. if (update_record($db_link, 'user_auth', 'id = ?', $update_fields, [$rec_id])) {
  224. LOG_VERBOSE($db_link, "API: User_auth $rec_id updated via API", $rec_id);
  225. http_response_code(200);
  226. echo json_encode(['status' => 'updated', 'id' => $rec_id]);
  227. } else {
  228. LOG_ERROR($db_link, "API: Failed to update user_auth $rec_id", $rec_id);
  229. http_response_code(500);
  230. echo json_encode(['error' => 'Update failed']);
  231. }
  232. do_exit();
  233. }
  234. // === get_user_auth ===
  235. if ($action === 'get_user_auth') {
  236. LOG_VERBOSE($db_link, "API: Get User Auth record with ip: $ip mac: $mac id: $rec_id");
  237. $result = null;
  238. $sql = "";
  239. $params = [];
  240. if ($rec_id > 0) {
  241. $sql = "SELECT * FROM user_auth WHERE id = ?";
  242. $params = [$rec_id];
  243. } elseif ($ip_aton !== null && !empty($mac)) {
  244. $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND mac = ? AND deleted = 0";
  245. $params = [$ip_aton, $mac];
  246. } elseif ($ip_aton !== null) {
  247. $sql = "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0";
  248. $params = [$ip_aton];
  249. } elseif (!empty($mac)) {
  250. $sql = "SELECT * FROM user_auth WHERE mac = ? AND deleted = 0";
  251. $params = [$mac];
  252. }
  253. if ($sql) {
  254. $result = get_record_sql($db_link, $sql, $params);
  255. if ($result) {
  256. LOG_VERBOSE($db_link, "API: Record found.");
  257. header('Content-Type: application/json; charset=utf-8');
  258. echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  259. } else {
  260. LOG_VERBOSE($db_link, "API: Record not found.");
  261. http_response_code(404);
  262. echo json_encode(['error' => 'Not found']);
  263. }
  264. } else {
  265. LOG_DEBUG($db_link, "API: not enough parameters | GET: " . json_encode($_GET, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . " | POST: " . json_encode($_POST, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  266. http_response_code(400);
  267. echo json_encode(['error' => 'Missing parameters']);
  268. }
  269. do_exit();
  270. }
  271. // === get_user ===
  272. if ($action === 'get_user') {
  273. LOG_VERBOSE($db_link, "API: Get User record with id: $rec_id");
  274. if ($rec_id > 0) {
  275. $user = get_record_sql($db_link, "SELECT * FROM user_list WHERE deleted = 0 AND id = ?", [$rec_id]);
  276. if ($user) {
  277. $auth_records = get_records_sql($db_link,
  278. "SELECT * FROM user_auth WHERE deleted = 0 AND user_id = ? ORDER BY id LIMIT 100",
  279. [$rec_id]
  280. );
  281. $user['auth'] = $auth_records ?: [];
  282. LOG_VERBOSE($db_link, "API: User record found.");
  283. header('Content-Type: application/json; charset=utf-8');
  284. echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  285. } else {
  286. LOG_VERBOSE($db_link, "API: User not found.");
  287. http_response_code(404);
  288. echo json_encode(['error' => 'User not found']);
  289. }
  290. } else {
  291. LOG_VERBOSE($db_link, "API: not enough parameters");
  292. http_response_code(400);
  293. echo json_encode(['error' => 'Missing user ID']);
  294. }
  295. do_exit();
  296. }
  297. // === get_dhcp_all ===
  298. if ($action === 'get_dhcp_all') {
  299. LOG_VERBOSE($db_link, "API: Get all dhcp records");
  300. $result = get_records_sql($db_link, "
  301. SELECT
  302. ua.id, ua.ip, ua.ip_int, ua.mac, ua.description,
  303. ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
  304. SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base
  305. FROM user_auth ua
  306. JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
  307. WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1
  308. ORDER BY ua.ip_int
  309. LIMIT ? OFFSET ?
  310. ", [$limit, $offset]);
  311. LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
  312. header('Content-Type: application/json; charset=utf-8');
  313. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  314. do_exit();
  315. }
  316. // === get_dhcp_subnet ===
  317. if ($action === 'get_dhcp_subnet' && !empty($f_subnet)) {
  318. // Валидация подсети как IPv4-адреса
  319. if (!filter_var($f_subnet, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  320. http_response_code(400);
  321. echo json_encode(['error' => 'Invalid subnet format']);
  322. do_exit();
  323. }
  324. LOG_VERBOSE($db_link, "API: Get dhcp records for subnet " . $f_subnet);
  325. $result = get_records_sql($db_link, "
  326. SELECT
  327. ua.id, ua.ip, ua.ip_int, ua.mac, ua.description,
  328. ua.dns_name, ua.dhcp_option_set, ua.dhcp_acl, ua.ou_id,
  329. SUBSTRING_INDEX(s.subnet, '/', 1) AS subnet_base
  330. FROM user_auth ua
  331. JOIN subnets s ON ua.ip_int BETWEEN s.ip_int_start AND s.ip_int_stop
  332. WHERE ua.dhcp = 1 AND ua.deleted = 0 AND s.dhcp = 1
  333. AND SUBSTRING_INDEX(s.subnet, '/', 1) = ?
  334. ORDER BY ua.ip_int
  335. LIMIT ? OFFSET ?
  336. ", [$f_subnet, $limit, $offset]);
  337. LOG_VERBOSE($db_link, "API: " . count($result) . " records found.");
  338. header('Content-Type: application/json; charset=utf-8');
  339. echo json_encode($result ?: [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  340. do_exit();
  341. }
  342. // === send_dhcp ===
  343. if ($action === 'send_dhcp') {
  344. if ($ip && $mac) {
  345. $faction = $dhcp_action !== null ? (int)$dhcp_action : 1;
  346. $action_str = ($faction === 0) ? 'del' : 'add';
  347. LOG_VERBOSE($db_link, "API: external dhcp request for $ip [$mac] $action_str");
  348. if (is_our_network($db_link, $ip)) {
  349. $dhcp_record = [
  350. 'action' => $action_str,
  351. 'mac' => $mac,
  352. 'ip' => $ip,
  353. 'dhcp_hostname' => $dhcp_hostname
  354. ];
  355. $insert_id = insert_record($db_link, "dhcp_queue", $dhcp_record);
  356. if ($insert_id !== false && $insert_id > 0) {
  357. LOG_VERBOSE($db_link, "API: DHCP record queued successfully. ID: $insert_id, IP: $ip, MAC: $mac, Action: $action_str");
  358. http_response_code(201);
  359. echo json_encode([
  360. 'status' => 'queued',
  361. 'id' => (int)$insert_id,
  362. 'ip' => $ip,
  363. 'mac' => $mac,
  364. 'action' => $action_str
  365. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  366. } else {
  367. $error_msg = "Failed to insert DHCP record into queue";
  368. LOG_ERROR($db_link, "API: $error_msg. IP: $ip, MAC: $mac, Action: $action_str");
  369. http_response_code(500);
  370. echo json_encode([
  371. 'error' => $error_msg,
  372. 'ip' => $ip,
  373. 'mac' => $mac
  374. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  375. }
  376. } else {
  377. $error_msg = "IP not in allowed network";
  378. LOG_ERROR($db_link, "API: $error_msg - $ip [$mac]");
  379. http_response_code(400);
  380. echo json_encode([
  381. 'error' => $error_msg,
  382. 'ip' => $ip
  383. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  384. }
  385. } else {
  386. $missing_params = [];
  387. if (!$ip) $missing_params[] = 'ip';
  388. if (!$mac) $missing_params[] = 'mac';
  389. $error_msg = 'Missing required parameters: ' . implode(', ', $missing_params);
  390. LOG_WARNING($db_link, "API: send_dhcp called with missing parameters. Missing: " . implode(', ', $missing_params));
  391. http_response_code(400);
  392. echo json_encode([
  393. 'error' => $error_msg
  394. ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
  395. }
  396. do_exit();
  397. }
  398. } else {
  399. LOG_WARNING($db_link, "API: Unknown request");
  400. http_response_code(400);
  401. echo json_encode(['error' => 'Unknown action']);
  402. }
  403. do_exit();
  404. ?>