89871783d747d79998ffbc767882e219dcd58f7f
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_enabled, $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;
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) && ( length($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 if(defined($ldap_uri) && length($ldap_uri)>0) {
98 $ldap = Net::LDAP->new($ldap_uri);
99 if (!$ldap) {
100 &main::daemon_log("Could not connect to LDAP Server at $ldap_uri!\n$@", 1);
101 } else {
102 $ldap->bind($ldap_admin_dn, password => $ldap_admin_password);
103 }
104 } else {
105 $ldap=undef;
106 }
108 # When interface is not configured (or 'all'), start arpwatch on all possible interfaces
109 if ((!defined($arp_interface)) || $arp_interface eq 'all') {
110 foreach my $device(&get_interfaces) {
111 # TODO: Need a better workaround for IPv4-to-IPv6 bridges
112 if($device =~ m/^sit\d+$/) {
113 next;
114 }
116 # If device has a valid mac address
117 # TODO: Check if this should be the right way
118 if(not(&get_mac($device) eq "00:00:00:00:00:00")) {
119 &main::daemon_log("Starting ArpWatch on $device", 1);
120 POE::Session->create(
121 inline_states => {
122 _start => sub {
123 &start(@_,$device);
124 },
125 _stop => sub {
126 $ldap->unbind if (defined($ldap));
127 $ldap->disconnect if (defined($ldap));
128 $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
129 },
130 got_packet => \&got_packet,
131 },
132 );
133 }
134 }
135 } else {
136 foreach my $device(split(/[\s,]+/, $arp_interface)) {
137 &main::daemon_log("Starting ArpWatch on $device", 1);
138 POE::Session->create(
139 inline_states => {
140 _start => sub {
141 &start(@_,$device);
142 },
143 _stop => sub {
144 $ldap->unbind if (defined($ldap));
145 $ldap->disconnect if (defined($ldap));
146 $_[KERNEL]->post( sprintf("arp_watch_$device") => 'shutdown' )
147 },
148 got_packet => \&got_packet,
149 },
150 );
151 }
152 }
153 } else {
154 &main::daemon_log("ArpHandler disabled. Not starting any capture processes");
155 }
156 return \@info;
157 }
159 sub process_incoming_msg {
160 return 1;
161 }
163 sub start {
164 my $device = (exists($_[ARG0])?$_[ARG0]:'eth0');
165 POE::Component::ArpWatch->spawn(
166 Alias => sprintf("arp_watch_$device"),
167 Device => $device,
168 Dispatch => 'got_packet',
169 Session => $_[SESSION],
170 );
172 $_[KERNEL]->post( sprintf("arp_watch_$device") => 'run' );
173 }
175 sub got_packet {
176 my ($kernel, $heap, $sender, $packet) = @_[KERNEL, HEAP, SENDER, ARG0];
178 if( $packet->{source_haddr} eq "00:00:00:00:00:00" ||
179 $packet->{source_haddr} eq "ff:ff:ff:ff:ff:ff" ||
180 $packet->{source_ipaddr} eq "0.0.0.0") {
181 return;
182 }
184 my $capture_device = sprintf "%s", $kernel->alias_list($sender) =~ /^arp_watch_(.*)$/;
186 if(!exists($hosts_database->{$packet->{source_haddr}})) {
187 my $dnsresult= $resolver->search($packet->{source_ipaddr});
188 my $dnsname= (defined($dnsresult))?$dnsresult->{answer}[0]->{ptrdname}:$packet->{source_ipaddr};
189 my $ldap_result=&get_host_from_ldap($packet->{source_haddr});
190 if(exists($ldap_result->{dn})) {
191 $hosts_database->{$packet->{source_haddr}}=$ldap_result;
192 $hosts_database->{$packet->{source_haddr}}->{dnsname}= $dnsname;
193 if(!exists($ldap_result->{ipHostNumber})) {
194 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}=$packet->{source_ipaddr};
195 } else {
196 if(!($ldap_result->{ipHostNumber} eq $packet->{source_ipaddr})) {
197 &main::daemon_log(
198 "Current IP Address ".$packet->{source_ipaddr}.
199 " of host ".$hosts_database->{$packet->{source_haddr}}->{dnsname}.
200 " differs from LDAP (".$ldap_result->{ipHostNumber}.")", 4);
201 }
202 }
203 $hosts_database->{$packet->{source_haddr}}->{dnsname}=$dnsname;
204 &main::daemon_log("Host was found in LDAP as ".$ldap_result->{dn}, 8);
205 } else {
206 $hosts_database->{$packet->{source_haddr}}={
207 macAddress => $packet->{source_haddr},
208 ipHostNumber => $packet->{source_ipaddr},
209 dnsname => $dnsname,
210 cn => (($dnsname =~ /^(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}/) ? $dnsname : sprintf "%s", $dnsname =~ /([^\.]+)\./),
211 macVendor => (($lookup_vendor) ? &get_vendor_for_mac($packet->{source_haddr}) : "Unknown Vendor"),
212 };
213 &main::daemon_log("Host was not found in LDAP (".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",6);
214 &main::daemon_log(
215 "New Host ".($hosts_database->{$packet->{source_haddr}}->{dnsname}).
216 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
217 "/".$hosts_database->{$packet->{source_haddr}}->{macAddress},4);
218 &add_ldap_entry(
219 $ldap,
220 $ldap_base,
221 $hosts_database->{$packet->{source_haddr}}->{macAddress},
222 'new-system',
223 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
224 'interface',
225 $hosts_database->{$packet->{source_haddr}}->{macVendor});
226 }
227 $hosts_database->{$packet->{source_haddr}}->{device}= $capture_device;
228 } else {
229 if(!($hosts_database->{$packet->{source_haddr}}->{ipHostNumber} eq $packet->{source_ipaddr})) {
230 &main::daemon_log(
231 "IP Address change of MAC ".$packet->{source_haddr}.
232 ": ".$hosts_database->{$packet->{source_haddr}}->{ipHostNumber}.
233 "->".$packet->{source_ipaddr}, 4);
234 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber}= $packet->{source_ipaddr};
235 &change_ldap_entry(
236 $ldap,
237 $ldap_base,
238 $hosts_database->{$packet->{source_haddr}}->{macAddress},
239 'ip-changed',
240 $hosts_database->{$packet->{source_haddr}}->{ipHostNumber},
241 );
243 }
244 &main::daemon_log("Host already in cache (".($hosts_database->{$packet->{source_haddr}}->{device})."->".($hosts_database->{$packet->{source_haddr}}->{dnsname}).")",8);
245 }
246 }
248 sub get_host_from_ldap {
249 my $mac=shift;
250 my $result={};
252 if(defined($ldap)) {
253 my $ldap_result= &search_ldap_entry(
254 $ldap,
255 $ldap_base,
256 "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))"
257 );
259 if(defined($ldap_result) && $ldap_result->count==1) {
260 if(exists($ldap_result->{entries}[0]) &&
261 exists($ldap_result->{entries}[0]->{asn}->{objectName}) &&
262 exists($ldap_result->{entries}[0]->{asn}->{attributes})) {
264 for my $attribute(@{$ldap_result->{entries}[0]->{asn}->{attributes}}) {
265 if($attribute->{type} eq 'cn') {
266 $result->{cn} = $attribute->{vals}[0];
267 }
268 if($attribute->{type} eq 'macAddress') {
269 $result->{macAddress} = $attribute->{vals}[0];
270 }
271 if($attribute->{type} eq 'dhcpHWAddress') {
272 $result->{dhcpHWAddress} = $attribute->{vals}[0];
273 }
274 if($attribute->{type} eq 'ipHostNumber') {
275 $result->{ipHostNumber} = $attribute->{vals}[0];
276 }
277 }
278 }
279 $result->{dn} = $ldap_result->{entries}[0]->{asn}->{objectName};
280 }
281 }
283 return $result;
284 }
286 #=== FUNCTION ================================================================
287 # NAME: get_interfaces
288 # PARAMETERS: none
289 # RETURNS: (list of interfaces)
290 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
291 #===============================================================================
292 sub get_interfaces {
293 my @result;
294 my $PROC_NET_DEV= ('/proc/net/dev');
296 open(PROC_NET_DEV, "<$PROC_NET_DEV")
297 or die "Could not open $PROC_NET_DEV";
299 my @ifs = <PROC_NET_DEV>;
301 close(PROC_NET_DEV);
303 # Eat first two line
304 shift @ifs;
305 shift @ifs;
307 chomp @ifs;
308 foreach my $line(@ifs) {
309 my $if= (split /:/, $line)[0];
310 $if =~ s/^\s+//;
311 push @result, $if;
312 }
314 return @result;
315 }
317 #=== FUNCTION ================================================================
318 # NAME: get_mac
319 # PARAMETERS: interface name (i.e. eth0)
320 # RETURNS: (mac address)
321 # DESCRIPTION: Uses ioctl to get mac address directly from system.
322 #===============================================================================
323 sub get_mac {
324 my $ifreq= shift;
325 my $result;
326 if ($ifreq && length($ifreq) > 0) {
327 if($ifreq eq "all") {
328 $result = "00:00:00:00:00:00";
329 } else {
330 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
332 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
333 or die "socket: $!";
335 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
336 my ($if, $mac)= unpack 'h36 H12', $ifreq;
338 if (length($mac) > 0) {
339 $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])$/;
340 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
341 $result = $mac;
342 }
343 }
344 }
345 }
346 return $result;
347 }
349 sub get_vendor_for_mac {
350 my $mac=shift;
351 my $result="Unknown Vendor";
353 if(defined($mac)) {
354 my $vendor= Net::MAC::Vendor::fetch_oui_from_cache(Net::MAC::Vendor::normalize_mac($mac));
355 if(length($vendor) > 0) {
356 $result= @{$vendor}[0];
357 }
358 &main::daemon_log("Looking up Vendor for MAC ".$mac.": $result", 4);
359 }
361 return $result;
362 }
364 #=== FUNCTION ================================================================
365 # NAME: add_ldap_entry
366 # PURPOSE: adds an element to ldap-tree
367 # PARAMETERS:
368 # RETURNS: none
369 # DESCRIPTION: ????
370 # THROWS: no exceptions
371 # COMMENTS: none
372 # SEE ALSO: n/a/bin
373 #===============================================================================
374 sub add_ldap_entry {
375 my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip, $interface, $desc) = @_;
376 if(defined($ldap_tree)) {
377 my $dn = "cn=".$hosts_database->{$mac}->{cn}.",ou=incoming,$ldap_base";
378 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
379 my $c_res = (defined($s_res))?$s_res->count:0;
380 if($c_res == 1) {
381 &main::daemon_log("WARNING: macAddress $mac already in LDAP", 1);
382 return;
383 } elsif($c_res > 0) {
384 &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
385 return;
386 }
388 # create LDAP entry
389 my $entry = Net::LDAP::Entry->new( $dn );
390 $entry->dn($dn);
391 $entry->add("objectClass" => "goHard");
392 $entry->add("cn" => $hosts_database->{$mac}->{cn});
393 $entry->add("macAddress" => $mac);
394 if(defined $gotoSysStatus) {$entry->add("gotoSysStatus" => $gotoSysStatus)}
395 if(defined $ip) {$entry->add("ipHostNumber" => $ip) }
396 #if(defined $interface) { }
397 if(defined $desc) {$entry->add("description" => $desc) }
399 # submit entry to LDAP
400 my $result = $entry->update ($ldap_tree);
402 # for $result->code constants please look at Net::LDAP::Constant
403 if($result->code == 68) { # entry already exists
404 &main::daemon_log("WARNING: $dn ".$result->error, 3);
405 } elsif($result->code == 0) { # everything went fine
406 &main::daemon_log("add entry $dn to ldap", 1);
407 } else { # if any other error occur
408 &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
409 }
410 } else {
411 &main::daemon_log("Not adding new Entry: LDAP disabled", 6);
412 }
413 return;
414 }
417 #=== FUNCTION ================================================================
418 # NAME: change_ldap_entry
419 # PURPOSE: ????
420 # PARAMETERS: ????
421 # RETURNS: ????
422 # DESCRIPTION: ????
423 # THROWS: no exceptions
424 # COMMENTS: none
425 # SEE ALSO: n/a
426 #===============================================================================
427 sub change_ldap_entry {
428 my ($ldap_tree, $ldap_base, $mac, $gotoSysStatus, $ip) = @_;
430 if(defined($ldap_tree)) {
431 # check if ldap_entry exists or not
432 my $s_res = &search_ldap_entry($ldap_tree, $ldap_base, "(|(macAddress=$mac)(dhcpHWAddress=ethernet $mac))");
433 my $c_res = (defined $s_res)?$s_res->count:0;
434 if($c_res == 0) {
435 &main::daemon_log("WARNING: macAddress $mac not in LDAP", 1);
436 return;
437 } elsif($c_res > 1) {
438 &main::daemon_log("ERROR: macAddress $mac exists $c_res times in LDAP", 1);
439 return;
440 }
442 my $s_res_entry = $s_res->pop_entry();
443 my $dn = $s_res_entry->dn();
444 my $replace = {
445 'gotoSysStatus' => $gotoSysStatus,
446 };
447 if (defined($ip)) {
448 $replace->{'ipHostNumber'} = $ip;
449 }
450 my $result = $ldap->modify( $dn, replace => $replace );
452 # for $result->code constants please look at Net::LDAP::Constant
453 if($result->code == 32) { # entry doesnt exists
454 &add_ldap_entry($mac, $gotoSysStatus);
455 } elsif($result->code == 0) { # everything went fine
456 &main::daemon_log("entry $dn changed successful", 1);
457 } else { # if any other error occur
458 &main::daemon_log("ERROR: $dn, ".$result->code.", ".$result->error, 1);
459 }
460 } else {
461 &main::daemon_log("Not changing Entry: LDAP disabled", 6);
462 }
464 return;
465 }
467 #=== FUNCTION ================================================================
468 # NAME: search_ldap_entry
469 # PURPOSE: ????
470 # PARAMETERS: [Net::LDAP] $ldap_tree - object of an ldap-tree
471 # string $sub_tree - dn of the subtree the search is performed
472 # string $search_string - either a string or a Net::LDAP::Filter object
473 # RETURNS: [Net::LDAP::Search] $msg - result object of the performed search
474 # DESCRIPTION: ????
475 # THROWS: no exceptions
476 # COMMENTS: none
477 # SEE ALSO: n/a
478 #===============================================================================
479 sub search_ldap_entry {
480 my ($ldap_tree, $sub_tree, $search_string) = @_;
481 my $msg;
482 if(defined($ldap_tree)) {
483 $msg = $ldap_tree->search( # perform a search
484 base => $sub_tree,
485 filter => $search_string,
486 ) or &main::daemon_log("cannot perform search at ldap: $@", 1);
487 #if(defined $msg) {
488 # print $sub_tree."\t".$search_string."\t";
489 # print $msg->count."\n";
490 # foreach my $entry ($msg->entries) { $entry->dump; };
491 #}
492 }
493 return $msg;
494 }
495 # $ldap = Net::LDAP->new( "localhost" ) or die "$@";
496 # $ldap->bind($bind_phrase,
497 # password => $password,
498 # ) ;
499 #
500 # switch($arp_sig) {
501 # case 0 {&change_ldap_entry($ldap, $ldap_base,
502 # $mac, "ip-changed",
503 # )}
504 # case 1 {&change_ldap_entry($ldap, $ldap_base,
505 # $mac, "mac-not-whitelisted",
506 # )}
507 # case 2 {&change_ldap_entry($ldap, $ldap_base,
508 # $mac, "mac-in-blacklist",
509 # )}
510 # case 3 {&add_ldap_entry($ldap, $ldap_base,
511 # $mac, "new-mac-address", $ip,
512 # $interface, $desc,
513 # )}
514 # case 4 {&change_ldap_entry($ldap, $ldap_base,
515 # $mac, "unauthorized-arp-request",
516 # )}
517 # case 5 {&change_ldap_entry($ldap, $ldap_base,
518 # $mac, "abusive-number-of-arp-requests",
519 # )}
520 # case 6 {&change_ldap_entry($ldap, $ldap_base,
521 # $mac, "ether-and-arp-mac-differs",
522 # )}
523 # case 7 {&change_ldap_entry($ldap, $ldap_base,
524 # $mac, "flood-detected",
525 # )}
526 # case 8 {&add_ldap_entry($ldap, $ldap_base,
527 # $mac, $ip, "new-system",
528 # )}
529 # case 9 {&change_ldap_entry($ldap, $ldap_base,
530 # $mac, "mac-changed",
531 # )}
532 # }
533 #
534 #
535 # ldap search
536 # my $base_phrase = "dc=gonicus,dc=de";
537 # my $filter_phrase = "cn=keinesorge";
538 # my $attrs_phrase = "cn macAdress";
539 # my $msg_search = $ldap->search( base => $base_phrase,
540 # filter => $filter_phrase,
541 # attrs => $attrs_phrase,
542 # );
543 # $msg_search->code && die $msg_search->error;
544 #
545 # my @entries = $msg_search->entries;
546 # my $max = $msg_search->count;
547 # print "anzahl der entries: $max\n";
548 # my $i;
549 # for ( $i = 0 ; $i < $max ; $i++ ) {
550 # my $entry = $msg_search->entry ( $i );
551 # foreach my $attr ( $entry->attributes ) {
552 # if( not $attr eq "cn") {
553 # next;
554 # }
555 # print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n\n";
556 # }
557 # }
558 #
559 # # ldap add
560 #
561 #
562 # $ldap->unbind;
563 # exit;
565 1;