098a5bad94ac9e106b0f475a217d081aa8539cb6
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;
156 }
158 sub process_incoming_msg {
159 return 1;
160 }
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' );
172 }
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 }
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 if(!exists($ldap_result->{ipHostNumber})) {
192 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}=$packet->{source_ipaddr};
193 } else {
194 if(!($ldap_result->{ipHostNumber} eq $packet->{source_ipaddr})) {
195 &main::daemon_log(
196 "Current IP Address ".$packet->{source_ipaddr}.
197 " of host ".$ldap_result->{dnsname}.
198 " differs from LDAP (".$ldap_result->{ipHostNumber}.")", 4);
199 }
200 }
201 $hosts_database->{$packet->{source_haddr}}->{dnsname}=$dnsname;
202 &main::daemon_log("Host was found in LDAP as ".$ldap_result->{dn}, 6);
203 } else {
204 $hosts_database->{$packet->{source_haddr}}={
205 macAddress => $packet->{source_haddr},
206 ipHostNumber => $packet->{source_ipaddr},
207 dnsname => $dnsname,
208 cn => (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\./),
209 macVendor => (($lookup_vendor) ? &get_vendor_for_mac($packet->{source_haddr}) : "Unknown Vendor"),
210 };
211 &main::daemon_log("Host was not found in LDAP (".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
212 &main::daemon_log(
213 "New Host ".($hosts_database->{$packet->{source_haddr}}->{dnsname}).
214 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
215 "/".$hosts_database->{$packet->{source_haddr}}->{macAddress},4);
216 &add_ldap_entry(
217 $ldap,
218 $ldap_base,
219 $hosts_database->{$packet->{source_haddr}}->{macAddress},
220 'new-system',
221 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
222 'interface',
223 $hosts_database->{$packet->{source_haddr}}->{macVendor});
224 }
225 $hosts_database->{$packet->{source_haddr}}->{device}= $capture_device;
226 } else {
227 if(!($hosts_database->{$packet->{source_haddr}}->{ipHostNumber} eq $packet->{source_ipaddr})) {
228 &main::daemon_log(
229 "IP Address change of MAC ".$packet->{source_haddr}.
230 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
231 "->".$packet->{source_ipaddr}, 4);
232 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}= $packet->{source_ipaddr};
233 &change_ldap_entry(
234 $ldap,
235 $ldap_base,
236 $hosts_database->{$packet->{source_haddr}}->{macAddress},
237 'ip-changed',
238 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
239 );
241 }
242 &main::daemon_log("Host already in cache (".($hosts_database->{$packet->{source_haddr}}->{device})."->".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
243 }
244 }
246 sub get_host_from_ldap {
247 my $mac=shift;
248 my $result={};
250 my $ldap_result= &search_ldap_entry(
251 $ldap,
252 $ldap_base,
253 "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))"
254 );
256 if(defined($ldap_result) && $ldap_result->count==1) {
257 if(exists($ldap_result->{entries}[0]) &&
258 exists($ldap_result->{entries}[0]->{asn}->{objectName}) &&
259 exists($ldap_result->{entries}[0]->{asn}->{attributes})) {
261 for my $attribute(@{$ldap_result->{entries}[0]->{asn}->{attributes}}) {
262 if($attribute->{type} eq 'cn') {
263 $result->{cn} = $attribute->{vals}[0];
264 }
265 if($attribute->{type} eq 'macAddress') {
266 $result->{macAddress} = $attribute->{vals}[0];
267 }
268 if($attribute->{type} eq 'dhcpHWAddress') {
269 $result->{dhcpHWAddress} = $attribute->{vals}[0];
270 }
271 if($attribute->{type} eq 'ipHostNumber') {
272 $result->{ipHostNumber} = $attribute->{vals}[0];
273 }
274 }
275 }
276 $result->{dn} = $ldap_result->{entries}[0]->{asn}->{objectName};
277 }
279 return $result;
280 }
282 #=== FUNCTION ================================================================
283 # NAME: get_interfaces
284 # PARAMETERS: none
285 # RETURNS: (list of interfaces)
286 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
287 #===============================================================================
288 sub get_interfaces {
289 my @result;
290 my $PROC_NET_DEV= ('/proc/net/dev');
292 open(PROC_NET_DEV, "<$PROC_NET_DEV")
293 or die "Could not open $PROC_NET_DEV";
295 my @ifs = <PROC_NET_DEV>;
297 close(PROC_NET_DEV);
299 # Eat first two line
300 shift @ifs;
301 shift @ifs;
303 chomp @ifs;
304 foreach my $line(@ifs) {
305 my $if= (split /:/, $line)[0];
306 $if =~ s/^\s+//;
307 push @result, $if;
308 }
310 return @result;
311 }
313 #=== FUNCTION ================================================================
314 # NAME: get_mac
315 # PARAMETERS: interface name (i.e. eth0)
316 # RETURNS: (mac address)
317 # DESCRIPTION: Uses ioctl to get mac address directly from system.
318 #===============================================================================
319 sub get_mac {
320 my $ifreq= shift;
321 my $result;
322 if ($ifreq && length($ifreq) > 0) {
323 if($ifreq eq "all") {
324 $result = "00:00:00:00:00:00";
325 } else {
326 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
328 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
329 or die "socket: $!";
331 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
332 my ($if, $mac)= unpack 'h36 H12', $ifreq;
334 if (length($mac) > 0) {
335 $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])$/;
336 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
337 $result = $mac;
338 }
339 }
340 }
341 }
342 return $result;
343 }
345 sub get_vendor_for_mac {
346 my $mac=shift;
347 my $result="Unknown Vendor";
349 if(defined($mac)) {
350 my $vendor= Net::MAC::Vendor::fetch_oui_from_cache(Net::MAC::Vendor::normalize_mac($mac));
351 if(length($vendor) > 0) {
352 $result= @{$vendor}[0];
353 }
354 &main::daemon_log("Looking up Vendor for MAC ".$mac.": $result", 4);
355 }
357 return $result;
358 }
360 #=== FUNCTION ================================================================
361 # NAME: add_ldap_entry
362 # PURPOSE: adds an element to ldap-tree
363 # PARAMETERS:
364 # RETURNS: none
365 # DESCRIPTION: ????
366 # THROWS: no exceptions
367 # COMMENTS: none
368 # SEE ALSO: n/a/bin
369 #===============================================================================
370 sub add_ldap_entry {
371 my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip, $interface, $desc) = @_;
372 my $dn = "cn=".$hosts_database->{$mac}->{cn}.",ou=incoming,$ldap_base";
373 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
374 my $c_res = (defined($s_res))?$s_res->count:0;
375 if($c_res == 1) {
376 &main::daemon_log("WARNING: macAddress $mac already in LDAP", 1);
377 return;
378 } elsif($c_res > 0) {
379 &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
380 return;
381 }
383 # create LDAP entry
384 my $entry = Net::LDAP::Entry->new( $dn );
385 $entry->dn($dn);
386 $entry->add("objectClass" => "goHard");
387 $entry->add("cn" => $hosts_database->{$mac}->{cn});
388 $entry->add("macAddress" => $mac);
389 if(defined $gotoSysStatus) {$entry->add("gotoSysStatus" => $gotoSysStatus)}
390 if(defined $ip) {$entry->add("ipHostNumber" => $ip) }
391 #if(defined $interface) { }
392 if(defined $desc) {$entry->add("description" => $desc) }
394 # submit entry to LDAP
395 my $result = $entry->update ($ldap_tree);
397 # for $result->code constants please look at Net::LDAP::Constant
398 if($result->code == 68) { # entry already exists
399 &main::daemon_log("WARNING: $dn ".$result->error, 3);
400 } elsif($result->code == 0) { # everything went fine
401 &main::daemon_log("add entry $dn to ldap", 1);
402 } else { # if any other error occur
403 &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
404 }
405 return;
406 }
409 #=== FUNCTION ================================================================
410 # NAME: change_ldap_entry
411 # PURPOSE: ????
412 # PARAMETERS: ????
413 # RETURNS: ????
414 # DESCRIPTION: ????
415 # THROWS: no exceptions
416 # COMMENTS: none
417 # SEE ALSO: n/a
418 #===============================================================================
419 sub change_ldap_entry {
420 my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip) = @_;
422 # check if ldap_entry exists or not
423 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
424 my $c_res = (defined $s_res)?$s_res->count:0;
425 if($c_res == 0) {
426 &main::daemon_log("WARNING: macAddress $mac not in LDAP", 1);
427 return;
428 } elsif($c_res > 1) {
429 &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
430 return;
431 }
433 my $s_res_entry = $s_res->pop_entry();
434 my $dn = $s_res_entry->dn();
435 my $replace = {
436 'gotoSysStatus' => $gotoSysStatus,
437 };
438 if (defined($ip)) {
439 $replace->{'ipHostNumber'} = $ip;
440 }
441 my $result = $ldap->modify( $dn, replace => $replace );
443 # for $result->code constants please look at Net::LDAP::Constant
444 if($result->code == 32) { # entry doesnt exists
445 &add_ldap_entry($mac, $gotoSysStatus);
446 } elsif($result->code == 0) { # everything went fine
447 &main::daemon_log("entry $dn changed successful", 1);
448 } else { # if any other error occur
449 &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
450 }
452 return;
453 }
455 #=== FUNCTION ================================================================
456 # NAME: search_ldap_entry
457 # PURPOSE: ????
458 # PARAMETERS: [Net::LDAP] $ldap_tree - object of an ldap-tree
459 # string $sub_tree - dn of the subtree the search is performed
460 # string $search_string - either a string or a Net::LDAP::Filter object
461 # RETURNS: [Net::LDAP::Search] $msg - result object of the performed search
462 # DESCRIPTION: ????
463 # THROWS: no exceptions
464 # COMMENTS: none
465 # SEE ALSO: n/a
466 #===============================================================================
467 sub search_ldap_entry {
468 my ($ldap_tree, $sub_tree, $search_string) = @_;
469 my $msg;
470 if(defined($ldap_tree)) {
471 $msg = $ldap_tree->search( # perform a search
472 base => $sub_tree,
473 filter => $search_string,
474 ) or &main::daemon_log("cannot perform search at ldap: $@", 1);
475 #if(defined $msg) {
476 # print $sub_tree."\t".$search_string."\t";
477 # print $msg->count."\n";
478 # foreach my $entry ($msg->entries) { $entry->dump; };
479 #}
480 }
481 return $msg;
482 }
483 # $ldap = Net::LDAP->new( "localhost" ) or die "$@";
484 # $ldap->bind($bind_phrase,
485 # password => $password,
486 # ) ;
487 #
488 # switch($arp_sig) {
489 # case 0 {&change_ldap_entry($ldap, $ldap_base,
490 # $mac, "ip-changed",
491 # )}
492 # case 1 {&change_ldap_entry($ldap, $ldap_base,
493 # $mac, "mac-not-whitelisted",
494 # )}
495 # case 2 {&change_ldap_entry($ldap, $ldap_base,
496 # $mac, "mac-in-blacklist",
497 # )}
498 # case 3 {&add_ldap_entry($ldap, $ldap_base,
499 # $mac, "new-mac-address", $ip,
500 # $interface, $desc,
501 # )}
502 # case 4 {&change_ldap_entry($ldap, $ldap_base,
503 # $mac, "unauthorized-arp-request",
504 # )}
505 # case 5 {&change_ldap_entry($ldap, $ldap_base,
506 # $mac, "abusive-number-of-arp-requests",
507 # )}
508 # case 6 {&change_ldap_entry($ldap, $ldap_base,
509 # $mac, "ether-and-arp-mac-differs",
510 # )}
511 # case 7 {&change_ldap_entry($ldap, $ldap_base,
512 # $mac, "flood-detected",
513 # )}
514 # case 8 {&add_ldap_entry($ldap, $ldap_base,
515 # $mac, $ip, "new-system",
516 # )}
517 # case 9 {&change_ldap_entry($ldap, $ldap_base,
518 # $mac, "mac-changed",
519 # )}
520 # }
521 #
522 #
523 # ldap search
524 # my $base_phrase = "dc=gonicus,dc=de";
525 # my $filter_phrase = "cn=keinesorge";
526 # my $attrs_phrase = "cn macAdress";
527 # my $msg_search = $ldap->search( base => $base_phrase,
528 # filter => $filter_phrase,
529 # attrs => $attrs_phrase,
530 # );
531 # $msg_search->code && die $msg_search->error;
532 #
533 # my @entries = $msg_search->entries;
534 # my $max = $msg_search->count;
535 # print "anzahl der entries: $max\n";
536 # my $i;
537 # for ( $i = 0 ; $i < $max ; $i++ ) {
538 # my $entry = $msg_search->entry ( $i );
539 # foreach my $attr ( $entry->attributes ) {
540 # if( not $attr eq "cn") {
541 # next;
542 # }
543 # print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n\n";
544 # }
545 # }
546 #
547 # # ldap add
548 #
549 #
550 # $ldap->unbind;
551 # exit;
553 1;