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