Code

* gosa-si-server-nobus
[gosa.git] / gosa-si / modules / ArpHandler.pm
1 package ArpHandler;
3 use Exporter;
4 @ISA = ("Exporter");
6 use strict;
7 use warnings;
8 use GOSA::GosaSupportDaemon;
9 use POSIX;
10 use Fcntl;
11 use Net::LDAP;
12 use Net::LDAP::LDIF;
13 use Net::LDAP::Entry;
14 use Net::DNS;
15 use Switch;
16 use Data::Dumper;
17 use Socket;
19 # Don't start if some of the modules are missing
20 my $start_service=1;
21 my $lookup_vendor=1;
22 BEGIN{
23         unless(eval('use Socket qw(PF_INET SOCK_DGRAM inet_ntoa sockaddr_in)')) {
24                 $start_service=0;
25         }
26         unless(eval('use POE qw(Component::Pcap Component::ArpWatch)')) {
27                 $start_service=0;
28         }
29         unless(eval('use Net::MAC::Vendor')) {
30                 $lookup_vendor=0;
31         }
32 }
34 END{}
36 my ($timeout, $mailto, $mailfrom, $user, $group);
37 my ($arp_enabled, $arp_interface, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password);
38 my $hosts_database={};
39 my $ldap;
41 my %cfg_defaults =
42 (
43         "ArpHandler" => {
44                 "enabled"           => [\$arp_enabled,         "true"],
45                 "interface"       => [\$arp_interface,    "all"],
46         },
47         "server" => {
48                 "ldap-uri"            => [\$ldap_uri,            ""],
49                 "ldap-base"           => [\$ldap_base,           ""],
50                 "ldap-admin-dn"       => [\$ldap_admin_dn,       ""],
51                 "ldap-admin-password" => [\$ldap_admin_password, ""],
52         },
53 );
55 #===  FUNCTION  ================================================================
56 #         NAME:  read_configfile
57 #   PARAMETERS:  cfg_file - string -
58 #      RETURNS:  nothing
59 #  DESCRIPTION:  read cfg_file and set variables
60 #===============================================================================
61 sub read_configfile {
62         my $cfg;
63         if( defined( $main::cfg_file) && ( (-s $main::cfg_file) > 0 )) {
64                 if( -r $main::cfg_file ) {
65                         $cfg = Config::IniFiles->new( -file => $main::cfg_file );
66                 } else {
67                         print STDERR "Couldn't read config file!";
68                 }
69         } else {
70                 $cfg = Config::IniFiles->new() ;
71         }
72         foreach my $section (keys %cfg_defaults) {
73                 foreach my $param (keys %{$cfg_defaults{ $section }}) {
74                         my $pinfo = $cfg_defaults{ $section }{ $param };
75                         ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
76                 }
77         }
78 }
80 sub get_module_info {
81         my @info = (undef,
82                 undef,
83         );
85         &read_configfile();
86         # Don't start if some of the modules are missing
87         if(($arp_enabled eq 'true') && $start_service) {
88                 if($lookup_vendor) {
89                         eval("Net::MAC::Vendor::load_cache('file:///usr/lib/gosa-si/modules/oui.txt')");
90                         if($@) {
91                                 &main::daemon_log("Loading OUI cache file failed! MAC Vendor lookup disabled", 1);
92                                 $lookup_vendor=0;
93                         } else {
94                                 &main::daemon_log("Loading OUI cache file suceeded!", 6);
95                         }
96                 }
97                 my $ldap_handle = &main::get_ldap_handle();
99                 # When interface is not configured (or 'all'), start arpwatch on all possible interfaces
100                 if ((!defined($arp_interface)) || $arp_interface eq 'all') {
101                         foreach my $device(&get_interfaces) {
102                                 # TODO: Need a better workaround for IPv4-to-IPv6 bridges
103                                 if($device =~ m/^sit\d+$/) {
104                                         next;
105                                 }
107                                 # If device has a valid mac address
108                                 # TODO: Check if this should be the right way
109                                 if(not(&get_mac($device) eq "00:00:00:00:00:00")) {
110                                         &main::daemon_log("Starting ArpWatch on $device", 1);
111                                         POE::Session->create( 
112                                                 inline_states => {
113                                                         _start => sub {
114                                                                 &start(@_,$device);
115                                                         },
116                                                         _stop => sub {
117                                                                 $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
118                                                         },
119                                                         got_packet => \&got_packet,
120                                                 },
121                                         );
122                                 }
123                         }
124                 } else {
125                         foreach my $device(split(/[\s,]+/, $arp_interface)) {
126                                 &main::daemon_log("Starting ArpWatch on $device", 1);
127                                 POE::Session->create( 
128                                         inline_states => {
129                                                 _start => sub {
130                                                         &start(@_,$device);
131                                                 },
132                                                 _stop => sub {
133                                                         $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
134                                                 },
135                                                 got_packet => \&got_packet,
136                                         },
137                                 );
138                         }
139                 }
140         } else {
141                 &main::daemon_log("ArpHandler disabled. Not starting any capture processes");
142         }
143         return \@info;
146 sub process_incoming_msg {
147         return 1;
150 sub start {
151         my $device = (exists($_[ARG0])?$_[ARG0]:'eth0');
152         POE::Component::ArpWatch->spawn( 
153                 Alias => sprintf("arp_watch_$device"),
154                 Device => $device, 
155                 Dispatch => 'got_packet',
156                 Session => $_[SESSION],
157         );
159         $_[KERNEL]->post( sprintf("arp_watch_$device") => 'run' );
162 sub got_packet {
163         my ($kernel, $heap, $sender, $packet) = @_[KERNEL, HEAP, SENDER, ARG0];
165         if(     $packet->{source_haddr} eq "00:00:00:00:00:00" || 
166                 $packet->{source_haddr} eq "ff:ff:ff:ff:ff:ff" || 
167                 $packet->{source_ipaddr} eq "0.0.0.0") {
168                 return;
169         }
170         
171         my $capture_device = sprintf "%s", $kernel->alias_list($sender) =~ /^arp_watch_(.*)$/;
173         my $ldap_handle = &main::get_ldap_handle(); 
174     if(!exists($hosts_database->{$packet->{source_haddr}})) {
175                 my $dnsname= gethostbyaddr(inet_aton($packet->{source_ipaddr}), AF_INET) || $packet->{source_ipaddr};
176                 my $ldap_result=&get_host_from_ldap($packet->{source_haddr});
177                 if(exists($ldap_result->{dn})) {
178                         $hosts_database->{$packet->{source_haddr}}=$ldap_result;
179                         $hosts_database->{$packet->{source_haddr}}->{dnsname}= $dnsname;
180                         if(!exists($ldap_result->{ipHostNumber})) {
181                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}=$packet->{source_ipaddr};
182                         } else {
183                                 if(!($ldap_result->{ipHostNumber} eq $packet->{source_ipaddr})) {
184                                         &main::daemon_log(
185                                                 "Current IP Address ".$packet->{source_ipaddr}.
186                                                 " of host ".$hosts_database->{$packet->{source_haddr}}->{dnsname}.
187                                                 " differs from LDAP (".$ldap_result->{ipHostNumber}.")", 4);
188                                 }
189                         }
190                         $hosts_database->{$packet->{source_haddr}}->{dnsname}=$dnsname;
191                         &main::daemon_log("Host was found in LDAP as ".$ldap_result->{dn}, 8);
192                 } else {
193                         $hosts_database->{$packet->{source_haddr}}={
194                                 macAddress => $packet->{source_haddr},
195                                 ipHostNumber => $packet->{source_ipaddr},
196                                 dnsname => $dnsname,
197                                 cn => (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\./),
198                                 macVendor => (($lookup_vendor) ? &get_vendor_for_mac($packet->{source_haddr}) : "Unknown Vendor"),
199                         };
200                         &main::daemon_log("Host was not found in LDAP (".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
201                         &main::daemon_log(
202                                 "New Host ".($hosts_database->{$packet->{source_haddr}}->{dnsname}).
203                                 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
204                                 "/".$hosts_database->{$packet->{source_haddr}}->{macAddress},4);
205                         &add_ldap_entry(
206                                 $ldap_handle, 
207                                 $ldap_base, 
208                                 $hosts_database->{$packet->{source_haddr}}->{macAddress},
209                                 'new-system',
210                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
211                                 'interface',
212                                 $hosts_database->{$packet->{source_haddr}}->{macVendor});
213                 }
214                 $hosts_database->{$packet->{source_haddr}}->{device}= $capture_device;
215         } else {
216                 if(!($hosts_database->{$packet->{source_haddr}}->{ipHostNumber} eq $packet->{source_ipaddr})) {
217                         &main::daemon_log(
218                                 "IP Address change of MAC ".$packet->{source_haddr}.
219                                 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
220                                 "->".$packet->{source_ipaddr}, 4);
221                         $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}= $packet->{source_ipaddr};
222                         &change_ldap_entry(
223                                 $ldap_handle, 
224                                 $ldap_base, 
225                                 $hosts_database->{$packet->{source_haddr}}->{macAddress},
226                                 'ip-changed',
227                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
228                         );
230                 }
231                 &main::daemon_log("Host already in cache (".($hosts_database->{$packet->{source_haddr}}->{device})."->".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",8);
232         }
233
235 sub get_host_from_ldap {
236         my $mac=shift;
237         my $result={};
238                 
239     my $ldap_handle = &main::get_ldap_handle();     
240         if(defined($ldap_handle)) {
241                 my $ldap_result= &search_ldap_entry(
242                         $ldap_handle,
243                         $ldap_base,
244                         "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))"
245                 );
247                 if(defined($ldap_result) && $ldap_result->count==1) {
248                         if(exists($ldap_result->{entries}[0]) && 
249                                 exists($ldap_result->{entries}[0]->{asn}->{objectName}) && 
250                                 exists($ldap_result->{entries}[0]->{asn}->{attributes})) {
252                                 for my $attribute(@{$ldap_result->{entries}[0]->{asn}->{attributes}}) {
253                                         if($attribute->{type} eq 'cn') {
254                                                 $result->{cn} = $attribute->{vals}[0];
255                                         }
256                                         if($attribute->{type} eq 'macAddress') {
257                                                 $result->{macAddress} = $attribute->{vals}[0];
258                                         }
259                                         if($attribute->{type} eq 'dhcpHWAddress') {
260                                                 $result->{dhcpHWAddress} = $attribute->{vals}[0];
261                                         }
262                                         if($attribute->{type} eq 'ipHostNumber') {
263                                                 $result->{ipHostNumber} = $attribute->{vals}[0];
264                                         }
265                                 }
266                         }
267                         $result->{dn} = $ldap_result->{entries}[0]->{asn}->{objectName};
268                 }
269         }
271         return $result;
274 # moved to GosaSupportDaemon: 03-06-2008: rettenbe
275 #===  FUNCTION  ================================================================
276 #         NAME:  get_interfaces 
277 #   PARAMETERS:  none
278 #      RETURNS:  (list of interfaces) 
279 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
280 #===============================================================================
281 #sub get_interfaces {
282 #       my @result;
283 #       my $PROC_NET_DEV= ('/proc/net/dev');
285 #       open(PROC_NET_DEV, "<$PROC_NET_DEV")
286 #               or die "Could not open $PROC_NET_DEV";
288 #       my @ifs = <PROC_NET_DEV>;
290 #       close(PROC_NET_DEV);
292 #       # Eat first two line
293 #       shift @ifs;
294 #       shift @ifs;
296 #       chomp @ifs;
297 #       foreach my $line(@ifs) {
298 #               my $if= (split /:/, $line)[0];
299 #               $if =~ s/^\s+//;
300 #               push @result, $if;
301 #       }
303 #       return @result;
304 #}
306 #===  FUNCTION  ================================================================
307 #         NAME:  get_mac 
308 #   PARAMETERS:  interface name (i.e. eth0)
309 #      RETURNS:  (mac address) 
310 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
311 #===============================================================================
312 sub get_mac {
313         my $ifreq= shift;
314         my $result;
315         if ($ifreq && length($ifreq) > 0) { 
316                 if($ifreq eq "all") {
317                         $result = "00:00:00:00:00:00";
318                 } else {
319                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
321                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
322                                 or die "socket: $!";
324                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
325                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
327                                 if (length($mac) > 0) {
328                                         $mac=~ m/^([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/;
329                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
330                                         $result = $mac;
331                                 }
332                         }
333                 }
334         }
335         return $result;
338 sub get_vendor_for_mac {
339         my $mac=shift;
340         my $result="Unknown Vendor";
342         if(defined($mac)) {
343                 my $vendor= Net::MAC::Vendor::fetch_oui_from_cache(Net::MAC::Vendor::normalize_mac($mac));
344                 if(length($vendor) > 0) {
345                         $result= @{$vendor}[0];
346                 }
347                 &main::daemon_log("Looking up Vendor for MAC ".$mac.": $result", 4);
348         }
350         return $result;
353 #===  FUNCTION  ================================================================
354 #         NAME:  add_ldap_entry
355 #      PURPOSE:  adds an element to ldap-tree
356 #   PARAMETERS:  
357 #      RETURNS:  none
358 #  DESCRIPTION:  ????
359 #       THROWS:  no exceptions
360 #     COMMENTS:  none
361 #     SEE ALSO:  n/a/bin
362 #===============================================================================
363 sub add_ldap_entry {
364         my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip, $interface, $desc) = @_;
365         if(defined($ldap_tree)) {
366                 my $dn = "cn=".$hosts_database->{$mac}->{cn}.",ou=incoming,$ldap_base";
367                 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
368                 my $c_res = (defined($s_res))?$s_res->count:0;
369                 if($c_res == 1) {
370                         &main::daemon_log("WARNING: macAddress $mac already in LDAP", 1);
371                         return;
372                 } elsif($c_res > 0) {
373                         &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
374                         return;
375                 }
377                 # create LDAP entry 
378                 my $entry = Net::LDAP::Entry->new( $dn );
379                 $entry->dn($dn);
380                 $entry->add("objectClass" => "goHard");
381                 $entry->add("cn" => $hosts_database->{$mac}->{cn});
382                 $entry->add("macAddress" => $mac);
383                 if(defined $gotoSysStatus) {$entry->add("gotoSysStatus" => $gotoSysStatus)}
384                 if(defined $ip) {$entry->add("ipHostNumber" => $ip) }
385                 #if(defined $interface) { }
386                 if(defined $desc) {$entry->add("description" => $desc) }
388                 # submit entry to LDAP
389                 my $result = $entry->update ($ldap_tree); 
391                 # for $result->code constants please look at Net::LDAP::Constant
392                 if($result->code == 68) {   # entry already exists 
393                         &main::daemon_log("WARNING: $dn ".$result->error, 3);
394                 } elsif($result->code == 0) {   # everything went fine
395                         &main::daemon_log("add entry $dn to ldap", 1);
396                 } else {  # if any other error occur
397                         &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
398                 }
399         } else {
400                 &main::daemon_log("Not adding new Entry: LDAP disabled", 6);
401         }
402         return;
406 #===  FUNCTION  ================================================================
407 #         NAME:  change_ldap_entry
408 #      PURPOSE:  ????
409 #   PARAMETERS:  ????
410 #      RETURNS:  ????
411 #  DESCRIPTION:  ????
412 #       THROWS:  no exceptions
413 #     COMMENTS:  none
414 #     SEE ALSO:  n/a
415 #===============================================================================
416 sub change_ldap_entry {
417         my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip) = @_;
419         if(defined($ldap_tree)) {
420                 # check if ldap_entry exists or not
421                 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
422                 my $c_res = (defined $s_res)?$s_res->count:0;
423                 if($c_res == 0) {
424                         &main::daemon_log("WARNING: macAddress $mac not in LDAP", 1);
425                         return;
426                 } elsif($c_res > 1) {
427                         &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
428                         return;
429                 }
431                 my $s_res_entry = $s_res->pop_entry();
432                 my $dn = $s_res_entry->dn();
433                 my $replace = {
434                         'gotoSysStatus' => $gotoSysStatus,
435                 };
436                 if (defined($ip)) {
437                         $replace->{'ipHostNumber'} = $ip;
438                 }
439                 my $result = $ldap_tree->modify( $dn, replace => $replace );
441                 # for $result->code constants please look at Net::LDAP::Constant
442                 if($result->code == 32) {   # entry doesnt exists 
443                         &add_ldap_entry($mac, $gotoSysStatus);
444                 } elsif($result->code == 0) {   # everything went fine
445                         &main::daemon_log("entry $dn changed successful", 1);
446                 } else {  # if any other error occur
447                         &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
448                 }
449         } else {
450                 &main::daemon_log("Not changing Entry: LDAP disabled", 6);
451         }
453         return;
456 #===  FUNCTION  ================================================================
457 #         NAME:  search_ldap_entry
458 #      PURPOSE:  ????
459 #   PARAMETERS:  [Net::LDAP] $ldap_tree - object of an ldap-tree
460 #                string $sub_tree - dn of the subtree the search is performed
461 #                string $search_string - either a string or a Net::LDAP::Filter object
462 #      RETURNS:  [Net::LDAP::Search] $msg - result object of the performed search
463 #  DESCRIPTION:  ????
464 #       THROWS:  no exceptions
465 #     COMMENTS:  none
466 #     SEE ALSO:  n/a
467 #===============================================================================
468 sub search_ldap_entry {
469         my ($ldap_tree, $sub_tree, $search_string) = @_;
470         my $msg;
471         if(defined($ldap_tree)) {
472                 $msg = $ldap_tree->search( # perform a search
473                         base   => $sub_tree,
474                         filter => $search_string,
475                 ) or &main::daemon_log("cannot perform search at ldap: $@", 1);
476         }
477         return $msg;
480 1;