]> git.proxmox.com Git - pve-container.git/blame_incremental - src/PVE/LXC/Setup/Base.pm
getty setup: move hack for old systemd getty services out
[pve-container.git] / src / PVE / LXC / Setup / Base.pm
... / ...
CommitLineData
1package PVE::LXC::Setup::Base;
2
3use strict;
4use warnings;
5
6use File::stat;
7use Digest::SHA;
8use IO::File;
9use Encode;
10use Fcntl;
11use File::Path;
12use File::Spec;
13use File::Basename;
14
15use PVE::INotify;
16use PVE::Tools;
17use PVE::Network;
18
19sub new {
20 my ($class, $conf, $rootdir, $os_release) = @_;
21
22 return bless { conf => $conf, rootdir => $rootdir, os_release => $os_release }, $class;
23}
24
25sub lookup_dns_conf {
26 my ($self, $conf) = @_;
27
28 my $nameserver = $conf->{nameserver};
29 my $searchdomains = $conf->{searchdomain};
30
31 if ($conf->{'testmode'}) {
32 return ('proxmox.com', '8.8.8.8 8.8.8.9');
33 }
34
35 my $host_resolv_conf = $self->{host_resolv_conf};
36
37 if (!defined($nameserver)) {
38 my @list = ();
39 foreach my $k ("dns1", "dns2", "dns3") {
40 if (my $ns = $host_resolv_conf->{$k}) {
41 push @list, $ns;
42 }
43 }
44 $nameserver = join(' ', @list);
45 }
46
47 if (!defined($searchdomains)) {
48 $searchdomains = $host_resolv_conf->{search};
49 }
50
51 return ($searchdomains, $nameserver);
52}
53
54sub update_etc_hosts {
55 my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
56
57 my $hosts_fn = '/etc/hosts';
58 return if $self->ct_is_file_ignored($hosts_fn);
59
60 my $namepart = ($newname =~ s/\..*$//r);
61
62 my $all_names = '';
63 if ($newname =~ /\./) {
64 $all_names .= "$newname $namepart";
65 } else {
66 foreach my $domain (PVE::Tools::split_list($searchdomains)) {
67 $all_names .= ' ' if $all_names;
68 $all_names .= "$newname.$domain";
69 }
70 $all_names .= ' ' if $all_names;
71 $all_names .= $newname;
72 }
73
74 # Prepare section:
75 my $section = '';
76
77 my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
78 my $lo6 = "::1 localhost.localnet localhost\n";
79 if ($self->ct_file_exists($hosts_fn)) {
80 my $data = $self->ct_file_get_contents($hosts_fn);
81 # don't take localhost entries within our hosts sections into account
82 $data = remove_pve_sections($data);
83
84 # check for existing localhost entries
85 $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
86 $section .= $lo6 if $data !~ /^\h*::1\h+/m;
87 } else {
88 $section .= $lo4 . $lo6;
89 }
90
91 if (defined($hostip)) {
92 $section .= "$hostip $all_names\n";
93 } elsif ($namepart ne 'localhost') {
94 $section .= "127.0.1.1 $all_names\n";
95 } else {
96 $section .= "127.0.1.1 $namepart\n";
97 }
98
99 $self->ct_modify_file($hosts_fn, $section);
100}
101
102sub template_fixup {
103 my ($self, $conf) = @_;
104
105 # do nothing by default
106}
107
108sub set_dns {
109 my ($self, $conf) = @_;
110
111 my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
112
113 my $data = '';
114
115 $data .= "search " . join(' ', PVE::Tools::split_list($searchdomains)) . "\n"
116 if $searchdomains;
117
118 foreach my $ns ( PVE::Tools::split_list($nameserver)) {
119 $data .= "nameserver $ns\n";
120 }
121
122 $self->ct_modify_file("/etc/resolv.conf", $data, replace => 1);
123}
124
125sub set_hostname {
126 my ($self, $conf) = @_;
127
128 my $hostname = $conf->{hostname} || 'localhost';
129
130 my $namepart = ($hostname =~ s/\..*$//r);
131
132 my $hostname_fn = "/etc/hostname";
133
134 my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
135
136 my ($ipv4, $ipv6) = PVE::LXC::get_primary_ips($conf);
137 my $hostip = $ipv4 || $ipv6;
138
139 my ($searchdomains) = $self->lookup_dns_conf($conf);
140
141 $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
142
143 $self->ct_file_set_contents($hostname_fn, "$namepart\n");
144}
145
146sub setup_network {
147 my ($self, $conf) = @_;
148
149 die "please implement this inside subclass"
150}
151
152sub setup_init {
153 my ($self, $conf) = @_;
154
155 die "please implement this inside subclass"
156}
157
158sub setup_systemd_console {
159 my ($self, $conf) = @_;
160
161 my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
162 "/lib/systemd/system" : "/usr/lib/systemd/system";
163
164 my $systemd_getty_service_rel = "$systemd_dir_rel/getty\@.service";
165
166 return if !$self->ct_file_exists($systemd_getty_service_rel);
167
168 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
169
170 for (my $i = 1; $i < 7; $i++) {
171 my $tty_service_lnk = "/etc/systemd/system/getty.target.wants/getty\@tty$i.service";
172 if ($i > $ttycount) {
173 $self->ct_unlink($tty_service_lnk);
174 } else {
175 if (!$self->ct_is_symlink($tty_service_lnk)) {
176 $self->ct_unlink($tty_service_lnk);
177 $self->ct_symlink($systemd_getty_service_rel, $tty_service_lnk);
178 }
179 }
180 }
181}
182
183# A few distros as well as unprivileged containers cannot deal with the
184# /dev/lxc/ tty subdirectory.
185sub devttydir {
186 my ($self, $conf) = @_;
187 return $conf->{unprivileged} ? '' : 'lxc/';
188}
189
190sub fixup_old_getty {
191 my ($self) = @_;
192
193 my $sd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
194 "/lib/systemd/system" : "/usr/lib/systemd/system";
195
196 my $sd_getty_service_rel = "$sd_dir_rel/getty\@.service";
197 return if !$self->ct_file_exists($sd_getty_service_rel);
198
199 my $raw = $self->ct_file_get_contents($sd_getty_service_rel);
200
201 my $sd_container_getty_service_rel = "$sd_dir_rel/container-getty\@.service";
202 # systemd on CenoOS 7.1 is too old (version 205), so there is no
203 # container-getty service
204 if (!$self->ct_file_exists($sd_container_getty_service_rel)) {
205 if ($raw =~ s!^ConditionPathExists=/dev/tty0$!ConditionPathExists=/dev/tty!m) {
206 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
207 }
208 } else {
209 # undo above change (in case someone updated systemd)
210 if ($raw =~ s!^ConditionPathExists=/dev/tty$!ConditionPathExists=/dev/tty0!m) {
211 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
212 }
213 }
214}
215
216sub setup_container_getty_service {
217 my ($self, $conf) = @_;
218
219 my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
220 "/lib/systemd/system" : "/usr/lib/systemd/system";
221 my $servicefile = "$systemd_dir_rel/container-getty\@.service";
222 my $raw = $self->ct_file_get_contents($servicefile);
223 my $ttyname = $self->devttydir($conf) . 'tty%I';
224 if ($raw =~ s@pts/%I|lxc/tty%I@$ttyname@g) {
225 $self->ct_file_set_contents($servicefile, $raw);
226 }
227}
228
229sub setup_systemd_networkd {
230 my ($self, $conf) = @_;
231
232 foreach my $k (keys %$conf) {
233 next if $k !~ m/^net(\d+)$/;
234 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
235 next if !$d->{name};
236
237 my $filename = "/etc/systemd/network/$d->{name}.network";
238
239 my $data = <<"DATA";
240[Match]
241Name = $d->{name}
242
243[Network]
244Description = Interface $d->{name} autoconfigured by PVE
245DATA
246
247 my $routes = '';
248 my ($has_ipv4, $has_ipv6);
249
250 # DHCP bitflags:
251 my @DHCPMODES = ('none', 'v4', 'v6', 'both');
252 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
253 my $dhcp = $NONE;
254 my $accept_ra = 'false';
255
256 if (defined(my $ip = $d->{ip})) {
257 if ($ip eq 'dhcp') {
258 $dhcp |= $DHCP4;
259 } elsif ($ip ne 'manual') {
260 $has_ipv4 = 1;
261 $data .= "Address = $ip\n";
262 }
263 }
264 if (defined(my $gw = $d->{gw})) {
265 $data .= "Gateway = $gw\n";
266 if ($has_ipv4 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip}, 4)) {
267 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
268 }
269 }
270
271 if (defined(my $ip = $d->{ip6})) {
272 if ($ip eq 'dhcp') {
273 $dhcp |= $DHCP6;
274 } elsif ($ip eq 'auto') {
275 $accept_ra = 'true';
276 } elsif ($ip ne 'manual') {
277 $has_ipv6 = 1;
278 $data .= "Address = $ip\n";
279 }
280 }
281 if (defined(my $gw = $d->{gw6})) {
282 $accept_ra = 'false';
283 $data .= "Gateway = $gw\n";
284 if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6) &&
285 !PVE::Network::is_ip_in_cidr($gw, 'fe80::/10', 6)) {
286 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
287 }
288 }
289
290 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
291 $data .= "IPv6AcceptRA = $accept_ra\n";
292 $data .= $routes if $routes;
293
294 $self->ct_file_set_contents($filename, $data);
295 }
296}
297
298sub setup_securetty {
299 my ($self, $conf, @add) = @_;
300
301 my $filename = "/etc/securetty";
302 # root login is already allowed on every device if no securetty present
303 return if !$self->ct_file_exists($filename);
304
305 if (!scalar(@add)) {
306 @add = qw(console tty1 tty2 tty3 tty4);
307 if (my $dir = $self->devttydir($conf)) {
308 @add = map { "${dir}$_" } @add;
309 }
310 }
311
312 my $data = $self->ct_file_get_contents($filename);
313 chomp $data; $data .= "\n";
314 foreach my $dev (@add) {
315 if ($data !~ m!^\Q$dev\E\s*$!m) {
316 $data .= "$dev\n";
317 }
318 }
319 $self->ct_file_set_contents($filename, $data);
320}
321
322my $replacepw = sub {
323 my ($self, $file, $user, $epw, $shadow) = @_;
324
325 my $tmpfile = "$file.$$";
326
327 eval {
328 my $src = $self->ct_open_file_read($file) ||
329 die "unable to open file '$file' - $!";
330
331 my $st = $self->ct_stat($src) ||
332 die "unable to stat file - $!";
333
334 my $dst = $self->ct_open_file_write($tmpfile) ||
335 die "unable to open file '$tmpfile' - $!";
336
337 # copy owner and permissions
338 chmod $st->mode, $dst;
339 chown $st->uid, $st->gid, $dst;
340
341 my $last_change = int(time()/(60*60*24));
342
343 while (defined (my $line = <$src>)) {
344 if ($shadow) {
345 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
346 } else {
347 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
348 }
349 print $dst $line;
350 }
351
352 $src->close() || die "close '$file' failed - $!\n";
353 $dst->close() || die "close '$tmpfile' failed - $!\n";
354 };
355 if (my $err = $@) {
356 $self->ct_unlink($tmpfile);
357 } else {
358 $self->ct_rename($tmpfile, $file);
359 $self->ct_unlink($tmpfile); # in case rename fails
360 }
361};
362
363sub set_user_password {
364 my ($self, $conf, $user, $opt_password) = @_;
365
366 my $pwfile = "/etc/passwd";
367
368 return if !$self->ct_file_exists($pwfile);
369
370 my $shadow = "/etc/shadow";
371
372 if (defined($opt_password)) {
373 if ($opt_password !~ m/^\$(?:1|2[axy]?|5|6)\$[a-zA-Z0-9.\/]{1,16}\$[a-zA-Z0-9.\/]+$/) {
374 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
375 $opt_password = crypt(encode("utf8", $opt_password), "\$6\$$time\$");
376 };
377 } else {
378 $opt_password = '*';
379 }
380
381 if ($self->ct_file_exists($shadow)) {
382 &$replacepw ($self, $shadow, $user, $opt_password, 1);
383 &$replacepw ($self, $pwfile, $user, 'x');
384 } else {
385 &$replacepw ($self, $pwfile, $user, $opt_password);
386 }
387}
388
389my $parse_home_dir = sub {
390 my ($self, $passwdfile, $user) = @_;
391
392 my $fh = $self->ct_open_file_read($passwdfile);
393 while (defined (my $line = <$fh>)) {
394 return $2
395 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
396 }
397};
398
399sub set_user_authorized_ssh_keys {
400 my ($self, $conf, $user, $ssh_keys) = @_;
401
402 my $passwd = "/etc/passwd";
403 my $home = $user eq "root" ? "/root/" : "/home/$user/";
404
405 $home = &$parse_home_dir($self, $passwd, $user)
406 if $self->ct_file_exists($passwd);
407
408 die "home directory '$home' of $user does not exist!"
409 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
410
411 $self->ct_mkdir("$home/.ssh", 0700)
412 if ! $self->ct_is_directory("$home/.ssh");
413
414 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
415}
416
417my $randomize_crontab = sub {
418 my ($self, $conf) = @_;
419
420 my @files;
421 # Note: dir_glob_foreach() untaints filenames!
422 PVE::Tools::dir_glob_foreach("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
423 my ($name) = @_;
424 push @files, "/etc/cron.d/$name";
425 });
426
427 my $crontab_fn = "/etc/crontab";
428 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
429
430 foreach my $filename (@files) {
431 my $data = $self->ct_file_get_contents($filename);
432 my $new = '';
433 foreach my $line (split(/\n/, $data)) {
434 # we only randomize minutes for root crontab entries
435 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
436 my $rest = $1;
437 my $min = int(rand()*59);
438 $new .= "$min$rest\n";
439 } else {
440 $new .= "$line\n";
441 }
442 }
443 $self->ct_file_set_contents($filename, $new);
444 }
445};
446
447sub pre_start_hook {
448 my ($self, $conf) = @_;
449
450 $self->setup_init($conf);
451 $self->setup_network($conf);
452 $self->set_hostname($conf);
453 $self->set_dns($conf);
454
455 # fixme: what else ?
456}
457
458sub post_create_hook {
459 my ($self, $conf, $root_password, $ssh_keys) = @_;
460
461 $self->template_fixup($conf);
462
463 &$randomize_crontab($self, $conf);
464
465 $self->set_user_password($conf, 'root', $root_password);
466 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
467 $self->setup_init($conf);
468 $self->setup_network($conf);
469 $self->set_hostname($conf);
470 $self->set_dns($conf);
471
472 # fixme: what else ?
473}
474
475# File access wrappers for container setup code.
476# For user-namespace support these might need to take uid and gid maps into account.
477
478sub ct_is_file_ignored {
479 my ($self, $file) = @_;
480 my ($name, $path) = fileparse($file);
481 return -f "$path/.pve-ignore.$name";
482}
483
484sub ct_reset_ownership {
485 my ($self, @files) = @_;
486 my $conf = $self->{conf};
487 return if !$self->{id_map};
488
489 @files = grep { !$self->ct_is_file_ignored($_) } @files;
490 return if !@files;
491
492 my $uid = $self->{rootuid};
493 my $gid = $self->{rootgid};
494 chown($uid, $gid, @files);
495}
496
497sub ct_mkdir {
498 my ($self, $file, $mask) = @_;
499 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
500 if (defined($mask)) {
501 return CORE::mkdir($file, $mask) && $self->ct_reset_ownership($file);
502 } else {
503 return CORE::mkdir($file) && $self->ct_reset_ownership($file);
504 }
505}
506
507sub ct_unlink {
508 my ($self, @files) = @_;
509 foreach my $file (@files) {
510 next if $self->ct_is_file_ignored($file);
511 CORE::unlink($file);
512 }
513}
514
515sub ct_rename {
516 my ($self, $old, $new) = @_;
517 return if $self->ct_is_file_ignored($new);
518 CORE::rename($old, $new);
519}
520
521sub ct_open_file_read {
522 my $self = shift;
523 my $file = shift;
524 return IO::File->new($file, O_RDONLY, @_);
525}
526
527sub ct_open_file_write {
528 my $self = shift;
529 my $file = shift;
530 $file = '/dev/null' if $self->ct_is_file_ignored($file);
531 my $fh = IO::File->new($file, O_WRONLY | O_CREAT, @_);
532 $self->ct_reset_ownership($fh);
533 return $fh;
534}
535
536sub ct_make_path {
537 my $self = shift;
538 if ($self->{id_map}) {
539 my $opts = pop;
540 if (ref($opts) eq 'HASH') {
541 $opts->{owner} = $self->{rootuid} if !defined($self->{owner});
542 $opts->{group} = $self->{rootgid} if !defined($self->{group});
543 }
544 File::Path::make_path(@_, $opts);
545 } else {
546 File::Path::make_path(@_);
547 }
548}
549
550sub ct_symlink {
551 my ($self, $old, $new) = @_;
552 return if $self->ct_is_file_ignored($new);
553 return CORE::symlink($old, $new);
554}
555
556sub ct_readlink {
557 my ($self, $name) = @_;
558 return CORE::readlink($name);
559}
560
561sub ct_file_exists {
562 my ($self, $file) = @_;
563 return -f $file;
564}
565
566sub ct_is_directory {
567 my ($self, $file) = @_;
568 return -d $file;
569}
570
571sub ct_is_symlink {
572 my ($self, $file) = @_;
573 return -l $file;
574}
575
576sub ct_is_executable {
577 my ($self, $file) = @_;
578 return -x $file
579}
580
581sub ct_stat {
582 my ($self, $file) = @_;
583 return File::stat::stat($file);
584}
585
586sub ct_file_read_firstline {
587 my ($self, $file) = @_;
588 return PVE::Tools::file_read_firstline($file);
589}
590
591sub ct_file_get_contents {
592 my ($self, $file) = @_;
593 return PVE::Tools::file_get_contents($file);
594}
595
596sub ct_file_set_contents {
597 my ($self, $file, $data, $perms) = @_;
598 return if $self->ct_is_file_ignored($file);
599 PVE::Tools::file_set_contents($file, $data, $perms);
600 $self->ct_reset_ownership($file);
601}
602
603# Modify a marked portion of a file.
604# Optionally if the file becomes empty it will be deleted.
605sub ct_modify_file {
606 my ($self, $file, $data, %options) = @_;
607 return if $self->ct_is_file_ignored($file);
608
609 my $head = "# --- BEGIN PVE ---\n";
610 my $tail = "# --- END PVE ---\n";
611 my $perms = $options{perms};
612 $data .= "\n" if $data && $data !~ /\n$/;
613
614 if (!$self->ct_file_exists($file)) {
615 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
616 return;
617 }
618
619 my $old = $self->ct_file_get_contents($file);
620 my @lines = split(/\n/, $old);
621
622 my ($beg, $end);
623 foreach my $i (0..(@lines-1)) {
624 my $line = $lines[$i];
625 $beg = $i if !defined($beg) &&
626 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
627 $end = $i if !defined($end) && defined($beg) &&
628 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
629 last if defined($beg) && defined($end);
630 }
631
632 if (defined($beg) && defined($end)) {
633 # Found a section
634 if ($data) {
635 chomp $tail;
636 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
637 } else {
638 if ($beg == 0 && $end == (@lines-1)) {
639 $self->ct_unlink($file) if $options{delete};
640 return;
641 }
642 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
643 }
644 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
645 } elsif ($data) {
646 # No section found
647 my $content = join("\n", @lines);
648 chomp $content;
649 if (!$content && !$data && $options{delete}) {
650 $self->ct_unlink($file);
651 return;
652 }
653 $content .= "\n";
654 $data = $head.$data.$tail;
655 if ($options{replace}) {
656 $self->ct_file_set_contents($file, $data, $perms);
657 } elsif ($options{prepend}) {
658 $self->ct_file_set_contents($file, $data . $content, $perms);
659 } else { # append
660 $self->ct_file_set_contents($file, $content . $data, $perms);
661 }
662 }
663}
664
665sub remove_pve_sections {
666 my ($data) = @_;
667
668 my $head = "# --- BEGIN PVE ---";
669 my $tail = "# --- END PVE ---";
670
671 # Remove the sections enclosed with the above headers and footers.
672 # from a line (^) starting with '\h*$head'
673 # to a line (the other ^) starting with '\h*$tail' up to including that
674 # line's end (.*?$).
675 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;
676}
677
6781;