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