Code

417b9263e02e01caf5408fc749ad850e15af7b2b
[gosa.git] / gosa-si / gosa-si-client
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 POE qw(Component::Server::TCP);
29 use IO::Socket::INET;
30 use NetAddr::IP;
31 use Data::Dumper;
32 use Crypt::Rijndael;
33 use GOSA::GosaSupportDaemon;
34 use Digest::MD5  qw(md5_hex md5 md5_base64);
35 use MIME::Base64;
36 use XML::Simple;
37 use Net::DNS;
39 my $event_dir = "/usr/lib/gosa-si/client/events";
40 use lib "/usr/lib/gosa-si/client/events";
42 my ($cfg_file, %cfg_defaults, $foreground, $verbose, $pid_file, $procid, $pid, $log_file);
43 my ($server_ip, $server_port, $server_key, $server_timeout, $server_domain);
44 my ($client_ip, $client_port, $client_mac_address, $ldap_enabled, $ldap_config, $pam_config, $nss_config);
45 my $xml;
46 my $default_server_key;
47 my $event_hash;
48 my @servers;
49 my $gotoHardwareChecksum;
51 # globalise variables which are used in imported events
52 our $cfg_file;
53 our $server_address;
54 our $client_address;
55 our $server_key;
57 # default variables
58 our $REGISTERED_FLAG = 1;
60 %cfg_defaults = (
61 "general" =>
62     {"log_file" => [\$log_file, "/var/run/".$0.".log"],
63     "pid_file" => [\$pid_file, "/var/run/".$0.".pid"],
64     },
65 "client" => 
66     {"client_port" => [\$client_port, "20083"],
67      "client_ip" => [\$client_ip, "0.0.0.0"],
68      "client_mac_address" => [\$client_mac_address, "00:00:00:00:00:00"],
69      "ldap" => [\$ldap_enabled, 1],
70      "ldap_config" => [\$ldap_config, "/etc/ldap/ldap.conf"],
71      "pam_config" => [\$pam_config, "/etc/pam_ldap.conf"],
72      "nss_config" => [\$nss_config, "/etc/libnss_ldap.conf"],
73     },
74 "server" =>
75     {"server_ip" => [\$server_ip, "127.0.0.1"],
76     "server_port" => [\$server_port, "20081"],
77     "server_key" => [\$server_key, ""],
78     "server_timeout" => [\$server_timeout, 10],
79     "server_domain" => [\$server_domain, ""],
80     },
82 );
85 #=== FUNCTIONS = functions =====================================================
87 #===  FUNCTION  ================================================================
88 #         NAME: check_cmdline_param
89 #   PARAMETERS: 
90 #      RETURNS:  
91 #  DESCRIPTION: 
92 #===============================================================================
93 sub check_cmdline_param () {
94     my $err_config;
95     my $err_counter = 0;
96         if(not defined($cfg_file)) {
97                 $cfg_file = "/etc/gosa-si/client.conf";
98                 if(! -r $cfg_file) {
99                         $err_config = "please specify a config file";
100                         $err_counter += 1;
101                 }
102     }
103     if( $err_counter > 0 ) {
104         &usage( "", 1 );
105         if( defined( $err_config)) { print STDERR "$err_config\n"}
106         print STDERR "\n";
107         exit( -1 );
108     }
112 #===  FUNCTION  ================================================================
113 #         NAME:  read_configfile
114 #   PARAMETERS:  cfg_file - string - 
115 #      RETURNS:  
116 #  DESCRIPTION: 
117 #===============================================================================
118 sub read_configfile {
119     my ($cfg_file, %cfg_defaults) = @_ ;
120     my $cfg;
121     if( defined( $cfg_file) && ( length($cfg_file) > 0 )) {
122         if( -r $cfg_file ) {
123             $cfg = Config::IniFiles->new( -file => $cfg_file );
124         } else {
125             print STDERR "Couldn't read config file!";
126         }
127     } else {
128         $cfg = Config::IniFiles->new() ;
129     }
130     foreach my $section (keys %cfg_defaults) {
131         foreach my $param (keys %{$cfg_defaults{ $section }}) {
132             my $pinfo = $cfg_defaults{ $section }{ $param };
133             ${@$pinfo[ 0 ]} = $cfg->val( $section, $param, @$pinfo[ 1 ] );
134         }
135     }
139 #===  FUNCTION  ================================================================
140 #         NAME: check_pid
141 #   PARAMETERS:
142 #      RETURNS:
143 #  DESCRIPTION:
144 #===============================================================================
145 sub check_pid {
146     $pid = -1;
147     # Check, if we are already running
148     if( open(LOCK_FILE, "<$pid_file") ) {
149         $pid = <LOCK_FILE>;
150         if( defined $pid ) {
151             chomp( $pid );
152             if( -f "/proc/$pid/stat" ) {
153                 my($stat) = `cat /proc/$pid/stat` =~ m/$pid \((.+)\).*/;
154                 if( $0 eq $stat ) {
155                     close( LOCK_FILE );
156                     exit -1;
157                 }
158             }
159         }
160         close( LOCK_FILE );
161         unlink( $pid_file );
162     }
164     # create a syslog msg if it is not to possible to open PID file
165     if (not sysopen(LOCK_FILE, $pid_file, O_WRONLY|O_CREAT|O_EXCL, 0644)) {
166         my($msg) = "Couldn't obtain lockfile '$pid_file' ";
167         if (open(LOCK_FILE, '<', $pid_file)
168                 && ($pid = <LOCK_FILE>))
169         {
170             chomp($pid);
171             $msg .= "(PID $pid)\n";
172         } else {
173             $msg .= "(unable to read PID)\n";
174         }
175         if( ! ($foreground) ) {
176             openlog( $0, "cons,pid", "daemon" );
177             syslog( "warning", $msg );
178             closelog();
179         }
180         else {
181             print( STDERR " $msg " );
182         }
183         exit( -1 );
184     }
188 #===  FUNCTION  ================================================================
189 #         NAME:  logging
190 #   PARAMETERS:  level - string - default 'info' 
191 #                msg - string - 
192 #                facility - string - default 'LOG_DAEMON' 
193 #      RETURNS:  
194 #  DESCRIPTION: 
195 #===============================================================================
196 sub daemon_log {
197     # log into log_file
198     my( $msg, $level ) = @_;
199     if(not defined $msg) { return }
200     if(not defined $level) { $level = 1 }
201     if(defined $log_file){
202         open(LOG_HANDLE, ">>$log_file");
203         if(not defined open( LOG_HANDLE, ">>$log_file" )) {
204             print STDERR "cannot open $log_file: $!";
205             return }
206             chomp($msg);
207             if($level <= $verbose){
208                 my ($seconds, $minutes, $hours, $monthday, $month,
209                         $year, $weekday, $yearday, $sommertime) = localtime(time);
210                 $hours = $hours < 10 ? $hours = "0".$hours : $hours;
211                 $minutes = $minutes < 10 ? $minutes = "0".$minutes : $minutes;
212                 $seconds = $seconds < 10 ? $seconds = "0".$seconds : $seconds;
213                 my @monthnames = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
214                 $month = $monthnames[$month];
215                 $monthday = $monthday < 10 ? $monthday = "0".$monthday : $monthday;
216                 $year+=1900;
217                 my $name = $0;
218                 $name =~ s/\.\///;
220                 my $log_msg = "$month $monthday $hours:$minutes:$seconds $name $msg\n";
221                 print LOG_HANDLE $log_msg;
222                 if( $foreground ) { 
223                     print STDERR $log_msg;
224                 }
225             }
226         close( LOG_HANDLE );
227     }
228 #log into syslog
229 #    my ($msg, $level, $facility) = @_;
230 #    if(not defined $msg) {return}
231 #    if(not defined $level) {$level = "info"}
232 #    if(not defined $facility) {$facility = "LOG_DAEMON"}
233 #    openlog($0, "pid,cons,", $facility);
234 #    syslog($level, $msg);
235 #    closelog;
236 #    return;
240 #===  FUNCTION  ================================================================
241 #         NAME:  get_interfaces 
242 #   PARAMETERS:  none
243 #      RETURNS:  (list of interfaces) 
244 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
245 #===============================================================================
246 sub get_interfaces {
247     my @result;
248     my $PROC_NET_DEV= ('/proc/net/dev');
250     open(PROC_NET_DEV, "<$PROC_NET_DEV")
251         or die "Could not open $PROC_NET_DEV";
253     my @ifs = <PROC_NET_DEV>;
255     close(PROC_NET_DEV);
257     # Eat first two line
258     shift @ifs;
259     shift @ifs;
261     chomp @ifs;
262     foreach my $line(@ifs) {
263         my $if= (split /:/, $line)[0];
264         $if =~ s/^\s+//;
265         push @result, $if;
266     }
268     return @result;
271 #===  FUNCTION  ================================================================
272 #         NAME:  get_mac 
273 #   PARAMETERS:  interface name (i.e. eth0)
274 #      RETURNS:  (mac address) 
275 #  DESCRIPTION:  Uses ioctl to get mac address directly from system.
276 #===============================================================================
277 sub get_mac {
278         my $ifreq= shift;
279         my $result;
280         if ($ifreq && length($ifreq) > 0) { 
281                 if($ifreq eq "all") {
282                         if(defined($server_ip)) {
283                                 $result = &get_local_mac_for_remote_ip($server_ip);
284                         } 
285                         elsif ($client_mac_address && length($client_mac_address) > 0 && !($client_mac_address eq "00:00:00:00:00:00")){
286                                 $result = &client_mac_address;
287                         } 
288                         else {
289                                 $result = "00:00:00:00:00:00";
290                         }
291                 } else {
292                         my $SIOCGIFHWADDR= 0x8927;     # man 2 ioctl_list
294                         # A configured MAC Address should always override a guessed value
295                         if ($client_mac_address and length($client_mac_address) > 0 and not($client_mac_address eq "00:00:00:00:00:00")) {
296                                 $result= $client_mac_address;
297                         }
298                         else {
299                                 socket SOCKET, PF_INET, SOCK_DGRAM, getprotobyname('ip')
300                                         or die "socket: $!";
302                                 if(ioctl SOCKET, $SIOCGIFHWADDR, $ifreq) {
303                                         my ($if, $mac)= unpack 'h36 H12', $ifreq;
305                                         if (length($mac) > 0) {
306                                                 $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])$/;
307                                                 $mac= sprintf("%s:%s:%s:%s:%s:%s", $1, $2, $3, $4, $5, $6);
308                                                 $result = $mac;
309                                         }
310                                 }
311                         }
312                 }
313         }
314         return $result;
318 #===  FUNCTION  ================================================================
319 #         NAME:  get_interface_for_ip
320 #   PARAMETERS:  ip address (i.e. 192.168.0.1)
321 #      RETURNS:  array: list of interfaces if ip=0.0.0.0, matching interface if found, undef else
322 #  DESCRIPTION:  Uses proc fs (/proc/net/dev) to get list of interfaces.
323 #===============================================================================
324 sub get_interface_for_ip {
325     my $result;
326     my $ip= shift;
327     if ($ip && length($ip) > 0) {
328         my @ifs= &get_interfaces();
329         if($ip eq "0.0.0.0") {
330             $result = "all";
331         } else {
332             foreach (@ifs) {
333                 my $if=$_;
334                 if(get_ip($if) eq $ip) {
335                     $result = $if;
336                     last;
337                 }
338             }       
339         }
340     }       
341     return $result;
345 #===  FUNCTION  ================================================================
346 #         NAME:  get_ip 
347 #   PARAMETERS:  interface name (i.e. eth0)
348 #      RETURNS:  (ip address) 
349 #  DESCRIPTION:  Uses ioctl to get ip address directly from system.
350 #===============================================================================
351 sub get_ip {
352     my $ifreq= shift;
353     my $result= "";
354     my $SIOCGIFADDR= 0x8915;       # man 2 ioctl_list
355         my $proto= getprotobyname('ip');
357     socket SOCKET, PF_INET, SOCK_DGRAM, $proto
358         or die "socket: $!";
360     if(ioctl SOCKET, $SIOCGIFADDR, $ifreq) {
361         my ($if, $sin)    = unpack 'a16 a16', $ifreq;
362         my ($port, $addr) = sockaddr_in $sin;
363         my $ip            = inet_ntoa $addr;
365         if ($ip && length($ip) > 0) {
366             $result = $ip;
367         }
368     }
370     return $result;
374 #===  FUNCTION  ================================================================
375 #         NAME:  get_local_mac_for_remote_ip
376 #   PARAMETERS:  none (takes server_ip from global variable)
377 #      RETURNS:  (ip address from interface that is used for communication) 
378 #  DESCRIPTION:  Uses ioctl to get routing table from system, checks which entry
379 #                matches (defaultroute last).
380 #===============================================================================
381 sub get_local_mac_for_remote_ip {
382         my $server_ip= shift;
383         my $result= "00:00:00:00:00:00";
385         if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
386                 my $PROC_NET_ROUTE= ('/proc/net/route');
388                 open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
389                         or die "Could not open $PROC_NET_ROUTE";
391                 my @ifs = <PROC_NET_ROUTE>;
393                 close(PROC_NET_ROUTE);
395                 # Eat header line
396                 shift @ifs;
397                 chomp @ifs;
398                 foreach my $line(@ifs) {
399                         my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
400                         my $destination;
401                         my $mask;
402                         my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
403                         $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
404                         ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
405                         $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
406                         if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
407                                 # destination matches route, save mac and exit
408                                 $result= &get_mac($Iface);
409                                 last;
410                         }
411                 }
412         } else {
413                 daemon_log("get_local_mac_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
414         }
415         return $result;
418 sub get_local_ip_for_remote_ip {
419         my $server_ip= shift;
420         my $result="0.0.0.0";
422         if($server_ip =~ /^(\d\d?\d?\.){3}\d\d?\d?$/) {
423                 if($server_ip eq "127.0.0.1") {
424                         $result="127.0.0.1";
425                 } else {
426                         my $PROC_NET_ROUTE= ('/proc/net/route');
428                         open(PROC_NET_ROUTE, "<$PROC_NET_ROUTE")
429                                 or die "Could not open $PROC_NET_ROUTE";
431                         my @ifs = <PROC_NET_ROUTE>;
433                         close(PROC_NET_ROUTE);
435                         # Eat header line
436                         shift @ifs;
437                         chomp @ifs;
438                         foreach my $line(@ifs) {
439                                 my ($Iface,$Destination,$Gateway,$Flags,$RefCnt,$Use,$Metric,$Mask,$MTU,$Window,$IRTT)=split(/\s/, $line);
440                                 my $destination;
441                                 my $mask;
442                                 my ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Destination);
443                                 $destination= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
444                                 ($d,$c,$b,$a)=unpack('a2 a2 a2 a2', $Mask);
445                                 $mask= sprintf("%d.%d.%d.%d", hex($a), hex($b), hex($c), hex($d));
446                                 if(new NetAddr::IP($server_ip)->within(new NetAddr::IP($destination, $mask))) {
447                                         # destination matches route, save mac and exit
448                                         $result= &get_ip($Iface);
449                                         last;
450                                 }
451                         }
452                 }
453         } else {
454                 daemon_log("get_local_ip_for_remote_ip was called with a non-ip parameter: $server_ip", 1);
455         }
456         return $result;
459 sub new_ldap_config {
460     my ($msg_hash) = @_ ;
461     my $element;
462     my @ldap_uris;
463     my $ldap_base;
464     my @ldap_options;
465     my @pam_options;
466     my @nss_options;
467     my $goto_admin;
468     my $goto_secret;
469     my $admin_base= "";
470     my $department= "";
471     my $unit_tag;
473     # Transform input into array
474     while ( my ($key, $value) = each(%$msg_hash) ) {
475         if ($key =~ /^(source|target|header)$/) {
476                 next;
477         }
479         foreach $element (@$value) {
480                 if ($key =~ /^ldap_uri$/) {
481                         push (@ldap_uris, $element);
482                         next;
483                 }
484                 if ($key =~ /^ldap_base$/) {
485                         $ldap_base= $element;
486                         next;
487                 }
488                 if ($key =~ /^goto_admin$/) {
489                         $goto_admin= $element;
490                         next;
491                 }
492                 if ($key =~ /^goto_secret$/) {
493                         $goto_secret= $element;
494                         next;
495                 }
496                 if ($key =~ /^ldap_cfg$/) {
497                         push (@ldap_options, "$element");
498                         next;
499                 }
500                 if ($key =~ /^pam_cfg$/) {
501                         push (@pam_options, "$element");
502                         next;
503                 }
504                 if ($key =~ /^nss_cfg$/) {
505                         push (@nss_options, "$element");
506                         next;
507                 }
508                 if ($key =~ /^admin_base$/) {
509                         $admin_base= $element;
510                         next;
511                 }
512                 if ($key =~ /^department$/) {
513                         $department= $element;
514                         next;
515                 }
516                 if ($key =~ /^unit_tag$/) {
517                         $unit_tag= $element;
518                         next;
519                 }
520         }
521     }
523     # Unit tagging enabled?
524     if (defined $unit_tag){
525             push (@pam_options, "pam_filter gosaUnitTag=$unit_tag");
526             push (@nss_options, "nss_base_passwd  $admin_base?sub?gosaUnitTag=$unit_tag");
527             push (@nss_options, "nss_base_group   $admin_base?sub?gosaUnitTag=$unit_tag");
528     }
530     # Setup ldap.conf
531     my $file1;
532     my $file2;
533     open(file1, "> $ldap_config");
534     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
535     print file1 "URI";
536     foreach $element (@ldap_uris) {
537         print file1 " $element";
538     }
539     print file1 "\nBASE $ldap_base\n";
540     foreach $element (@ldap_options) {
541         print file1 "$element\n";
542     }
543     close (file1);
544     daemon_log("wrote $ldap_config", 5);
546     # Setup pam_ldap.conf / libnss_ldap.conf
547     open(file1, "> $pam_config");
548     open(file2, "> $nss_config");
549     print file1 "# This file was automatically generated by gosa-si-client. Do not change.\n";
550     print file2 "# This file was automatically generated by gosa-si-client. Do not change.\n";
551     print file1 "uri";
552     print file2 "uri";
553     foreach $element (@ldap_uris) {
554         print file1 " $element";
555         print file2 " $element";
556     }
557     print file1 "\nbase $ldap_base\n";
558     print file2 "\nbase $ldap_base\n";
559     foreach $element (@pam_options) {
560         print file1 "$element\n";
561     }
562     foreach $element (@nss_options) {
563         print file2 "$element\n";
564     }
565     close (file2);
566     daemon_log("wrote $nss_config", 5);
567     close (file1);
568     daemon_log("wrote $pam_config", 5);
570     # Create goto.secrets if told so - for compatibility reasons
571     if (defined $goto_admin){
572             open(file1, "> /etc/goto/secret");
573             close(file1);
574             chown(0,0, "/etc/goto/secret");
575             chmod(0600, "/etc/goto/secret");
576             open(file1, "> /etc/goto/secret");
577             print file1 "GOTOADMIN=\"$goto_admin\"\nGOTOSECRET=\"$goto_secret\"\n";
578             close(file1);
579             daemon_log("wrote /etc/goto/secret", 5);
580     }
582     
584     # Write shell based config
585     my $cfg_name= dirname($ldap_config)."/ldap-shell.conf";
586     open(file1, "> $cfg_name");
587     print file1 "LDAP_BASE=\"$ldap_base\"\n";
588     print file1 "ADMIN_BASE=\"$admin_base\"\n";
589     print file1 "DEPARTMENT=\"$department\"\n";
590     print file1 "UNIT_TAG=\"".(defined $unit_tag ? "$unit_tag" : "")."\"\n";
591     print file1 "UNIT_TAG_FILTER=\"".(defined $unit_tag ? "(gosaUnitTag=$unit_tag)" : "")."\"\n";
592     close(file1);
593     daemon_log("wrote $cfg_name", 5);
595     return;
600 sub generate_hw_digest {
601         my $hw_data;
602         foreach my $line (split /\n/, `cat /proc/bus/pci/devices`) {
603                 $hw_data.= sprintf "%s", $line =~ /[^\s]+\s([^\s]+)\s.*/;
604         }
605         return(md5_base64($hw_data));
609 sub create_passwd {
610     my $new_passwd = "";
611     for(my $i=0; $i<31; $i++) {
612         $new_passwd .= ("a".."z","A".."Z",0..9)[int(rand(62))]
613     }
615     return $new_passwd;
619 sub get_server_addresses {
620     my $domain= shift;
621     my @result;
622  
623     my $error = 0;
624     my $res   = Net::DNS::Resolver->new;
625     my $query = $res->send("_gosad._tcp.".$domain, "SRV");
626     my @hits;
628     if ($query) {
629         foreach my $rr ($query->answer) {
630             push(@hits, $rr->target.":".$rr->port);
631         }
632     }
633     else {
634         #warn "query failed: ", $res->errorstring, "\n";
635         $error++;
636     }
638     if( $error == 0 ) {
639         foreach my $hit (@hits) {
640             my ($hit_name, $hit_port) = split(/:/, $hit);
642             my $address_query = $res->send($hit_name);
643             if( 1 == length($address_query->answer) ) {
644                 foreach my $rr ($address_query->answer) {
645                     push(@result, $rr->address.":".$hit_port);
646                 }
647             }
648         }
649     }
651 #    my $dig_cmd= 'dig +nocomments srv _gosad._tcp.'.$domain;
653 #    my $output= `$dig_cmd 2>&1`;
654 #    open (PIPE, "$dig_cmd 2>&1 |");
655 #    while(<PIPE>) {
656 #        chomp $_;
657 #        # If it's not a comment
658 #        if($_ =~ m/^[^;]/) {
659 #            my @matches= split /\s+/;
661 #            # Push hostname with port
662 #            if($matches[3] eq 'SRV') {
663 #                push @result, $matches[7].':'.$matches[6];
664 #            } elsif ($matches[3] eq 'A') {
665 #                my $i=0;
667 #                # Substitute the hostname with the ip address of the matching A record
668 #                foreach my $host (@result) {
669 #                    if ((split /\:/, $host)[0] eq $matches[0]) {
670 #                        $result[$i]= $matches[4].':'.(split /\:/, $host)[1];
671 #                    }
672 #                    $i++;
673 #                }
674 #            }
675 #        }
676 #    }
677 #    close(PIPE);
678     return @result;
682 ##===  FUNCTION  ================================================================
683 ##         NAME:  create_ciphering
684 ##   PARAMETERS:  passwd - string - used to create ciphering
685 ##      RETURNS:  cipher - object
686 ##  DESCRIPTION:  creates a Crypt::Rijndael::MODE_CBC object with passwd as key
687 ##===============================================================================
688 #sub create_ciphering {
689 #    my ($passwd) = @_;
690 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
691 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
693 #    #daemon_log("iv: $iv", 7);
694 #    #daemon_log("key: $passwd", 7);
695 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
696 #    $my_cipher->set_iv($iv);
697 #    return $my_cipher;
698 #}
701 #sub create_ciphering {
702 #    my ($passwd) = @_;
703 #    $passwd = substr(md5_hex("$passwd") x 32, 0, 32);
704 #    my $iv = substr(md5_hex('GONICUS GmbH'),0, 16);
705 #    my $my_cipher = Crypt::Rijndael->new($passwd , Crypt::Rijndael::MODE_CBC());
706 #    $my_cipher->set_iv($iv);
707 #    return $my_cipher;
708 #}
711 #sub encrypt_msg {
712 #    my ($msg, $key) = @_;
713 #    my $my_cipher = &create_ciphering($key);
714 #    {
715 #      use bytes;
716 #      $msg = "\0"x(16-length($msg)%16).$msg;
717 #    }
718 #    $msg = $my_cipher->encrypt($msg);
719 #    chomp($msg = &encode_base64($msg));
720 #    # there are no newlines allowed inside msg
721 #    $msg=~ s/\n//g;
722 #    return $msg;
723 #}
726 #sub decrypt_msg {
727 #    my ($msg, $key) = @_ ;
728 #    $msg = &decode_base64($msg);
729 #    my $my_cipher = &create_ciphering($key);
730 #    $msg = $my_cipher->decrypt($msg); 
731 #    $msg =~ s/\0*//g;
732 #    return $msg;
733 #}
736 #===  FUNCTION  ================================================================
737 #         NAME:  send_msg_hash2address
738 #   PARAMETERS:  msg_hash - hash - xml_hash created with function create_xml_hash
739 #                PeerAddr string - socket address to send msg
740 #                PeerPort string - socket port, if not included in socket address
741 #      RETURNS:  nothing
742 #  DESCRIPTION:  ????
743 #===============================================================================
744 sub send_msg_hash2address {
745     my ($msg_hash, $address, $passwd) = @_ ;
747     # fetch header for logging
748     my $header = @{$msg_hash->{header}}[0];  
750     # generate xml string
751     my $msg_xml = &create_xml_string($msg_hash);
752     
753     # encrypt xml msg
754     my $crypted_msg = &encrypt_msg($msg_xml, $passwd);
756     # opensocket
757     my $socket = &open_socket($address);
758     if(not defined $socket){
759         daemon_log("cannot send '$header'-msg to $address , server not reachable", 5);
760         return 1;
761     }
762     
763     # send xml msg
764     print $socket $crypted_msg."\n";
765     
766     close $socket;
768     daemon_log("send '$header'-msg to $address", 1);
769     daemon_log("message:\n$msg_xml", 8);
770     return 0;
774 sub send_msg_to_target {
775     my ($msg, $address, $encrypt_key, $msg_header) = @_ ;
776     my $error = 0;
778     if( $msg_header ) {
779         $msg_header = "'$msg_header'-";
780     }
781     else {
782         $msg_header = "";
783     }
785     # encrypt xml msg
786     my $crypted_msg = &encrypt_msg($msg, $encrypt_key);
788     # opensocket
789     my $socket = &open_socket($address);
790     if( !$socket ) {
791         daemon_log("cannot send ".$msg_header."msg to $address , host not reachable", 1);
792         $error++;
793     }
794     
795     if( $error == 0 ) {
796         # send xml msg
797         print $socket $crypted_msg."\n";
799         daemon_log("send ".$msg_header."msg to $address", 1);
800         daemon_log("message:\n$msg", 8);
802     }
804     # close socket in any case
805     if( $socket ) {
806         close $socket;
807     }
809     return;
813 sub open_socket {
814     my ($PeerAddr, $PeerPort) = @_ ;
815     if(defined($PeerPort)){
816         $PeerAddr = $PeerAddr.":".$PeerPort;
817     }
818     my $socket;
819     $socket = new IO::Socket::INET(PeerAddr => $PeerAddr,
820             Porto => "tcp",
821             Type => SOCK_STREAM,
822             Timeout => 5,
823             );
824     if(not defined $socket) {
825         return;
826     }
827     &daemon_log("open_socket: $PeerAddr", 7);
828     return $socket;
832 #===  FUNCTION  ================================================================
833 #         NAME:  register_at_server
834 #   PARAMETERS:  
835 #      RETURNS:  
836 #  DESCRIPTION:  
837 #===============================================================================
838 sub register_at_gosa_si_server {
839     my ($kernel) = $_[KERNEL];
841     if( $REGISTERED_FLAG == 1 ) {
843         # create new passwd and ciphering object for client-server communication
844         $server_key = &create_passwd();
846         my $events = join( ", ", keys %{$event_hash} );
848         while(1) {
850             # fetch first gosa-si-server from @servers
851             my $server = shift(@servers);
853             if( !$server ) {
854                 daemon_log("no gosa-si-server left in list of servers", 1);
855                 daemon_log("unable to register at a gosa-si-server, force shutdown", 1);
856                 exit(1);
857             }
859             # create registration msg
860             my $register_hash = &create_xml_hash("here_i_am", &get_local_ip_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/)).":".$client_port, $server);
861             &add_content2xml_hash($register_hash, "new_passwd", $server_key);
862                         &add_content2xml_hash($register_hash, "mac_address", &get_local_mac_for_remote_ip(sprintf("%s", $server =~ /^([0-9\.]*?):.*$/)));
863             &add_content2xml_hash($register_hash, "events", $events);
864             &add_content2xml_hash($register_hash, "gotoHardwareChecksum", $gotoHardwareChecksum);
866             # send xml hash to server with general server passwd
867             my $res = &send_msg_hash2address($register_hash, $server, $default_server_key);
868             last;
869         }
870         daemon_log("waiting for msg 'register_at_gosa_si_server'",1);
871         $kernel->delay_set('register_at_gosa_si_server',2);
872     }
873     return;
875     
877 sub check_key_and_xml_validity {
878     my ($crypted_msg, $module_key) = @_;
879 #print STDERR "crypted_msg:$crypted_msg\n";
880 #print STDERR "modul_key:$module_key\n";
882     my $msg;
883     my $msg_hash;
884     eval{
885         $msg = &decrypt_msg($crypted_msg, $module_key);
886         &main::daemon_log("decrypted_msg: \n$msg", 8);
888         $msg_hash = $xml->XMLin($msg, ForceArray=>1);
890         # check header
891         my $header_l = $msg_hash->{'header'};
892         if( 1 != @{$header_l} ) {
893             die 'no or more headers specified';
894         }
895         my $header = @{$header_l}[0];
896         if( 0 == length $header) {
897             die 'header has length 0';
898         }
900         # check source
901         my $source_l = $msg_hash->{'source'};
902         if( 1 != @{$source_l} ) {
903             die 'no or more sources specified';
904         }
905         my $source = @{$source_l}[0];
906         if( 0 == length $source) {
907             die 'source has length 0';
908         }
910         # check target
911         my $target_l = $msg_hash->{'target'};
912         if( 1 != @{$target_l} ) {
913             die 'no or more targets specified ';
914         }
915         my $target = @{$target_l}[0];
916         if( 0 == length $target) {
917             die 'target has length 0 ';
918         }
920     };
921     if($@) {
922         &main::daemon_log("WARNING: do not understand the message or msg is not gosa-si envelope conform:", 5);
923         &main::daemon_log("$@", 8);
924     }
926     return ($msg, $msg_hash);
930 sub import_events {
932     if (not -e $event_dir) {
933         daemon_log("ERROR: cannot find directory or directory is not readable: $event_dir", 1);   
934     }
935     opendir (DIR, $event_dir) or die "ERROR while loading gosa-si-events from directory $event_dir : $!\n";
937     while (defined (my $event = readdir (DIR))) {
938         if( $event eq "." || $event eq ".." ) { next; }    
940         eval{ require $event; };
941         if( $@ ) {
942             daemon_log("import of event module '$event' failed", 1);
943             daemon_log("$@", 8);
944             next;
945         }
947         $event =~ /(\S*?).pm$/;
948         my $event_module = $1;
949         my $events_l = eval( $1."::get_events()") ;
950         foreach my $event_name (@{$events_l}) {
951             $event_hash->{$event_name} = $event_module;
952         }
954     }
958 sub server_input {
959     my ($heap,$input,$wheel) = @_[HEAP, ARG0, ARG1];
960     my $error = 0;
961     my $answer;
962     
963     daemon_log("Incoming msg:\n$input\n", 8);
965     my ($msg, $msg_hash) = &check_key_and_xml_validity($input, $server_key);
966     if( (!$msg) || (!$msg_hash) ) {
967         daemon_log("Deciphering of incoming msg failed", 5);
968         $error++;
969     }
971     ######################
972     # process incoming msg
973     if( $error == 0 ) {
974         my $header = @{$msg_hash->{header}}[0];
975         my $source = @{$msg_hash->{source}}[0];
977         if( exists $event_hash->{$header} ) {
978             # a event exists with the header as name
979             daemon_log("found event '$header' at event-module '".$event_hash->{$header}."'", 5);
980             no strict 'refs';
981             $answer = &{$event_hash->{$header}."::$header"}($msg, $msg_hash);
982          }
983     }
985     ########
986     # answer
987     if( $answer ) {
988         if( $answer =~ "<header>registered</header>") {
989             $REGISTERED_FLAG = 0;
990         } 
991         else {
992         &send_msg_to_address($answer, $server_address, $server_key);
993         }
994     }
996     return;
999 #==== MAIN = main ==============================================================
1000 #  parse commandline options
1001 Getopt::Long::Configure( "bundling" );
1002 GetOptions("h|help" => \&usage,
1003            "c|config=s" => \$cfg_file,
1004            "f|foreground" => \$foreground,
1005            "v|verbose+" => \$verbose,
1006            );
1008 #  read and set config parameters
1009 &check_cmdline_param ;
1010 &read_configfile($cfg_file, %cfg_defaults);
1011 &check_pid;
1014 # forward error messages to logfile
1015 if ( ! $foreground ) {
1016         open STDIN, '/dev/null' or die "Can’t read /dev/null: $!";
1017         open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
1018         open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
1021 # Just fork, if we are not in foreground mode
1022 if( ! $foreground ) { 
1023     chdir '/'                 or die "Can't chdir to /: $!";
1024     $pid = fork;
1025     setsid                    or die "Can't start a new session: $!";
1026     umask 0;
1027
1028 else { 
1029     $pid = $$; 
1032 # Do something useful - put our PID into the pid_file
1033 if( 0 != $pid ) {
1034     open( LOCK_FILE, ">$pid_file" );
1035     print LOCK_FILE "$pid\n";
1036     close( LOCK_FILE );
1037     if( !$foreground ) { 
1038         exit( 0 ) 
1039     };
1042 daemon_log(" ", 1);
1043 daemon_log("$0 started!", 1);
1045 # delete old DBsqlite lock files
1046 system('rm -f /tmp/gosa_si_lock*gosa-si-client*');
1049 # complete client_address
1050 $client_address = $client_ip.":".$client_port;
1053 # detect own ip and mac address
1054 my $network_interface= &get_interface_for_ip($client_ip);
1055 $client_mac_address= &get_mac($network_interface);
1056 daemon_log("gosa-si-client ip address detected: $client_ip", 1);
1057 daemon_log("gosa-si-client mac address detected: $client_mac_address", 1);
1060 # import events
1061 &import_events();
1064 # compute hardware checksum
1065 $gotoHardwareChecksum= &generate_hw_digest();
1066 daemon_log("gosa-si-client gotoHardwareChecksum detected: $gotoHardwareChecksum", 1);
1069 # create socket for incoming xml messages
1070 POE::Component::Server::TCP->new(
1071     Alias => 'gosa-si-client',
1072         Port => $client_port,
1073         ClientInput => \&server_input,
1074 );
1075 daemon_log("start socket for incoming xml messages at port '$client_port' ", 1);
1078 # prepare variables
1079 if (defined $server_ip && defined $server_port) {
1080     $server_address = $server_ip.":".$server_port;
1082 $xml = new XML::Simple();
1083 $default_server_key = $server_key;
1086 # find all possible gosa-si-servers in DNS
1087 if (defined $server_domain) {
1088     my @tmp_servers = &get_server_addresses($server_domain);
1089     foreach my $server (@tmp_servers) { 
1090         unshift(@servers, $server); 
1091     }
1093 # add gosa-si-server address from config file at first position of server list
1094 if (defined $server_address) {
1095     unshift(@servers, $server_address);
1097 my $servers_string = join(", ", @servers);
1098 daemon_log("found servers in configuration file and via DNS: $servers_string", 5);
1101 POE::Session->create(
1102         inline_states => {
1103                 _start => \&register_at_gosa_si_server ,
1104         register_at_gosa_si_server => \&register_at_gosa_si_server,
1105         }
1106 );
1108 POE::Kernel->run();
1109 exit;