Code

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