1 package PVE
::LXC
::Setup
::Base
;
21 use PVE
::LXC
::Setup
::Plugin
;
22 use base
qw(PVE::LXC::Setup::Plugin);
25 my ($class, $conf, $rootdir, $os_release) = @_;
27 return bless { conf
=> $conf, rootdir
=> $rootdir, os_release
=> $os_release }, $class;
31 my ($self, $conf) = @_;
33 my $nameserver = $conf->{nameserver
};
34 my $searchdomains = $conf->{searchdomain
};
36 if ($conf->{'testmode'}) {
37 $nameserver //= '8.8.8.8 8.8.8.9';
38 $searchdomains //= 'proxmox.com';
41 my $host_resolv_conf = $self->{host_resolv_conf
};
43 if (!defined($nameserver)) {
45 foreach my $k ("dns1", "dns2", "dns3") {
46 if (my $ns = $host_resolv_conf->{$k}) {
50 $nameserver = join(' ', @list);
53 if (!defined($searchdomains)) {
54 $searchdomains = $host_resolv_conf->{search
};
57 return ($searchdomains, $nameserver);
60 sub update_etc_hosts
{
61 my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
63 my $hosts_fn = '/etc/hosts';
64 return if $self->ct_is_file_ignored($hosts_fn);
66 my $namepart = ($newname =~ s/\..*$//r);
69 if ($newname =~ /\./) {
70 $all_names .= "$newname $namepart";
72 foreach my $domain (PVE
::Tools
::split_list
($searchdomains)) {
73 $all_names .= ' ' if $all_names;
74 $all_names .= "$newname.$domain";
76 $all_names .= ' ' if $all_names;
77 $all_names .= $newname;
83 my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
84 my $lo6 = "::1 localhost.localnet localhost\n";
85 if ($self->ct_file_exists($hosts_fn)) {
86 my $data = $self->ct_file_get_contents($hosts_fn);
87 # don't take localhost entries within our hosts sections into account
88 $data = remove_pve_sections
($data);
90 # check for existing localhost entries
91 $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
92 $section .= $lo6 if $data !~ /^\h*::1\h+/m;
94 $section .= $lo4 . $lo6;
97 if (defined($hostip)) {
98 $section .= "$hostip $all_names\n";
99 } elsif ($namepart ne 'localhost') {
100 $section .= "127.0.1.1 $all_names\n";
102 $section .= "127.0.1.1 $namepart\n";
105 $self->ct_modify_file($hosts_fn, $section);
109 my ($self, $conf) = @_;
111 # do nothing by default
115 my ($self, $conf) = @_;
117 my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
121 $data .= "search " . join(' ', PVE
::Tools
::split_list
($searchdomains)) . "\n"
124 foreach my $ns ( PVE
::Tools
::split_list
($nameserver)) {
125 $data .= "nameserver $ns\n";
128 $self->ct_modify_file("/etc/resolv.conf", $data, replace
=> 1);
132 my ($self, $conf) = @_;
134 my $hostname = $conf->{hostname
} || 'localhost';
136 my $namepart = ($hostname =~ s/\..*$//r);
138 my $hostname_fn = "/etc/hostname";
140 my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
142 my ($ipv4, $ipv6) = PVE
::LXC
::get_primary_ips
($conf);
143 my $hostip = $ipv4 || $ipv6;
145 my ($searchdomains) = $self->lookup_dns_conf($conf);
147 $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
149 $self->ct_file_set_contents($hostname_fn, "$namepart\n");
153 my ($self, $conf) = @_;
155 die "please implement this inside subclass"
159 my ($self, $conf) = @_;
161 die "please implement this inside subclass"
164 # A few distros as well as unprivileged containers cannot deal with the
165 # /dev/lxc/ tty subdirectory.
167 my ($self, $conf) = @_;
168 return $conf->{unprivileged
} ?
'' : 'lxc/';
171 sub fixup_old_getty
{
174 my $sd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
175 "/lib/systemd/system" : "/usr/lib/systemd/system";
177 my $sd_getty_service_rel = "$sd_dir_rel/getty\@.service";
178 return if !$self->ct_file_exists($sd_getty_service_rel);
180 my $raw = $self->ct_file_get_contents($sd_getty_service_rel);
182 my $sd_container_getty_service_rel = "$sd_dir_rel/container-getty\@.service";
183 # systemd on CenoOS 7.1 is too old (version 205), so there is no
184 # container-getty service
185 if (!$self->ct_file_exists($sd_container_getty_service_rel)) {
186 if ($raw =~ s!^ConditionPathExists=/dev/tty0$!ConditionPathExists=/dev/tty!m) {
187 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
190 # undo above change (in case someone updated systemd)
191 if ($raw =~ s!^ConditionPathExists=/dev/tty$!ConditionPathExists=/dev/tty0!m) {
192 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
197 sub setup_container_getty_service
{
198 my ($self, $conf) = @_;
200 my $sd_dir = $self->ct_is_executable("/lib/systemd/systemd") ?
201 "/lib/systemd/system" : "/usr/lib/systemd/system";
203 # prefer container-getty.service shipped by newer systemd versions
204 # fallback to getty.service and just return if that doesn't exists either..
205 my $template_base = "container-getty\@";
206 my $template_path = "${sd_dir}/${template_base}.service";
207 my $instance_base = $template_base;
209 if (!$self->ct_file_exists($template_path)) {
210 $template_base = "getty\@";
211 $template_path = "${template_base}.service";
212 $instance_base = "{$template_base}tty";
213 return if !$self->ct_file_exists($template_path);
216 my $raw = $self->ct_file_get_contents($template_path);
217 my $ttyname = $self->devttydir($conf) . 'tty%I';
218 if ($raw =~ s
@pts/%I|lxc
/tty
%I@$ttyname@g) {
219 $self->ct_file_set_contents($template_path, $raw);
222 my $getty_target_fn = "/etc/systemd/system/getty.target.wants/";
223 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
225 for (my $i = 1; $i < 7; $i++) {
226 # ensure that not two gettys are using the same tty!
227 $self->ct_unlink("$getty_target_fn/getty\@tty$i.service");
228 $self->ct_unlink("$getty_target_fn/container-getty\@$i.service");
230 # re-enable only those requested
231 if ($i <= $ttycount) {
232 my $tty_service = "${instance_base}${i}.service";
234 $self->ct_symlink($template_path, "$getty_target_fn/$tty_service");
238 # ensure getty.target is not masked
239 $self->ct_unlink("/etc/systemd/system/getty.target");
242 sub setup_systemd_networkd
{
243 my ($self, $conf) = @_;
245 foreach my $k (keys %$conf) {
246 next if $k !~ m/^net(\d+)$/;
247 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
250 my $filename = "/etc/systemd/network/$d->{name}.network";
257 Description = Interface $d->{name} autoconfigured by PVE
261 my ($has_ipv4, $has_ipv6);
264 my @DHCPMODES = ('no', 'ipv4', 'ipv6', 'yes');
265 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
267 my $accept_ra = 'false';
269 if (defined(my $ip = $d->{ip
})) {
272 } elsif ($ip ne 'manual') {
274 $data .= "Address = $ip\n";
277 if (defined(my $gw = $d->{gw
})) {
278 $data .= "Gateway = $gw\n";
279 if ($has_ipv4 && !PVE
::Network
::is_ip_in_cidr
($gw, $d->{ip
}, 4)) {
280 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
284 if (defined(my $ip = $d->{ip6
})) {
287 } elsif ($ip eq 'auto') {
289 } elsif ($ip ne 'manual') {
291 $data .= "Address = $ip\n";
294 if (defined(my $gw = $d->{gw6
})) {
295 $accept_ra = 'false';
296 $data .= "Gateway = $gw\n";
297 if ($has_ipv6 && !PVE
::Network
::is_ip_in_cidr
($gw, $d->{ip6
}, 6) &&
298 !PVE
::Network
::is_ip_in_cidr
($gw, 'fe80::/10', 6)) {
299 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
303 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
304 $data .= "IPv6AcceptRA = $accept_ra\n";
305 $data .= $routes if $routes;
307 $self->ct_file_set_contents($filename, $data);
311 sub setup_securetty
{
312 my ($self, $conf, @add) = @_;
314 my $filename = "/etc/securetty";
315 # root login is already allowed on every device if no securetty present
316 return if !$self->ct_file_exists($filename);
319 @add = qw(console tty1 tty2 tty3 tty4);
320 if (my $dir = $self->devttydir($conf)) {
321 @add = map { "${dir}$_" } @add;
325 my $data = $self->ct_file_get_contents($filename);
326 chomp $data; $data .= "\n";
327 foreach my $dev (@add) {
328 if ($data !~ m!^\Q$dev\E\s*$!m) {
332 $self->ct_file_set_contents($filename, $data);
335 my $replacepw = sub {
336 my ($self, $file, $user, $epw, $shadow) = @_;
338 my $tmpfile = "$file.$$";
341 my $src = $self->ct_open_file_read($file) ||
342 die "unable to open file '$file' - $!";
344 my $st = $self->ct_stat($src) ||
345 die "unable to stat file - $!";
347 my $dst = $self->ct_open_file_write($tmpfile) ||
348 die "unable to open file '$tmpfile' - $!";
350 # copy owner and permissions
351 chmod $st->mode, $dst;
352 chown $st->uid, $st->gid, $dst;
354 my $last_change = int(time()/(60*60*24));
356 while (defined (my $line = <$src>)) {
358 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
360 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
365 $src->close() || die "close '$file' failed - $!\n";
366 $dst->close() || die "close '$tmpfile' failed - $!\n";
369 $self->ct_unlink($tmpfile);
371 $self->ct_rename($tmpfile, $file);
372 $self->ct_unlink($tmpfile); # in case rename fails
376 sub set_user_password
{
377 my ($self, $conf, $user, $opt_password) = @_;
379 my $pwfile = "/etc/passwd";
381 return if !$self->ct_file_exists($pwfile);
383 my $shadow = "/etc/shadow";
385 if (defined($opt_password)) {
386 if ($opt_password !~ m/^\$(?:1|2[axy]?|5|6)\$[a-zA-Z0-9.\/]{1,16}\
$[a-zA-Z0-9
.\
/]+$/) {
387 my $time = substr (Digest
::SHA
::sha1_base64
(time), 0, 8);
388 $opt_password = crypt(encode
("utf8", $opt_password), "\$6\$$time\$");
394 if ($self->ct_file_exists($shadow)) {
395 &$replacepw ($self, $shadow, $user, $opt_password, 1);
396 &$replacepw ($self, $pwfile, $user, 'x');
398 &$replacepw ($self, $pwfile, $user, $opt_password);
402 my $parse_home_dir = sub {
403 my ($self, $passwdfile, $user) = @_;
405 my $fh = $self->ct_open_file_read($passwdfile);
406 while (defined (my $line = <$fh>)) {
408 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
412 sub set_user_authorized_ssh_keys
{
413 my ($self, $conf, $user, $ssh_keys) = @_;
415 my $passwd = "/etc/passwd";
416 my $home = $user eq "root" ?
"/root/" : "/home/$user/";
418 $home = &$parse_home_dir($self, $passwd, $user)
419 if $self->ct_file_exists($passwd);
421 die "home directory '$home' of $user does not exist!"
422 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
424 $self->ct_mkdir("$home/.ssh", 0700)
425 if ! $self->ct_is_directory("$home/.ssh");
427 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms
=> 0700);
430 my $randomize_crontab = sub {
431 my ($self, $conf) = @_;
434 # Note: dir_glob_foreach() untaints filenames!
435 PVE
::Tools
::dir_glob_foreach
("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
437 push @files, "/etc/cron.d/$name";
440 my $crontab_fn = "/etc/crontab";
441 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
443 foreach my $filename (@files) {
444 my $data = $self->ct_file_get_contents($filename);
446 foreach my $line (split(/\n/, $data)) {
447 # we only randomize minutes for root crontab entries
448 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
450 my $min = int(rand()*59);
451 $new .= "$min$rest\n";
456 $self->ct_file_set_contents($filename, $new);
461 my ($self, $conf) = @_;
463 my $zoneinfo = $conf->{timezone
};
465 return if !defined($zoneinfo);
467 my $tz_path = "/usr/share/zoneinfo/$zoneinfo";
469 if ($zoneinfo eq 'host') {
470 $tz_path = $self->{host_localtime
};
473 if ($self->ct_file_exists($tz_path)) {
474 if (abs_path
('/etc/localtime') ne $tz_path) {
475 my $tmpfile = "localtime.$$.new.tmpfile";
476 $self->ct_symlink($tz_path, $tmpfile);
477 $self->ct_rename($tmpfile, "/etc/localtime");
480 # not all distributions have /etc/timezone
481 if ($self->ct_file_exists('/etc/timezone')) {
482 my $contents = $zoneinfo eq 'host' ?
$self->{host_timezone
} : $zoneinfo;
483 $self->ct_file_set_contents('/etc/timezone', "$contents\n");
486 warn "container does not have $tz_path, timezone can not be modified\n";
490 sub clear_machine_id
{
491 my ($self, $conf, $clone) = @_;
493 my $uses_systemd = $self->ct_is_executable("/lib/systemd/systemd")
494 || $self->ct_is_executable("/usr/lib/systemd/systemd");
496 my $dbus_machine_id_path = "/var/lib/dbus/machine-id";
497 my $machine_id_path = "/etc/machine-id";
499 my $machine_id_existed = $self->ct_file_exists($machine_id_path);
502 $self->ct_file_exists($dbus_machine_id_path)
503 && !$self->ct_is_symlink($dbus_machine_id_path)
506 $self->ct_unlink($dbus_machine_id_path);
509 if ($machine_id_existed) {
510 # truncate exiting ones on clone to avoid FirstBoot condition. admins can override this by
511 # removing the machine-id file or setting it to uninitialized before creating a template, or
512 # cloning a guest - as per machine-id(5) man page. TODO: add explicit switch to API?
514 my $old_machine_id = $self->ct_file_read_firstline($machine_id_path) // '';
515 if ($uses_systemd && $old_machine_id ne 'uninitialized') {
516 $self->ct_file_set_contents($machine_id_path, "\n") if $uses_systemd;
519 $self->ct_unlink($machine_id_path);
524 # tries to guess the systemd (major) version based on the
525 # libsystemd-shared<version>.so linked with /sbin/init
526 sub get_systemd_version
{
527 my ($self, $init) = @_;
530 PVE
::Tools
::run_command
(
531 ['objdump', '-p', $self->{rootdir
}.$init],
534 if ($line =~ /libsystemd-shared-(\d+)(?:[-.][a-zA-Z0-9]+)*\.so:?$/) {
538 errmsg
=> "objdump on $init failed",
544 sub unified_cgroupv2_support
{
545 my ($self, $init) = @_;
547 # https://www.freedesktop.org/software/systemd/man/systemd.html
548 # systemd is installed as symlink to /sbin/init
549 # assume non-systemd init will run with unified cgroupv2
550 if (!defined($init) || $init !~ m
@/systemd$@) {
554 # systemd version 232 (e.g. debian stretch) supports the unified hierarchy
555 my $sdver = $self->get_systemd_version($init);
556 if (!defined($sdver) || $sdver < 232) {
563 sub get_ct_init_path
{
566 my $init_path = "/sbin/init";
567 if ($self->ct_is_symlink($init_path)) {
568 $init_path = $self->ct_readlink_recursive($init_path);
573 sub ssh_host_key_types_to_generate
{
577 rsa
=> 'ssh_host_rsa_key',
578 dsa
=> 'ssh_host_dsa_key',
579 ecdsa
=> 'ssh_host_ecdsa_key',
580 ed25519
=> 'ssh_host_ed25519_key',
585 my ($self, $conf) = @_;
587 $self->ct_file_set_contents('/fastboot', ''); # skips fsck, among other things
589 $self->setup_init($conf);
590 $self->setup_network($conf);
591 $self->set_hostname($conf);
592 $self->set_dns($conf);
593 $self->set_timezone($conf);
598 sub post_clone_hook
{
599 my ($self, $conf) = @_;
601 $self->clear_machine_id($conf, 1);
604 sub post_create_hook
{
605 my ($self, $conf, $root_password, $ssh_keys) = @_;
607 $self->clear_machine_id($conf);
608 $self->template_fixup($conf);
610 &$randomize_crontab($self, $conf);
612 $self->set_user_password($conf, 'root', $root_password);
613 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
614 $self->setup_init($conf);
615 $self->setup_network($conf);
616 $self->set_hostname($conf);
617 $self->set_dns($conf);
618 $self->set_timezone($conf);
623 # File access wrappers for container setup code.
624 # NOTE: those are not direct part of the Plugin API (yet), avoid using them outside the child plugins
625 # For user-namespace support these might need to take uid and gid maps into account.
627 sub ct_is_file_ignored
{
628 my ($self, $file) = @_;
629 my ($name, $path) = fileparse
($file);
630 return -f
"$path/.pve-ignore.$name";
633 sub ct_reset_ownership
{
634 my ($self, @files) = @_;
635 my $conf = $self->{conf
};
636 return if !$self->{id_map
};
638 @files = grep { !$self->ct_is_file_ignored($_) } @files;
641 my $uid = $self->{rootuid
};
642 my $gid = $self->{rootgid
};
643 chown($uid, $gid, @files);
647 my ($self, $file, $mask) = @_;
648 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
649 if (defined($mask)) {
650 return CORE
::mkdir($file, $mask) && $self->ct_reset_ownership($file);
652 return CORE
::mkdir($file) && $self->ct_reset_ownership($file);
657 my ($self, @files) = @_;
658 foreach my $file (@files) {
659 next if $self->ct_is_file_ignored($file);
665 my ($self, $old, $new) = @_;
666 return if $self->ct_is_file_ignored($new);
667 CORE
::rename($old, $new);
670 sub ct_open_file_read
{
673 return IO
::File-
>new($file, O_RDONLY
, @_);
676 sub ct_open_file_write
{
679 $file = '/dev/null' if $self->ct_is_file_ignored($file);
680 my $fh = IO
::File-
>new($file, O_WRONLY
| O_CREAT
, @_);
681 $self->ct_reset_ownership($fh);
689 if (defined($self->{id_map
})) {
690 $opts->{owner
} = $self->{rootuid
};
691 $opts->{group
} = $self->{rootgid
};
693 File
::Path
::make_path
(@_, $opts);
697 my ($self, $old, $new) = @_;
698 return if $self->ct_is_file_ignored($new);
699 if (CORE
::symlink($old, $new)) {
700 if (defined($self->{id_map
})) {
701 POSIX
::lchown
($self->{rootuid
}, $self->{rootgid
}, $new);
710 my ($self, $name) = @_;
711 return CORE
::readlink($name);
714 sub ct_readlink_recursive
{
715 my ($self, $name) = @_;
718 for (my $i = 0; $self->ct_is_symlink($res); $i++) {
719 # arbitrary limit, but should be enough for all for our management relevant things
720 die "maximal link depth of 10 for resolving '$name' reached, abort\n" if $i >= 10;
721 $res = $self->ct_readlink($res);
722 $res = abs_path
($res);
728 my ($self, $file) = @_;
732 sub ct_is_directory
{
733 my ($self, $file) = @_;
738 my ($self, $file) = @_;
742 sub ct_is_executable
{
743 my ($self, $file) = @_;
748 my ($self, $file) = @_;
749 return File
::stat::stat($file);
752 sub ct_file_read_firstline
{
753 my ($self, $file) = @_;
754 return PVE
::Tools
::file_read_firstline
($file);
757 sub ct_file_get_contents
{
758 my ($self, $file) = @_;
759 return PVE
::Tools
::file_get_contents
($file);
762 sub ct_file_set_contents
{
763 my ($self, $file, $data, $perms) = @_;
764 return if $self->ct_is_file_ignored($file);
765 PVE
::Tools
::file_set_contents
($file, $data, $perms);
766 $self->ct_reset_ownership($file);
769 # Modify a marked portion of a file.
770 # Optionally if the file becomes empty it will be deleted.
772 my ($self, $file, $data, %options) = @_;
773 return if $self->ct_is_file_ignored($file);
775 my $head = "# --- BEGIN PVE ---\n";
776 my $tail = "# --- END PVE ---\n";
777 my $perms = $options{perms
};
778 $data .= "\n" if $data && $data !~ /\n$/;
780 if (!$self->ct_file_exists($file)) {
781 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
785 my $old = $self->ct_file_get_contents($file);
786 my @lines = split(/\n/, $old);
789 foreach my $i (0..(@lines-1)) {
790 my $line = $lines[$i];
791 $beg = $i if !defined($beg) &&
792 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
793 $end = $i if !defined($end) && defined($beg) &&
794 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
795 last if defined($beg) && defined($end);
798 if (defined($beg) && defined($end)) {
802 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
804 if ($beg == 0 && $end == (@lines-1)) {
805 $self->ct_unlink($file) if $options{delete};
808 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
810 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
813 my $content = join("\n", @lines);
815 if (!$content && !$data && $options{delete}) {
816 $self->ct_unlink($file);
820 $data = $head.$data.$tail;
821 if ($options{replace
}) {
822 $self->ct_file_set_contents($file, $data, $perms);
823 } elsif ($options{prepend
}) {
824 $self->ct_file_set_contents($file, $data . $content, $perms);
826 $self->ct_file_set_contents($file, $content . $data, $perms);
831 sub remove_pve_sections
{
834 my $head = "# --- BEGIN PVE ---";
835 my $tail = "# --- END PVE ---";
837 # Remove the sections enclosed with the above headers and footers.
838 # from a line (^) starting with '\h*$head'
839 # to a line (the other ^) starting with '\h*$tail' up to including that
841 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;