Code

GosaPackages answers are now gosa-si envelope conform
[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;
18 # Don't start if some of the modules are missing
19 my $start_service=1;
20 my $lookup_vendor=1;
21 BEGIN{
22         unless(eval('use Socket qw(PF_INET SOCK_DGRAM inet_ntoa sockaddr_in)')) {
23                 $start_service=0;
24         }
25         unless(eval('use POE qw(Component::Pcap Component::ArpWatch)')) {
26                 $start_service=0;
27         }
28         unless(eval('use Net::MAC::Vendor')) {
29                 $lookup_vendor=0;
30         }
31 }
33 END{}
35 my ($timeout, $mailto, $mailfrom, $user, $group);
36 my ($arp_activ, $arp_interface, $ldap_uri, $ldap_base, $ldap_admin_dn, $ldap_admin_password);
37 my $hosts_database={};
38 my $resolver=Net::DNS::Resolver->new;
39 my $ldap;
40 if($lookup_vendor) {
41         eval("Net::MAC::Vendor::load_cache('file:///usr/lib/gosa-si/modules/oui.txt')");
42         if($@) {
43                 &main::daemon_log("Loading OUI cache file failed! MAC Vendor lookup disabled", 1);
44                 $lookup_vendor=0;
45         } else {
46                 &main::daemon_log("Loading OUI cache file suceeded!", 6);
47         }
48 }
50 my %cfg_defaults =
51 (
52         "arp" => {
53                 "arp_activ"           => [\$arp_activ,         "on"],
54                 "arp_interface"       => [\$arp_interface,    "all"],
55         },
56         "server" => {
57                 "ldap_uri"            => [\$ldap_uri,            ""],
58                 "ldap_base"           => [\$ldap_base,           ""],
59                 "ldap_admin_dn"       => [\$ldap_admin_dn,       ""],
60                 "ldap_admin_password" => [\$ldap_admin_password, ""],
61         },
62 );
64 #===  FUNCTION  ================================================================
65 #         NAME:  read_configfile
66 #   PARAMETERS:  cfg_file - string -
67 #      RETURNS:  nothing
68 #  DESCRIPTION:  read cfg_file and set variables
69 #===============================================================================
70 sub read_configfile {
71         my $cfg;
72         if( defined( $main::cfg_file) && ( length($main::cfg_file) > 0 )) {
73                 if( -r $main::cfg_file ) {
74                         $cfg = Config::IniFiles->new( -file => $main::cfg_file );
75                 } else {
76                         print STDERR "Couldn't read config file!";
77                 }
78         } else {
79                 $cfg = Config::IniFiles->new() ;
80         }
81         foreach my $section (keys %cfg_defaults) {
82                 foreach my $param (keys %{$cfg_defaults{ $section }}) {
83                         my $pinfo = $cfg_defaults{ $section }{ $param };
84                         ${@$pinfo[0]} = $cfg->val( $section, $param, @$pinfo[1] );
85                 }
86         }
87 }
89 sub get_module_info {
90         my @info = (undef,
91                 undef,
92                 undef,
93                 undef,
94                 "socket",
95         );
97         &read_configfile();
98         # Don't start if some of the modules are missing
99         if(($arp_activ eq 'on') && $start_service) {
100                 $ldap = Net::LDAP->new($ldap_uri);
101                 if (!$ldap) {
102                         &main::daemon_log("Could not connect to LDAP Server at $ldap_uri!\n$@", 1);
103                 } else {
104                         $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
105                 }
107                 # When interface is not configured (or 'all'), start arpwatch on all possible interfaces
108                 if ((!defined($arp_interface)) || $arp_interface eq 'all') {
109                         foreach my $device(&get_interfaces) {
110                                 # TODO: Need a better workaround for IPv4-to-IPv6 bridges
111                                 if($device =~ m/^sit\d+$/) {
112                                         next;
113                                 }
115                                 # If device has a valid mac address
116                                 # TODO: Check if this should be the right way
117                                 if(not(&get_mac($device) eq "00:00:00:00:00:00")) {
118                                         &main::daemon_log("Starting ArpWatch on $device", 1);
119                                         POE::Session->create( 
120                                                 inline_states => {
121                                                         _start => sub {
122                                                                 &start(@_,$device);
123                                                         },
124                                                         _stop => sub {
125                                                                 $ldap->unbind if (defined($ldap));
126                                                                 $ldap->disconnect if (defined($ldap));
127                                                                 $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
128                                                         },
129                                                         got_packet => \&got_packet,
130                                                 },
131                                         );
132                                 }
133                         }
134                 } else {
135                         foreach my $device(split(/[\s,]+/, $arp_interface)) {
136                                 &main::daemon_log("Starting ArpWatch on $device", 1);
137                                 POE::Session->create( 
138                                         inline_states => {
139                                                 _start => sub {
140                                                         &start(@_,$device);
141                                                 },
142                                                 _stop => sub {
143                                                         $ldap->unbind if (defined($ldap));
144                                                         $ldap->disconnect if (defined($ldap));
145                                                         $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
146                                                 },
147                                                 got_packet => \&got_packet,
148                                         },
149                                 );
150                         }
151                 }
152         } else {
153                 &main::daemon_log("ArpHandler disabled. Not starting any capture processes");
154         }
155         return \@info;
158 sub process_incoming_msg {
159         return 1;
162 sub start {
163         my $device = (exists($_[ARG0])?$_[ARG0]:'eth0');
164         POE::Component::ArpWatch->spawn( 
165                 Alias => sprintf("arp_watch_$device"),
166                 Device => $device, 
167                 Dispatch => 'got_packet',
168                 Session => $_[SESSION],
169         );
171         $_[KERNEL]->post( sprintf("arp_watch_$device") => 'run' );
174 sub got_packet {
175         my ($kernel, $heap, $sender, $packet) = @_[KERNEL, HEAP, SENDER, ARG0];
177         if(     $packet->{source_haddr} eq "00:00:00:00:00:00" || 
178                 $packet->{source_haddr} eq "ff:ff:ff:ff:ff:ff" || 
179                 $packet->{source_ipaddr} eq "0.0.0.0") {
180                 return;
181         }
182         
183         my $capture_device = sprintf "%s", $kernel->alias_list($sender) =~ /^arp_watch_(.*)$/;
185         if(!exists($hosts_database->{$packet->{source_haddr}})) {
186                 my $dnsresult= $resolver->search($packet->{source_ipaddr});
187                 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$packet->{source_ipaddr};
188                 my $ldap_result=&get_host_from_ldap($packet->{source_haddr});
189                 if(exists($ldap_result->{dn})) {
190                         $hosts_database->{$packet->{source_haddr}}=$ldap_result;
191                         $hosts_database->{$packet->{source_haddr}}->{dnsname}= $dnsname;
192                         if(!exists($ldap_result->{ipHostNumber})) {
193                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}=$packet->{source_ipaddr};
194                         } else {
195                                 if(!($ldap_result->{ipHostNumber} eq $packet->{source_ipaddr})) {
196                                         &main::daemon_log(
197                                                 "Current IP Address ".$packet->{source_ipaddr}.
198                                                 " of host ".$hosts_database->{$packet->{source_haddr}}->{dnsname}.
199                                                 " differs from LDAP (".$ldap_result->{ipHostNumber}.")", 4);
200                                 }
201                         }
202                         $hosts_database->{$packet->{source_haddr}}->{dnsname}=$dnsname;
203                         &main::daemon_log("Host was found in LDAP as ".$ldap_result->{dn}, 6);
204                 } else {
205                         $hosts_database->{$packet->{source_haddr}}={
206                                 macAddress => $packet->{source_haddr},
207                                 ipHostNumber => $packet->{source_ipaddr},
208                                 dnsname => $dnsname,
209                                 cn => (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\./),
210                                 macVendor => (($lookup_vendor) ? &get_vendor_for_mac($packet->{source_haddr}) : "Unknown Vendor"),
211                         };
212                         &main::daemon_log("Host was not found in LDAP (".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
213                         &main::daemon_log(
214                                 "New Host ".($hosts_database->{$packet->{source_haddr}}->{dnsname}).
215                                 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
216                                 "/".$hosts_database->{$packet->{source_haddr}}->{macAddress},4);
217                         &add_ldap_entry(
218                                 $ldap, 
219                                 $ldap_base, 
220                                 $hosts_database->{$packet->{source_haddr}}->{macAddress},
221                                 'new-system',
222                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
223                                 'interface',
224                                 $hosts_database->{$packet->{source_haddr}}->{macVendor});
225                 }
226                 $hosts_database->{$packet->{source_haddr}}->{device}= $capture_device;
227         } else {
228                 if(!($hosts_database->{$packet->{source_haddr}}->{ipHostNumber} eq $packet->{source_ipaddr})) {
229                         &main::daemon_log(
230                                 "IP Address change of MAC ".$packet->{source_haddr}.
231                                 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
232                                 "->".$packet->{source_ipaddr}, 4);
233                         $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}= $packet->{source_ipaddr};
234                         &change_ldap_entry(
235                                 $ldap, 
236                                 $ldap_base, 
237                                 $hosts_database->{$packet->{source_haddr}}->{macAddress},
238                                 'ip-changed',
239                                 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
240                         );
242                 }
243                 &main::daemon_log("Host already in cache (".($hosts_database->{$packet->{source_haddr}}->{device})."->".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
244         }
245
247 sub get_host_from_ldap {
248         my $mac=shift;
249         my $result={};
250                 
251         my $ldap_result= &search_ldap_entry(
252                 $ldap,
253                 $ldap_base,
254                 "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))"
255         );
257         if(defined($ldap_result) && $ldap_result->count==1) {
258                 if(exists($ldap_result->{entries}[0]) && 
259                         exists($ldap_result->{entries}[0]->{asn}->{objectName}) && 
260                         exists($ldap_result->{entries}[0]->{asn}->{attributes})) {
262                         for my $attribute(@{$ldap_result->{entries}[0]->{asn}->{attributes}}) {
263                                 if($attribute->{type} eq 'cn') {
264                                         $result->{cn} = $attribute->{vals}[0];
265                                 }
266                                 if($attribute->{type} eq 'macAddress') {
267                                         $result->{macAddress} = $attribute->{vals}[0];
268                                 }
269                                 if($attribute->{type} eq 'dhcpHWAddress') {
270                                         $result->{dhcpHWAddress} = $attribute->{vals}[0];
271                                 }
272                                 if($attribute->{type} eq 'ipHostNumber') {
273                                         $result->{ipHostNumber} = $attribute->{vals}[0];
274                                 }
275                         }
276                 }
277                 $result->{dn} = $ldap_result->{entries}[0]->{asn}->{objectName};
278         }
280         return $result;
283 #===  FUNCTION  ================================================================
284 #         NAME:  get_interfaces 
285 #   PARAMETERS:  none
286 #      RETURNS:  (list of interfaces) 
287 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
288 #===============================================================================
289 sub get_interfaces {
290         my @result;
291         my $PROC_NET_DEV= ('/proc/net/dev');
293         open(PROC_NET_DEV, "<$PROC_NET_DEV")
294                 or die "Could not open $PROC_NET_DEV";
296         my @ifs = <PROC_NET_DEV>;
298         close(PROC_NET_DEV);
300         # Eat first two line
301         shift @ifs;
302         shift @ifs;
304         chomp @ifs;
305         foreach my $line(@ifs) {
306                 my $if= (split /:/, $line)[0];
307                 $if =~ s/^\s+//;
308                 push @result, $if;
309         }
311         return @result;
314 #===  FUNCTION  ================================================================
315 #         NAME:  get_mac 
316 #   PARAMETERS:  interface name (i.e. eth0)
317 #      RETURNS:  (mac address) 
318 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
319 #===============================================================================
320 sub get_mac {
321         my $ifreq= shift;
322         my $result;
323         if ($ifreq && length($ifreq) > 0) { 
324                 if($ifreq eq "all") {
325                         $result = "00:00:00:00:00:00";
326                 } else {
327                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
329                         socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
330                                 or die "socket: $!";
332                         if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
333                                 my ($if, $mac)= unpack 'h36 H12', $ifreq;
335                                 if (length($mac) > 0) {
336                                         $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])$/;
337                                         $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
338                                         $result = $mac;
339                                 }
340                         }
341                 }
342         }
343         return $result;
346 sub get_vendor_for_mac {
347         my $mac=shift;
348         my $result="Unknown Vendor";
350         if(defined($mac)) {
351                 my $vendor= Net::MAC::Vendor::fetch_oui_from_cache(Net::MAC::Vendor::normalize_mac($mac));
352                 if(length($vendor) > 0) {
353                         $result= @{$vendor}[0];
354                 }
355                 &main::daemon_log("Looking up Vendor for MAC ".$mac.": $result", 4);
356         }
358         return $result;
361 #===  FUNCTION  ================================================================
362 #         NAME:  add_ldap_entry
363 #      PURPOSE:  adds an element to ldap-tree
364 #   PARAMETERS:  
365 #      RETURNS:  none
366 #  DESCRIPTION:  ????
367 #       THROWS:  no exceptions
368 #     COMMENTS:  none
369 #     SEE ALSO:  n/a/bin
370 #===============================================================================
371 sub add_ldap_entry {
372     my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip, $interface, $desc) = @_;
373     my $dn = "cn=".$hosts_database->{$mac}->{cn}.",ou=incoming,$ldap_base";
374     my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
375     my $c_res = (defined($s_res))?$s_res->count:0;
376     if($c_res == 1) {
377         &main::daemon_log("WARNING: macAddress $mac already in LDAP", 1);
378         return;
379     } elsif($c_res > 0) {
380         &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
381         return;
382     }
384     # create LDAP entry 
385     my $entry = Net::LDAP::Entry->new( $dn );
386     $entry->dn($dn);
387     $entry->add("objectClass" => "goHard");
388     $entry->add("cn" => $hosts_database->{$mac}->{cn});
389     $entry->add("macAddress" => $mac);
390     if(defined $gotoSysStatus) {$entry->add("gotoSysStatus" => $gotoSysStatus)}
391     if(defined $ip) {$entry->add("ipHostNumber" => $ip) }
392     #if(defined $interface) { }
393     if(defined $desc) {$entry->add("description" => $desc) }
394     
395     # submit entry to LDAP
396         my $result = $entry->update ($ldap_tree); 
397         
398     # for $result->code constants please look at Net::LDAP::Constant
399     if($result->code == 68) {   # entry already exists 
400         &main::daemon_log("WARNING: $dn ".$result->error, 3);
401     } elsif($result->code == 0) {   # everything went fine
402         &main::daemon_log("add entry $dn to ldap", 1);
403     } else {  # if any other error occur
404         &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
405     }
406     return;
410 #===  FUNCTION  ================================================================
411 #         NAME:  change_ldap_entry
412 #      PURPOSE:  ????
413 #   PARAMETERS:  ????
414 #      RETURNS:  ????
415 #  DESCRIPTION:  ????
416 #       THROWS:  no exceptions
417 #     COMMENTS:  none
418 #     SEE ALSO:  n/a
419 #===============================================================================
420 sub change_ldap_entry {
421     my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip) = @_;
422     
423     # check if ldap_entry exists or not
424     my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
425     my $c_res = (defined $s_res)?$s_res->count:0;
426     if($c_res == 0) {
427         &main::daemon_log("WARNING: macAddress $mac not in LDAP", 1);
428         return;
429     } elsif($c_res > 1) {
430         &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
431         return;
432     }
434     my $s_res_entry = $s_res->pop_entry();
435     my $dn = $s_res_entry->dn();
436         my $replace = {
437                 'gotoSysStatus' => $gotoSysStatus,
438         };
439         if (defined($ip)) {
440                 $replace->{'ipHostNumber'} = $ip;
441         }
442     my $result = $ldap->modify( $dn, replace => $replace );
444     # for $result->code constants please look at Net::LDAP::Constant
445     if($result->code == 32) {   # entry doesnt exists 
446         &add_ldap_entry($mac, $gotoSysStatus);
447     } elsif($result->code == 0) {   # everything went fine
448         &main::daemon_log("entry $dn changed successful", 1);
449     } else {  # if any other error occur
450         &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
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                 #if(defined $msg) {
477         #    print $sub_tree."\t".$search_string."\t";
478         #    print $msg->count."\n";
479         #    foreach my $entry ($msg->entries) { $entry->dump; };
480         #}
481         }
482         return $msg;
484 #        $ldap = Net::LDAP->new( "localhost" ) or die "$@";
485 #        $ldap->bind($bind_phrase,
486 #                    password => $password,
487 #                    ) ;
488 #        
489 #        switch($arp_sig) {
490 #            case 0 {&change_ldap_entry($ldap, $ldap_base, 
491 #                                      $mac, "ip-changed",
492 #                                      )} 
493 #            case 1 {&change_ldap_entry($ldap, $ldap_base, 
494 #                                      $mac, "mac-not-whitelisted",
495 #                                      )}
496 #            case 2 {&change_ldap_entry($ldap, $ldap_base, 
497 #                                      $mac, "mac-in-blacklist",
498 #                                      )}
499 #            case 3 {&add_ldap_entry($ldap, $ldap_base, 
500 #                                   $mac, "new-mac-address", $ip, 
501 #                                   $interface, $desc, 
502 #                                   )}
503 #            case 4 {&change_ldap_entry($ldap, $ldap_base, 
504 #                                      $mac, "unauthorized-arp-request",
505 #                                      )}
506 #            case 5 {&change_ldap_entry($ldap, $ldap_base, 
507 #                                      $mac, "abusive-number-of-arp-requests",
508 #                                      )}
509 #            case 6 {&change_ldap_entry($ldap, $ldap_base, 
510 #                                      $mac, "ether-and-arp-mac-differs",
511 #                                      )}
512 #            case 7 {&change_ldap_entry($ldap, $ldap_base, 
513 #                                      $mac, "flood-detected",
514 #                                      )}
515 #            case 8 {&add_ldap_entry($ldap, $ldap_base, 
516 #                                   $mac, $ip, "new-system",
517 #                                   )}
518 #            case 9 {&change_ldap_entry($ldap, $ldap_base, 
519 #                                      $mac, "mac-changed",
520 #                                      )}
521 #        }
524         # ldap search
525 #        my $base_phrase = "dc=gonicus,dc=de";
526 #        my $filter_phrase = "cn=keinesorge";
527 #        my $attrs_phrase = "cn macAdress";
528 #        my $msg_search = $ldap->search( base   => $base_phrase,
529 #                                        filter => $filter_phrase,
530 #                                        attrs => $attrs_phrase,
531 #                                        );
532 #        $msg_search->code && die $msg_search->error;
533 #        
534 #        my @entries = $msg_search->entries;
535 #        my $max = $msg_search->count;
536 #        print "anzahl der entries: $max\n";
537 #        my $i;
538 #        for ( $i = 0 ; $i < $max ; $i++ ) {
539 #            my $entry = $msg_search->entry ( $i );
540 #            foreach my $attr ( $entry->attributes ) {
541 #                if( not $attr eq "cn") {
542 #                    next;
543 #                }
544 #                print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n\n";
545 #            }
546 #        }
547                 #
548                 #        # ldap add
549                 #       
550                 #        
551                 #        $ldap->unbind;
552                 #        exit;
554 1;