Skip to content

Commit

Permalink
Github #1007: Fixing non-root ssh key generation
Browse files Browse the repository at this point in the history
Running ssh-keygen as root (or with sudo) will always generated
a ssh-key binded to the user 'root' under /root/.ssh dir. This
patch makes the following changes in the ssh-key generation
process when the user is not 'root':

- ssh-keygen now always generate the key under /home/<user>/.ssh

- the generated .pub file is edited, changing 'root@...' to
'user@...'

- file permissions are changed accordingly to the new generated
key files (both private and public).

Signed-off-by: Daniel Henrique Barboza <danielhb@linux.vnet.ibm.com>
  • Loading branch information
danielhb authored and alinefm committed Oct 14, 2016
1 parent c9e50d4 commit f42d8b5
Showing 1 changed file with 30 additions and 14 deletions.
44 changes: 30 additions & 14 deletions model/vms.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import os
import paramiko
import platform
import pwd
import random
import socket
import subprocess
Expand Down Expand Up @@ -1756,26 +1757,41 @@ def _set_password_less_login(self, remote_host, user, passwd):
ssh_port = 22
ssh_client = None

def create_root_ssh_key_if_required():
if not os.path.isfile(id_rsa_pub_file):

with open("/dev/zero") as zero_input:
cmd = ['ssh-keygen', '-q', '-N', '', '-f', id_rsa_file]
proc = subprocess.Popen(
cmd,
stdin=zero_input,
stdout=open(os.devnull, 'wb')
)
out, err = proc.communicate()
if not os.path.isfile(id_rsa_pub_file):
raise OperationFailed("KCHVM0070E")

def read_id_rsa_pub_file():
data = None
with open(id_rsa_pub_file, "r") as id_file:
data = id_file.read()
return data

def create_root_ssh_key_if_required():
if os.path.isfile(id_rsa_pub_file):
return

with open("/dev/zero") as zero_input:
cmd = ['ssh-keygen', '-q', '-N', '', '-f', id_rsa_file]
proc = subprocess.Popen(
cmd,
stdin=zero_input,
stdout=open(os.devnull, 'wb')
)
out, err = proc.communicate()

if not os.path.isfile(id_rsa_pub_file):
raise OperationFailed("KCHVM0070E")

if user is not 'root':
id_rsa_content = read_id_rsa_pub_file()
updated_content = id_rsa_content.replace(
' root@', ' %s@' % user
)
with open(id_rsa_pub_file, 'w+') as f:
f.write(updated_content)

user_uid = pwd.getpwnam(user).pw_uid
user_gid = pwd.getpwnam(user).pw_gid
os.chown(id_rsa_pub_file, user_uid, user_gid)
os.chown(id_rsa_file, user_uid, user_gid)

def get_ssh_client(remote_host, user, passwd):
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Expand Down

0 comments on commit f42d8b5

Please sign in to comment.