api.php 13 KB

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