users: Multiple SSH keys and better home creation

- Allow setting multiple SSH keys one per line (which is already
  allowed, but advertise it better).

- Use mkhomedir_helper to create the user's home directory.  Avoid
  security and accuracy complexities of creating a home directory.

- Allow homes that don't exist in /home.
This commit is contained in:
Sunil Mohan Adapa 2016-01-30 15:27:16 +05:30
parent ad7d6db968
commit 506bff5c7b
No known key found for this signature in database
GPG Key ID: 36C361440C9BC971
3 changed files with 48 additions and 53 deletions

View File

@ -25,6 +25,7 @@ import os
import re import re
import shutil import shutil
import stat import stat
import subprocess
import sys import sys
@ -33,64 +34,56 @@ def parse_arguments():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subcommand', help='Sub command') subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')
get_key = subparsers.add_parser('get-key', help='Get SSH authorized key') get_keys = subparsers.add_parser('get-keys', help='Get SSH authorized keys')
get_key.add_argument('--username') get_keys.add_argument('--username')
set_key = subparsers.add_parser('set-key', help='Set SSH authorized key') set_keys = subparsers.add_parser('set-keys', help='Set SSH authorized keys')
set_key.add_argument('--username') set_keys.add_argument('--username')
set_key.add_argument('--key') set_keys.add_argument('--keys')
return parser.parse_args() return parser.parse_args()
def subcommand_get_key(arguments): def _assert_valid_username(username):
"""Get SSH authorized key.""" """Verify that username is a valid one."""
user = arguments.username if not re.match(r'^[a-z][-a-z0-9_]*$', username):
if not re.match(r'^[a-z][-a-z0-9_]*$', user):
print('Bad username') print('Bad username')
sys.exit(-1) sys.exit(1)
home = '/home/' + user
ssh_folder = home + '/.ssh'
keyfile_path = ssh_folder + '/authorized_keys'
if not os.path.exists(keyfile_path):
return
with open(keyfile_path, 'r') as keyfile:
key = keyfile.read()
print(key)
def subcommand_set_key(arguments): def subcommand_get_keys(arguments):
"""Set SSH authorized key.""" """Get SSH authorized keys."""
user = arguments.username user = arguments.username
if not re.match(r'^[a-z][-a-z0-9_]*$', user): _assert_valid_username(user)
print('Bad username')
sys.exit(-1)
home = '/home/' + user path = os.path.join(os.path.expanduser('~' + user),
ssh_folder = home + '/.ssh' '.ssh', 'authorized_keys')
keyfile_path = ssh_folder + '/authorized_keys' try:
with open(path, 'r') as file_handle:
print(file_handle.read())
except FileNotFoundError:
pass
if not os.path.exists(home):
shutil.copytree('/etc/skel', home) def subcommand_set_keys(arguments):
shutil.chown(home, user, 'users') """Set SSH authorized keys."""
for root, dirs, files in os.walk(home): user = arguments.username
for directory in dirs: _assert_valid_username(user)
shutil.chown(os.path.join(root, directory), user, 'users')
for filename in files: subprocess.check_call(['mkhomedir_helper', user])
shutil.chown(os.path.join(root, filename), user, 'users')
ssh_folder = os.path.join(os.path.expanduser('~' + user), '.ssh')
key_file_path = os.path.join(ssh_folder, 'authorized_keys')
if not os.path.exists(ssh_folder): if not os.path.exists(ssh_folder):
os.makedirs(ssh_folder) os.makedirs(ssh_folder)
shutil.chown(ssh_folder, user, 'users') shutil.chown(ssh_folder, user, 'users')
with open(keyfile_path, 'w') as keyfile: with open(key_file_path, 'w') as file_handle:
keyfile.write(arguments.key) file_handle.write(arguments.keys)
shutil.chown(keyfile_path, user, 'users')
os.chmod(keyfile_path, stat.S_IRUSR | stat.S_IWUSR) shutil.chown(key_file_path, user, 'users')
os.chmod(key_file_path, stat.S_IRUSR | stat.S_IWUSR)
def main(): def main():

View File

@ -88,18 +88,20 @@ class CreateUserForm(UserCreationForm):
class UserUpdateForm(forms.ModelForm): class UserUpdateForm(forms.ModelForm):
"""When user info is changed, also updates LDAP user.""" """When user info is changed, also updates LDAP user."""
ssh_key = forms.CharField( ssh_keys = forms.CharField(
label=ugettext_lazy('SSH Key'), label=ugettext_lazy('SSH Keys'),
required=False, required=False,
widget=forms.Textarea, widget=forms.Textarea,
help_text=\ help_text=\
ugettext_lazy('Setting an SSH public key will allow this user to log ' ugettext_lazy('Setting an SSH public key will allow this user to '
'in to the system without having to send a password ' 'securely log in to the system without using a '
'over the network.')) 'password. You may enter multiple keys, one on each '
'line. Blank lines and lines starting with # will be '
'ignored.'))
class Meta: class Meta:
"""Metadata to control automatic form building.""" """Metadata to control automatic form building."""
fields = ('username', 'groups', 'ssh_key', 'is_active') fields = ('username', 'groups', 'ssh_keys', 'is_active')
model = User model = User
widgets = { widgets = {
'groups': forms.widgets.CheckboxSelectMultiple(), 'groups': forms.widgets.CheckboxSelectMultiple(),
@ -157,9 +159,8 @@ class UserUpdateForm(forms.ModelForm):
_('Failed to add user to group.')) _('Failed to add user to group.'))
actions.superuser_run( actions.superuser_run(
'ssh', ['set-key', 'ssh', ['set-keys', '--username', user.get_username(),
'--username', user.get_username(), '--keys', self.cleaned_data['ssh_keys'].strip()])
'--key', self.cleaned_data['ssh_key'].strip()])
return user return user

View File

@ -86,9 +86,10 @@ class UserUpdate(ContextMixin, SuccessMessageMixin, UpdateView):
return kwargs return kwargs
def get_initial(self): def get_initial(self):
"""Return the data for initial form load."""
initial = super(UserUpdate, self).get_initial() initial = super(UserUpdate, self).get_initial()
initial['ssh_key'] = actions.superuser_run( initial['ssh_keys'] = actions.superuser_run(
'ssh', ['get-key', '--username', self.object.username]).strip() 'ssh', ['get-keys', '--username', self.object.username]).strip()
return initial return initial
def get_success_url(self): def get_success_url(self):