1 package PVE
::Cluster
::Setup
;
14 use PVE
::APIClient
::LWP
;
23 # relevant for joining or getting joined checks, after that versions in cluster can differ
24 use constant JOIN_API_VERSION
=> 1;
25 # (APIVER-this) is oldest version a new node in addnode can have and still be accepted
26 use constant JOIN_API_AGE_AS_CLUSTER
=> 1;
27 # (APIVER-this) is oldest version a cluster node can have to still try joining
28 use constant JOIN_API_AGE_AS_JOINEE
=> 1;
30 sub assert_we_can_join_cluster_version
{
32 my $min_version = JOIN_API_VERSION
- JOIN_API_AGE_AS_JOINEE
;
33 return if $version >= $min_version;
34 die "error: incompatible join API version on cluster ($version), local node"
35 ." has ". JOIN_API_VERSION
." and supports >= $min_version. Make sure"
36 ."all cluster nodes are up-to-date.\n";
39 sub assert_node_can_join_our_version
{
41 my $min_version = JOIN_API_VERSION
- JOIN_API_AGE_AS_CLUSTER
;
42 return if $version >= $min_version;
43 die "error: unsupported old API version on joining node ($version), cluster"
44 ." node has ". JOIN_API_VERSION
." and supports >= $min_version. Please"
45 ." upgrade node before joining\n";
48 my $pmxcfs_base_dir = PVE
::Cluster
::base_dir
();
49 my $pmxcfs_auth_dir = PVE
::Cluster
::auth_dir
();
51 # only write output if something fails
56 my $record = sub { $outbuf .= shift . "\n"; };
58 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> $record, errfunc
=> $record) };
66 # Corosync related files
67 my $localclusterdir = "/etc/corosync";
68 my $localclusterconf = "$localclusterdir/corosync.conf";
69 my $authfile = "$localclusterdir/authkey";
70 my $clusterconf = "$pmxcfs_base_dir/corosync.conf";
72 # CA/certificate related files
73 my $pveca_key_fn = "$pmxcfs_auth_dir/pve-root-ca.key";
74 my $pveca_srl_fn = "$pmxcfs_auth_dir/pve-root-ca.srl";
75 my $pveca_cert_fn = "$pmxcfs_base_dir/pve-root-ca.pem";
76 # this is just a secret accessable by the web browser
77 # and is used for CSRF prevention
78 my $pvewww_key_fn = "$pmxcfs_base_dir/pve-www.key";
81 my $ssh_rsa_id_priv = "/root/.ssh/id_rsa";
82 my $ssh_rsa_id = "/root/.ssh/id_rsa.pub";
83 my $ssh_host_rsa_id = "/etc/ssh/ssh_host_rsa_key.pub";
84 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts";
85 my $sshknownhosts = "$pmxcfs_auth_dir/known_hosts";
86 my $sshauthkeys = "$pmxcfs_auth_dir/authorized_keys";
87 my $sshd_config_fn = "/etc/ssh/sshd_config";
88 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
89 my $rootsshauthkeysbackup = "${rootsshauthkeys}.org";
90 my $rootsshconfig = "/root/.ssh/config";
92 # ssh related utility functions
95 # remove duplicate keys in $sshauthkeys
96 # ssh-copy-id simply add keys, so the file can grow to large
99 if (-f
$sshauthkeys) {
100 $data = PVE
::Tools
::file_get_contents
($sshauthkeys, 128*1024);
105 if (-f
$rootsshauthkeysbackup) {
107 $data .= PVE
::Tools
::file_get_contents
($rootsshauthkeysbackup, 128*1024);
113 if (-f
$ssh_rsa_id) {
114 my $pub = PVE
::Tools
::file_get_contents
($ssh_rsa_id);
121 my @lines = split(/\n/, $data);
122 foreach my $line (@lines) {
123 if ($line !~ /^#/ && $line =~ m/(^|\s)ssh-(rsa|dsa)\s+(\S+)\s+\S+$/) {
124 next if $vhash->{$3}++;
126 $newdata .= "$line\n";
129 PVE
::Tools
::file_set_contents
($sshauthkeys, $newdata, 0600);
131 if ($found_backup && -l
$rootsshauthkeys) {
132 # everything went well, so we can remove the backup
133 unlink $rootsshauthkeysbackup;
137 sub setup_sshd_config
{
140 my $conf = PVE
::Tools
::file_get_contents
($sshd_config_fn);
142 return if $conf =~ m/^PermitRootLogin\s+yes\s*$/m;
144 if ($conf !~ s/^#?PermitRootLogin.*$/PermitRootLogin yes/m) {
146 $conf .= "\nPermitRootLogin yes\n";
149 PVE
::Tools
::file_set_contents
($sshd_config_fn, $conf);
151 PVE
::Tools
::run_command
(['systemctl', 'reload-or-restart', 'sshd']);
154 sub setup_rootsshconfig
{
156 # create ssh key if it does not exist
157 if (! -f
$ssh_rsa_id) {
159 system ("echo|ssh-keygen -t rsa -N '' -b 2048 -f ${ssh_rsa_id_priv}");
162 # create ssh config if it does not exist
163 if (! -f
$rootsshconfig) {
165 if (my $fh = IO
::File-
>new($rootsshconfig, O_CREAT
|O_WRONLY
|O_EXCL
, 0640)) {
166 # this is the default ciphers list from Debian's OpenSSH package (OpenSSH_7.4p1 Debian-10, OpenSSL 1.0.2k 26 Jan 2017)
167 # changed order to put AES before Chacha20 (most hardware has AESNI)
168 print $fh "Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm\@openssh.com,aes256-gcm\@openssh.com,chacha20-poly1305\@openssh.com\n";
176 mkdir $pmxcfs_auth_dir;
180 if (! -f
$sshauthkeys) {
182 if (-f
$rootsshauthkeys) {
183 $old = PVE
::Tools
::file_get_contents
($rootsshauthkeys, 128*1024);
185 if (my $fh = IO
::File-
>new ($sshauthkeys, O_CREAT
|O_WRONLY
|O_EXCL
, 0400)) {
186 PVE
::Tools
::safe_print
($sshauthkeys, $fh, $old) if $old;
192 warn "can't create shared ssh key database '$sshauthkeys'\n"
193 if ! -f
$sshauthkeys;
195 if (-f
$rootsshauthkeys && ! -l
$rootsshauthkeys) {
196 if (!rename($rootsshauthkeys , $rootsshauthkeysbackup)) {
197 warn "rename $rootsshauthkeys failed - $!\n";
201 if (! -l
$rootsshauthkeys) {
202 symlink $sshauthkeys, $rootsshauthkeys;
205 if (! -l
$rootsshauthkeys) {
206 warn "can't create symlink for ssh keys '$rootsshauthkeys' -> '$sshauthkeys'\n";
208 unlink $rootsshauthkeysbackup if $import_ok;
212 sub ssh_unmerge_known_hosts
{
213 return if ! -l
$sshglobalknownhosts;
216 $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024)
217 if -f
$sshknownhosts;
219 PVE
::Tools
::file_set_contents
($sshglobalknownhosts, $old);
222 sub ssh_merge_known_hosts
{
223 my ($nodename, $ip_address, $createLink) = @_;
225 die "no node name specified" if !$nodename;
226 die "no ip address specified" if !$ip_address;
228 # ssh lowercases hostnames (aliases) before comparision, so we need too
229 $nodename = lc($nodename);
230 $ip_address = lc($ip_address);
232 mkdir $pmxcfs_auth_dir;
234 if (! -f
$sshknownhosts) {
235 if (my $fh = IO
::File-
>new($sshknownhosts, O_CREAT
|O_WRONLY
|O_EXCL
, 0600)) {
240 my $old = PVE
::Tools
::file_get_contents
($sshknownhosts, 128*1024);
244 if ((! -l
$sshglobalknownhosts) && (-f
$sshglobalknownhosts)) {
245 $new = PVE
::Tools
::file_get_contents
($sshglobalknownhosts, 128*1024);
248 my $hostkey = PVE
::Tools
::file_get_contents
($ssh_host_rsa_id);
249 # Note: file sometimes containe emty lines at start, so we use multiline match
250 die "can't parse $ssh_host_rsa_id" if $hostkey !~ m/^(ssh-rsa\s\S+)(\s.*)?$/m;
259 my $merge_line = sub {
260 my ($line, $all) = @_;
262 return if $line =~ m/^\s*$/; # skip empty lines
263 return if $line =~ m/^#/; # skip comments
265 if ($line =~ m/^(\S+)\s(ssh-rsa\s\S+)(\s.*)?$/) {
268 if (!$vhash->{$key}) {
270 if ($key =~ m/\|1\|([^\|\s]+)\|([^\|\s]+)$/) {
271 my $salt = decode_base64
($1);
273 my $hmac = Digest
::HMAC_SHA1-
>new($salt);
274 $hmac->add($nodename);
275 my $hd = $hmac->b64digest . '=';
276 if ($digest eq $hd) {
277 if ($rsakey eq $hostkey) {
283 $hmac = Digest
::HMAC_SHA1-
>new($salt);
284 $hmac->add($ip_address);
285 $hd = $hmac->b64digest . '=';
286 if ($digest eq $hd) {
287 if ($rsakey eq $hostkey) {
294 $key = lc($key); # avoid duplicate entries, ssh compares lowercased
295 if ($key eq $ip_address) {
296 $found_local_ip = 1 if $rsakey eq $hostkey;
297 } elsif ($key eq $nodename) {
298 $found_nodename = 1 if $rsakey eq $hostkey;
308 while ($old && $old =~ s/^((.*?)(\n|$))//) {
310 &$merge_line($line, 1);
313 while ($new && $new =~ s/^((.*?)(\n|$))//) {
318 # add our own key if not already there
319 $data .= "$nodename $hostkey\n" if !$found_nodename;
320 $data .= "$ip_address $hostkey\n" if !$found_local_ip;
322 PVE
::Tools
::file_set_contents
($sshknownhosts, $data);
324 return if !$createLink;
326 unlink $sshglobalknownhosts;
327 symlink $sshknownhosts, $sshglobalknownhosts;
329 warn "can't create symlink for ssh known hosts '$sshglobalknownhosts' -> '$sshknownhosts'\n"
330 if ! -l
$sshglobalknownhosts;
334 # directory and file creation
339 PVE
::Cluster
::check_cfs_is_mounted
();
341 my @required_dirs = (
342 "$pmxcfs_base_dir/priv",
343 "$pmxcfs_base_dir/nodes",
344 "$pmxcfs_base_dir/nodes/$nodename",
345 "$pmxcfs_base_dir/nodes/$nodename/lxc",
346 "$pmxcfs_base_dir/nodes/$nodename/qemu-server",
347 "$pmxcfs_base_dir/nodes/$nodename/openvz",
348 "$pmxcfs_base_dir/nodes/$nodename/priv");
350 foreach my $dir (@required_dirs) {
352 mkdir($dir) || $! == EEXIST
|| die "unable to create directory '$dir' - $!\n";
358 my $authprivkeyfn = "$pmxcfs_auth_dir/authkey.key";
359 my $authpubkeyfn = "$pmxcfs_base_dir/authkey.pub";
361 return if -f
"$authprivkeyfn";
363 PVE
::Cluster
::check_cfs_is_mounted
();
365 PVE
::Cluster
::cfs_lock_authkey
(undef, sub {
366 mkdir $pmxcfs_auth_dir || $! == EEXIST
|| die "unable to create dir '$pmxcfs_auth_dir' - $!\n";
368 run_silent_cmd
(['openssl', 'genrsa', '-out', $authprivkeyfn, '2048']);
370 run_silent_cmd
(['openssl', 'rsa', '-in', $authprivkeyfn, '-pubout', '-out', $authpubkeyfn]);
378 return if -f
$pveca_key_fn;
381 run_silent_cmd
(['openssl', 'genrsa', '-out', $pveca_key_fn, '4096']);
384 die "unable to generate pve ca key:\n$@" if $@;
389 if (-f
$pveca_key_fn && -f
$pveca_cert_fn) {
395 # we try to generate an unique 'subject' to avoid browser problems
396 # (reused serial numbers, ..)
398 UUID
::generate
($uuid);
400 UUID
::unparse
($uuid, $uuid_str);
403 # wrap openssl with faketime to prevent bug #904
404 run_silent_cmd
(['faketime', 'yesterday', 'openssl', 'req', '-batch',
405 '-days', '3650', '-new', '-x509', '-nodes', '-key',
406 $pveca_key_fn, '-out', $pveca_cert_fn, '-subj',
407 "/CN=Proxmox Virtual Environment/OU=$uuid_str/O=PVE Cluster Manager CA/"]);
410 die "generating pve root certificate failed:\n$@" if $@;
415 sub gen_pve_ssl_key
{
418 die "no node name specified" if !$nodename;
420 my $pvessl_key_fn = "$pmxcfs_base_dir/nodes/$nodename/pve-ssl.key";
422 return if -f
$pvessl_key_fn;
425 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvessl_key_fn, '2048']);
428 die "unable to generate pve ssl key for node '$nodename':\n$@" if $@;
431 sub gen_pve_www_key
{
433 return if -f
$pvewww_key_fn;
436 run_silent_cmd
(['openssl', 'genrsa', '-out', $pvewww_key_fn, '2048']);
439 die "unable to generate pve www key:\n$@" if $@;
445 PVE
::Tools
::file_set_contents
($pveca_srl_fn, $serial);
448 sub gen_pve_ssl_cert
{
449 my ($force, $nodename, $ip) = @_;
451 die "no node name specified" if !$nodename;
452 die "no IP specified" if !$ip;
454 my $pvessl_cert_fn = "$pmxcfs_base_dir/nodes/$nodename/pve-ssl.pem";
456 return if !$force && -f
$pvessl_cert_fn;
458 my $names = "IP:127.0.0.1,IP:::1,DNS:localhost";
460 my $rc = PVE
::INotify
::read_file
('resolvconf');
464 $names .= ",DNS:$nodename";
466 my $fqdn = $nodename;
467 if ($rc && $rc->{search
}) {
468 $fqdn .= ".$rc->{search}";
469 $names .= ",DNS:$fqdn";
472 my $sslconf = <<__EOD;
473 RANDFILE = /root/.rnd
478 distinguished_name = req_distinguished_name
479 req_extensions = v3_req
481 string_mask = nombstr
483 [ req_distinguished_name ]
484 organizationalUnitName = PVE Cluster Node
485 organizationName = Proxmox Virtual Environment
489 basicConstraints = CA:FALSE
490 extendedKeyUsage = serverAuth
491 subjectAltName = $names
494 my $cfgfn = "/tmp/pvesslconf-$$.tmp";
495 my $fh = IO
::File-
>new ($cfgfn, "w");
499 my $reqfn = "/tmp/pvecertreq-$$.tmp";
502 my $pvessl_key_fn = "$pmxcfs_base_dir/nodes/$nodename/pve-ssl.key";
505 'openssl', 'req', '-batch', '-new', '-config', $cfgfn, '-key', $pvessl_key_fn, '-out', $reqfn
512 die "unable to generate pve certificate request:\n$err";
515 update_serial
("0000000000000000") if ! -f
$pveca_srl_fn;
518 my $cainfo = PVE
::Certificate
::get_certificate_info
($pveca_cert_fn);
519 my $daysleft = int(($cainfo->{notafter
} - time())/(24*60*60));
521 if ($daysleft < 14) {
522 die "CA expires in less than 2 weeks, unable to generate certificate.\n";
525 # let the certificate expire a little sooner that the ca, so subtract 2 days
528 # we want the certificates to only last 2 years, since some browsers
529 # do not accept certificates with very long expiry time
530 if ($daysleft >= 2*365) {
536 'faketime', 'yesterday', # NOTE: wrap openssl with faketime to prevent bug #904
537 'openssl', 'x509', '-req', '-in', $reqfn, '-days', $daysleft, '-out', $pvessl_cert_fn,
538 '-CAkey', $pveca_key_fn, '-CA', $pveca_cert_fn, '-CAserial', $pveca_srl_fn, '-extfile', $cfgfn
545 die "unable to generate pve ssl certificate:\n$err";
552 sub gen_pve_node_files
{
553 my ($nodename, $ip, $opt_force) = @_;
555 gen_local_dirs
($nodename);
559 # make sure we have a (cluster wide) secret
560 # for CSRFR prevention
563 # make sure we have a (per node) private key
564 gen_pve_ssl_key
($nodename);
566 # make sure we have a CA
567 my $force = gen_pveca_cert
();
569 $force = 1 if $opt_force;
571 gen_pve_ssl_cert
($force, $nodename, $ip);
574 my $vzdump_cron_dummy = <<__EOD;
575 # cluster wide vzdump cron schedule
576 # Atomatically generated file - do not edit
578 PATH="/usr/sbin:/usr/bin:/sbin:/bin"
582 sub gen_pve_vzdump_symlink
{
584 my $filename = "/etc/pve/vzdump.cron";
586 my $link_fn = "/etc/cron.d/vzdump";
588 if ((-f
$filename) && (! -l
$link_fn)) {
589 rename($link_fn, "/root/etc_cron_vzdump.org"); # make backup if file exists
590 symlink($filename, $link_fn);
594 sub gen_pve_vzdump_files
{
596 my $filename = "/etc/pve/vzdump.cron";
598 PVE
::Tools
::file_set_contents
($filename, $vzdump_cron_dummy)
601 gen_pve_vzdump_symlink
();
606 sub assert_joinable
{
607 my ($local_addr, $links, $force) = @_;
610 my $error = sub { $errors .= "* $_[0]\n"; };
613 $error->("authentication key '$authfile' already exists");
616 if (-f
$clusterconf) {
617 $error->("cluster config '$clusterconf' already exists");
620 my $vmlist = PVE
::Cluster
::get_vmlist
();
621 if ($vmlist && $vmlist->{ids
} && scalar(keys %{$vmlist->{ids
}})) {
622 $error->("this host already contains virtual guests");
625 if (PVE
::Tools
::run_command
(['corosync-quorumtool', '-l'], noerr
=> 1, quiet
=> 1) == 0) {
626 $error->("corosync is already running, is this node already in a cluster?!");
629 # check if corosync ring IPs are configured on the current nodes interfaces
631 my $ip = shift // return;
633 if (!PVE
::JSONSchema
::pve_verify_ip
($ip, 1)) {
635 eval { $ip = PVE
::Network
::get_ip_from_hostname
($host); };
637 $error->("$logid: cannot use '$host': $@\n") ;
642 my $cidr = (Net
::IP
::ip_is_ipv6
($ip)) ?
"$ip/128" : "$ip/32";
643 my $configured_ips = PVE
::Network
::get_local_ip_from_cidr
($cidr);
645 $error->("$logid: cannot use IP '$ip', not found on local node!\n")
646 if scalar(@$configured_ips) < 1;
649 $check_ip->($local_addr, 'local node address');
651 foreach my $link (keys %$links) {
652 $check_ip->($links->{$link}->{address
}, "link$link");
656 warn "detected the following error(s):\n$errors";
657 die "Check if node may join a cluster failed!\n" if !$force;
658 warn "\nWARNING : detected error but forced to continue!\n\n";
665 my $nodename = PVE
::INotify
::nodename
();
666 my $local_ip_address = PVE
::Cluster
::remote_node_ip
($nodename);
668 my $links = PVE
::Corosync
::extract_corosync_link_args
($param);
670 # check if we can join with the given parameters and current node state
671 assert_joinable
($local_ip_address, $links, $param->{force
});
674 setup_rootsshconfig
();
677 # make sure known_hosts is on local filesystem
678 ssh_unmerge_known_hosts
();
680 my $host = $param->{hostname
};
682 username
=> 'root@pam',
683 password
=> $param->{password
},
684 cookie_name
=> 'PVEAuthCookie',
690 if (my $fp = $param->{fingerprint
}) {
691 $conn_args->{cached_fingerprints
} = { uc($fp) => 1 };
693 # API schema ensures that we can only get here from CLI handler
694 $conn_args->{manual_verification
} = 1;
697 print "Establishing API connection with host '$host'\n";
699 my $conn = PVE
::APIClient
::LWP-
>new(%$conn_args);
702 # login raises an exception on failure, so if we get here we're good
703 print "Login succeeded.\n";
705 print "check cluster join API version\n";
706 my $apiver = eval { $conn->get("/cluster/config/apiversion") } // 0;
707 assert_we_can_join_cluster_version
($apiver);
710 $args->{force
} = $param->{force
} if defined($param->{force
});
711 $args->{nodeid
} = $param->{nodeid
} if $param->{nodeid
};
712 $args->{votes
} = $param->{votes
} if defined($param->{votes
});
713 foreach my $link (keys %$links) {
714 $args->{"link$link"} = PVE
::Corosync
::print_corosync_link
($links->{$link});
717 # this will be used as fallback if no links are specified
719 $args->{link0
} = $local_ip_address if $apiver == 0;
720 $args->{new_node_ip
} = $local_ip_address if $apiver >= 1;
722 print "No cluster network links passed explicitly, fallback to local node"
723 . " IP '$local_ip_address'\n";
727 $args->{apiversion
} = JOIN_API_VERSION
;
730 print "Request addition of this node\n";
731 my $res = eval { $conn->post("/cluster/config/nodes/$nodename", $args); };
733 if (ref($err) && $err->isa('PVE::APIClient::Exception')) {
734 # we received additional info about the error, show the user
736 warn "An error occurred on the cluster node: $err->{msg}\n";
737 foreach my $key (sort keys %{$err->{errors
}}) {
738 my $symbol = ($key =~ m/^warning/) ?
'*' : '!';
739 warn "$symbol $err->{errors}->{$key}\n";
742 die "Cluster join aborted!\n";
748 if (defined($res->{warnings
})) {
749 foreach my $warn (@{$res->{warnings
}}) {
750 warn "cluster: $warn\n";
754 print "Join request OK, finishing setup locally\n";
756 # added successfuly - now prepare local node
757 finish_join
($nodename, $res->{corosync_conf
}, $res->{corosync_authkey
});
761 my ($nodename, $corosync_conf, $corosync_authkey) = @_;
763 mkdir "$localclusterdir";
764 PVE
::Tools
::file_set_contents
($authfile, $corosync_authkey);
765 PVE
::Tools
::file_set_contents
($localclusterconf, $corosync_conf);
767 print "stopping pve-cluster service\n";
768 my $cmd = ['systemctl', 'stop', 'pve-cluster'];
769 PVE
::Tools
::run_command
($cmd, errmsg
=> "can't stop pve-cluster service");
771 my $dbfile = PVE
::Cluster
::cfs_backup_database
();
774 $cmd = ['systemctl', 'start', 'corosync', 'pve-cluster'];
775 PVE
::Tools
::run_command
($cmd, errmsg
=> "starting pve-cluster failed");
779 while (!PVE
::Cluster
::check_cfs_quorum
(1)) {
781 print "waiting for quorum...";
787 print "OK\n" if !$printqmsg;
789 updatecerts_and_ssh
(1);
791 print "generated new node certificate, restart pveproxy and pvedaemon services\n";
792 PVE
::Tools
::run_command
(['systemctl', 'reload-or-restart', 'pvedaemon', 'pveproxy']);
794 print "successfully added node '$nodename' to cluster.\n";
797 sub updatecerts_and_ssh
{
798 my ($force_new_cert, $silent) = @_;
800 my $p = sub { print "$_[0]\n" if !$silent };
802 setup_rootsshconfig
();
804 gen_pve_vzdump_symlink
();
806 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
807 return undef if $silent;
808 die "no quorum - unable to update files\n";
813 my $nodename = PVE
::INotify
::nodename
();
814 my $local_ip_address = PVE
::Cluster
::remote_node_ip
($nodename);
816 $p->("(re)generate node files");
817 $p->("generate new node certificate") if $force_new_cert;
818 gen_pve_node_files
($nodename, $local_ip_address, $force_new_cert);
820 $p->("merge authorized SSH keys and known hosts");
822 ssh_merge_known_hosts
($nodename, $local_ip_address, 1);
823 gen_pve_vzdump_files
();