[pve-devel] [PATCH container 1/4] Add authorized ssh key setup to post_create_hook
Fabian Grünbichler
f.gruenbichler at proxmox.com
Tue Apr 5 13:17:00 CEST 2016
provide helpers to copy public ssh keys to a user's
$HOME/.ssh/authorized_keys file, creating directories and
files when needed.
Use these in post_create_hook to setup provided ssh keys for
the root user.
---
src/PVE/LXC/Setup.pm | 4 ++--
src/PVE/LXC/Setup/Base.pm | 31 ++++++++++++++++++++++++++++++-
2 files changed, 32 insertions(+), 3 deletions(-)
diff --git a/src/PVE/LXC/Setup.pm b/src/PVE/LXC/Setup.pm
index b22f32a..6568b90 100644
--- a/src/PVE/LXC/Setup.pm
+++ b/src/PVE/LXC/Setup.pm
@@ -256,12 +256,12 @@ sub pre_start_hook {
}
sub post_create_hook {
- my ($self, $root_password) = @_;
+ my ($self, $root_password, $ssh_keys) = @_;
return if !$self->{plugin}; # unmanaged
my $code = sub {
- $self->{plugin}->post_create_hook($self->{conf}, $root_password);
+ $self->{plugin}->post_create_hook($self->{conf}, $root_password, $ssh_keys);
};
$self->protected_call($code);
$self->rewrite_ssh_host_keys();
diff --git a/src/PVE/LXC/Setup/Base.pm b/src/PVE/LXC/Setup/Base.pm
index eefc506..e8263af 100644
--- a/src/PVE/LXC/Setup/Base.pm
+++ b/src/PVE/LXC/Setup/Base.pm
@@ -354,6 +354,34 @@ sub set_user_password {
}
}
+my $parse_home_dir = sub {
+ my ($self, $passwdfile, $user) = @_;
+
+ my $fh = $self->ct_open_file_read($passwdfile);
+ while (defined (my $line = <$fh>)) {
+ return $2
+ if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
+ }
+};
+
+sub set_user_authorized_ssh_keys {
+ my ($self, $conf, $user, $ssh_keys) = @_;
+
+ my $passwd = "/etc/passwd";
+ my $home = $user eq "root" ? "/root/" : "/home/$user/";
+
+ $home = &$parse_home_dir($self, $passwd, $user)
+ if $self->ct_file_exists($passwd);
+
+ die "home directory '$home' of $user does not exist!"
+ if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
+
+ $self->ct_mkdir("$home/.ssh", 0700)
+ if ! $self->ct_is_directory("$home/.ssh");
+
+ $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
+}
+
my $randomize_crontab = sub {
my ($self, $conf) = @_;
@@ -396,13 +424,14 @@ sub pre_start_hook {
}
sub post_create_hook {
- my ($self, $conf, $root_password) = @_;
+ my ($self, $conf, $root_password, $ssh_keys) = @_;
$self->template_fixup($conf);
&$randomize_crontab($self, $conf);
$self->set_user_password($conf, 'root', $root_password);
+ $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
$self->setup_init($conf);
$self->setup_network($conf);
$self->set_hostname($conf);
--
2.1.4
More information about the pve-devel
mailing list