8 use Storable
qw(dclone);
13 use Digest
::HMAC_SHA1
;
33 use Data
::Dumper
; # fixme: remove
35 # x509 certificate utils
37 my $basedir = "/etc/pve";
38 my $authdir = "$basedir/priv";
39 my $lockdir = "/etc/pve/priv/lock";
41 my $authprivkeyfn = "$authdir/authkey.key";
42 my $authpubkeyfn = "$basedir/authkey.pub";
43 my $pveca_key_fn = "$authdir/pve-root-ca.key";
44 my $pveca_srl_fn = "$authdir/pve-root-ca.srl";
45 my $pveca_cert_fn = "$basedir/pve-root-ca.pem";
46 # this is just a secret accessable by the web browser
47 # and is used for CSRF prevention
48 my $pvewww_key_fn = "$basedir/pve-www.key";
51 my $ssh_rsa_id_priv = "/root/.ssh/id_rsa";
52 my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
53 my $ssh_host_rsa_id = "/etc/ssh/ssh_host_rsa_key.pub";
54 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts";
55 my $sshknownhosts = "/etc/pve/priv/known_hosts";
56 my $sshauthkeys = "/etc/pve/priv/authorized_keys";
57 my $sshd_config_fn = "/etc/ssh/sshd_config";
58 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
59 my $rootsshauthkeysbackup = "${rootsshauthkeys}.org";
60 my $rootsshconfig = "/root/.ssh/config";
65 'datacenter.cfg' => 1,
67 'corosync.conf.new' => 1,
70 'priv/shadow.cfg' => 1,
74 'ha/crm_commands' => 1,
75 'ha/manager_status' => 1,
76 'ha/resources.cfg' => 1,
82 # only write output if something fails
88 my $record_output = sub {
94 PVE
::Tools
::run_command
($cmd, outfunc
=> $record_output,
95 errfunc
=> $record_output);
101 print STDERR
$outbuf;
106 sub check_cfs_quorum
{
109 # note: -w filename always return 1 for root, so wee need
110 # to use File::lstat here
111 my $st = File
::stat::lstat("$basedir/local");
112 my $quorate = ($st && (($st->mode & 0200) != 0));
114 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
119 sub check_cfs_is_mounted
{
122 my $res = -l
"$basedir/local";
124 die "pve configuration filesystem not mounted\n"
133 check_cfs_is_mounted
();
135 my @required_dirs = (
138 "$basedir/nodes/$nodename",
139 "$basedir/nodes/$nodename/lxc",
140 "$basedir/nodes/$nodename/qemu-server",
141 "$basedir/nodes/$nodename/openvz",
142 "$basedir/nodes/$nodename/priv");
144 foreach my $dir (@required_dirs) {
146 mkdir($dir) || $! == EEXIST
|| die "unable to create directory '$dir' - $!\n";
153 return if -f
"$authprivkeyfn";
155 check_cfs_is_mounted
();
157 mkdir $authdir || $! == EEXIST
|| die "unable to create dir '$authdir' - $!\n";
159 run_silent_cmd
(['openssl', 'genrsa', '-out', $authprivkeyfn, '2048']);
161 run_silent_cmd
(['openssl', 'rsa', '-in', $authprivkeyfn, '-pubout', '-out', $authpubkeyfn]);
166 return if -f
$pveca_key_fn;
169 run_silent_cmd
(['openssl', 'genrsa', '-out', $pveca_key_fn, '4096']);
172 die "unable to generate pve ca key:\n$@" if $@;
177 if (-f
$pveca_key_fn && -f
$pveca_cert_fn) {
183 # we try to generate an unique 'subject' to avoid browser problems
184 # (reused serial numbers, ..)
186 UUID
::generate
($uuid);
188 UUID
::unparse
($uuid, $uuid_str);
191 # wrap openssl with faketime to prevent bug #904
192 run_silent_cmd
(['faketime', 'yesterday', 'openssl', 'req', '-batch',
193 '-days', '3650', '-new', '-x509', '-nodes', '-key',
194 $pveca_key_fn, '-out', $pveca_cert_fn, '-subj',
195 "/CN=Proxmox Virtual Environment/OU=$uuid_str/O=PVE Cluster Manager CA/"]);
198 die "generating pve root certificate failed:\n$@" if $@;
203 sub gen_pve_ssl_key
{
206 die "no node name specified" if !$nodename;
208 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
210 return if -f
$pvessl_key_fn;
213 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvessl_key_fn, '2048']);
216 die "unable to generate pve ssl key for node '$nodename':\n$@" if $@;
219 sub gen_pve_www_key
{
221 return if -f
$pvewww_key_fn;
224 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvewww_key_fn, '2048']);
227 die "unable to generate pve www key:\n$@" if $@;
233 PVE
::Tools
::file_set_contents
($pveca_srl_fn, $serial);
236 sub gen_pve_ssl_cert
{
237 my ($force, $nodename, $ip) = @_;
239 die "no node name specified" if !$nodename;
240 die "no IP specified" if !$ip;
242 my $pvessl_cert_fn = "$basedir/nodes/$nodename/pve-ssl.pem";
244 return if !$force && -f
$pvessl_cert_fn;
246 my $names = "IP:127.0.0.1,IP:::1,DNS:localhost";
248 my $rc = PVE
::INotify
::read_file
('resolvconf');
252 my $fqdn = $nodename;
254 $names .= ",DNS:$nodename";
256 if ($rc && $rc->{search
}) {
257 $fqdn = $nodename . "." . $rc->{search
};
258 $names .= ",DNS:$fqdn";
261 my $sslconf = <<__EOD;
262 RANDFILE = /root/.rnd
267 distinguished_name = req_distinguished_name
268 req_extensions = v3_req
270 string_mask = nombstr
272 [ req_distinguished_name ]
273 organizationalUnitName = PVE Cluster Node
274 organizationName = Proxmox Virtual Environment
278 basicConstraints = CA:FALSE
279 extendedKeyUsage = serverAuth
280 subjectAltName = $names
283 my $cfgfn = "/tmp/pvesslconf-$$.tmp";
284 my $fh = IO
::File-
>new ($cfgfn, "w");
288 my $reqfn = "/tmp/pvecertreq-$$.tmp";
291 my $pvessl_key_fn = "$basedir/nodes/$nodename/pve-ssl.key";
293 run_silent_cmd
(['openssl', 'req', '-batch', '-new', '-config', $cfgfn,
294 '-key', $pvessl_key_fn, '-out', $reqfn]);
300 die "unable to generate pve certificate request:\n$err";
303 update_serial
("0000000000000000") if ! -f
$pveca_srl_fn;
306 # wrap openssl with faketime to prevent bug #904
307 run_silent_cmd
(['faketime', 'yesterday', 'openssl', 'x509', '-req',
308 '-in', $reqfn, '-days', '3650', '-out', $pvessl_cert_fn,
309 '-CAkey', $pveca_key_fn, '-CA', $pveca_cert_fn,
310 '-CAserial', $pveca_srl_fn, '-extfile', $cfgfn]);
316 die "unable to generate pve ssl certificate:\n$err";
323 sub gen_pve_node_files
{
324 my ($nodename, $ip, $opt_force) = @_;
326 gen_local_dirs
($nodename);
330 # make sure we have a (cluster wide) secret
331 # for CSRFR prevention
334 # make sure we have a (per node) private key
335 gen_pve_ssl_key
($nodename);
337 # make sure we have a CA
338 my $force = gen_pveca_cert
();
340 $force = 1 if $opt_force;
342 gen_pve_ssl_cert
($force, $nodename, $ip);
345 my $vzdump_cron_dummy = <<__EOD;
346 # cluster wide vzdump cron schedule
347 # Atomatically generated file - do not edit
349 PATH="/usr/sbin:/usr/bin:/sbin:/bin"
353 sub gen_pve_vzdump_symlink
{
355 my $filename = "/etc/pve/vzdump.cron";
357 my $link_fn = "/etc/cron.d/vzdump";
359 if ((-f
$filename) && (! -l
$link_fn)) {
360 rename($link_fn, "/root/etc_cron_vzdump.org"); # make backup if file exists
361 symlink($filename, $link_fn);
365 sub gen_pve_vzdump_files
{
367 my $filename = "/etc/pve/vzdump.cron";
369 PVE
::Tools
::file_set_contents
($filename, $vzdump_cron_dummy)
372 gen_pve_vzdump_symlink
();
379 my $ipcc_send_rec = sub {
380 my ($msgid, $data) = @_;
382 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
384 die "ipcc_send_rec failed: $!\n" if !defined($res) && ($! != 0);
389 my $ipcc_send_rec_json = sub {
390 my ($msgid, $data) = @_;
392 my $res = PVE
::IPCC
::ipcc_send_rec
($msgid, $data);
394 die "ipcc_send_rec failed: $!\n" if !defined($res) && ($! != 0);
396 return decode_json
($res);
399 my $ipcc_get_config = sub {
402 my $bindata = pack "Z*", $path;
403 my $res = PVE
::IPCC
::ipcc_send_rec
(6, $bindata);
404 if (!defined($res)) {
405 return undef if ($! != 0);
412 my $ipcc_get_status = sub {
413 my ($name, $nodename) = @_;
415 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
416 return PVE
::IPCC
::ipcc_send_rec
(5, $bindata);
419 my $ipcc_update_status = sub {
420 my ($name, $data) = @_;
422 my $raw = ref($data) ? encode_json
($data) : $data;
424 my $bindata = pack "Z[256]Z*", $name, $raw;
426 return &$ipcc_send_rec(4, $bindata);
430 my ($priority, $ident, $tag, $msg) = @_;
432 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes
::length($ident) + 1,
433 bytes
::length($tag) + 1, $ident, $tag, $msg;
435 return &$ipcc_send_rec(7, $bindata);
438 my $ipcc_get_cluster_log = sub {
439 my ($user, $max) = @_;
441 $max = 0 if !defined($max);
443 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
444 return &$ipcc_send_rec(8, $bindata);
451 my $res = &$ipcc_send_rec_json(1);
452 #warn "GOT1: " . Dumper($res);
453 die "no starttime\n" if !$res->{starttime
};
455 if (!$res->{starttime
} || !$versions->{starttime
} ||
456 $res->{starttime
} != $versions->{starttime
}) {
457 #print "detected changed starttime\n";
475 if (!$clinfo->{version
} || $clinfo->{version
} != $versions->{clinfo
}) {
476 #warn "detected new clinfo\n";
477 $clinfo = &$ipcc_send_rec_json(2);
487 if (!$vmlist->{version
} || $vmlist->{version
} != $versions->{vmlist
}) {
488 #warn "detected new vmlist1\n";
489 $vmlist = &$ipcc_send_rec_json(3);
508 return $clinfo->{nodelist
};
513 my $nodelist = $clinfo->{nodelist
};
517 my $nodename = PVE
::INotify
::nodename
();
519 if (!$nodelist || !$nodelist->{$nodename}) {
520 return [ $nodename ];
523 return [ keys %$nodelist ];
526 sub broadcast_tasklist
{
530 &$ipcc_update_status("tasklist", $data);
536 my $tasklistcache = {};
541 my $kvstore = $versions->{kvstore
} || {};
543 my $nodelist = get_nodelist
();
546 foreach my $node (@$nodelist) {
547 next if $nodename && ($nodename ne $node);
549 my $ver = $kvstore->{$node}->{tasklist
} if $kvstore->{$node};
550 my $cd = $tasklistcache->{$node};
551 if (!$cd || !$ver || !$cd->{version
} ||
552 ($cd->{version
} != $ver)) {
553 my $raw = &$ipcc_get_status("tasklist", $node) || '[]';
554 my $data = decode_json
($raw);
556 $cd = $tasklistcache->{$node} = {
560 } elsif ($cd && $cd->{data
}) {
561 push @$res, @{$cd->{data
}};
565 syslog
('err', $err) if $err;
572 my ($rrdid, $data) = @_;
575 &$ipcc_update_status("rrd/$rrdid", $data);
582 my $last_rrd_dump = 0;
583 my $last_rrd_data = "";
589 my $diff = $ctime - $last_rrd_dump;
591 return $last_rrd_data;
596 $raw = &$ipcc_send_rec(10);
608 while ($raw =~ s/^(.*)\n//) {
609 my ($key, @ela) = split(/:/, $1);
611 next if !(scalar(@ela) > 1);
612 $res->{$key} = \
@ela;
616 $last_rrd_dump = $ctime;
617 $last_rrd_data = $res;
622 sub create_rrd_data
{
623 my ($rrdname, $timeframe, $cf) = @_;
625 my $rrddir = "/var/lib/rrdcached/db";
627 my $rrd = "$rrddir/$rrdname";
631 day
=> [ 60*30, 70 ],
632 week
=> [ 60*180, 70 ],
633 month
=> [ 60*720, 70 ],
634 year
=> [ 60*10080, 70 ],
637 my ($reso, $count) = @{$setup->{$timeframe}};
638 my $ctime = $reso*int(time()/$reso);
639 my $req_start = $ctime - $reso*$count;
641 $cf = "AVERAGE" if !$cf;
649 my $socket = "/var/run/rrdcached.sock";
650 push @args, "--daemon" => "unix:$socket" if -S
$socket;
652 my ($start, $step, $names, $data) = RRDs
::fetch
($rrd, $cf, @args);
654 my $err = RRDs
::error
;
655 die "RRD error: $err\n" if $err;
657 die "got wrong time resolution ($step != $reso)\n"
661 my $fields = scalar(@$names);
662 for my $line (@$data) {
663 my $entry = { 'time' => $start };
665 for (my $i = 0; $i < $fields; $i++) {
666 my $name = $names->[$i];
667 if (defined(my $val = $line->[$i])) {
668 $entry->{$name} = $val;
670 # leave empty fields undefined
671 # maybe make this configurable?
680 sub create_rrd_graph
{
681 my ($rrdname, $timeframe, $ds, $cf) = @_;
683 # Using RRD graph is clumsy - maybe it
684 # is better to simply fetch the data, and do all display
685 # related things with javascript (new extjs html5 graph library).
687 my $rrddir = "/var/lib/rrdcached/db";
689 my $rrd = "$rrddir/$rrdname";
691 my @ids = PVE
::Tools
::split_list
($ds);
693 my $ds_txt = join('_', @ids);
695 my $filename = "${rrd}_${ds_txt}.png";
699 day
=> [ 60*30, 70 ],
700 week
=> [ 60*180, 70 ],
701 month
=> [ 60*720, 70 ],
702 year
=> [ 60*10080, 70 ],
705 my ($reso, $count) = @{$setup->{$timeframe}};
708 "--imgformat" => "PNG",
712 "--start" => - $reso*$count,
714 "--lower-limit" => 0,
717 my $socket = "/var/run/rrdcached.sock";
718 push @args, "--daemon" => "unix:$socket" if -S
$socket;
720 my @coldef = ('#00ddff', '#ff0000');
722 $cf = "AVERAGE" if !$cf;
725 foreach my $id (@ids) {
726 my $col = $coldef[$i++] || die "fixme: no color definition";
727 push @args, "DEF:${id}=$rrd:${id}:$cf";
729 if ($id eq 'cpu' || $id eq 'iowait') {
730 push @args, "CDEF:${id}_per=${id},100,*";
731 $dataid = "${id}_per";
733 push @args, "LINE2:${dataid}${col}:${id}";
736 push @args, '--full-size-mode';
738 # we do not really store data into the file
739 my $res = RRDs
::graphv
('', @args);
741 my $err = RRDs
::error
;
742 die "RRD error: $err\n" if $err;
744 return { filename
=> $filename, image
=> $res->{image
} };
747 # a fast way to read files (avoid fuse overhead)
751 return &$ipcc_get_config($path);
754 sub get_cluster_log
{
755 my ($user, $max) = @_;
757 return &$ipcc_get_cluster_log($user, $max);
762 sub cfs_register_file
{
763 my ($filename, $parser, $writer) = @_;
765 $observed->{$filename} || die "unknown file '$filename'";
767 die "file '$filename' already registered" if $file_info->{$filename};
769 $file_info->{$filename} = {
775 my $ccache_read = sub {
776 my ($filename, $parser, $version) = @_;
778 $ccache->{$filename} = {} if !$ccache->{$filename};
780 my $ci = $ccache->{$filename};
782 if (!$ci->{version
} || !$version || $ci->{version
} != $version) {
783 # we always call the parser, even when the file does not exists
784 # (in that case $data is undef)
785 my $data = get_config
($filename);
786 $ci->{data
} = &$parser("/etc/pve/$filename", $data);
787 $ci->{version
} = $version;
790 my $res = ref($ci->{data
}) ? dclone
($ci->{data
}) : $ci->{data
};
795 sub cfs_file_version
{
800 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
801 my ($type, $vmid) = ($1, $2);
802 if ($vmlist && $vmlist->{ids
} && $vmlist->{ids
}->{$vmid}) {
803 $version = $vmlist->{ids
}->{$vmid}->{version
};
805 $infotag = "/$type/";
807 $infotag = $filename;
808 $version = $versions->{$filename};
811 my $info = $file_info->{$infotag} ||
812 die "unknown file type '$filename'\n";
814 return wantarray ?
($version, $info) : $version;
820 my ($version, $info) = cfs_file_version
($filename);
821 my $parser = $info->{parser
};
823 return &$ccache_read($filename, $parser, $version);
827 my ($filename, $data) = @_;
829 my ($version, $info) = cfs_file_version
($filename);
831 my $writer = $info->{writer
} || die "no writer defined";
833 my $fsname = "/etc/pve/$filename";
835 my $raw = &$writer($fsname, $data);
837 if (my $ci = $ccache->{$filename}) {
838 $ci->{version
} = undef;
841 PVE
::Tools
::file_set_contents
($fsname, $raw);
845 my ($lockid, $timeout, $code, @param) = @_;
849 # this timeout is for aquire the lock
850 $timeout = 10 if !$timeout;
852 my $filename = "$lockdir/$lockid";
854 my $msg = "can't aquire cfs lock '$lockid'";
861 die "$msg: pve cluster filesystem not online.\n";
864 local $SIG{ALRM
} = sub { die "got lock request timeout\n"; };
868 if (!(mkdir $filename)) {
869 print STDERR
"trying to aquire cfs lock '$lockid' ...";
871 if (!(mkdir $filename)) {
872 (utime 0, 0, $filename); # cfs unlock request
874 print STDERR
" OK\n";
881 # fixed command timeout: cfs locks have a timeout of 120
882 # using 60 gives us another 60 seconds to abort the task
884 local $SIG{ALRM
} = sub { die "got lock timeout - aborting command\n"; };
886 cfs_update
(); # make sure we read latest versions inside code()
888 $res = &$code(@param);
897 if ($err && ($err eq "got lock request timeout\n") &&
898 !check_cfs_quorum
()){
899 $err = "$msg: no quorum!\n";
902 if (!$err || $err !~ /^got lock timeout -/) {
903 rmdir $filename; # cfs unlock
917 my ($filename, $timeout, $code, @param) = @_;
919 my $info = $observed->{$filename} || die "unknown file '$filename'";
921 my $lockid = "file-$filename";
922 $lockid =~ s/[.\/]/_
/g
;
924 &$cfs_lock($lockid, $timeout, $code, @param);
927 sub cfs_lock_storage
{
928 my ($storeid, $timeout, $code, @param) = @_;
930 my $lockid = "storage-$storeid";
932 &$cfs_lock($lockid, $timeout, $code, @param);
935 sub cfs_lock_domain
{
936 my ($domainname, $timeout, $code, @param) = @_;
938 my $lockid = "domain-$domainname";
940 &$cfs_lock($lockid, $timeout, $code, @param);
958 my ($priority, $ident, $msg) = @_;
960 if (my $tmp = $log_levels->{$priority}) {
964 die "need numeric log priority" if $priority !~ /^\d+$/;
966 my $tag = PVE
::SafeSyslog
::tag
();
968 $msg = "empty message" if !$msg;
970 $ident = "" if !$ident;
971 $ident = encode
("ascii", $ident,
972 sub { sprintf "\\u%04x", shift });
974 my $ascii = encode
("ascii", $msg, sub { sprintf "\\u%04x", shift });
977 syslog
($priority, "<%s> %s", $ident, $ascii);
979 syslog
($priority, "%s", $ascii);
982 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
984 syslog
("err", "writing cluster log failed: $@") if $@;
987 sub check_vmid_unused
{
988 my ($vmid, $noerr) = @_;
990 my $vmlist = get_vmlist
();
992 my $d = $vmlist->{ids
}->{$vmid};
993 return 1 if !defined($d);
995 return undef if $noerr;
997 my $vmtypestr = $d->{type
} eq 'qemu' ?
'VM' : 'CT';
998 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
1001 sub check_node_exists
{
1002 my ($nodename, $noerr) = @_;
1004 my $nodelist = $clinfo->{nodelist
};
1005 return 1 if $nodelist && $nodelist->{$nodename};
1007 return undef if $noerr;
1009 die "no such cluster node '$nodename'\n";
1012 # this is also used to get the IP of the local node
1013 sub remote_node_ip
{
1014 my ($nodename, $noerr) = @_;
1016 my $nodelist = $clinfo->{nodelist
};
1017 if ($nodelist && $nodelist->{$nodename}) {
1018 if (my $ip = $nodelist->{$nodename}->{ip
}) {
1019 return $ip if !wantarray;
1020 my $family = $nodelist->{$nodename}->{address_family
};
1022 $nodelist->{$nodename}->{address_family
} =
1024 PVE
::Tools
::get_host_address_family
($ip);
1026 return ($ip, $family);
1030 # fallback: try to get IP by other means
1031 my ($family, $packed_ip);
1034 my @res = PVE
::Tools
::getaddrinfo_all
($nodename);
1035 $family = $res[0]->{family
};
1036 $packed_ip = (PVE
::Tools
::unpack_sockaddr_in46
($res[0]->{addr
}))[2];
1040 die "hostname lookup failed:\n$@" if !$noerr;
1044 my $ip = Socket
::inet_ntop
($family, $packed_ip);
1045 if ($ip =~ m/^127\.|^::1$/) {
1046 die "hostname lookup failed - got local IP address ($nodename = $ip)\n" if !$noerr;
1050 return wantarray ?
($ip, $family) : $ip;
1053 sub get_local_migration_ip
{
1054 my ($migration_network, $noerr) = @_;
1056 my $cidr = $migration_network;
1058 if (!defined($cidr)) {
1059 my $dc_conf = cfs_read_file
('datacenter.cfg');
1060 $cidr = $dc_conf->{migration
}->{network
}
1061 if defined($dc_conf->{migration
}->{network
});
1064 if (defined($cidr)) {
1065 my $ips = PVE
::Network
::get_local_ip_from_cidr
($cidr);
1067 die "could not get migration ip: no IP address configured on local " .
1068 "node for network '$cidr'\n" if !$noerr && (scalar(@$ips) == 0);
1070 die "could not get migration ip: multiple IP address configured for " .
1071 "network '$cidr'\n" if !$noerr && (scalar(@$ips) > 1);
1079 # ssh related utility functions
1081 sub ssh_merge_keys
{
1082 # remove duplicate keys in $sshauthkeys
1083 # ssh-copy-id simply add keys, so the file can grow to large
1086 if (-f
$sshauthkeys) {
1087 $data = PVE
::Tools
::file_get_contents
($sshauthkeys, 128*1024);
1092 if (-f
$rootsshauthkeysbackup) {
1094 $data .= PVE
::Tools
::file_get_contents
($rootsshauthkeysbackup, 128*1024);
1099 # always add ourself
1100 if (-f
$ssh_rsa_id) {
1101 my $pub = PVE
::Tools
::file_get_contents
($ssh_rsa_id);
1103 $data .= "\n$pub\n";
1108 my @lines = split(/\n/, $data);
1109 foreach my $line (@lines) {
1110 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
1111 next if $vhash->{$3}++;
1113 $newdata .= "$line\n";
1116 PVE
::Tools
::file_set_contents
($sshauthkeys, $newdata, 0600);
1118 if ($found_backup && -l
$rootsshauthkeys) {
1119 # everything went well, so we can remove the backup
1120 unlink $rootsshauthkeysbackup;
1124 sub setup_sshd_config
{
1125 my ($start_sshd) = @_;
1127 my $conf = PVE
::Tools
::file_get_contents
($sshd_config_fn);
1129 return if $conf =~ m/^PermitRootLogin\s+yes\s*$/m;
1131 if ($conf !~ s/^#?PermitRootLogin.*$/PermitRootLogin yes/m) {
1133 $conf .= "\nPermitRootLogin yes\n";
1136 PVE
::Tools
::file_set_contents
($sshd_config_fn, $conf);
1138 my $cmd = $start_sshd ?
'reload-or-restart' : 'reload-or-try-restart';
1139 PVE
::Tools
::run_command
(['systemctl', $cmd, 'sshd']);
1142 sub setup_rootsshconfig
{
1144 # create ssh key if it does not exist
1145 if (! -f
$ssh_rsa_id) {
1146 mkdir '/root/.ssh/';
1147 system ("echo|ssh-keygen -t rsa -N '' -b 2048 -f ${ssh_rsa_id_priv}");
1150 # create ssh config if it does not exist
1151 if (! -f
$rootsshconfig) {
1153 if (my $fh = IO
::File-
>new($rootsshconfig, O_CREAT
|O_WRONLY
|O_EXCL
, 0640)) {
1154 # this is the default ciphers list from debian openssl0.9.8 except blowfish is added as prefered
1155 print $fh "Ciphers blowfish-cbc,aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc\n";
1161 sub setup_ssh_keys
{
1167 if (! -f
$sshauthkeys) {
1169 if (-f
$rootsshauthkeys) {
1170 $old = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 128*1024);
1172 if (my $fh = IO
::File-
>new ($sshauthkeys, O_CREAT
|O_WRONLY
|O_EXCL
, 0400)) {
1173 PVE
::Tools
::safe_print
($sshauthkeys, $fh, $old) if $old;
1179 warn "can't create shared ssh key database '$sshauthkeys'\n"
1180 if ! -f
$sshauthkeys;
1182 if (-f
$rootsshauthkeys && ! -l
$rootsshauthkeys) {
1183 if (!rename($rootsshauthkeys , $rootsshauthkeysbackup)) {
1184 warn "rename $rootsshauthkeys failed - $!\n";
1188 if (! -l
$rootsshauthkeys) {
1189 symlink $sshauthkeys, $rootsshauthkeys;
1192 if (! -l
$rootsshauthkeys) {
1193 warn "can't create symlink for ssh keys '$rootsshauthkeys' -> '$sshauthkeys'\n";
1195 unlink $rootsshauthkeysbackup if $import_ok;
1199 sub ssh_unmerge_known_hosts
{
1200 return if ! -l
$sshglobalknownhosts;
1203 $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024)
1204 if -f
$sshknownhosts;
1206 PVE
::Tools
::file_set_contents
($sshglobalknownhosts, $old);
1209 sub ssh_merge_known_hosts
{
1210 my ($nodename, $ip_address, $createLink) = @_;
1212 die "no node name specified" if !$nodename;
1213 die "no ip address specified" if !$ip_address;
1217 if (! -f
$sshknownhosts) {
1218 if (my $fh = IO
::File-
>new($sshknownhosts, O_CREAT
|O_WRONLY
|O_EXCL
, 0600)) {
1223 my $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024);
1227 if ((! -l
$sshglobalknownhosts) && (-f
$sshglobalknownhosts)) {
1228 $new = PVE
::Tools
::file_get_contents
($sshglobalknownhosts, 128*1024);
1231 my $hostkey = PVE
::Tools
::file_get_contents
($ssh_host_rsa_id);
1232 # Note: file sometimes containe emty lines at start, so we use multiline match
1233 die "can't parse $ssh_host_rsa_id" if $hostkey !~ m/^(ssh-rsa\s\S+)(\s.*)?$/m;
1242 my $merge_line = sub {
1243 my ($line, $all) = @_;
1245 if ($line =~ m/^(\S+)\s(ssh-rsa\s\S+)(\s.*)?$/) {
1248 if (!$vhash->{$key}) {
1250 if ($key =~ m/\|1\|([^\|\s]+)\|([^\|\s]+)$/) {
1251 my $salt = decode_base64
($1);
1253 my $hmac = Digest
::HMAC_SHA1-
>new($salt);
1254 $hmac->add($nodename);
1255 my $hd = $hmac->b64digest . '=';
1256 if ($digest eq $hd) {
1257 if ($rsakey eq $hostkey) {
1258 $found_nodename = 1;
1263 $hmac = Digest
::HMAC_SHA1-
>new($salt);
1264 $hmac->add($ip_address);
1265 $hd = $hmac->b64digest . '=';
1266 if ($digest eq $hd) {
1267 if ($rsakey eq $hostkey) {
1268 $found_local_ip = 1;
1281 while ($old && $old =~ s/^((.*?)(\n|$))//) {
1283 next if $line =~ m/^\s*$/; # skip empty lines
1284 next if $line =~ m/^#/; # skip comments
1285 &$merge_line($line, 1);
1288 while ($new && $new =~ s/^((.*?)(\n|$))//) {
1290 next if $line =~ m/^\s*$/; # skip empty lines
1291 next if $line =~ m/^#/; # skip comments
1292 &$merge_line($line);
1296 my $add_known_hosts_entry = sub {
1297 my ($name, $hostkey) = @_;
1299 my $hmac = Digest
::HMAC_SHA1-
>new("$addIndex" . time());
1300 my $b64salt = $hmac->b64digest . '=';
1301 $hmac = Digest
::HMAC_SHA1-
>new(decode_base64
($b64salt));
1303 my $digest = $hmac->b64digest . '=';
1304 $data .= "|1|$b64salt|$digest $hostkey\n";
1307 if (!$found_nodename || !$found_local_ip) {
1308 &$add_known_hosts_entry($nodename, $hostkey) if !$found_nodename;
1309 &$add_known_hosts_entry($ip_address, $hostkey) if !$found_local_ip;
1312 PVE
::Tools
::file_set_contents
($sshknownhosts, $data);
1314 return if !$createLink;
1316 unlink $sshglobalknownhosts;
1317 symlink $sshknownhosts, $sshglobalknownhosts;
1319 warn "can't create symlink for ssh known hosts '$sshglobalknownhosts' -> '$sshknownhosts'\n"
1320 if ! -l
$sshglobalknownhosts;
1324 my $migration_format = {
1328 enum
=> ['secure', 'insecure'],
1329 description
=> "Migration traffic is encrypted using an SSH tunnel by " .
1330 "default. On secure, completely private networks this can be " .
1331 "disabled to increase performance.",
1332 default => 'secure',
1336 type
=> 'string', format
=> 'CIDR',
1337 format_description
=> 'CIDR',
1338 description
=> "CIDR of the (sub) network that is used for migration."
1342 my $datacenter_schema = {
1344 additionalProperties
=> 0,
1349 description
=> "Default keybord layout for vnc server.",
1350 enum
=> PVE
::Tools
::kvmkeymaplist
(),
1355 description
=> "Default GUI language.",
1356 enum
=> [ 'en', 'de' ],
1361 description
=> "Specify external http proxy which is used for downloads (example: 'http://username:password\@host:port/')",
1362 pattern
=> "http://.*",
1364 migration_unsecure
=> {
1367 description
=> "Migration is secure using SSH tunnel by default. " .
1368 "For secure private networks you can disable it to speed up " .
1369 "migration. Deprecated, use the 'migration' property instead!",
1373 type
=> 'string', format
=> $migration_format,
1374 description
=> "For cluster wide migration settings.",
1379 description
=> "Select the default Console viewer. You can either use the builtin java applet (VNC), an external virt-viewer comtatible application (SPICE), or an HTML5 based viewer (noVNC).",
1380 enum
=> ['applet', 'vv', 'html5'],
1385 format
=> 'email-opt',
1386 description
=> "Specify email address to send notification from (default is root@\$hostname)",
1392 description
=> "Defines how many workers (per node) are maximal started ".
1393 " on actions like 'stopall VMs' or task from the ha-manager.",
1398 default => 'watchdog',
1399 enum
=> [ 'watchdog', 'hardware', 'both' ],
1400 description
=> "Set the fencing mode of the HA cluster. Hardware mode " .
1401 "needs a valid configuration of fence devices in /etc/pve/ha/fence.cfg." .
1402 " With both all two modes are used." .
1403 "\n\nWARNING: 'hardware' and 'both' are EXPERIMENTAL & WIP",
1408 pattern
=> qr/[a-f0-9]{2}(?::[a-f0-9]{2}){0,2}:?/i,
1409 description
=> 'Prefix for autogenerated MAC addresses.',
1414 # make schema accessible from outside (for documentation)
1415 sub get_datacenter_schema
{ return $datacenter_schema };
1417 sub parse_datacenter_config
{
1418 my ($filename, $raw) = @_;
1420 my $res = PVE
::JSONSchema
::parse_config
($datacenter_schema, $filename, $raw // '');
1422 if (my $migration = $res->{migration
}) {
1423 $res->{migration
} = PVE
::JSONSchema
::parse_property_string
($migration_format, $migration);
1426 # for backwards compatibility only, new migration property has precedence
1427 if (defined($res->{migration_unsecure
})) {
1428 if (defined($res->{migration
}->{type
})) {
1429 warn "deprecated setting 'migration_unsecure' and new 'migration: type' " .
1430 "set at same time! Ignore 'migration_unsecure'\n";
1432 $res->{migration
}->{type
} = ($res->{migration_unsecure
}) ?
'insecure' : 'secure';
1439 sub write_datacenter_config
{
1440 my ($filename, $cfg) = @_;
1442 # map deprecated setting to new one
1443 if (defined($cfg->{migration_unsecure
}) && !defined($cfg->{migration
})) {
1444 my $migration_unsecure = delete $cfg->{migration_unsecure
};
1445 $cfg->{migration
}->{type
} = ($migration_unsecure) ?
'insecure' : 'secure';
1448 return PVE
::JSONSchema
::dump_config
($datacenter_schema, $filename, $cfg);
1451 cfs_register_file
('datacenter.cfg',
1452 \
&parse_datacenter_config
,
1453 \
&write_datacenter_config
);
1455 # a very simply parser ...
1456 sub parse_corosync_conf
{
1457 my ($filename, $raw) = @_;
1461 my $digest = Digest
::SHA
::sha1_hex
(defined($raw) ?
$raw : '');
1464 $raw =~ s/\r?\n/ /g;
1469 my @tokens = split(/\s/, $raw);
1471 my $conf = { section
=> 'main', children
=> [] };
1474 my $section = $conf;
1476 while (defined(my $token = shift @tokens)) {
1477 my $nexttok = $tokens[0];
1479 if ($nexttok && ($nexttok eq '{')) {
1480 shift @tokens; # skip '{'
1485 push @{$section->{children
}}, $new_section;
1486 push @$stack, $section;
1487 $section = $new_section;
1491 if ($token eq '}') {
1492 $section = pop @$stack;
1493 die "parse error - uncexpected '}'\n" if !$section;
1498 die "missing ':' after key '$key'\n" if ! ($key =~ s/:$//);
1500 die "parse error - no value for '$key'\n" if !defined($nexttok);
1501 my $value = shift @tokens;
1503 push @{$section->{children
}}, { key
=> $key, value
=> $value };
1506 $conf->{digest
} = $digest;
1511 my $dump_corosync_section;
1512 $dump_corosync_section = sub {
1513 my ($section, $prefix) = @_;
1515 my $raw = $prefix . $section->{section
} . " {\n";
1517 my @list = grep { defined($_->{key
}) } @{$section->{children
}};
1518 foreach my $child (sort {$a->{key
} cmp $b->{key
}} @list) {
1519 $raw .= $prefix . " $child->{key}: $child->{value}\n";
1522 @list = grep { defined($_->{section
}) } @{$section->{children
}};
1523 foreach my $child (sort {$a->{section
} cmp $b->{section
}} @list) {
1524 $raw .= &$dump_corosync_section($child, "$prefix ");
1527 $raw .= $prefix . "}\n\n";
1533 sub write_corosync_conf
{
1534 my ($filename, $conf) = @_;
1540 die "no main section" if $conf->{section
} ne 'main';
1542 my @list = grep { defined($_->{key
}) } @{$conf->{children
}};
1543 foreach my $child (sort {$a->{key
} cmp $b->{key
}} @list) {
1544 $raw .= "$child->{key}: $child->{value}\n";
1547 @list = grep { defined($_->{section
}) } @{$conf->{children
}};
1548 foreach my $child (sort {$a->{section
} cmp $b->{section
}} @list) {
1549 $raw .= &$dump_corosync_section($child, $prefix);
1555 sub corosync_conf_version
{
1556 my ($conf, $noerr, $new_value) = @_;
1558 foreach my $child (@{$conf->{children
}}) {
1559 next if !defined($child->{section
});
1560 if ($child->{section
} eq 'totem') {
1561 foreach my $e (@{$child->{children
}}) {
1562 next if !defined($e->{key
});
1563 if ($e->{key
} eq 'config_version') {
1565 $e->{value
} = $new_value;
1567 } elsif (my $version = int($e->{value
})) {
1576 return undef if $noerr;
1578 die "invalid corosync config - unable to read version\n";
1581 # read only - use "rename corosync.conf.new corosync.conf" to write
1582 PVE
::Cluster
::cfs_register_file
('corosync.conf', \
&parse_corosync_conf
);
1583 # this is read/write
1584 PVE
::Cluster
::cfs_register_file
('corosync.conf.new', \
&parse_corosync_conf
,
1585 \
&write_corosync_conf
);
1587 sub check_corosync_conf_exists
{
1590 $silent = $silent // 0;
1592 my $exists = -f
"$basedir/corosync.conf";
1594 warn "Corosync config '$basedir/corosync.conf' does not exist - is this node part of a cluster?\n"
1595 if !$silent && !$exists;
1600 sub corosync_update_nodelist
{
1601 my ($conf, $nodelist) = @_;
1603 delete $conf->{digest
};
1605 my $version = corosync_conf_version
($conf);
1606 corosync_conf_version
($conf, undef, $version + 1);
1609 foreach my $v (values %$nodelist) {
1610 next if !($v->{ring0_addr
} || $v->{name
});
1612 foreach my $k (keys %$v) {
1613 push @$kv, { key
=> $k, value
=> $v->{$k} };
1615 my $ns = { section
=> 'node', children
=> $kv };
1616 push @$children, $ns;
1619 foreach my $main (@{$conf->{children
}}) {
1620 next if !defined($main->{section
});
1621 if ($main->{section
} eq 'nodelist') {
1622 $main->{children
} = $children;
1628 cfs_write_file
("corosync.conf.new", $conf);
1630 rename("/etc/pve/corosync.conf.new", "/etc/pve/corosync.conf")
1631 || die "activate corosync.conf.new failed - $!\n";
1634 sub corosync_nodelist
{
1639 foreach my $main (@{$conf->{children
}}) {
1640 next if !defined($main->{section
});
1641 if ($main->{section
} eq 'nodelist') {
1642 foreach my $ne (@{$main->{children
}}) {
1643 next if !defined($ne->{section
}) || ($ne->{section
} ne 'node');
1644 my $node = { quorum_votes
=> 1 };
1646 foreach my $child (@{$ne->{children
}}) {
1647 next if !defined($child->{key
});
1648 $node->{$child->{key
}} = $child->{value
};
1649 # use 'name' over 'ring0_addr' if set
1650 if ($child->{key
} eq 'name') {
1651 delete $nodelist->{$name} if $name;
1652 $name = $child->{value
};
1653 $nodelist->{$name} = $node;
1654 } elsif(!$name && $child->{key
} eq 'ring0_addr') {
1655 $name = $child->{value
};
1656 $nodelist->{$name} = $node;
1666 # get a hash representation of the corosync config totem section
1667 sub corosync_totem_config
{
1672 foreach my $main (@{$conf->{children
}}) {
1673 next if !defined($main->{section
}) ||
1674 $main->{section
} ne 'totem';
1676 foreach my $e (@{$main->{children
}}) {
1678 if ($e->{section
} && $e->{section
} eq 'interface') {
1681 $res->{interface
} = {};
1683 foreach my $child (@{$e->{children
}}) {
1684 next if !defined($child->{key
});
1685 $entry->{$child->{key
}} = $child->{value
};
1686 if($child->{key
} eq 'ringnumber') {
1687 $res->{interface
}->{$child->{value
}} = $entry;
1691 } elsif ($e->{key
}) {
1692 $res->{$e->{key
}} = $e->{value
};
1700 # X509 Certificate cache helper
1702 my $cert_cache_nodes = {};
1703 my $cert_cache_timestamp = time();
1704 my $cert_cache_fingerprints = {};
1706 sub update_cert_cache
{
1707 my ($update_node, $clear) = @_;
1709 syslog
('info', "Clearing outdated entries from certificate cache")
1712 $cert_cache_timestamp = time() if !defined($update_node);
1714 my $node_list = defined($update_node) ?
1715 [ $update_node ] : [ keys %$cert_cache_nodes ];
1717 foreach my $node (@$node_list) {
1718 my $clear_old = sub {
1719 if (my $old_fp = $cert_cache_nodes->{$node}) {
1720 # distrust old fingerprint
1721 delete $cert_cache_fingerprints->{$old_fp};
1722 # ensure reload on next proxied request
1723 delete $cert_cache_nodes->{$node};
1727 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
1728 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
1730 $cert_path = $custom_cert_path if -f
$custom_cert_path;
1734 my $bio = Net
::SSLeay
::BIO_new_file
($cert_path, 'r');
1735 $cert = Net
::SSLeay
::PEM_read_bio_X509
($bio);
1736 Net
::SSLeay
::BIO_free
($bio);
1739 if ($err || !defined($cert)) {
1740 &$clear_old() if $clear;
1746 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
1749 if ($err || !defined($fp) || $fp eq '') {
1750 &$clear_old() if $clear;
1754 my $old_fp = $cert_cache_nodes->{$node};
1755 $cert_cache_fingerprints->{$fp} = 1;
1756 $cert_cache_nodes->{$node} = $fp;
1758 if (defined($old_fp) && $fp ne $old_fp) {
1759 delete $cert_cache_fingerprints->{$old_fp};
1764 # load and cache cert fingerprint once
1765 sub initialize_cert_cache
{
1768 update_cert_cache
($node)
1769 if defined($node) && !defined($cert_cache_nodes->{$node});
1772 sub check_cert_fingerprint
{
1775 # clear cache every 30 minutes at least
1776 update_cert_cache
(undef, 1) if time() - $cert_cache_timestamp >= 60*30;
1778 # get fingerprint of server certificate
1781 $fp = Net
::SSLeay
::X509_get_fingerprint
($cert, 'sha256');
1783 return 0 if $@ || !defined($fp) || $fp eq ''; # error
1786 for my $expected (keys %$cert_cache_fingerprints) {
1787 return 1 if $fp eq $expected;
1792 return 1 if &$check();
1794 # clear cache and retry at most once every minute
1795 if (time() - $cert_cache_timestamp >= 60) {
1796 syslog
('info', "Could not verify remote node certificate '$fp' with list of pinned certificates, refreshing cache");
1797 update_cert_cache
();
1804 # bash completion helpers
1806 sub complete_next_vmid
{
1808 my $vmlist = get_vmlist
() || {};
1809 my $idlist = $vmlist->{ids
} || {};
1811 for (my $i = 100; $i < 10000; $i++) {
1812 return [$i] if !defined($idlist->{$i});
1820 my $vmlist = get_vmlist
();
1821 my $ids = $vmlist->{ids
} || {};
1823 return [ keys %$ids ];
1826 sub complete_local_vmid
{
1828 my $vmlist = get_vmlist
();
1829 my $ids = $vmlist->{ids
} || {};
1831 my $nodename = PVE
::INotify
::nodename
();
1834 foreach my $vmid (keys %$ids) {
1835 my $d = $ids->{$vmid};
1836 next if !$d->{node
} || $d->{node
} ne $nodename;
1843 sub complete_migration_target
{
1847 my $nodename = PVE
::INotify
::nodename
();
1849 my $nodelist = get_nodelist
();
1850 foreach my $node (@$nodelist) {
1851 next if $node eq $nodename;