示例#1
0
文件: ssh.py 项目: jonhadfield/creds
def read_authorized_keys(username=None):
    """Read public keys from specified user's authorized_keys file.

    args:
        username (str): username.

    returns:
        list: Authorised keys for the specified user.
    """
    authorized_keys_path = '{0}/.ssh/authorized_keys'.format(os.path.expanduser('~{0}'.format(username)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(username, rnd_chars)
    authorized_keys = list()
    copy_result = execute_command(
        shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), authorized_keys_path, tmp_authorized_keys_path))))
    result_message = copy_result[0][1].decode('UTF-8')
    if 'you must have a tty to run sudo' in result_message:  # pragma: no cover
        raise OSError("/etc/sudoers is blocked sudo. Remove entry: 'Defaults    requiretty'.")
    elif 'No such file or directory' not in result_message:
        execute_command(shlex.split(str('{0} chmod 755 {1}'.format(sudo_check(), tmp_authorized_keys_path))))
        with open(tmp_authorized_keys_path) as keys_file:
            for key in keys_file:
                authorized_keys.append(PublicKey(raw=key))
        execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
    return authorized_keys
示例#2
0
def delete_test_user_and_group():
    if PLATFORM == 'Linux':
        del_user_command = shlex.split(
            str('{0} {1} -r -f testuserx1234'.format(sudo_check(),
                                                     LINUX_CMD_USERDEL)))
        execute_command(command=del_user_command)
    elif PLATFORM == 'OpenBSD':
        del_user_command = shlex.split(
            str('{0} {1} -r testuserx1234'.format(sudo_check(),
                                                  LINUX_CMD_USERDEL)))
        execute_command(command=del_user_command)
    elif PLATFORM == 'FreeBSD':
        del_user_command = shlex.split(
            str('{0} {1} userdel -r -n testuserx1234'.format(
                sudo_check(), FREEBSD_CMD_PW)))
        execute_command(command=del_user_command)
    if PLATFORM in ('Linux', 'OpenBSD'):
        del_group_command = shlex.split(
            str('{0} {1} testuserx1234'.format(sudo_check(), GROUPDEL)))
        execute_command(command=del_group_command)
        del_user_ssh_dir_command = shlex.split(str('/bin/rm -rf /tmp/.ssh'))
        execute_command(command=del_user_ssh_dir_command)
    remove_sudoers_entry(username='******')
    execute_command(command=shlex.split(
        str('{0} rm -rf /home/testuserx1234'.format(sudo_check()))))
示例#3
0
def create_test_group():
    if PLATFORM in ('Linux', 'OpenBSD'):
        command = shlex.split(
            str('{0} {1} -g 59999 testuserx1234'.format(
                sudo_check(), LINUX_CMD_GROUP_ADD)))
    elif PLATFORM == 'FreeBSD':
        command = shlex.split(
            str('{0} {1} groupadd -g 59999 -n testuserx1234'.format(
                sudo_check(), FREEBSD_CMD_PW)))
    assert execute_command(command=command)
示例#4
0
def create_test_user():
    if PLATFORM in ('Linux', 'OpenBSD'):
        command = shlex.split(
            str('{0} {1} -u 59999 -c \"test user gecos\" -m  -s /bin/bash testuserx1234'
                .format(sudo_check(), LINUX_CMD_USERADD)))
    elif PLATFORM == 'FreeBSD':
        command = shlex.split(
            str('{0} {1} useradd -u 59999 -c \"test user gecos\" -m  -s /bin/bash -n testuserx1234'
                .format(sudo_check(), FREEBSD_CMD_PW)))
    assert execute_command(command=command)
示例#5
0
def generate_modify_user_command(task=None, manage_home=None):
    """Generate command to modify existing user to become the proposed user.

    args:
        task (dict): A proposed user and the differences between it and the existing user

    returns:
        list: The command string split into shell-like syntax
    """
    name = task['proposed_user'].name
    comparison_result = task['user_comparison']['result']
    command = None
    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERMOD)
        if comparison_result.get('replacement_uid_value'):
            command = '{0} -u {1}'.format(
                command, comparison_result.get('replacement_uid_value'))
        if comparison_result.get('replacement_gid_value'):
            command = '{0} -g {1}'.format(
                command, comparison_result.get('replacement_gid_value'))
        if comparison_result.get('replacement_gecos_value'):
            command = '{0} -c {1}'.format(
                command, comparison_result.get('replacement_gecos_value'))
        if comparison_result.get('replacement_shell_value'):
            command = '{0} -s {1}'.format(
                command, comparison_result.get('replacement_shell_value'))
        if manage_home and comparison_result.get('replacement_home_dir_value'):
            command = '{0} -d {1}'.format(
                command, comparison_result.get('replacement_home_dir_value'))
        command = '{0} {1}'.format(command, name)
    if get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} usermod'.format(sudo_check(), FREEBSD_CMD_PW)
        if comparison_result.get('replacement_uid_value'):
            command = '{0} -u {1}'.format(
                command, comparison_result.get('replacement_uid_value'))
        if comparison_result.get('replacement_gid_value'):
            command = '{0} -g {1}'.format(
                command, comparison_result.get('replacement_gid_value'))
        if comparison_result.get('replacement_gecos_value'):
            command = '{0} -c {1}'.format(
                command, comparison_result.get('replacement_gecos_value'))
        if comparison_result.get('replacement_shell_value'):
            command = '{0} -s {1}'.format(
                command, comparison_result.get('replacement_shell_value'))
        if manage_home and comparison_result.get('replacement_home_dir_value'):
            command = '{0} -d {1}'.format(
                command, comparison_result.get('replacement_home_dir_value'))
        command = '{0} -n {1}'.format(command, name)
    if command:
        return shlex.split(str(command))
示例#6
0
def generate_add_user_command(proposed_user=None, manage_home=None):
    """Generate command to add a user.

    args:
        proposed_user (User): User
        manage_home: bool

    returns:
        list: The command string split into shell-like syntax
    """
    command = None
    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERADD)
        if proposed_user.uid:
            command = '{0} -u {1}'.format(command, proposed_user.uid)
        if proposed_user.gid:
            command = '{0} -g {1}'.format(command, proposed_user.gid)
        if proposed_user.gecos:
            command = '{0} -c \'{1}\''.format(command, proposed_user.gecos)
        if manage_home:
            if proposed_user.home_dir:
                if os.path.exists(proposed_user.home_dir):
                    command = '{0} -d {1}'.format(command,
                                                  proposed_user.home_dir)
            elif not os.path.exists('/home/{0}'.format(proposed_user.name)):
                command = '{0} -m'.format(command)
        if proposed_user.shell:
            command = '{0} -s {1}'.format(command, proposed_user.shell)
        command = '{0} {1}'.format(command, proposed_user.name)
    elif get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} useradd'.format(sudo_check(), FREEBSD_CMD_PW)
        if proposed_user.uid:
            command = '{0} -u {1}'.format(command, proposed_user.uid)
        if proposed_user.gid:
            command = '{0} -g {1}'.format(command, proposed_user.gid)
        if proposed_user.gecos:
            command = '{0} -c \'{1}\''.format(command, proposed_user.gecos)
        if manage_home:
            if proposed_user.home_dir:
                command = '{0} -d {1}'.format(command, proposed_user.home_dir)
            else:
                command = '{0} -m'.format(command)
        if proposed_user.shell:
            command = '{0} -s {1}'.format(command, proposed_user.shell)
        command = '{0} -n {1}'.format(command, proposed_user.name)

    if command:
        return shlex.split(str(command))
示例#7
0
def generate_add_user_command(proposed_user=None, manage_home=None):
    """Generate command to add a user.

    args:
        proposed_user (User): User
        manage_home: bool

    returns:
        list: The command string split into shell-like syntax
    """
    command = None
    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERADD)
        if proposed_user.uid:
            command = '{0} -u {1}'.format(command, proposed_user.uid)
        if proposed_user.gid:
            command = '{0} -g {1}'.format(command, proposed_user.gid)
        if proposed_user.gecos:
            command = '{0} -c \'{1}\''.format(command, proposed_user.gecos)
        if manage_home:
            if proposed_user.home_dir:
                if os.path.exists(proposed_user.home_dir):
                    command = '{0} -d {1}'.format(command, proposed_user.home_dir)
            elif not os.path.exists('/home/{0}'.format(proposed_user.name)):
                command = '{0} -m'.format(command)
        if proposed_user.shell:
            command = '{0} -s {1}'.format(command, proposed_user.shell)
        command = '{0} {1}'.format(command, proposed_user.name)
    elif get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} useradd'.format(sudo_check(), FREEBSD_CMD_PW)
        if proposed_user.uid:
            command = '{0} -u {1}'.format(command, proposed_user.uid)
        if proposed_user.gid:
            command = '{0} -g {1}'.format(command, proposed_user.gid)
        if proposed_user.gecos:
            command = '{0} -c \'{1}\''.format(command, proposed_user.gecos)
        if manage_home:
            if proposed_user.home_dir:
                command = '{0} -d {1}'.format(command, proposed_user.home_dir)
            else:
                command = '{0} -m'.format(command)
        if proposed_user.shell:
            command = '{0} -s {1}'.format(command, proposed_user.shell)
        command = '{0} -n {1}'.format(command, proposed_user.name)

    if command:
        return shlex.split(str(command))
示例#8
0
def generate_delete_user_command(username=None, manage_home=None):
    """Generate command to delete a user.

    args:
        username (str): user name
        manage_home (bool): manage home directory

    returns:
        list: The user delete command string split into shell-like syntax
    """
    command = None
    remove_home = '-r' if manage_home else ''

    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_USERDEL, remove_home, username)
    elif get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} userdel {2} -n {3}'.format(sudo_check(), FREEBSD_CMD_PW, remove_home, username)
    if command:
        return shlex.split(str(command))
示例#9
0
def generate_modify_user_command(task=None, manage_home=None):
    """Generate command to modify existing user to become the proposed user.

    args:
        task (dict): A proposed user and the differences between it and the existing user

    returns:
        list: The command string split into shell-like syntax
    """
    name = task['proposed_user'].name
    comparison_result = task['user_comparison']['result']
    command = None
    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1}'.format(sudo_check(), LINUX_CMD_USERMOD)
        if comparison_result.get('replacement_uid_value'):
            command = '{0} -u {1}'.format(command, comparison_result.get('replacement_uid_value'))
        if comparison_result.get('replacement_gid_value'):
            command = '{0} -g {1}'.format(command, comparison_result.get('replacement_gid_value'))
        if comparison_result.get('replacement_gecos_value'):
            command = '{0} -c {1}'.format(command, comparison_result.get('replacement_gecos_value'))
        if comparison_result.get('replacement_shell_value'):
            command = '{0} -s {1}'.format(command, comparison_result.get('replacement_shell_value'))
        if manage_home and comparison_result.get('replacement_home_dir_value'):
                command = '{0} -d {1}'.format(command, comparison_result.get('replacement_home_dir_value'))
        command = '{0} {1}'.format(command, name)
    if get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} usermod'.format(sudo_check(), FREEBSD_CMD_PW)
        if comparison_result.get('replacement_uid_value'):
            command = '{0} -u {1}'.format(command, comparison_result.get('replacement_uid_value'))
        if comparison_result.get('replacement_gid_value'):
            command = '{0} -g {1}'.format(command, comparison_result.get('replacement_gid_value'))
        if comparison_result.get('replacement_gecos_value'):
            command = '{0} -c {1}'.format(command, comparison_result.get('replacement_gecos_value'))
        if comparison_result.get('replacement_shell_value'):
            command = '{0} -s {1}'.format(command, comparison_result.get('replacement_shell_value'))
        if manage_home and comparison_result.get('replacement_home_dir_value'):
            command = '{0} -d {1}'.format(command, comparison_result.get('replacement_home_dir_value'))
        command = '{0} -n {1}'.format(command, name)
    if command:
        return shlex.split(str(command))
示例#10
0
文件: ssh.py 项目: jonhadfield/creds
def write_authorized_keys(user=None):
    """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist.

    args:
        user (User): Instance of User containing keys.

    returns:
        list: Authorised keys for the specified user.
    """
    authorized_keys = list()
    authorized_keys_dir = '{0}/.ssh'.format(os.path.expanduser('~{0}'.format(user.name)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    authorized_keys_path = '{0}/authorized_keys'.format(authorized_keys_dir)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(user.name, rnd_chars)

    if not os.path.isdir(authorized_keys_dir):
        execute_command(shlex.split(str('{0} mkdir -p {1}'.format(sudo_check(), authorized_keys_dir))))
    for key in user.public_keys:
        authorized_keys.append('{0}\n'.format(key.raw))
    with open(tmp_authorized_keys_path, mode=text_type('w+')) as keys_file:
        keys_file.writelines(authorized_keys)
    execute_command(
        shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), tmp_authorized_keys_path, authorized_keys_path))))
    execute_command(shlex.split(str('{0} chown -R {1} {2}'.format(sudo_check(), user.name, authorized_keys_dir))))
    execute_command(shlex.split(str('{0} chmod 700 {1}'.format(sudo_check(), authorized_keys_dir))))
    execute_command(shlex.split(str('{0} chmod 600 {1}'.format(sudo_check(), authorized_keys_path))))
    execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
示例#11
0
def generate_delete_user_command(username=None, manage_home=None):
    """Generate command to delete a user.

    args:
        username (str): user name
        manage_home (bool): manage home directory

    returns:
        list: The user delete command string split into shell-like syntax
    """
    command = None
    remove_home = '-r' if manage_home else ''

    if get_platform() in ('Linux', 'OpenBSD'):
        command = '{0} {1} {2} {3}'.format(sudo_check(), LINUX_CMD_USERDEL,
                                           remove_home, username)
    elif get_platform() == 'FreeBSD':  # pragma: FreeBSD
        command = '{0} {1} userdel {2} -n {3}'.format(sudo_check(),
                                                      FREEBSD_CMD_PW,
                                                      remove_home, username)
    if command:
        return shlex.split(str(command))
示例#12
0
文件: ssh.py 项目: jonhadfield/creds
def read_authorized_keys(username=None):
    """Read public keys from specified user's authorized_keys file.

    args:
        username (str): username.

    returns:
        list: Authorised keys for the specified user.
    """
    authorized_keys_path = '{0}/.ssh/authorized_keys'.format(
        os.path.expanduser('~{0}'.format(username)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(
        username, rnd_chars)
    authorized_keys = list()
    copy_result = execute_command(
        shlex.split(
            str('{0} cp {1} {2}'.format(sudo_check(), authorized_keys_path,
                                        tmp_authorized_keys_path))))
    result_message = copy_result[0][1].decode('UTF-8')
    if 'you must have a tty to run sudo' in result_message:  # pragma: no cover
        raise OSError(
            "/etc/sudoers is blocked sudo. Remove entry: 'Defaults    requiretty'."
        )
    elif 'No such file or directory' not in result_message:
        execute_command(
            shlex.split(
                str('{0} chmod 755 {1}'.format(sudo_check(),
                                               tmp_authorized_keys_path))))
        with open(tmp_authorized_keys_path) as keys_file:
            for key in keys_file:
                authorized_keys.append(PublicKey(raw=key))
        execute_command(
            shlex.split(
                str('{0} rm {1}'.format(sudo_check(),
                                        tmp_authorized_keys_path))))
    return authorized_keys
示例#13
0
文件: ssh.py 项目: jonhadfield/creds
def write_authorized_keys(user=None):
    """Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist.

    args:
        user (User): Instance of User containing keys.

    returns:
        list: Authorised keys for the specified user.
    """
    authorized_keys = list()
    authorized_keys_dir = '{0}/.ssh'.format(
        os.path.expanduser('~{0}'.format(user.name)))
    rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH)
    authorized_keys_path = '{0}/authorized_keys'.format(authorized_keys_dir)
    tmp_authorized_keys_path = '/tmp/authorized_keys_{0}_{1}'.format(
        user.name, rnd_chars)

    if not os.path.isdir(authorized_keys_dir):
        execute_command(
            shlex.split(
                str('{0} mkdir -p {1}'.format(sudo_check(),
                                              authorized_keys_dir))))
    for key in user.public_keys:
        authorized_keys.append('{0}\n'.format(key.raw))
    with open(tmp_authorized_keys_path, mode=text_type('w+')) as keys_file:
        keys_file.writelines(authorized_keys)
    execute_command(
        shlex.split(
            str('{0} cp {1} {2}'.format(sudo_check(), tmp_authorized_keys_path,
                                        authorized_keys_path))))
    execute_command(
        shlex.split(
            str('{0} chown -R {1} {2}'.format(sudo_check(), user.name,
                                              authorized_keys_dir))))
    execute_command(
        shlex.split(
            str('{0} chmod 700 {1}'.format(sudo_check(),
                                           authorized_keys_dir))))
    execute_command(
        shlex.split(
            str('{0} chmod 600 {1}'.format(sudo_check(),
                                           authorized_keys_path))))
    execute_command(
        shlex.split(
            str('{0} rm {1}'.format(sudo_check(), tmp_authorized_keys_path))))
示例#14
0
def test_user_detection(monkeypatch):
    monkeypatch.setattr("os.geteuid", lambda: 1)
    assert sudo_check().endswith('sudo')
    monkeypatch.setattr("os.geteuid", lambda: 0)
    assert sudo_check() == ''
示例#15
0
def test_user_detection(monkeypatch):
    monkeypatch.setattr("os.geteuid", lambda: 1)
    assert sudo_check().endswith('sudo')
    monkeypatch.setattr("os.geteuid", lambda: 0)
    assert sudo_check() == ''