api.php 13 KB

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