""" This module defines classes regarding sssd tools,
AD Operations and LDAP Operations"""
import os
import tempfile
import subprocess
import array
import random
import socket
import shlex
import ConfigParser
import ldap
import ldif
import paramiko
""" Collection of assorted functions which is used in fixtures
Attributes:
Host(obj: `Multihost object type`): Multihost Object
authbackup(str): Backup directory of authconfig
"""
""" Update /etc/resolv.conf with Windows AD IP address
:param str ip_addr: IP Address to be added in resolv.conf
:return: None
:Exception: Raises exception of builtin type Exception
"""
'/etc/resolv.conf.backup'],
else:
""" Run authconfig to configure Kerberos and SSSD auth on remote host
:param str hostname: Hostname of server(AD) to
which client is configured to auth
:return: None
:Exceptions: None
"""
""" Restore the default authconfig """
""" Configure smb.conf as Domain Member to Windows AD
:return: None
:Exception: None
"""
client_software='sssd',
server_software='active-directory',
membership_software='adcli'):
:param str admin_password: Administrator password required to join
:param str server_software: server software (active-directory/ipa)
else raises Exception
:Exception: Raises exception(builtin)
"""
'--client-software=%s' %
'--server-software=%s' %
'--membership-software=%s' %
(membership_software), '-v'],
else:
return True
else raises Exception
:Exception: Raises exception(builtin)
"""
domainname, '-v'],
else:
return True
Todo: We are not checking if the directories added
:param str path_list: list of directories to be created
:param str nfs_client: hostname/ip-address of nfs client
:Exception: Raises exception(builtin) if not successfully added
"""
'(rw,sync,fsid=0)')
return True
""" Remove the sssd cache
:param str cache_path: The relative path of cache
:return bool: True if deletion and mkdir is successful
:Exception: Raises exception(builtin)
"""
# for index in range(len(db_list)):
# sss_db = db_list[index]
else:
print("Successfully deleted %s" % (relative_path))
return True
""" Domain name from the suffix
:param suffix: The suffix of 389 RHDS instance
:return: domain name in upper case
:Exception: Raises exception(builtin)
"""
if suffix is None:
raise Exception("Error: suffix should be passed")
else:
elist = []
for i in l1:
return u_domain
""" Remove the sssd domain log
:param str cache_path: domain name from default configuration file
:return bool: True if deletion is successful
:Exception: Raises exception(builtin)
"""
else:
return True
""" Get the ad user information through 'net ads dn' command
:param str username: The name of ad user
:param str ad_host: Host of active directory
:return bool: True is command is successful
:return: output of command
:Exception: Raises exception(builtin)
"""
else:
""" ssh to user from client environment
:param str username: The name of user
:param str password: Login password of user
:return: exit status
if timeout the return status is 0
if user successfully login then return status is 3
if not then return status is 10
"""
expect_script = 'spawn ssh -o NumberOfPasswordPrompts=1 ' \
'-o StrictHostKeyChecking=no '\
expect_script += 'expect "*assword: "\n'
expect_script += 'expect {\n'
expect_script += '\ttimeout { set result_code 0 }\n'
expect_script += '\teof {}\n'
expect_script += '\t"Permission denied " { set result_code 10 }\n'
expect_script += '}\n'
expect_script += 'exit $result_code\n'
print(expect_script)
for _ in range(10))
print(("remote side expect script filename: %s") % exp_file)
# Next run expect
print("----expect output start----")
print(cmd.stdout_text)
print(cmd.stderr_text)
print("----expect output end----")
return cmd.returncode
:param str realm: Kerberos realm
:param krb5_server: kerberos server
:return: None
:Exception: Raise exception(builtin)
"""
if krb5_server is None:
if realm is None:
raise Exception("Error: realm should be passed")
else:
realm_def = ("{\n"
"kdc = %s\n"
"admin_server = %s\n"
"FILE:/var/log/kadmind.log")
prefix='krb5conf')
'/etc/krb5.conf.orig'])
""" Enable kcm
:param: None
:Return: None
:Exception: Raise Exception("message")
"""
prefix='krb5cc')
enable_sssd_kcm_socket = 'systemctl enable sssd-kcm.socket'
try:
except subprocess.CalledProcessError:
raise Exception("kcm socket not enabled")
start_ssd_kcm_socket = 'systemctl start sssd-kcm.socket'
raise Exception("sssd-kcm.socket service not started")
start_sssd_kcm_service = 'systemctl enable sssd-kcm.service'
raise Exception("sssd-kcm.service not enabled")
try:
except subprocess.CalledProcessError:
raise Exception("kcm socket not enabled")
"""
LDapOperations consists of functions related to ldap operations, like
adding entry, adding a DN, modifying DN, search entries.
Attributes:
binddn(str): Binddn required to bind
bindpw(str): Bind password
conn: ldap bind object (already initialized)
"""
""" Bind to ldap server
:param: None
:return: None
:Exceptions: None
"""
try:
else:
""" Add an entry to ldap server
:param dict entry: attributes/objectclass to be added to dn
:param str dn: Entry dn to be added
"""
print("Adding entry: %s" % (ldap_dn))
try:
except:
raise
else:
return "Success", True
""" Parsing Exception """
return err, return_value
"""Delete dn
:param str ldap_dn: DN to be deleted
:return tupele: "Success", return_value
:Exception: ldap exception
"""
try:
except:
raise
else:
return "Success", ret
""" Search ldap server and return results
:param str base: basedn of ldap server
:param str criteria: Search criteria(ex:
"(&(objectClass=user)(sAMAccountName=Administrator))"
:param str attributes: Attributes to be returned in the result
:scope obj : scope to be used when search default:
ldap.SCOPE_SUBTREE
"""
return result_set
""" Modify ldap dn """
try:
except ldap.NO_SUCH_ATTRIBUTE:
return "Fail", False
except ldap.UNWILLING_TO_PERFORM:
else:
return 'Success', True
""" Add POSIX Users
:param str ou: Organizational unit (ou=Users)
:param str basedn: Base dn ('dc=example,dc=test')
:param dict user_attr: Entry attributes
:Return bool: Return True
:Exception: Raise Exception if unable to add user
"""
try:
except KeyError:
try:
except KeyError:
try:
except KeyError:
password = 'Secret123'
try:
except KeyError:
try:
except KeyError:
try:
except KeyError:
try:
except KeyError:
location = 'US'
attr = {
'objectClass': ['top', 'posixAccount', 'inetOrgPerson'],
if ret == 'Success':
return True
else:
raise Exception('Unable to add User to ldap')
""" Add POSIX group
:param str ou: Organizational unit (ou=Groups)
:param str basedn: Base dn ('dc=example,dc=test')
:param dict group_attr: Entry attributes
:Return bool: Return True
:Exception: Raise Exception if unable to add user
"""
user_password = '{crypt}x'
attr = {
'objectClass': ['posixGroup', 'top', 'groupOfUniqueNames'],
if ret != 'Success':
raise Exception('Unable to add group to ldap')
""" Enable autofs schema
:param str basedn: base dn of the ldap server
:return: None
:Exceptions: None
"""
autofs_schema = ("""
dn: ou=automount,%s
ou: automount
objectClass: organizationalUnit
dn: CN=auto.master,OU=automount,%s
objectClass: top
objectClass: nisMap
cn: auto.master
nisMapName: auto.master
dn: cn=/-,cn=auto.master,ou=automount,%s
objectClass: nisObject
objectClass: top
cn: /-
nisMapEntry: auto.direct
nisMapName: auto.master
dn: cn=/home,cn=auto.master,ou=automount,%s
objectClass: nisObject
objectClass: top
cn: /home
nisMapEntry: auto.home
nisMapName: auto.master
dn: cn=auto.direct,ou=automount,%s
objectClass: nisMap
objectClass: top
cn: auto.direct
nisMapName: auto.direct
dn: cn=auto.home,ou=automount,%s
objectClass: nisMap
objectClass: top
"""
PkiTools consists of functions related to creation of
certificate requests, updating profile XML with certificate
requests.
"""
if nssdir is None:
else:
if nssdir_pwd is None:
else:
"""
Create a NSS Database on a temporary Directory
:return:
str nssdb: path of the NSS DB Directory
"""
if ret != 0:
else:
args,
stdin=None,
env=None,
cwd=None):
"""
Execute a command and return stdout, stderr and return code
:param str args: List of arguments for the command
:param str stdin: Optional input
:param bool: capture_output: Capture output of the command
(default True)
:param bool raiseonerr: Raise exception if command fails
:param str env: Env variables to be set before the command is run
:param str cwd: Current working Directory
:return stdout, stderr and returncode: if command return code is 0
:Exception: raises exception if raiseonerr is True
"""
p_in = None
p_out = None
p_err = None
if env is None:
if capture_output:
try:
except KeyboardInterrupt:
raise
else:
ca_dn=None,
passphrase='Secret123',
canickname='Example CA'):
"""
Creates a NSS DB in /tmp/nssDirxxxx where self signed Root CA
and Server Certs are created
:param str CA_DN: Distinguished Name for CA Cert
:param str Server_DN: Distinguished Name for Server Cert
"""
if ca_dn is None:
ca_dn = 'CN=Example CA,O=Example,L=Raleigh,C=US'
pin_filename = 'pin.txt'
ca_args = 'certutil -d %s -f %s -S -n "%s" -s %s' \
ca_pem = 'certutil -d %s -f %s -L -n "%s"' \
if return_code != 0:
raise PkiLibException('Could not create Self signed CA Cert')
else:
for server in serverlist:
server_pem = 'certutil -d %s -f %s -L '\
'-n "%s" -a -o %s' % (nss_dir,
server_args = 'certutil -d %s -f %s -S -n "%s" -s %s -c "%s"'\
' -t u,u,u -v 720 -m %s -z %s' % (nss_dir,
if return_code != 0:
raise PkiLibException('Could not create Server-Cert')
else:
if return_code != 0:
raise PkiLibException('Could not create Server pem file')
return nss_dir
"""
ADOperations class consists of methods related to managing AD User With
Unix properties.
"""
cmd = ['powershell.exe',
'-inputformat',
'none',
'-noprofile',
'(Get-ADDomain -Current LocalComputer).NetBIOSName']
""" Create a LDAP Connection with AD
:param None
:Return obj: Object of LdapOperations
:Exceptions: None
"""
return ad_conn_inst
password='Secret123'):
""" Create a AD User with Unix Attributes
:param str username: AD User Name
:param str groupname: AD Group Name
:param str password: User password (default: Secret123)
:Exceptions: False
"""
user_dn])
'/home/%s' % (username))]
else:
return False
return True
""" Create AD Group with UNIX Attributes
:param str groupname: Windows AD Group name
:Return bool : True if AD group was created with Unix Attributes
:Exceptions: None
"""
else:
return False
return True
""" Delete AD user
:param str user_group: User or Group Name to be deleted
:Return bool: True if delete is successful else false
:Exceptions: None
"""
try:
except CalledProcessError:
return False
else:
return True
""" Add user member of a group
:param str group: Name of Windows AD Group
:param str user: Name of Windows AD user
:Return bool: True if user is added as member to group
:Exceptions: None
"""
try:
user_dn])
except CalledProcessError:
return False
else:
return True
""" Remove User from Group membership
:param str group: Name of Windows AD Group
:param str user: Name of Windows AD user
:Return bool: True if user is removed from group else False
:Exceptions: None
"""
try:
user_dn])
except CalledProcessError:
return False
return True
""" This class Inherits paramiko.SSHClient and implements
client.exec_commands channel.exec_command """
""" Initialize connection to Remote Host using Paramiko SSHClient.
Can be initialized with hostname, port, username and password.
"""
if port is None:
else:
try:
timeout=30)
except (paramiko.AuthenticationException,
raise
""" This Function executes commands using SSHClient.exec_commands().
:param str args: actual command to run
:param str stdin: stdin for the command
:Return tuple: stdin stdout stderr
:Exception: paramiko.SSHException
"""
try:
except paramiko.SSHException:
raise
else:
if stdin:
else:
try:
except paramiko.SSHException:
raise
else:
if stdin: