]> git.proxmox.com Git - pve-container.git/commitdiff
Add authorized ssh key setup to post_create_hook
authorFabian Grünbichler <f.gruenbichler@proxmox.com>
Tue, 5 Apr 2016 11:17:00 +0000 (13:17 +0200)
committerDietmar Maurer <dietmar@proxmox.com>
Tue, 5 Apr 2016 13:26:55 +0000 (15:26 +0200)
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
src/PVE/LXC/Setup/Base.pm

index b22f32a9951a2b5f1642537aa09d20618823aded..6568b90640249b533500e5c41ce63cd9ab215917 100644 (file)
@@ -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();
index eefc506efc2f9e632bf1b5d788140b76686d83b9..e8263af3703a1b52d08f6e7c442f4b380540a6f6 100644 (file)
@@ -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);