1 #!/usr/bin/perl
2 #===============================================================================
3 #
4 # FILE: gosa-server
5 #
6 # USAGE: gosa-si-client
7 #
8 # DESCRIPTION:
9 #
10 # OPTIONS: ---
11 # REQUIREMENTS: libnetaddr-ip-perl
12 # BUGS: ---
13 # NOTES:
14 # AUTHOR: (Andreas Rettenberger), <rettenberger@gonicus.de>
15 # COMPANY:
16 # VERSION: 1.0
17 # CREATED: 12.09.2007 08:54:41 CEST
18 # REVISION: ---
19 #===============================================================================
21 use strict;
22 use warnings;
23 use Getopt::Long;
24 use Config::IniFiles;
25 use POSIX;
26 use Time::HiRes qw( gettimeofday );
28 use Fcntl;
29 use IO::Socket::INET;
30 use Crypt::Rijndael;
31 use MIME::Base64;
32 use Digest::MD5 qw(md5 md5_hex md5_base64);
33 use XML::Simple;
34 use Data::Dumper;
35 use Sys::Syslog qw( :DEFAULT setlogsock);
36 use File::Spec;
37 use Cwd;
38 use NetAddr::IP;
39 use GOSA::GosaSupportDaemon;
42 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
43 my ($server_address, $server_ip, $server_port, $server_domain, $server_passwd, $server_cipher, $server_timeout);
44 my ($client_address, $client_ip, $client_port, $client_mac_address, $network_interface, $ldap_config, $pam_config, $nss_config);
45 my ($input_socket, $rbits, $wbits, $ebits, $xml, $known_hosts, $ldap_enabled);
46 my (@events);
48 # default variables
49 my $event_dir = "/usr/lib/gosa-si/client/events";
50 $known_hosts = {};
51 $foreground = 0 ;
52 %cfg_defaults =
53 ("general" =>
54 {"log_file" => [\$log_file, "/var/run/".$0.".log"],
55 "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
56 },
57 "client" =>
58 {"client_port" => [\$client_port, "20083"],
59 "client_ip" => [\$client_ip, "0.0.0.0"],
60 "ldap" => [\$ldap_enabled, 1],
61 "ldap_config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
62 "pam_config" => [\$pam_config, "/etc/pam_ldap.conf"],
63 "nss_config" => [\$nss_config, "/etc/libnss_ldap.conf"],
64 },
65 "server" =>
66 {"server_ip" => [\$server_ip, ""],
67 "server_port" => [\$server_port, "20081"],
68 "server_passwd" => [\$server_passwd, ""],
69 "server_timeout" => [\$server_timeout, 10],
70 "server_domain" => [\$server_domain, ""],
71 },
72 );
75 #=== FUNCTION ================================================================
76 # NAME: read_configfile
77 # PARAMETERS: cfg_file - string -
78 # RETURNS:
79 # DESCRIPTION:
80 #===============================================================================
81 sub read_configfile {
82 my $cfg;
83 if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
84 if( -r $cfg_file ) {
85 $cfg = Config::IniFiles->new( -file => $cfg_file );
86 } else {
87 print STDERR "Couldn't read config file!";
88 }
89 } else {
90 $cfg = Config::IniFiles->new() ;
91 }
92 foreach my $section (keys %cfg_defaults) {
93 foreach my $param (keys %{$cfg_defaults{ $section }}) {
94 my $pinfo = $cfg_defaults{ $section }{ $param };
95 ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
96 }
97 }
98 }
101 #=== FUNCTION ================================================================
102 # NAME: logging
103 # PARAMETERS: level - string - default 'info'
104 # msg - string -
105 # facility - string - default 'LOG_DAEMON'
106 # RETURNS:
107 # DESCRIPTION:
108 #===============================================================================
109 sub daemon_log {
110 my( $msg, $level ) = @_;
111 if(not defined $msg) { return }
112 if(not defined $level) { $level = 1 }
113 if(defined $log_file){
114 open(LOG_HANDLE, ">>$log_file");
115 if(not defined open( LOG_HANDLE, ">>$log_file" )) {
116 print STDERR "cannot open $log_file: $!";
117 return }
118 chomp($msg);
119 if($level <= $verbose){
120 print LOG_HANDLE $msg."\n";
121 if(defined $foreground) { print $msg."\n" }
122 }
123 }
124 close( LOG_HANDLE );
125 # my ($msg, $level, $facility) = @_;
126 # if(not defined $msg) {return}
127 # if(not defined $level) {$level = "info"}
128 # if(not defined $facility) {$facility = "LOG_DAEMON"}
129 # openlog($0, "pid,cons,", $facility);
130 # syslog($level, $msg);
131 # closelog;
132 # return;
133 }
136 #=== FUNCTION ================================================================
137 # NAME: check_cmdline_param
138 # PARAMETERS:
139 # RETURNS:
140 # DESCRIPTION:
141 #===============================================================================
142 sub check_cmdline_param () {
143 my $err_config;
144 my $err_counter = 0;
145 if(not defined($cfg_file)) {
146 $cfg_file = "/etc/gosa-si/client.conf";
147 if(! -r $cfg_file) {
148 $err_config = "please specify a config file";
149 $err_counter += 1;
150 }
151 }
152 if( $err_counter > 0 ) {
153 &usage( "", 1 );
154 if( defined( $err_config)) { print STDERR "$err_config\n"}
155 print STDERR "\n";
156 exit( -1 );
157 }
158 }
161 #=== FUNCTION ================================================================
162 # NAME: check_pid
163 # PARAMETERS:
164 # RETURNS:
165 # DESCRIPTION:
166 #===============================================================================
167 sub check_pid {
168 $pid = -1;
169 # Check, if we are already running
170 if( open(LOCK_FILE, "<$pid_file") ) {
171 $pid = <LOCK_FILE>;
172 if( defined $pid ) {
173 chomp( $pid );
174 if( -f "/proc/$pid/stat" ) {
175 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
176 if( $0 eq $stat ) {
177 close( LOCK_FILE );
178 exit -1;
179 }
180 }
181 }
182 close( LOCK_FILE );
183 unlink( $pid_file );
184 }
186 # create a syslog msg if it is not to possible to open PID file
187 if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
188 my($msg) = "Couldn't obtain lockfile '$pid_file' ";
189 if (open(LOCK_FILE, '<', $pid_file)
190 && ($pid = <LOCK_FILE>))
191 {
192 chomp($pid);
193 $msg .= "(PID $pid)\n";
194 } else {
195 $msg .= "(unable to read PID)\n";
196 }
197 if( ! ($foreground) ) {
198 openlog( $0, "cons,pid", "daemon" );
199 syslog( "warning", $msg );
200 closelog();
201 }
202 else {
203 print( STDERR " $msg " );
204 }
205 exit( -1 );
206 }
207 }
209 #=== FUNCTION ================================================================
210 # NAME: get_interface_for_ip
211 # PARAMETERS: ip address (i.e. 192.168.0.1)
212 # RETURNS: array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
213 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
214 #===============================================================================
215 sub get_interface_for_ip {
216 my $result;
217 my $ip= shift;
218 if ($ip && length($ip) > 0) {
219 my @ifs= &get_interfaces();
220 if($ip eq "0.0.0.0") {
221 $result = "all";
222 } else {
223 foreach (@ifs) {
224 my $if=$_;
225 if(get_ip($if) eq $ip) {
226 $result = $if;
227 last;
228 }
229 }
230 }
231 }
232 return $result;
233 }
235 #=== FUNCTION ================================================================
236 # NAME: get_interfaces
237 # PARAMETERS: none
238 # RETURNS: (list of interfaces)
239 # DESCRIPTION: Uses proc fs (/proc/net/dev) to get list of interfaces.
240 #===============================================================================
241 sub get_interfaces {
242 my @result;
243 my $PROC_NET_DEV= ('/proc/net/dev');
245 open(PROC_NET_DEV, "<$PROC_NET_DEV")
246 or die "Could not open $PROC_NET_DEV";
248 my @ifs = <PROC_NET_DEV>;
250 close(PROC_NET_DEV);
252 # Eat first two line
253 shift @ifs;
254 shift @ifs;
256 chomp @ifs;
257 foreach my $line(@ifs) {
258 my $if= (split /:/, $line)[0];
259 $if =~ s/^\s+//;
260 push @result, $if;
261 }
263 return @result;
264 }
266 #=== FUNCTION ================================================================
267 # NAME: get_mac
268 # PARAMETERS: interface name (i.e. eth0)
269 # RETURNS: (mac address)
270 # DESCRIPTION: Uses ioctl to get mac address directly from system.
271 #===============================================================================
272 sub get_mac {
273 my $ifreq= shift;
274 my $result;
275 if ($ifreq && length($ifreq) > 0) {
276 if($ifreq eq "all") {
277 if(defined($server_ip)) {
278 $result = &get_local_mac_for_remote_ip($server_ip);
279 } else {
280 $result = "00:00:00:00:00:00";
281 }
282 } else {
283 my $SIOCGIFHWADDR= 0x8927; # man 2 ioctl_list
285 # A configured MAC Address should always override a guessed value
286 if ($client_mac_address and length($client_mac_address) > 0) {
287 $result= $client_mac_address;
288 }
290 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
291 or die "socket: $!";
293 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
294 my ($if, $mac)= unpack 'h36 H12', $ifreq;
296 if (length($mac) > 0) {
297 $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])$/;
298 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
299 $result = $mac;
300 }
301 }
302 }
303 }
304 return $result;
305 }
307 #=== FUNCTION ================================================================
308 # NAME: get_ip
309 # PARAMETERS: interface name (i.e. eth0)
310 # RETURNS: (ip address)
311 # DESCRIPTION: Uses ioctl to get ip address directly from system.
312 #===============================================================================
313 sub get_ip {
314 my $ifreq= shift;
315 my $result= "";
316 my $SIOCGIFADDR= 0x8915; # man 2 ioctl_list
317 my $proto= getprotobyname('ip');
319 socket SOCKET, PF_INET, SOCK_DGRAM, $proto
320 or die "socket: $!";
322 if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
323 my ($if, $sin) = unpack 'a16 a16', $ifreq;
324 my ($port, $addr) = sockaddr_in $sin;
325 my $ip = inet_ntoa $addr;
327 if ($ip && length($ip) > 0) {
328 $result = $ip;
329 }
330 }
332 return $result;
333 }
335 #=== FUNCTION ================================================================
336 # NAME: get_local_mac_for_remote_ip
337 # PARAMETERS: none (takes server_ip from global variable)
338 # RETURNS: (ip address from interface that is used for communication)
339 # DESCRIPTION: Uses ioctl to get routing table from system, checks which entry
340 # matches (defaultroute last).
341 #===============================================================================
342 sub get_local_mac_for_remote_ip {
343 my $ifreq= shift;
344 my $result= "00:00:00:00:00:00";
345 my $PROC_NET_ROUTE= ('/proc/net/route');
347 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
348 or die "Could not open $PROC_NET_ROUTE";
350 my @ifs = <PROC_NET_ROUTE>;
352 close(PROC_NET_ROUTE);
354 # Eat header line
355 shift @ifs;
356 chomp @ifs;
357 foreach my $line(@ifs) {
358 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
359 my $destination;
360 my $mask;
361 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
362 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
363 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
364 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
365 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
366 # destination matches route, save mac and exit
367 $result= &get_mac($Iface);
368 last;
369 }
370 }
373 return $result;
374 }
376 #=== FUNCTION ================================================================
377 # NAME: usage
378 # PARAMETERS:
379 # RETURNS:
380 # DESCRIPTION:
381 #===============================================================================
382 sub usage {
383 my( $text, $help ) = @_;
384 $text = undef if( "h" eq $text );
385 (defined $text) && print STDERR "\n$text\n";
386 if( (defined $help && $help) || (!defined $help && !defined $text) ) {
387 print STDERR << "EOF" ;
388 usage: $0 [-hvf] [-c config]
390 -h : this (help) message
391 -c <file> : config file
392 -f : foreground, process will not be forked to background
393 -v : be verbose (multiple to increase verbosity)
394 EOF
395 }
396 print "\n" ;
397 }
399 #=== FUNCTION ================================================================
400 # NAME: get_server_addresses
401 # PARAMETERS:
402 # RETURNS:
403 # DESCRIPTION:
404 #===============================================================================
405 sub get_server_addresses {
406 my $domain= shift;
407 my @result;
408 my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
410 my $output= `$dig_cmd 2>&1`;
411 open (PIPE, "$dig_cmd 2>&1 |");
412 while(<PIPE>) {
413 chomp $_;
414 # If it's not a comment
415 if($_ =~ m/^[^;]/) {
416 my @matches= split /\s+/;
418 # Push hostname with port
419 if($matches[3] eq 'SRV') {
420 push @result, $matches[7].':'.$matches[6];
421 } elsif ($matches[3] eq 'A') {
422 my $i=0;
424 # Substitute the hostname with the ip address of the matching A record
425 foreach my $host (@result) {
426 if ((split /\:/, $host)[0] eq $matches[0]) {
427 $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
428 }
429 $i++;
430 }
431 }
432 }
433 }
434 close(PIPE);
435 return @result;
436 }
439 #=== FUNCTION ================================================================
440 # NAME: register_at_server
441 # PARAMETERS:
442 # RETURNS:
443 # DESCRIPTION:
444 #===============================================================================
445 sub register_at_server {
446 my ($tmp) = @_;
448 # create new passwd and ciphering object for client-server communication
449 my $new_server_passwd = &create_passwd();
450 my $new_server_cipher;
452 # detect all client accepted events
453 opendir(DIR, $event_dir)
454 or daemon_log("cannot find directory $event_dir!\ngosa-si-client starts without any accepting events!", 1);
455 my $file_name;
456 my @events_list = ();
457 while(defined($file_name = readdir(DIR))){
458 if ($file_name eq "." || $file_name eq "..") {
459 next;
460 }
461 push(@events_list, $file_name);
462 }
463 my $events = join(",", @events_list);
464 daemon_log("found events: $events", 1);
466 # fill in all possible servers
467 my @servers;
468 if (defined $server_domain) {
469 my @tmp_servers = &get_server_addresses($server_domain);
470 foreach my $server (@tmp_servers) { unshift(@servers, $server); }
471 }
472 # add server address from config file at first position of server list
473 if (defined $server_address) {
474 unshift(@servers, $server_address);
475 }
476 daemon_log("found servers in configuration file and via DNS:", 5);
477 foreach my $server (@servers) {
478 daemon_log("\t$server", 5);
479 }
481 my ($rout, $wout, $reg_server);
482 foreach my $server (@servers) {
484 # create msg hash
485 my $register_hash = &create_xml_hash("here_i_am", $client_address, $server);
486 &add_content2xml_hash($register_hash, "new_passwd", $new_server_passwd);
487 &add_content2xml_hash($register_hash, "mac_address", $client_mac_address);
488 &add_content2xml_hash($register_hash, "events", $events);
490 my $tmp = print Dumper $register_hash;
492 # send xml hash to server with general server passwd
493 my $answer = &send_msg_hash2address($register_hash, $server, $server_passwd);
495 if ($answer != 0) { next; }
497 # waiting for response
498 daemon_log("waiting for response...\n", 5);
499 my $nf = select($rout=$rbits, $wout=$wbits, undef, $server_timeout);
501 # something is coming in
502 if(vec $rout, fileno $input_socket, 1) {
503 my $crypted_msg;
504 my $client = $input_socket->accept();
505 my $other_end = getpeername($client);
506 if(not defined $other_end) {
507 daemon_log("client cannot be identified: $!\n");
508 } else {
509 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
510 my $actual_ip = inet_ntoa($iaddr);
511 daemon_log("\naccept client from $actual_ip\n", 5);
512 my $in_msg = &read_from_socket($client);
513 if(defined $in_msg){
514 chomp($in_msg);
515 $crypted_msg = $in_msg;
516 } else {
517 daemon_log("cannot read from $actual_ip\n", 5);
518 }
519 }
520 close($client);
522 # validate acknowledge msg from server
523 $new_server_cipher = &create_ciphering($new_server_passwd);
524 my $msg_hash;
525 eval {
526 my $decrypted_msg = &decrypt_msg($crypted_msg, $new_server_cipher);
527 daemon_log("decrypted register msg: $decrypted_msg", 5);
528 $msg_hash = $xml->XMLin($decrypted_msg, ForceArray=>1);
529 };
530 if($@) {
531 daemon_log("ERROR: do not understand the incoming message:" , 5);
532 daemon_log("$@", 7);
533 } else {
534 my $header = @{$msg_hash->{header}}[0];
535 if($header eq "registered") {
536 $reg_server = $server;
537 last;
538 } elsif($header eq "denied") {
539 my $reason = (&get_content_from_xml_hash($msg_hash, "denied"))[0];
540 daemon_log("registration at $server denied: $reason", 1);
541 } else {
542 daemon_log("cannot register at $server", 1);
543 }
544 }
545 }
546 # if no answer arrive, try next server in list
548 }
550 if(defined $reg_server) {
551 daemon_log("registered at $reg_server", 1);
552 } else {
553 daemon_log("cannot register at any server", 1);
554 daemon_log("exiting!!!", 1);
555 exit(1);
556 }
558 # update the global available variables
559 $server_address = $reg_server;
560 $server_passwd = $new_server_passwd;
561 $server_cipher = $new_server_cipher;
562 return;
563 }
566 #=== FUNCTION ================================================================
567 # NAME: create_xml_hash
568 # PARAMETERS:
569 # RETURNS:
570 # DESCRIPTION:
571 #===============================================================================
572 #sub create_xml_hash {
573 # my ($header, $source, $target, $header_value) = @_;
574 # my $hash = {
575 # header => [$header],
576 # source => [$source],
577 # target => [$target],
578 # $header => [$header_value],
579 # };
580 # daemon_log("create_xml_hash:", 7),
581 # chomp(my $tmp = Dumper $hash);
582 # daemon_log("\t$tmp\n", 7);
583 # return $hash
584 #}
587 #=== FUNCTION ================================================================
588 # NAME: create_xml_string
589 # PARAMETERS:
590 # RETURNS:
591 # DESCRIPTION:
592 #===============================================================================
593 #sub create_xml_string {
594 # my ($xml_hash) = @_ ;
595 # my $xml_string = $xml->XMLout($xml_hash, RootName => 'xml');
596 # $xml_string =~ s/[\n]+//g;
597 # daemon_log("create_xml_string:\n\t$xml_string\n", 7);
598 # return $xml_string;
599 #}
602 #=== FUNCTION ================================================================
603 # NAME: add_content2xml_hash
604 # PARAMETERS:
605 # RETURNS:
606 # DESCRIPTION:
607 #===============================================================================
608 #sub add_content2xml_hash {
609 # my ($xml_ref, $element, $content) = @_;
610 # if(not exists $$xml_ref{$element} ) {
611 # $$xml_ref{$element} = [];
612 # }
613 # my $tmp = $$xml_ref{$element};
614 # push(@$tmp, $content);
615 # return;
616 #}
619 #=== FUNCTION ================================================================
620 # NAME: get_content_from_xml_hash
621 # PARAMETERS: ref : reference to the xml hash
622 # string: key of the value you want
623 # RETURNS: STRING AND ARRAY
624 # DESCRIPTION: if key of the hash is either 'header', 'target' or 'source' the
625 # function returns a string cause it is expected that these keys
626 # do just have one value, all other keys returns an array!!!
627 #===============================================================================
628 #sub get_content_from_xml_hash {
629 # my ($xml_ref, $element) = @_;
630 # my $result = $xml_ref->{$element};
631 # if( $element eq "header" || $element eq "target" || $element eq "source") {
632 # return @$result[0];
633 # }
634 # return @$result;
635 #}
637 # my ($xml_ref, $element) = @_;
638 # if (exists $xml_ref->{$element}) {
639 # my $result = $xml_ref->{$element};
640 # if( $element eq "header" || $element eq "target" || $element eq "source") {
641 # return @$result[0];
642 # } else {
643 # return @$result;
644 # }
645 #
646 # } else {
647 # my $result = ();
648 # return @$result;
649 # }
650 #}
653 #=== FUNCTION ================================================================
654 # NAME: encrypt_msg
655 # PARAMETERS:
656 # RETURNS:
657 # DESCRIPTION:
658 #===============================================================================
659 #sub encrypt_msg {
660 # my ($msg, $my_cipher) = @_;
661 # if(not defined $my_cipher) { print "no cipher object\n"; }
662 # $msg = "\0"x(16-length($msg)%16).$msg;
663 # my $crypted_msg = $my_cipher->encrypt($msg);
664 # chomp($crypted_msg = &encode_base64($crypted_msg));
665 # return $crypted_msg;
666 #}
669 #=== FUNCTION ================================================================
670 # NAME: decrypt_msg
671 # PARAMETERS:
672 # RETURNS:
673 # DESCRIPTION:
674 #===============================================================================
675 #sub decrypt_msg {
676 # my ($crypted_msg, $my_cipher) = @_ ;
677 # $crypted_msg = &decode_base64($crypted_msg);
678 # my $msg = $my_cipher->decrypt($crypted_msg);
679 # $msg =~ s/\0*//g;
680 # return $msg;
681 #}
684 #=== FUNCTION ================================================================
685 # NAME: create_ciphering
686 # PARAMETERS:
687 # RETURNS: cipher object
688 # DESCRIPTION:
689 #===============================================================================
690 #sub create_ciphering {
691 # my ($passwd) = @_;
692 # $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
693 # my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
694 #
695 # #daemon_log("iv: $iv", 7);
696 # #daemon_log("key: $passwd", 7);
697 # my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
698 # $my_cipher->set_iv($iv);
699 # return $my_cipher;
700 #}
703 #=== FUNCTION ================================================================
704 # NAME: create_passwd
705 # PARAMETERS:
706 # RETURNS: cipher object
707 # DESCRIPTION:
708 #===============================================================================
709 sub create_passwd {
710 my $new_passwd = "";
711 for(my $i=0; $i<31; $i++) {
712 $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
713 }
715 return $new_passwd;
716 }
719 #=== FUNCTION ================================================================
720 # NAME: send_msg_hash2address
721 # PARAMETERS: msg string - xml message
722 # PeerAddr string - socket address to send msg
723 # PeerPort string - socket port, if not included in socket address
724 # RETURNS: nothing
725 # DESCRIPTION: ????
726 #===============================================================================
727 #sub send_msg_hash2address {
728 # my ($msg_hash, $address, $passwd) = @_ ;
729 #
730 # # fetch header for logging
731 # my $header = @{$msg_hash->{header}}[0];
732 #
733 # # generiere xml string
734 # my $msg_xml = &create_xml_string($msg_hash);
735 #
736 # # hole das entsprechende passwd aus dem hash
737 # if(not defined $passwd) {
738 # if(exists $known_hosts->{$address}) {
739 # $passwd = $known_hosts->{$address}->{passwd};
740 # } elsif ($address eq $server_address) {
741 # $passwd = $server_passwd;
742 # } else {
743 # daemon_log("$address not known, neither as server nor as client", 1);
744 # return "failed";
745 # }
746 # }
747 #
748 # # erzeuge ein ciphering object
749 # my $act_cipher = &create_ciphering($passwd);
750 #
751 # # encrypt xml msg
752 # my $crypted_msg = &encrypt_msg($msg_xml, $act_cipher);
753 #
754 # # öffne socket
755 # my $socket = &open_socket($address);
756 # if(not defined $socket){
757 # daemon_log("cannot open socket to $address, server not reachable", 1);
758 # daemon_log("cannot send '$header'-msg", 1);
759 # return "failed";
760 # }
761 #
762 # # versende xml msg
763 # print $socket $crypted_msg."\n";
764 #
765 # # schlieĂźe socket
766 # close $socket;
767 #
768 # daemon_log("send '$header'-msg to $address", 5);
769 # daemon_log("crypted_msg:\n\t$crypted_msg", 7);
770 #
771 # return "done";
772 #}
775 #=== FUNCTION ================================================================
776 # NAME: open_socket
777 # PARAMETERS: PeerAddr string something like 192.168.1.1 or 192.168.1.1:10000
778 # [PeerPort] string necessary if port not appended by PeerAddr
779 # RETURNS: socket IO::Socket::INET
780 # DESCRIPTION:
781 #===============================================================================
782 sub open_socket {
783 my ($PeerAddr, $PeerPort) = @_ ;
784 if(defined($PeerPort)){
785 $PeerAddr = $PeerAddr.":".$PeerPort;
786 }
787 my $socket;
788 $socket = new IO::Socket::INET(PeerAddr => $PeerAddr ,
789 Porto => "tcp" ,
790 Type => SOCK_STREAM,
791 Timeout => 5,
792 );
793 if(not defined $socket) {
794 #daemon_log("cannot connect to socket at $PeerAddr, $@\n");
795 return;
796 }
797 daemon_log("open_socket:\n\t$PeerAddr", 7);
798 return $socket;
799 }
802 #=== FUNCTION ================================================================
803 # NAME: read_from_socket
804 # PARAMETERS: socket fh -
805 # RETURNS: result string - readed characters from socket
806 # DESCRIPTION: reads data from socket in 16 byte steps
807 #===============================================================================
808 sub read_from_socket {
809 my ($socket) = @_;
810 my $result = "";
812 $socket->blocking(1);
813 $result = <$socket>;
815 $socket->blocking(0);
816 while ( my $char = <$socket> ) {
817 if (not defined $char) { last }
818 $result .= $char;
819 }
820 return $result;
824 # my ($socket) = @_;
825 # my $result = "";
826 # my $len = 16;
827 # while($len == 16){
828 # my $char;
829 # $len = sysread($socket, $char, 16);
830 # if($len != 16) { last }
831 # if($len != 16) { last }
832 # $result .= $char;
833 # }
834 # return $result;
835 }
838 #=== FUNCTION ================================================================
839 # NAME: print_known_hosts_hash
840 # PARAMETERS:
841 # RETURNS:
842 # DESCRIPTION:
843 #===============================================================================
844 sub print_known_hosts_hash {
845 my ($tmp) = @_;
846 print "####################################\n";
847 print "# status of known_hosts\n";
848 my $hosts;
849 my $host_hash;
850 my @hosts = keys %$known_hosts;
851 foreach my $host (@hosts) {
852 #my @elements = keys %$known_hosts->{$host};
853 my $status = $known_hosts->{$host}->{status} ;
854 my $passwd = $known_hosts->{$host}->{passwd};
855 my $timestamp = $known_hosts->{$host}->{timestamp};
856 print "$host\n";
857 print "\t$status\n";
858 print "\t$passwd\n";
859 print "\t$timestamp\n";
860 }
861 print "####################################\n";
862 return;
863 }
865 #=== FUNCTION ================================================================
866 # NAME:
867 # PARAMETERS:
868 # RETURNS:
869 # DESCRIPTION:
870 #===============================================================================
871 sub create_known_hosts_entry {
872 my ($hostname) = @_;
873 $known_hosts->{$hostname} = {};
874 $known_hosts->{$hostname}->{status} = "none";
875 $known_hosts->{$hostname}->{passwd} = "none";
876 $known_hosts->{$hostname}->{timestamp} = "none";
877 return;
878 }
881 #=== FUNCTION ================================================================
882 # NAME:
883 # PARAMETERS:
884 # RETURNS:
885 # DESCRIPTION:
886 #===============================================================================
887 sub update_known_hosts_entry {
888 my ($hostname, $status, $passwd, $timestamp) = @_;
889 my ($seconds, $minutes, $hours, $monthday, $month,
890 $year, $weekday, $yearday, $sommertime) = localtime(time);
891 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
892 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
893 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
894 $month+=1;
895 $month = $month < 10 ? $month = "0".$month : $month;
896 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
897 $year+=1900;
898 my $t = "$year$month$monthday$hours$minutes$seconds";
900 if($status) {
901 $known_hosts->{$hostname}->{status} = $status;
902 }
903 if($passwd) {
904 $known_hosts->{$hostname}->{passwd} = $passwd;
905 }
906 if($timestamp) {
907 $t = $timestamp;
908 }
909 $known_hosts->{$hostname}->{timestamp} = $t;
910 return;
911 }
914 #=== FUNCTION ================================================================
915 # NAME:
916 # PARAMETERS:
917 # RETURNS:
918 # DESCRIPTION:
919 #===============================================================================
920 sub add_content2known_hosts {
921 my ($hostname, $element, $content) = @_;
922 my ($seconds, $minutes, $hours, $monthday, $month,
923 $year, $weekday, $yearday, $sommertime) = localtime(time);
924 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
925 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
926 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
927 $month+=1;
928 $month = $month < 10 ? $month = "0".$month : $month;
929 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
930 $year+=1900;
931 my $t = "$year$month$monthday$hours$minutes$seconds";
933 $known_hosts->{$hostname}->{$element} = $content;
934 $known_hosts->{$hostname}->{timestamp} = $t;
935 return;
936 }
939 #=== FUNCTION ================================================================
940 # NAME:
941 # PARAMETERS:
942 # RETURNS:
943 # DESCRIPTION:
944 #===============================================================================
945 sub process_incoming_msg {
946 my ($crypted_msg) = @_;
947 if(not defined $crypted_msg) {
948 daemon_log("function 'process_incoming_msg': got no msg", 7);
949 }
950 $crypted_msg =~ /^([\s\S]*?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)\.(\d{1,3}?)$/;
951 $crypted_msg = $1;
952 my $host = sprintf("%s.%s.%s.%s", $2, $3, $4, $5);
953 daemon_log("msg from host:", 1);
954 daemon_log("\t$host", 1);
955 daemon_log("crypted msg:", 7);
956 daemon_log("\t$crypted_msg", 7);
958 my $act_cipher = &create_ciphering($server_passwd);
960 # try to decrypt incoming msg
961 my ($msg, $msg_hash);
962 eval{
963 $msg = &decrypt_msg($crypted_msg, $act_cipher);
964 $msg_hash = $xml->XMLin($msg, ForceArray=>1);
965 };
966 if($@) {
967 daemon_log("ERROR: incoming msg cannot be decrypted with server passwd", 1);
968 return;
969 }
971 my $header = @{$msg_hash->{header}}[0];
973 daemon_log("receive '$header' from $host", 1);
974 # daemon_log("header from msg:", 1);
975 # daemon_log("\t$header", 1);
976 # daemon_log("msg to process:", 7);
977 # daemon_log("\t$msg", 7);
979 #check whether msg to process is a event
980 opendir(DIR, $event_dir)
981 or daemon_log("cannot find directory $event_dir, no events specified", 5);
982 my $file_name;
983 while(defined($file_name = readdir(DIR))){
984 if ($file_name eq "." || $file_name eq "..") {
985 next;
986 }
987 if ($file_name eq $header) {
988 my $cmd = "$event_dir/$file_name '$msg'";
989 my $result_xml = "";
990 open(PIPE, "$cmd 2>&1 |");
991 while(<PIPE>) {
992 $result_xml.=$_;
993 last;
994 }
995 close(PIPE);
996 my $res_hash = &transform_msg2hash($result_xml);
997 my $res_target = @{$res_hash->{target}}[0];
998 &send_msg_hash2address($res_hash, $server_address);
1000 return;
1001 }
1002 }
1003 close(DIR);
1004 daemon_log("could not assign the msg $header to an event", 5);
1006 if ($header eq 'new_ldap_config') { if ($ldap_enabled == 1) {&new_ldap_config($msg_hash)}}
1007 elsif ($header eq 'ping') { &got_ping($msg_hash) }
1008 elsif ($header eq 'wake_up') { &execute_event($msg_hash)}
1009 elsif ($header eq 'new_passwd') { &new_passwd()}
1010 else { daemon_log("ERROR: no function assigned to msg $header", 5) }
1012 return;
1013 }
1016 #=== FUNCTION ================================================================
1017 # NAME:
1018 # PARAMETERS:
1019 # RETURNS:
1020 # DESCRIPTION:
1021 #===============================================================================
1022 sub update_status {
1023 my ($new_status) = @_ ;
1024 my $out_hash = &create_xml_hash("update_status", $client_address, $server_address);
1025 &add_content2xml_hash($out_hash, "update_status", $new_status);
1026 &send_msg_hash2address($out_hash, $server_address);
1027 return;
1028 }
1031 #=== FUNCTION ================================================================
1032 # NAME:
1033 # PARAMETERS:
1034 # RETURNS:
1035 # DESCRIPTION:
1036 #===============================================================================
1037 sub server_leaving {
1038 my ($msg_hash) = @_ ;
1039 my $source = &get_content_from_xml_hash("source");
1040 my $header = &get_content_from_xml_hash("header");
1042 daemon_log("gosa daemon $source is going down, cause registration procedure", 1);
1043 my $server_address = "none";
1044 my $server_passwd = "none";
1045 my $server_cipher = "none";
1047 # reinitialization of default values in config file
1048 &read_configfile;
1050 # registrated at new daemon
1051 ®ister_at_server();
1053 return;
1054 }
1057 sub got_ping {
1058 my ($msg_hash) = @_ ;
1060 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1061 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1062 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1064 &add_content2known_hosts(hostname=>$target, status=>$header);
1066 my $out_hash = &create_xml_hash("got_ping", $target, $source);
1067 &send_msg_hash2address($out_hash, $source, $server_passwd);
1069 return;
1070 }
1073 sub new_ldap_config {
1074 my ($msg_hash) = @_ ;
1075 my $element;
1076 my @ldap_uris;
1077 my $ldap_base;
1078 my @ldap_options;
1079 my @pam_options;
1080 my @nss_options;
1081 my $goto_admin;
1082 my $goto_secret;
1084 # Transform input into array
1085 while ( my ($key, $value) = each(%$msg_hash) ) {
1086 if ($key =~ /^(source|target|header)$/) {
1087 next;
1088 }
1090 foreach $element (@$value) {
1091 if ($key =~ /^ldap_uri$/) {
1092 push (@ldap_uris, $element);
1093 next;
1094 }
1095 if ($key =~ /^ldap_base$/) {
1096 $ldap_base= $element;
1097 next;
1098 }
1099 if ($key =~ /^goto_admin$/) {
1100 $goto_admin= $element;
1101 next;
1102 }
1103 if ($key =~ /^goto_secret$/) {
1104 $goto_secret= $element;
1105 next;
1106 }
1107 if ($key =~ /^ldap_cfg$/) {
1108 push (@ldap_options, "$element");
1109 next;
1110 }
1111 if ($key =~ /^pam_cfg$/) {
1112 push (@pam_options, "$element");
1113 next;
1114 }
1115 if ($key =~ /^nss_cfg$/) {
1116 push (@nss_options, "$element");
1117 next;
1118 }
1119 }
1120 }
1122 # Setup ldap.conf
1123 my $file1;
1124 my $file2;
1125 open(file1, "> $ldap_config");
1126 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1127 print file1 "URI";
1128 foreach $element (@ldap_uris) {
1129 print file1 " $element";
1130 }
1131 print file1 "\nBASE $ldap_base\n";
1132 foreach $element (@ldap_options) {
1133 print file1 "$element\n";
1134 }
1135 close (file1);
1136 daemon_log("wrote $ldap_config", 5);
1138 # Setup pam_ldap.conf / libnss_ldap.conf
1139 open(file1, "> $pam_config");
1140 open(file2, "> $nss_config");
1141 print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1142 print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
1143 print file1 "uri";
1144 print file2 "uri";
1145 foreach $element (@ldap_uris) {
1146 print file1 " $element";
1147 print file2 " $element";
1148 }
1149 print file1 "\nbase $ldap_base\n";
1150 print file2 "\nbase $ldap_base\n";
1151 foreach $element (@pam_options) {
1152 print file1 "$element\n";
1153 }
1154 foreach $element (@nss_options) {
1155 print file2 "$element\n";
1156 }
1157 close (file2);
1158 daemon_log("wrote $nss_config", 5);
1159 close (file1);
1160 daemon_log("wrote $pam_config", 5);
1162 # Create goto.secrets if told so
1163 if (defined $goto_admin){
1164 open(file1, "> /etc/goto/secret");
1165 close(file1);
1166 chown(0,0, "/etc/goto/secret");
1167 chmod(0600, "/etc/goto/secret");
1168 open(file1, "> /etc/goto/secret");
1169 print file1 $goto_admin.":".$goto_secret."\n";
1170 close(file1);
1171 daemon_log("wrote /etc/goto/secret", 5);
1172 }
1174 return;
1176 }
1179 sub execute_event {
1180 my ($msg_hash)= @_;
1181 my $configdir= '/etc/gosa-si/client/events/';
1182 my $result;
1184 my $header = &get_content_from_xml_hash($msg_hash, 'header');
1185 my $source = &get_content_from_xml_hash($msg_hash, 'source');
1186 my $target = &get_content_from_xml_hash($msg_hash, 'target');
1189 if((not defined $source)
1190 && (not defined $target)
1191 && (not defined $header)) {
1192 daemon_log("ERROR: Entries missing in XML msg for gosa events under $configdir");
1193 } else {
1194 my $parameters="";
1195 my @params = &get_content_from_xml_hash($msg_hash, $header);
1196 my $params = join(", ", @params);
1197 daemon_log("execute_event: got parameters: $params", 5);
1199 if (@params) {
1200 foreach my $param (@params) {
1201 my $param_value = (&get_content_from_xml_hash($msg_hash, $param))[0];
1202 daemon_log("execute_event: parameter -> value: $param -> $param_value", 7);
1203 $parameters.= " ".$param_value;
1204 }
1205 }
1207 my $cmd= $configdir.$header."$parameters";
1208 daemon_log("execute_event: executing cmd: $cmd", 7);
1209 $result= "";
1210 open(PIPE, "$cmd 2>&1 |");
1211 while(<PIPE>) {
1212 $result.=$_;
1213 }
1214 close(PIPE);
1215 }
1217 # process the event result
1220 return;
1221 }
1224 sub new_passwd {
1225 # my ($msg_hash) = @_ ;
1226 my $new_server_passwd = &create_passwd();
1227 my $new_server_cipher = &create_ciphering($new_server_passwd);
1229 my $out_hash = &create_xml_hash("new_passwd", $client_address, $server_address, $new_server_passwd);
1231 &send_msg_hash2address($out_hash, $server_address, $server_passwd);
1233 $server_passwd = $new_server_passwd;
1234 $server_cipher = $new_server_cipher;
1235 return;
1236 }
1241 #==== MAIN = main ==============================================================
1243 # parse commandline options
1244 Getopt::Long::Configure( "bundling" );
1245 GetOptions("h|help" => \&usage,
1246 "c|config=s" => \$cfg_file,
1247 "f|foreground" => \$foreground,
1248 "v|verbose+" => \$verbose,
1249 );
1251 # read and set config parameters
1252 &check_cmdline_param ;
1253 &read_configfile;
1254 &check_pid;
1256 if ( ! $foreground ) {
1257 open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1258 open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1259 open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1260 }
1263 # restart daemon log file
1264 if(-e $log_file ) { unlink $log_file }
1265 daemon_log(" ", 1);
1266 daemon_log("$0 started!", 1);
1268 # Just fork, if we"re not in foreground mode
1269 if( ! $foreground ) { $pid = fork(); }
1270 else { $pid = $$; }
1272 # Do something useful - put our PID into the pid_file
1273 if( 0 != $pid ) {
1274 open( LOCK_FILE, ">$pid_file" );
1275 print LOCK_FILE "$pid\n";
1276 close( LOCK_FILE );
1277 if( !$foreground ) { exit( 0 ) };
1278 }
1280 # detect own ip and mac address
1281 $network_interface= &get_interface_for_ip($client_ip);
1282 $client_mac_address= &get_mac($network_interface);
1284 # ($client_ip, $client_mac_address) = &get_ip_and_mac();
1285 #if (not defined $client_ip) {
1286 # die "EXIT: ip address of $0 could not be detected";
1287 #}
1288 daemon_log("client ip address detected: $client_ip", 1);
1289 daemon_log("client mac address detected: $client_mac_address", 1);
1291 # prepare variables
1292 if (defined $server_ip && defined $server_port) {
1293 $server_address = $server_ip.":".$server_port;
1294 }
1295 $client_address = $client_ip.":".$client_port;
1297 # setup xml parser
1298 $xml = new XML::Simple();
1300 # create input socket
1301 daemon_log(" ", 1);
1302 $rbits = $wbits = $ebits = "";
1303 $input_socket = IO::Socket::INET->new(LocalPort => $client_port,
1304 Type => SOCK_STREAM,
1305 Reuse => 1,
1306 Listen => 20,
1307 );
1308 if(not defined $input_socket){
1309 daemon_log("cannot be a tcp server at $client_port : $@\n");
1310 } else {
1311 daemon_log("start client at $client_address",1) ;
1312 vec($rbits, fileno $input_socket, 1) = 1;
1313 vec($wbits, fileno $input_socket, 1) = 1;
1314 }
1316 # register at server
1317 daemon_log(" ", 1);
1318 ®ister_at_server();
1321 ##############
1322 # Debugging
1323 #############
1324 #sleep(2);
1325 #&update_status("ich_bin_ein_neuer_status");
1327 ###################################
1328 #everything ready, okay, lets start
1329 ###################################
1330 while(1) {
1331 my ($rout, $wout);
1332 my $nf = select($rout=$rbits, $wout=$wbits, undef, undef);
1334 # error handling
1335 if($nf < 0 ) {
1336 }
1338 # something is coming in
1339 if(vec $rout, fileno $input_socket, 1) {
1340 my $client = $input_socket->accept();
1341 my $other_end = getpeername($client);
1343 if(not defined $other_end) {
1344 daemon_log("client cannot be identified: $!");
1345 } else {
1346 my ($port, $iaddr) = unpack_sockaddr_in($other_end);
1347 my $actual_ip = inet_ntoa($iaddr);
1348 daemon_log("accept client from $actual_ip", 5);
1349 my $in_msg = &read_from_socket($client);
1350 if(defined $in_msg){
1351 chomp($in_msg);
1352 $in_msg = $in_msg.".".$actual_ip;
1353 &process_incoming_msg($in_msg);
1355 }
1356 }
1357 }
1358 }