api.php 15 KB

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