fetch_new_arp.pl 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use Encode;
  8. no warnings 'utf8';
  9. use English;
  10. use base;
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use strict;
  14. use DBI;
  15. use Time::Local;
  16. use Net::Patricia;
  17. use Data::Dumper;
  18. use Date::Parse;
  19. use Socket;
  20. use eyelib::config;
  21. use eyelib::main;
  22. use eyelib::net_utils;
  23. use eyelib::snmp;
  24. use eyelib::database;
  25. use NetAddr::IP;
  26. use Fcntl qw(:flock);
  27. use Parallel::ForkManager;
  28. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  29. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  30. setpriority(0,0,19);
  31. if ($config_ref{config_mode}) { log_info("System in configuration mode! Skip discovery."); exit; }
  32. db_log_verbose($dbh,'Clearing empty records.');
  33. ##### clean empty user account and corresponded devices for dynamic users and hotspot ################
  34. log_info($dbh,'Clearing empty user account and corresponded devices for dynamic users and hotspot');
  35. my $u_sql = "SELECT * FROM User_list as U WHERE (U.ou_id=".$default_hotspot_ou_id." OR U.ou_id=".$default_user_ou_id.") AND (SELECT COUNT(*) FROM User_auth WHERE User_auth.deleted=0 AND User_auth.user_id = U.id)=0";
  36. my @u_ref = get_records_sql($dbh,$u_sql);
  37. foreach my $row (@u_ref) {
  38. db_log_info($dbh,"Remove empty dynamic user with id: $row->{id} login: $row->{login}");
  39. delete_user($dbh,$row->{id});
  40. }
  41. ##### clean empty user account and corresponded devices ################
  42. if ($config_ref{clean_empty_user}) {
  43. log_info($dbh,'Clearing empty user account and corresponded devices');
  44. my $u_sql = "SELECT * FROM User_list as U WHERE U.permanent=0 AND (SELECT COUNT(*) FROM User_auth WHERE User_auth.deleted=0 AND User_auth.user_id = U.id)=0 AND (SELECT COUNT(*) FROM auth_rules WHERE auth_rules.user_id = U.id)=0;";
  45. my @u_ref = get_records_sql($dbh,$u_sql);
  46. foreach my $row (@u_ref) {
  47. db_log_info($dbh,"Remove empty user with id: $row->{id} login: $row->{login}");
  48. delete_user($dbh,$row->{id});
  49. }
  50. }
  51. #clean temporary user auth records
  52. my $now = DateTime->now(time_zone=>'local');
  53. my $clear_time =$dbh->quote($now->strftime('%Y-%m-%d %H:%M:%S'));
  54. my $users_sql = "SELECT * FROM User_auth WHERE deleted=0 AND dynamic=1 AND `eof`<=".$clear_time;
  55. my @users_auth = get_records_sql($dbh,$users_sql);
  56. if (@users_auth and scalar @users_auth) {
  57. foreach my $row (@users_auth) {
  58. delete_user_auth($dbh,$row->{id});
  59. db_log_info($dbh,"Removed dynamic user auth record for auth_id: $row->{'id'} by eof time: $row->{'eof'}",$row->{'id'});
  60. my $u_count=get_count_records($dbh,'User_auth','deleted=0 and user_id='.$row->{user_id});
  61. if (!$u_count) { delete_user($dbh,$row->{'user_id'}); }
  62. }
  63. }
  64. my %mac_history;
  65. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  66. $month += 1;
  67. $year += 1900;
  68. my $fork_count = $cpu_count*5;
  69. #disable fork for debug
  70. #if ($debug) { $fork_count = 0; }
  71. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  72. my $now_day=sprintf "%04d-%02d-%02d",$year,$month,$day;
  73. db_log_verbose($dbh,'Arp discovery started.');
  74. if ($ARGV[0]) {
  75. db_log_verbose($dbh,'Active check started!');
  76. my $subnets=get_subnets_ref($dbh);
  77. my @fping_cmd=();
  78. foreach my $net (keys %$subnets) {
  79. next if (!$net);
  80. next if (!$subnets->{$net}{discovery});
  81. my $run_cmd="$fping -g $subnets->{$net}{subnet} -B1.0 -c 1 >/dev/null 2>&1";
  82. db_log_debug($dbh,"Checked network $subnets->{$net}{subnet}") if ($debug);
  83. push(@fping_cmd,$run_cmd);
  84. }
  85. $parallel_process_count = $cpu_count*2;
  86. run_in_parallel(@fping_cmd);
  87. }
  88. my @router_ref = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND (device_type=2 or device_type=0) AND discovery=1 AND snmp_version>0 ORDER by ip" );
  89. $dbh->disconnect;
  90. my @arp_array=();
  91. my $pm_arp = Parallel::ForkManager->new($fork_count);
  92. # data structure retrieval and handling
  93. $pm_arp -> run_on_finish (
  94. sub {
  95. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  96. if (defined($data_structure_reference)) {
  97. # children are not forced to send anything
  98. my $result = ${$data_structure_reference};
  99. push(@arp_array,$result);
  100. }
  101. }
  102. );
  103. DATA_LOOP:
  104. foreach my $router (@router_ref) {
  105. my $router_ip=$router->{ip};
  106. setCommunity($router);
  107. if (!HostIsLive($router_ip)) { log_info("Host id: $router->{id} name: $router->{device_name} ip: $router_ip is down! Skip."); next; }
  108. $pm_arp->start() and next DATA_LOOP;
  109. my $arp_table;
  110. my $tmp_dbh=init_db();
  111. if (apply_device_lock($tmp_dbh,$router->{id})) {
  112. $arp_table=get_arp_table($router_ip,$router->{snmp});
  113. unset_lock_discovery($tmp_dbh,$router->{id});
  114. }
  115. $tmp_dbh->disconnect;
  116. $pm_arp->finish(0, \$arp_table);
  117. }
  118. $pm_arp->wait_all_children;
  119. ########################### end fork's #########################
  120. $dbh=init_db();
  121. #get userid list
  122. my @authlist_ref = get_records_sql($dbh,"SELECT * FROM User_auth WHERE deleted=0 ORDER by ip_int" );
  123. my $users = new Net::Patricia;
  124. my %ip_list;
  125. my %oper_arp_list;
  126. foreach my $row (@authlist_ref) {
  127. $users->add_string($row->{ip},$row->{id});
  128. $ip_list{$row->{id}}->{id}=$row->{id};
  129. $ip_list{$row->{id}}->{ip}=$row->{ip};
  130. $ip_list{$row->{id}}->{mac}=mac_splitted($row->{mac}) || '';
  131. }
  132. foreach my $arp_table (@arp_array) {
  133. foreach my $ip (keys %$arp_table) {
  134. next if (!$arp_table->{$ip});
  135. my $mac=trim($arp_table->{$ip});
  136. $mac=mac_splitted($mac);
  137. next if (!$mac);
  138. next if ($mac=~/ff:ff:ff:ff:ff:ff/i);
  139. next if ($mac!~/(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/);
  140. my $simple_mac=mac_simplify($mac);
  141. $ip=trim($ip);
  142. my $ip_aton=StrToIp($ip);
  143. $mac_history{$simple_mac}{changed}=0;
  144. $mac_history{$simple_mac}{ip}=$ip;
  145. $mac_history{$simple_mac}{auth_id}=0;
  146. next if (!$office_networks->match_string($ip));
  147. db_log_debug($dbh,"Analyze ip: $ip mac: $mac") if ($debug);
  148. my $auth_id = $users->match_string($ip);
  149. my $arp_record;
  150. $arp_record->{ip} = $ip;
  151. $arp_record->{mac} = $mac;
  152. $arp_record->{type} = 'arp';
  153. $arp_record->{ip_aton} = $ip_aton;
  154. $arp_record->{hotspot} = is_hotspot($dbh,$ip);
  155. my $cur_auth_id=resurrection_auth($dbh,$arp_record);
  156. if (!$cur_auth_id) {
  157. db_log_warning($dbh,"Unknown record ".Dumper($arp_record));
  158. } else {
  159. $mac_history{$simple_mac}{auth_id}=$cur_auth_id;
  160. $arp_record->{auth_id}=$cur_auth_id;
  161. $arp_record->{updated}=0;
  162. $oper_arp_list{$cur_auth_id}=$arp_record;
  163. if ($auth_id ne $cur_auth_id) { $mac_history{$simple_mac}{changed}=1; }
  164. }
  165. }
  166. }
  167. db_log_verbose($dbh,'Mac discovery started.');
  168. my %connections=();
  169. my @connections_list=get_records_sql($dbh,"SELECT * FROM connections ORDER BY auth_id");
  170. foreach my $connection (@connections_list) {
  171. next if (!$connection);
  172. $connections{$connection->{auth_id}}{port}=$connection->{port_id};
  173. $connections{$connection->{auth_id}}{id}=$connection->{id};
  174. }
  175. my $auth_filter=" AND last_found >='".$now_day."' ";
  176. my $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 $auth_filter ORDER BY id ASC";
  177. my @auth_list=get_records_sql($dbh,$auth_sql);
  178. my %auth_table;
  179. foreach my $auth (@auth_list) {
  180. next if (!$auth);
  181. my $auth_mac=mac_simplify($auth->{mac});
  182. $auth_table{oper_table}{$auth_mac}=$auth->{id};
  183. }
  184. $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 ORDER BY last_found DESC";
  185. my @auth_full_list=get_records_sql($dbh,$auth_sql);
  186. foreach my $auth (@auth_full_list) {
  187. next if (!$auth);
  188. my $auth_mac=mac_simplify($auth->{mac});
  189. next if (exists $auth_table{full_table}{$auth_mac});
  190. $auth_table{full_table}{$auth_mac}=$auth->{id};
  191. }
  192. my @unknown_list=get_records_sql($dbh,"SELECT id,mac,port_id,device_id FROM Unknown_mac WHERE mac !='' ORDER BY mac");
  193. my %unknown_table;
  194. foreach my $unknown (@unknown_list) {
  195. next if (!$unknown);
  196. my $unknown_mac=mac_simplify($unknown->{mac});
  197. $unknown_table{$unknown_mac}{unknown_id}=$unknown->{id};
  198. $unknown_table{$unknown_mac}{port_id}=$unknown->{port_id};
  199. $unknown_table{$unknown_mac}{device_id}=$unknown->{device_id};
  200. }
  201. my @device_list = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND discovery=1 AND device_type<=2 AND snmp_version>0" );
  202. my @fdb_array=();
  203. my $pm_fdb = Parallel::ForkManager->new($fork_count);
  204. # data structure retrieval and handling
  205. $pm_fdb -> run_on_finish (
  206. sub {
  207. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  208. if (defined($data_structure_reference)) { # children are not forced to send anything
  209. my $result = ${$data_structure_reference}; # child passed a string reference
  210. push(@fdb_array,$result);
  211. }
  212. }
  213. );
  214. $dbh->disconnect;
  215. FDB_LOOP:
  216. foreach my $device (@device_list) {
  217. setCommunity($device);
  218. if (!HostIsLive($device->{ip})) { log_info("Host id: $device->{id} name: $device->{device_name} ip: $device->{ip} is down! Skip."); next; }
  219. my $int_list = get_snmp_ifindex($device->{ip},$device->{snmp});
  220. if (!$int_list) { log_info("Host id: $device->{id} name: $device->{device_name} ip: $device->{ip} interfaces not found by snmp request! Skip."); next; }
  221. $pm_fdb->start() and next FDB_LOOP;
  222. my $result;
  223. my $tmp_dbh = init_db();
  224. if (apply_device_lock($tmp_dbh,$device->{id})) {
  225. my $fdb=get_fdb_table($device->{ip},$device->{snmp});
  226. unset_lock_discovery($tmp_dbh,$device->{id});
  227. $result->{id}=$device->{id};
  228. $result->{fdb} = $fdb;
  229. }
  230. $tmp_dbh->disconnect;
  231. $pm_fdb->finish(0, \$result);
  232. }
  233. $pm_fdb->wait_all_children;
  234. my %fdb_ref;
  235. foreach my $fdb_table (@fdb_array){
  236. next if (!$fdb_table);
  237. $fdb_ref{$fdb_table->{id}}{fdb}=$fdb_table->{fdb};
  238. }
  239. ################################ end fork's ##############################
  240. $dbh=init_db();
  241. foreach my $device (@device_list) {
  242. my %port_snmp_index=();
  243. my %port_index=();
  244. my %mac_port_count=();
  245. my %mac_address_table=();
  246. my %port_links=();
  247. my $dev_id = $device->{id};
  248. my $dev_name = $device->{device_name};
  249. my $fdb=$fdb_ref{$dev_id}{fdb};
  250. next if (!$fdb);
  251. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=$dev_id");
  252. foreach my $port_data (@device_ports) {
  253. my $fdb_port_index=$port_data->{port};
  254. my $port_id = $port_data->{id};
  255. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  256. $fdb_port_index=$port_data->{snmp_index};
  257. next if ($port_data->{skip});
  258. #snmp-индекс порта = номеру порта
  259. $port_snmp_index{$port_data->{snmp_index}}=$port_data->{port};
  260. # номер порта = id записи порта в таблице
  261. $port_index{$port_data->{port}}=$port_data->{id};
  262. # номер порта = id записи порта аплинка/даунлинка свича
  263. $port_links{$port_data->{port}}=$port_data->{target_port_id};
  264. $mac_port_count{$port_data->{port}}=0;
  265. }
  266. my $sw_mac;
  267. #for mikrotik - skip DL mac
  268. if ($device->{vendor_id} eq '9') {
  269. #get device mac
  270. my $sw_auth = get_record_sql($dbh,"SELECT mac FROM User_auth WHERE deleted=0 and ip='".$device->{ip}."'");
  271. $sw_mac = mac_simplify($sw_auth->{mac});
  272. $sw_mac =~s/.{2}$//s;
  273. }
  274. foreach my $mac (keys %$fdb) {
  275. #port from fdb table
  276. my $port = $fdb->{$mac};
  277. next if (!$port);
  278. #real port number
  279. if (exists $port_snmp_index{$port}) {
  280. #get real port number by snmp our snmp index
  281. $port=$port_snmp_index{$port};
  282. }
  283. if (!exists $port_index{$port}) { next; }
  284. #mikrotik patch - skip mikrotik device mac
  285. if ($sw_mac and $mac=~/^$sw_mac/i) { next; }
  286. $mac_port_count{$port}++;
  287. #мак = номер порта
  288. $mac_address_table{$mac}=$port;
  289. }
  290. # обновляем число маков на порту
  291. foreach my $port (keys %mac_port_count) {
  292. if (!$port) { next; }
  293. if (!exists $port_index{$port}) { next; }
  294. #skip uplink|downlink
  295. if ($port_links{$port}>0) { next; }
  296. my $dev_ports;
  297. $dev_ports->{last_mac_count}=$mac_port_count{$port};
  298. update_record($dbh,'device_ports',$dev_ports,"device_id=$dev_id and port=$port");
  299. }
  300. foreach my $mac (keys %mac_address_table) {
  301. my $port = $mac_address_table{$mac};
  302. if (!$port) { next; }
  303. if (!exists $port_index{$port}) { next; }
  304. #skip uplink|downlink
  305. if ($port_links{$port}>0) { next; }
  306. my $simple_mac=mac_simplify($mac);
  307. my $mac_splitted=mac_splitted($mac);
  308. $mac_history{$simple_mac}{port_id}=$port_index{$port};
  309. $mac_history{$simple_mac}{dev_id}=$dev_id;
  310. if (!$mac_history{$simple_mac}{changed}) { $mac_history{$simple_mac}{changed}=0; }
  311. my $port_id=$port_index{$port};
  312. if (exists $auth_table{full_table}{$simple_mac} or exists $auth_table{oper_table}{$simple_mac}) {
  313. my $auth_id;
  314. if (exists $auth_table{oper_table}{$simple_mac}) {
  315. $auth_id=$auth_table{oper_table}{$simple_mac};
  316. } else {
  317. $auth_id=$auth_table{full_table}{$simple_mac};
  318. db_log_debug($dbh,"Mac not found in oper ARP-table. Use old values auth_id: $auth_id [$simple_mac] at device $dev_name [$port]",$auth_id);
  319. }
  320. if (exists $connections{$auth_id}) {
  321. if ($port_id == $connections{$auth_id}{port}) {
  322. if (exists $auth_table{oper_table}{$simple_mac}) {
  323. my $auth_rec;
  324. $auth_rec->{last_found}=$now_str;
  325. $auth_rec->{arp_found}=$now_str;
  326. $oper_arp_list{$auth_id}{updated}=1;
  327. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  328. }
  329. next;
  330. }
  331. $connections{$auth_id}{port}=$port_id;
  332. $mac_history{$simple_mac}{changed}=1;
  333. $mac_history{$simple_mac}{auth_id}=$auth_id;
  334. db_log_info($dbh,"Found auth_id: $auth_id ip: $mac_history{$simple_mac}{ip} [$mac_splitted] at device $dev_name [$port]. Update connection",$auth_id);
  335. my $auth_rec;
  336. #for exists arp - update arp timestamp
  337. if (exists $auth_table{oper_table}{$simple_mac}) { $auth_rec->{arp_found}=$now_str; }
  338. $auth_rec->{last_found}=$now_str;
  339. $oper_arp_list{$auth_id}{updated}=1;
  340. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  341. my $conn_rec;
  342. $conn_rec->{port_id}=$port_id;
  343. $conn_rec->{device_id}=$dev_id;
  344. update_record($dbh,'connections',$conn_rec,"auth_id=$auth_id");
  345. } else {
  346. $mac_history{$simple_mac}{changed}=1;
  347. $mac_history{$simple_mac}{auth_id}=$auth_id;
  348. $connections{$auth_id}{port}=$port_id;
  349. db_log_info($dbh,"Found auth_id: $auth_id ip: $mac_history{$simple_mac}{ip} [$mac_splitted] at device $dev_name [$port]. Create connection.",$auth_id);
  350. my $auth_rec;
  351. #for exists arp - update arp timestamp
  352. if (exists $auth_table{oper_table}{$simple_mac}) { $auth_rec->{arp_found}=$now_str; }
  353. $auth_rec->{last_found}=$now_str;
  354. $oper_arp_list{$auth_id}{updated}=1;
  355. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  356. my $conn_rec;
  357. $conn_rec->{port_id}=$port_id;
  358. $conn_rec->{device_id}=$dev_id;
  359. $conn_rec->{auth_id}=$auth_id;
  360. insert_record($dbh,'connections',$conn_rec);
  361. }
  362. } else {
  363. if (exists $unknown_table{$simple_mac}{unknown_id}) {
  364. next if ($unknown_table{$simple_mac}{port_id} == $port_id and $unknown_table{$simple_mac}{device_id} == $dev_id);
  365. $mac_history{$simple_mac}{changed}=1;
  366. $mac_history{$simple_mac}{auth_id}=0;
  367. db_log_debug($dbh,"Unknown mac $mac_splitted moved to $dev_name [$port]") if ($debug);
  368. my $unknown_rec;
  369. $unknown_rec->{port_id}=$port_id;
  370. $unknown_rec->{device_id}=$dev_id;
  371. update_record($dbh,'Unknown_mac',$unknown_rec,"id=$unknown_table{$simple_mac}{unknown_id}");
  372. } else {
  373. $mac_history{$simple_mac}{changed}=1;
  374. $mac_history{$simple_mac}{auth_id}=0;
  375. db_log_debug($dbh,"Unknown mac $mac_splitted found at $dev_name [$port]") if ($debug);
  376. my $unknown_rec;
  377. $unknown_rec->{port_id}=$port_id;
  378. $unknown_rec->{device_id}=$dev_id;
  379. $unknown_rec->{mac}=$simple_mac;
  380. insert_record($dbh,'Unknown_mac',$unknown_rec);
  381. }
  382. }
  383. }
  384. }
  385. foreach my $auth_id (keys %oper_arp_list) {
  386. next if ($oper_arp_list{$auth_id}->{updated});
  387. my $auth_rec;
  388. $auth_rec->{last_found}=$now_str;
  389. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  390. db_log_debug($dbh,"Update by arp at unknown connect place for: ".Dumper($oper_arp_list{$auth_id})) if ($debug);
  391. }
  392. foreach my $mac (keys %mac_history) {
  393. next if (!$mac);
  394. next if (!$mac_history{$mac}->{changed});
  395. my $h_dev_id='';
  396. my $h_port_id='';
  397. my $h_ip='';
  398. $h_dev_id=$mac_history{$mac}->{dev_id} if ($mac_history{$mac}->{dev_id});
  399. $h_port_id=$mac_history{$mac}->{port_id} if ($mac_history{$mac}->{port_id});
  400. $h_ip=$mac_history{$mac}->{ip} if ($mac_history{$mac}->{ip});
  401. my $h_auth_id=$mac_history{$mac}->{auth_id} if ($mac_history{$mac}->{auth_id});
  402. if (!$h_auth_id) { $h_auth_id=0; }
  403. next if (!$h_dev_id);
  404. my $history_rec;
  405. $history_rec->{device_id}=$h_dev_id;
  406. $history_rec->{port_id}=$h_port_id;
  407. $history_rec->{mac}=$mac;
  408. $history_rec->{ip}=$h_ip;
  409. $history_rec->{auth_id}=$h_auth_id;
  410. insert_record($dbh,'mac_history',$history_rec);
  411. }
  412. $dbh->disconnect;
  413. exit 0;