Imported Upstream version 4.3.1

This commit is contained in:
Mario Fetka
2021-08-10 02:37:58 +02:00
parent a791de49a2
commit 2f177da8f2
2056 changed files with 421730 additions and 1668138 deletions

Binary file not shown.

View File

@@ -18,209 +18,12 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import absolute_import
import logging
import six
import abc
from ipaplatform.paths import paths
from ipapython import ipautil
from ipapython.admintool import ScriptError
import os
FILES_TO_NOT_BACKUP = ['passwd', 'group', 'shadow', 'gshadow']
logger = logging.getLogger(__name__)
def get_auth_tool():
return RedHatAuthSelect()
@six.add_metaclass(abc.ABCMeta)
class RedHatAuthToolBase(object):
@abc.abstractmethod
def configure(self, sssd, mkhomedir, statestore, sudo=True):
pass
@abc.abstractmethod
def unconfigure(self, fstore, statestore,
was_sssd_installed,
was_sssd_configured):
pass
@abc.abstractmethod
def backup(self, path):
"""
Backup the system authentication resources configuration
:param path: directory where the backup will be stored
"""
@abc.abstractmethod
def restore(self, path):
"""
Restore the system authentication resources configuration from a backup
:param path: directory where the backup is stored
"""
@abc.abstractmethod
def set_nisdomain(self, nisdomain):
pass
class RedHatAuthSelect(RedHatAuthToolBase):
def _get_authselect_current_output(self):
try:
current = ipautil.run(
[paths.AUTHSELECT, "current", "--raw"])
except ipautil.CalledProcessError:
logger.debug("Current configuration not managed by authselect")
return None
return current.raw_output.decode()
def _parse_authselect_output(self, output_text=None):
"""
Parses the output_text to extract the profile and options.
When no text is provided, runs the 'authselect profile' command to
generate the text to be parsed.
"""
if output_text is None:
output_text = self._get_authselect_current_output()
if output_text is None:
return None
output_text = output_text.strip()
if not output_text:
return None
output_items = output_text.split(' ')
profile = output_items[0]
features = output_items[1:]
return profile, features
def configure(self, sssd, mkhomedir, statestore, sudo=True):
# In the statestore, the following keys are used for the
# 'authselect' module:
# profile: name of the profile configured pre-installation
# features_list: list of features configured pre-installation
# mkhomedir: True if installation was called with --mkhomedir
# profile and features_list are used when reverting to the
# pre-install state
cfg = self._parse_authselect_output()
if cfg:
statestore.backup_state('authselect', 'profile', cfg[0])
statestore.backup_state(
'authselect', 'features_list', " ".join(cfg[1]))
else:
# cfg = None means that the current conf is not managed by
# authselect but by authconfig.
# As we are using authselect to configure the host,
# it will not be possible to revert to a custom authconfig
# configuration later (during uninstall)
# Best thing to do will be to use sssd profile at this time
logger.warning(
"WARNING: The configuration pre-client installation is not "
"managed by authselect and cannot be backed up. "
"Uninstallation may not be able to revert to the original "
"state.")
cmd = [paths.AUTHSELECT, "select", "sssd"]
if mkhomedir:
cmd.append("with-mkhomedir")
statestore.backup_state('authselect', 'mkhomedir', True)
if sudo:
cmd.append("with-sudo")
cmd.append("--force")
ipautil.run(cmd)
def unconfigure(
self, fstore, statestore, was_sssd_installed, was_sssd_configured
):
if not statestore.has_state('authselect') and was_sssd_installed:
logger.warning(
"WARNING: Unable to revert to the pre-installation state "
"('authconfig' tool has been deprecated in favor of "
"'authselect'). The default sssd profile will be used "
"instead.")
# Build the equivalent command line that will be displayed
# to the user
# This is a copy-paste of unconfigure code, except that it
# creates the command line but does not actually call it
authconfig = RedHatAuthConfig()
authconfig.prepare_unconfigure(
fstore, statestore, was_sssd_installed, was_sssd_configured)
args = authconfig.build_args()
logger.warning(
"The authconfig arguments would have been: authconfig %s",
" ".join(args))
profile = 'sssd'
features = []
else:
profile = statestore.restore_state('authselect', 'profile')
if not profile:
profile = 'sssd'
features_state = statestore.restore_state(
'authselect', 'features_list'
)
statestore.delete_state('authselect', 'mkhomedir')
# only non-empty features, https://pagure.io/freeipa/issue/7776
if features_state is not None:
features = [
f.strip() for f in features_state.split(' ') if f.strip()
]
else:
features = []
cmd = [paths.AUTHSELECT, "select", profile]
cmd.extend(features)
cmd.append("--force")
ipautil.run(cmd)
def backup(self, path):
current = self._get_authselect_current_output()
if current is None:
return
if not os.path.exists(path):
os.makedirs(path)
with open(os.path.join(path, "authselect.backup"), 'w') as f:
f.write(current)
def restore(self, path):
with open(os.path.join(path, "authselect.backup"), "r") as f:
cfg = self._parse_authselect_output(f.read())
if cfg:
profile = cfg[0]
cmd = [paths.AUTHSELECT, "select", profile]
cmd.extend(cfg[1])
cmd.append("--force")
ipautil.run(cmd)
def set_nisdomain(self, nisdomain):
try:
with open(paths.SYSCONF_NETWORK, 'r') as f:
content = [
line for line in f
if not line.strip().upper().startswith('NISDOMAIN')
]
except IOError:
content = []
content.append("NISDOMAIN={}\n".format(nisdomain))
with open(paths.SYSCONF_NETWORK, 'w') as f:
f.writelines(content)
# RedHatAuthConfig concrete class definition to be removed later
# when agreed on exact path to migrate to authselect
class RedHatAuthConfig(RedHatAuthToolBase):
class RedHatAuthConfig(object):
"""
AuthConfig class implements system-independent interface to configure
system authentication resources. In Red Hat systems this is done with
@@ -282,70 +85,10 @@ class RedHatAuthConfig(RedHatAuthToolBase):
self.add_option("update")
args = self.build_args()
try:
ipautil.run([paths.AUTHCONFIG] + args)
except ipautil.CalledProcessError:
raise ScriptError("Failed to execute authconfig command")
def configure(self, sssd, mkhomedir, statestore, sudo=True):
if sssd:
statestore.backup_state('authconfig', 'sssd', True)
statestore.backup_state('authconfig', 'sssdauth', True)
self.enable("sssd")
self.enable("sssdauth")
else:
statestore.backup_state('authconfig', 'ldap', True)
self.enable("ldap")
self.enable("forcelegacy")
statestore.backup_state('authconfig', 'krb5', True)
self.enable("krb5")
self.add_option("nostart")
if mkhomedir:
statestore.backup_state('authconfig', 'mkhomedir', True)
self.enable("mkhomedir")
self.execute()
self.reset()
def prepare_unconfigure(self, fstore, statestore,
was_sssd_installed,
was_sssd_configured):
if statestore.has_state('authconfig'):
# disable only those configurations that we enabled during install
for conf in ('ldap', 'krb5', 'sssd', 'sssdauth', 'mkhomedir'):
cnf = statestore.restore_state('authconfig', conf)
# Do not disable sssd, as this can cause issues with its later
# uses. Remove it from statestore however, so that it becomes
# empty at the end of uninstall process.
if cnf and conf != 'sssd':
self.disable(conf)
else:
# There was no authconfig status store
# It means the code was upgraded after original install
# Fall back to old logic
self.disable("ldap")
self.disable("krb5")
if not(was_sssd_installed and was_sssd_configured):
# Only disable sssdauth. Disabling sssd would cause issues
# with its later uses.
self.disable("sssdauth")
self.disable("mkhomedir")
def unconfigure(self, fstore, statestore,
was_sssd_installed,
was_sssd_configured):
self.prepare_unconfigure(
fstore, statestore, was_sssd_installed, was_sssd_configured)
self.execute()
self.reset()
ipautil.run(["/usr/sbin/authconfig"] + args)
def backup(self, path):
try:
ipautil.run([paths.AUTHCONFIG, "--savebackup", path])
except ipautil.CalledProcessError:
raise ScriptError("Failed to execute authconfig command")
ipautil.run(["/usr/sbin/authconfig", "--savebackup", path])
# do not backup these files since we don't want to mess with
# users/groups during restore. Authconfig doesn't seem to mind about
@@ -358,13 +101,4 @@ class RedHatAuthConfig(RedHatAuthToolBase):
pass
def restore(self, path):
try:
ipautil.run([paths.AUTHCONFIG, "--restorebackup", path])
except ipautil.CalledProcessError:
raise ScriptError("Failed to execute authconfig command")
def set_nisdomain(self, nisdomain):
# Let authconfig setup the permanent configuration
self.reset()
self.add_parameter("nisdomain", nisdomain)
self.execute()
ipautil.run(["/usr/sbin/authconfig", "--restorebackup", path])

View File

@@ -8,8 +8,6 @@ related constants for the Red Hat OS family-based systems.
'''
# Fallback to default path definitions
from __future__ import absolute_import
from ipaplatform.base.constants import BaseConstantsNamespace

View File

@@ -22,8 +22,6 @@ This Red Hat OS family base platform module exports default filesystem paths as
common in Red Hat OS family-based systems.
'''
from __future__ import absolute_import
import sys
# Fallback to default path definitions
@@ -34,11 +32,6 @@ class RedHatPathNamespace(BasePathNamespace):
# https://docs.python.org/2/library/platform.html#cross-platform
if sys.maxsize > 2**32:
LIBSOFTHSM2_SO = BasePathNamespace.LIBSOFTHSM2_SO_64
PAM_KRB5_SO = BasePathNamespace.PAM_KRB5_SO_64
BIND_LDAP_SO = BasePathNamespace.BIND_LDAP_SO_64
AUTHCONFIG = '/usr/sbin/authconfig'
AUTHSELECT = '/usr/bin/authselect'
SYSCONF_NETWORK = '/etc/sysconfig/network'
paths = RedHatPathNamespace()

Binary file not shown.

View File

@@ -22,20 +22,19 @@
Contains Red Hat OS family-specific service class implementations.
"""
from __future__ import absolute_import
import logging
import os
import time
import xml.dom.minidom
import contextlib
from ipaplatform.tasks import tasks
from ipaplatform.base import services as base_services
from ipapython import ipautil, dogtag
from ipapython.ipa_log_manager import root_logger
from ipalib import api
from ipaplatform.paths import paths
logger = logging.getLogger(__name__)
# Mappings from service names as FreeIPA code references to these services
# to their actual systemd service names
@@ -47,7 +46,6 @@ redhat_system_units = dict((x, "%s.service" % x)
redhat_system_units['rpcgssd'] = 'nfs-secure.service'
redhat_system_units['rpcidmapd'] = 'nfs-idmap.service'
redhat_system_units['domainname'] = 'nis-domainname.service'
# Rewrite dirsrv and pki-tomcatd services as they support instances via separate
# service generator. To make this working, one needs to have both foo@.servic
@@ -72,7 +70,6 @@ redhat_system_units['ods-enforcerd'] = 'ods-enforcerd.service'
redhat_system_units['ods_enforcerd'] = redhat_system_units['ods-enforcerd']
redhat_system_units['ods-signerd'] = 'ods-signerd.service'
redhat_system_units['ods_signerd'] = redhat_system_units['ods-signerd']
redhat_system_units['gssproxy'] = 'gssproxy.service'
# Service classes that implement Red Hat OS family-specific behaviour
@@ -80,7 +77,7 @@ redhat_system_units['gssproxy'] = 'gssproxy.service'
class RedHatService(base_services.SystemdService):
system_units = redhat_system_units
def __init__(self, service_name, api=None):
def __init__(self, service_name):
systemd_name = service_name
if service_name in self.system_units:
systemd_name = self.system_units[service_name]
@@ -90,14 +87,38 @@ class RedHatService(base_services.SystemdService):
# and not a foo.target. Thus, not correct service name for
# systemd, default to foo.service style then
systemd_name = "%s.service" % (service_name)
super(RedHatService, self).__init__(service_name, systemd_name, api)
super(RedHatService, self).__init__(service_name, systemd_name)
class RedHatDirectoryService(RedHatService):
def is_installed(self, instance_name):
file_path = "{}/{}-{}".format(paths.ETC_DIRSRV, "slapd", instance_name)
return os.path.exists(file_path)
def tune_nofile_platform(self, num=8192, fstore=None):
"""
Increase the number of files descriptors available to directory server
from the default 1024 to 8192. This will allow to support a greater
number of clients out of the box.
This is a part of the implementation that is systemd-specific.
Returns False if the setting of the nofile limit needs to be skipped.
"""
if os.path.exists(paths.SYSCONFIG_DIRSRV_SYSTEMD):
# We need to enable LimitNOFILE=8192 in the dirsrv@.service
# Since 389-ds-base-1.2.10-0.8.a7 the configuration of the
# service parameters is performed via
# /etc/sysconfig/dirsrv.systemd file which is imported by systemd
# into dirsrv@.service unit
replacevars = {'LimitNOFILE': str(num)}
ipautil.inifile_replace_variables(paths.SYSCONFIG_DIRSRV_SYSTEMD,
'service',
replacevars=replacevars)
tasks.restore_context(paths.SYSCONFIG_DIRSRV_SYSTEMD)
ipautil.run(["/bin/systemctl", "--system", "daemon-reload"],
raiseonerr=False)
return True
def restart(self, instance_name="", capture_output=True, wait=True,
ldapi=False):
@@ -167,21 +188,48 @@ class RedHatIPAService(RedHatService):
self.restart(instance_name)
class RedHatSSHService(RedHatService):
def get_config_dir(self, instance_name=""):
return '/etc/ssh'
class RedHatCAService(RedHatService):
def wait_until_running(self):
logger.debug('Waiting until the CA is running')
timeout = float(self.api.env.startup_timeout)
root_logger.debug('Waiting until the CA is running')
timeout = float(api.env.startup_timeout)
op_timeout = time.time() + timeout
while time.time() < op_timeout:
try:
# check status of CA instance on this host, not remote ca_host
status = dogtag.ca_status(self.api.env.host)
# FIXME https://fedorahosted.org/freeipa/ticket/4716
# workaround
#
# status = dogtag.ca_status(use_proxy=use_proxy)
#
port = 8443
url = "https://%(host_port)s%(path)s" % {
"host_port": ipautil.format_netloc(api.env.ca_host, port),
"path": "/ca/admin/ca/getStatus"
}
args = [
paths.BIN_CURL,
'-o', '-',
'--connect-timeout', '30',
'-k',
url
]
result = ipautil.run(args, capture_output=True)
status = dogtag._parse_ca_status(result.output)
# end of workaround
except Exception as e:
status = 'check interrupted due to error: %s' % e
logger.debug('The CA status is: %s', status)
root_logger.debug('The CA status is: %s' % status)
if status == 'running':
break
logger.debug('Waiting for CA to start...')
root_logger.debug('Waiting for CA to start...')
time.sleep(1)
else:
raise RuntimeError('CA did not start in %ss' % timeout)
@@ -198,55 +246,38 @@ class RedHatCAService(RedHatService):
if wait:
self.wait_until_running()
def is_running(self, instance_name="", wait=True):
if instance_name:
return super(RedHatCAService, self).is_running(instance_name)
try:
status = dogtag.ca_status()
if status == 'running':
return True
elif status == 'starting' and wait:
# Exception is raised if status is 'starting' even after wait
self.wait_until_running()
return True
except Exception as e:
logger.debug(
'Failed to check CA status: %s', e
)
return False
# Function that constructs proper Red Hat OS family-specific server classes for
# services of specified name
def redhat_service_class_factory(name, api=None):
def redhat_service_class_factory(name):
if name == 'dirsrv':
return RedHatDirectoryService(name, api)
return RedHatDirectoryService(name)
if name == 'ipa':
return RedHatIPAService(name, api)
return RedHatIPAService(name)
if name == 'sshd':
return RedHatSSHService(name)
if name in ('pki-tomcatd', 'pki_tomcatd'):
return RedHatCAService(name, api)
return RedHatService(name, api)
return RedHatCAService(name)
return RedHatService(name)
# Magicdict containing RedHatService instances.
class RedHatServices(base_services.KnownServices):
def service_class_factory(self, name):
return redhat_service_class_factory(name)
def __init__(self):
# pylint: disable=ipa-forbidden-import
import ipalib # FixMe: break import cycle
# pylint: enable=ipa-forbidden-import
services = dict()
for s in base_services.wellknownservices:
services[s] = self.service_class_factory(s, ipalib.api)
services[s] = self.service_class_factory(s)
# Call base class constructor. This will lock services to read-only
super(RedHatServices, self).__init__(services)
def service_class_factory(self, name, api=None):
return redhat_service_class_factory(name, api)
# Objects below are expected to be exported by platform module
timedate_services = base_services.timedate_services
from ipaplatform.base.services import timedate_services
service = redhat_service_class_factory
knownservices = RedHatServices()

View File

@@ -23,33 +23,43 @@
This module contains default Red Hat OS family-specific implementations of
system tasks.
'''
from __future__ import print_function, absolute_import
from __future__ import print_function
import ctypes
import logging
import os
import stat
import socket
import traceback
import errno
import sys
import base64
from cffi import FFI
from ctypes.util import find_library
from functools import total_ordering
from subprocess import CalledProcessError
from subprocess import CalledProcessError
from nss.error import NSPRError
from pyasn1.error import PyAsn1Error
from six.moves import urllib
from ipapython import directivesetter
from ipapython.ipa_log_manager import root_logger, log_mgr
from ipapython import ipautil
import ipapython.errors
from ipalib import x509 # FIXME: do not import from ipalib
from ipaplatform.constants import constants
from ipaplatform.paths import paths
from ipaplatform.redhat.authconfig import get_auth_tool
from ipaplatform.redhat.authconfig import RedHatAuthConfig
from ipaplatform.base.tasks import BaseTaskNamespace
logger = logging.getLogger(__name__)
_ffi = FFI()
_ffi.cdef("""
int rpmvercmp (const char *a, const char *b);
""")
# use ctypes loader to get correct librpm.so library version according to
# https://cffi.readthedocs.org/en/latest/overview.html#id8
_librpm = _ffi.dlopen(find_library("rpm"))
log = log_mgr.get_logger(__name__)
def selinux_enabled():
@@ -70,67 +80,36 @@ def selinux_enabled():
@total_ordering
class IPAVersion(object):
_rpmvercmp_func = None
@classmethod
def _rpmvercmp(cls, a, b):
"""Lazy load and call librpm's rpmvercmp
"""
rpmvercmp_func = cls._rpmvercmp_func
if rpmvercmp_func is None:
librpm = ctypes.CDLL(find_library('rpm'))
rpmvercmp_func = librpm.rpmvercmp
# int rpmvercmp(const char *a, const char *b)
rpmvercmp_func.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
rpmvercmp_func.restype = ctypes.c_int
cls._rpmvercmp_func = rpmvercmp_func
return rpmvercmp_func(a, b)
def __init__(self, version):
self._version = version
self._bytes = version.encode('utf-8')
@property
def version(self):
return self._version
self.version = version
def __eq__(self, other):
if not isinstance(other, IPAVersion):
return NotImplemented
return self._rpmvercmp(self._bytes, other._bytes) == 0
assert isinstance(other, IPAVersion)
return _librpm.rpmvercmp(self.version, other.version) == 0
def __lt__(self, other):
if not isinstance(other, IPAVersion):
return NotImplemented
return self._rpmvercmp(self._bytes, other._bytes) < 0
def __hash__(self):
return hash(self._version)
assert isinstance(other, IPAVersion)
return _librpm.rpmvercmp(self.version, other.version) < 0
class RedHatTaskNamespace(BaseTaskNamespace):
def restore_context(self, filepath, force=False):
"""Restore SELinux security context on the given filepath.
def restore_context(self, filepath, restorecon=paths.SBIN_RESTORECON):
"""
restore security context on the file path
SELinux equivalent is /path/to/restorecon <filepath>
restorecon's return values are not reliable so we have to
ignore them (BZ #739604).
ipautil.run() will do the logging.
"""
restorecon = paths.SBIN_RESTORECON
if not selinux_enabled() or not os.path.exists(restorecon):
if not selinux_enabled():
return
# Force reset of context to match file_context for customizable
# files, and the default file context, changing the user, role,
# range portion as well as the type.
args = [restorecon]
if force:
args.append('-F')
args.append(filepath)
ipautil.run(args, raiseonerr=False)
if (os.path.exists(restorecon)):
ipautil.run([restorecon, filepath], raiseonerr=False)
def check_selinux_status(self, restorecon=paths.RESTORECON):
"""
@@ -150,129 +129,93 @@ class RedHatTaskNamespace(BaseTaskNamespace):
'Install the policycoreutils package and start '
'the installation again.' % restorecon)
def check_ipv6_stack_enabled(self):
"""Checks whether IPv6 kernel module is loaded.
Function checks if /proc/net/if_inet6 is present. If IPv6 stack is
enabled, it exists and contains the interfaces configuration.
:raises: RuntimeError when IPv6 stack is disabled
"""
if not os.path.exists(paths.IF_INET6):
raise RuntimeError(
"IPv6 stack has to be enabled in the kernel and some "
"interface has to have ::1 address assigned. Typically "
"this is 'lo' interface. If you do not wish to use IPv6 "
"globally, disable it on the specific interfaces in "
"sysctl.conf except 'lo' interface.")
# XXX This is a hack to work around an issue with Travis CI by
# skipping IPv6 address test. The Dec 2017 update removed ::1 from
# loopback, see https://github.com/travis-ci/travis-ci/issues/8891.
if os.environ.get('TRAVIS') == 'true':
return
try:
localhost6 = ipautil.CheckedIPAddress('::1', allow_loopback=True)
if localhost6.get_matching_interface() is None:
raise ValueError("no interface for ::1 address found")
except ValueError:
raise RuntimeError(
"IPv6 stack is enabled in the kernel but there is no "
"interface that has ::1 address assigned. Add ::1 address "
"resolution to 'lo' interface. You might need to enable IPv6 "
"on the interface 'lo' in sysctl.conf.")
def restore_pre_ipa_client_configuration(self, fstore, statestore,
was_sssd_installed,
was_sssd_configured):
auth_config = get_auth_tool()
auth_config.unconfigure(
fstore, statestore, was_sssd_installed, was_sssd_configured
)
auth_config = RedHatAuthConfig()
if statestore.has_state('authconfig'):
# disable only those configurations that we enabled during install
for conf in ('ldap', 'krb5', 'sssd', 'sssdauth', 'mkhomedir'):
cnf = statestore.restore_state('authconfig', conf)
# Do not disable sssd, as this can cause issues with its later
# uses. Remove it from statestore however, so that it becomes
# empty at the end of uninstall process.
if cnf and conf != 'sssd':
auth_config.disable(conf)
else:
# There was no authconfig status store
# It means the code was upgraded after original install
# Fall back to old logic
auth_config.disable("ldap")
auth_config.disable("krb5")
if not(was_sssd_installed and was_sssd_configured):
# Only disable sssdauth. Disabling sssd would cause issues
# with its later uses.
auth_config.disable("sssdauth")
auth_config.disable("mkhomedir")
auth_config.execute()
def set_nisdomain(self, nisdomain):
try:
with open(paths.SYSCONF_NETWORK, 'r') as f:
content = [
line for line in f
if not line.strip().upper().startswith('NISDOMAIN')
]
except IOError:
content = []
# Let authconfig setup the permanent configuration
auth_config = RedHatAuthConfig()
auth_config.add_parameter("nisdomain", nisdomain)
auth_config.execute()
content.append("NISDOMAIN={}\n".format(nisdomain))
def modify_nsswitch_pam_stack(self, sssd, mkhomedir, statestore):
auth_config = RedHatAuthConfig()
with open(paths.SYSCONF_NETWORK, 'w') as f:
f.writelines(content)
if sssd:
statestore.backup_state('authconfig', 'sssd', True)
statestore.backup_state('authconfig', 'sssdauth', True)
auth_config.enable("sssd")
auth_config.enable("sssdauth")
else:
statestore.backup_state('authconfig', 'ldap', True)
auth_config.enable("ldap")
auth_config.enable("forcelegacy")
def modify_nsswitch_pam_stack(self, sssd, mkhomedir, statestore,
sudo=True):
auth_config = get_auth_tool()
auth_config.configure(sssd, mkhomedir, statestore, sudo)
if mkhomedir:
statestore.backup_state('authconfig', 'mkhomedir', True)
auth_config.enable("mkhomedir")
def is_nosssd_supported(self):
# The flag --no-sssd is not supported any more for rhel-based distros
return False
auth_config.execute()
def modify_pam_to_use_krb5(self, statestore):
auth_config = RedHatAuthConfig()
statestore.backup_state('authconfig', 'krb5', True)
auth_config.enable("krb5")
auth_config.add_option("nostart")
auth_config.execute()
def backup_auth_configuration(self, path):
auth_config = get_auth_tool()
auth_config = RedHatAuthConfig()
auth_config.backup(path)
def restore_auth_configuration(self, path):
auth_config = get_auth_tool()
auth_config = RedHatAuthConfig()
auth_config.restore(path)
def migrate_auth_configuration(self, statestore):
"""
Migrate the pam stack configuration from authconfig to an authselect
profile.
"""
# Check if mkhomedir was enabled during installation
mkhomedir = statestore.get_state('authconfig', 'mkhomedir')
# Force authselect 'sssd' profile
authselect_cmd = [paths.AUTHSELECT, "select", "sssd", "with-sudo"]
if mkhomedir:
authselect_cmd.append("with-mkhomedir")
authselect_cmd.append("--force")
ipautil.run(authselect_cmd)
# Remove all remaining keys from the authconfig module
for conf in ('ldap', 'krb5', 'sssd', 'sssdauth', 'mkhomedir'):
statestore.restore_state('authconfig', conf)
# Create new authselect module in the statestore
statestore.backup_state('authselect', 'profile', 'sssd')
statestore.backup_state(
'authselect', 'features_list', '')
statestore.backup_state('authselect', 'mkhomedir', bool(mkhomedir))
def reload_systemwide_ca_store(self):
try:
ipautil.run([paths.UPDATE_CA_TRUST])
except CalledProcessError as e:
logger.error(
root_logger.error(
"Could not update systemwide CA trust database: %s", e)
return False
else:
logger.info("Systemwide CA database updated.")
root_logger.info("Systemwide CA database updated.")
return True
def insert_ca_certs_into_systemwide_ca_store(self, ca_certs):
# pylint: disable=ipa-forbidden-import
from ipalib import x509 # FixMe: break import cycle
from ipalib.errors import CertificateError
# pylint: enable=ipa-forbidden-import
new_cacert_path = paths.SYSTEMWIDE_IPA_CA_CRT
if os.path.exists(new_cacert_path):
try:
os.remove(new_cacert_path)
except OSError as e:
logger.error(
root_logger.error(
"Could not remove %s: %s", new_cacert_path, e)
return False
@@ -280,23 +223,22 @@ class RedHatTaskNamespace(BaseTaskNamespace):
try:
f = open(new_cacert_path, 'w')
os.fchmod(f.fileno(), 0o644)
except IOError as e:
logger.info("Failed to open %s: %s", new_cacert_path, e)
root_logger.info("Failed to open %s: %s" % (new_cacert_path, e))
return False
f.write("# This file was created by IPA. Do not edit.\n"
"\n")
has_eku = set()
for cert, nickname, trusted, _ext_key_usage in ca_certs:
for cert, nickname, trusted, ext_key_usage in ca_certs:
try:
subject = cert.subject_bytes
issuer = cert.issuer_bytes
serial_number = cert.serial_number_bytes
public_key_info = cert.public_key_info_bytes
except (PyAsn1Error, ValueError, CertificateError) as e:
logger.warning(
subject = x509.get_der_subject(cert, x509.DER)
issuer = x509.get_der_issuer(cert, x509.DER)
serial_number = x509.get_der_serial_number(cert, x509.DER)
public_key_info = x509.get_der_public_key_info(cert, x509.DER)
except (NSPRError, PyAsn1Error, ValueError) as e:
root_logger.warning(
"Failed to decode certificate \"%s\": %s", nickname, e)
continue
@@ -306,6 +248,9 @@ class RedHatTaskNamespace(BaseTaskNamespace):
serial_number = urllib.parse.quote(serial_number)
public_key_info = urllib.parse.quote(public_key_info)
cert = base64.b64encode(cert)
cert = x509.make_pem(cert)
obj = ("[p11-kit-object-v1]\n"
"class: certificate\n"
"certificate-type: x-509\n"
@@ -324,16 +269,16 @@ class RedHatTaskNamespace(BaseTaskNamespace):
obj += "trusted: true\n"
elif trusted is False:
obj += "x-distrusted: true\n"
obj += "{pem}\n\n".format(
pem=cert.public_bytes(x509.Encoding.PEM).decode('ascii'))
obj += "%s\n\n" % cert
f.write(obj)
if (cert.extended_key_usage is not None and
public_key_info not in has_eku):
if ext_key_usage is not None and public_key_info not in has_eku:
if not ext_key_usage:
ext_key_usage = {x509.EKU_PLACEHOLDER}
try:
ext_key_usage = cert.extended_key_usage_bytes
ext_key_usage = x509.encode_ext_key_usage(ext_key_usage)
except PyAsn1Error as e:
logger.warning(
root_logger.warning(
"Failed to encode extended key usage for \"%s\": %s",
nickname, e)
continue
@@ -370,7 +315,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
try:
os.remove(new_cacert_path)
except OSError as e:
logger.error(
root_logger.error(
"Could not remove %s: %s", new_cacert_path, e)
result = False
else:
@@ -382,31 +327,64 @@ class RedHatTaskNamespace(BaseTaskNamespace):
return result
def backup_hostname(self, fstore, statestore):
def backup_and_replace_hostname(self, fstore, statestore, hostname):
old_hostname = socket.gethostname()
try:
ipautil.run([paths.BIN_HOSTNAME, hostname])
except ipautil.CalledProcessError as e:
print(("Failed to set this machine hostname to "
"%s (%s)." % (hostname, str(e))), file=sys.stderr)
filepath = paths.ETC_HOSTNAME
if os.path.exists(filepath):
# read old hostname
with open(filepath, 'r') as f:
for line in f.readlines():
line = line.strip()
if not line or line.startswith('#'):
# skip comment or empty line
continue
old_hostname = line
break
fstore.backup_file(filepath)
with open(filepath, 'w') as f:
f.write("%s\n" % hostname)
os.chmod(filepath,
stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
os.chown(filepath, 0, 0)
self.restore_context(filepath)
# store old hostname
old_hostname = socket.gethostname()
statestore.backup_state('network', 'hostname', old_hostname)
def restore_hostname(self, fstore, statestore):
old_hostname = statestore.restore_state('network', 'hostname')
def restore_network_configuration(self, fstore, statestore):
old_filepath = paths.SYSCONFIG_NETWORK
old_hostname = statestore.get_state('network', 'hostname')
hostname_was_configured = False
if old_hostname is not None:
try:
self.set_hostname(old_hostname)
except ipautil.CalledProcessError as e:
logger.debug("%s", traceback.format_exc())
logger.error(
"Failed to restore this machine hostname to %s (%s).",
old_hostname, e
)
if fstore.has_file(old_filepath):
# This is Fedora >=18 instance that was upgraded from previous
# Fedora version which held network configuration
# in /etc/sysconfig/network
old_filepath_restore = paths.SYSCONFIG_NETWORK_IPABKP
fstore.restore_file(old_filepath, old_filepath_restore)
print("Deprecated configuration file '%s' was restored to '%s'" \
% (old_filepath, old_filepath_restore))
hostname_was_configured = True
filepath = paths.ETC_HOSTNAME
if fstore.has_file(filepath):
fstore.restore_file(filepath)
hostname_was_configured = True
if not hostname_was_configured and old_hostname:
# hostname was not configured before but was set by IPA. Delete
# /etc/hostname to restore previous configuration
try:
os.remove(filepath)
except OSError:
pass
def set_selinux_booleans(self, required_settings, backup_func=None):
def get_setsebool_args(changes):
@@ -435,7 +413,7 @@ class RedHatTaskNamespace(BaseTaskNamespace):
if original_state != state:
updated_vars[setting] = state
except ipautil.CalledProcessError as e:
logger.error("Cannot get SELinux boolean '%s': %s", setting, e)
log.error("Cannot get SELinux boolean '%s': %s", setting, e)
failed_vars[setting] = state
if updated_vars:
@@ -452,6 +430,29 @@ class RedHatTaskNamespace(BaseTaskNamespace):
return True
def create_system_user(self, name, group, homedir, shell, uid=None, gid=None, comment=None, create_homedir=False):
"""
Create a system user with a corresponding group
According to https://fedoraproject.org/wiki/Packaging:UsersAndGroups?rd=Packaging/UsersAndGroups#Soft_static_allocation
some system users should have fixed UID, GID and other parameters set.
This values should be constant and may be hardcoded.
Add other values for other users when needed.
"""
if name == constants.PKI_USER:
if uid is None:
uid = 17
if gid is None:
gid = 17
if comment is None:
comment = 'CA System User'
if name == constants.DS_USER:
if comment is None:
comment = 'DS System User'
super(RedHatTaskNamespace, self).create_system_user(name, group,
homedir, shell, uid, gid, comment, create_homedir)
def parse_ipa_version(self, version):
"""
:param version: textual version
@@ -459,122 +460,5 @@ class RedHatTaskNamespace(BaseTaskNamespace):
"""
return IPAVersion(version)
def configure_httpd_service_ipa_conf(self):
"""Create systemd config for httpd service to work with IPA
"""
if not os.path.exists(paths.SYSTEMD_SYSTEM_HTTPD_D_DIR):
os.mkdir(paths.SYSTEMD_SYSTEM_HTTPD_D_DIR, 0o755)
ipautil.copy_template_file(
os.path.join(paths.USR_SHARE_IPA_DIR, 'ipa-httpd.conf.template'),
paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF,
dict(
KDCPROXY_CONFIG=paths.KDCPROXY_CONFIG,
IPA_HTTPD_KDCPROXY=paths.IPA_HTTPD_KDCPROXY,
KRB5CC_HTTPD=paths.KRB5CC_HTTPD,
)
)
os.chmod(paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF, 0o644)
self.restore_context(paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF)
ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"],
raiseonerr=False)
def configure_http_gssproxy_conf(self, ipaapi_user):
ipautil.copy_template_file(
os.path.join(paths.USR_SHARE_IPA_DIR, 'gssproxy.conf.template'),
paths.GSSPROXY_CONF,
dict(
HTTP_KEYTAB=paths.HTTP_KEYTAB,
HTTP_CCACHE=paths.HTTP_CCACHE,
HTTPD_USER=constants.HTTPD_USER,
IPAAPI_USER=ipaapi_user,
)
)
os.chmod(paths.GSSPROXY_CONF, 0o600)
self.restore_context(paths.GSSPROXY_CONF)
def configure_httpd_wsgi_conf(self):
"""Configure WSGI for correct Python version (Fedora)
See https://pagure.io/freeipa/issue/7394
"""
conf = paths.HTTPD_IPA_WSGI_MODULES_CONF
if sys.version_info.major == 2:
wsgi_module = constants.MOD_WSGI_PYTHON2
else:
wsgi_module = constants.MOD_WSGI_PYTHON3
if conf is None or wsgi_module is None:
logger.info("Nothing to do for configure_httpd_wsgi_conf")
return
confdir = os.path.dirname(conf)
if not os.path.isdir(confdir):
os.makedirs(confdir)
ipautil.copy_template_file(
os.path.join(
paths.USR_SHARE_IPA_DIR, 'ipa-httpd-wsgi.conf.template'
),
conf,
dict(WSGI_MODULE=wsgi_module)
)
os.chmod(conf, 0o644)
self.restore_context(conf)
def remove_httpd_service_ipa_conf(self):
"""Remove systemd config for httpd service of IPA"""
try:
os.unlink(paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF)
except OSError as e:
if e.errno == errno.ENOENT:
logger.debug(
'Trying to remove %s but file does not exist',
paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF
)
else:
logger.error(
'Error removing %s: %s',
paths.SYSTEMD_SYSTEM_HTTPD_IPA_CONF, e
)
return
ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"],
raiseonerr=False)
def set_hostname(self, hostname):
ipautil.run([paths.BIN_HOSTNAMECTL, 'set-hostname', hostname])
def is_fips_enabled(self):
"""
Checks whether this host is FIPS-enabled.
Returns a boolean indicating if the host is FIPS-enabled, i.e. if the
file /proc/sys/crypto/fips_enabled contains a non-0 value. Otherwise,
or if the file /proc/sys/crypto/fips_enabled does not exist,
the function returns False.
"""
try:
with open(paths.PROC_FIPS_ENABLED, 'r') as f:
if f.read().strip() != '0':
return True
except IOError:
# Consider that the host is not fips-enabled if the file does not
# exist
pass
return False
def setup_httpd_logging(self):
directivesetter.set_directive(paths.HTTPD_SSL_CONF,
'ErrorLog',
'logs/error_log', False)
directivesetter.set_directive(paths.HTTPD_SSL_CONF,
'TransferLog',
'logs/access_log', False)
tasks = RedHatTaskNamespace()