id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
17,100
__init__.py
freeipa_freeipa/ipaclient/install/__init__.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license #
71
Python
.py
3
22.666667
66
0.779412
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,101
ipa_client_automount.py
freeipa_freeipa/ipaclient/install/ipa_client_automount.py
# # Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2012, 2019 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Configure the automount client for ldap. from __future__ import print_function import logging import sys import os import shutil import time import tempfile import gssapi import SSSDConfig from six.moves.urllib.parse import urlsplit from optparse import OptionParser # pylint: disable=deprecated-module from ipapython import ipachangeconf from ipaclient import discovery from ipaclient.install.client import ( CLIENT_NOT_CONFIGURED, CLIENT_ALREADY_CONFIGURED, ) from ipalib import api, errors from ipalib.install import sysrestore from ipalib.kinit import kinit_keytab from ipalib.util import check_client_configuration from ipapython import ipautil from ipapython.ipa_log_manager import standard_logging_setup from ipaplatform.constants import constants from ipaplatform.tasks import tasks from ipaplatform import services from ipaplatform.paths import paths from ipapython.admintool import ScriptError logger = logging.getLogger(os.path.basename(__file__)) def parse_options(): usage = "%prog [options]\n" parser = OptionParser(usage=usage) parser.add_option("--server", dest="server", help="FQDN of IPA server") parser.add_option( "--location", dest="location", default="default", help="Automount location", ) parser.add_option( "--idmap-domain", dest="idmapdomain", default=None, help="nfs domain for idmapd.conf", ) parser.add_option( "-d", "--debug", dest="debug", action="store_true", default=False, help="enable debugging", ) parser.add_option( "-U", "--unattended", dest="unattended", action="store_true", default=False, help="unattended installation never prompts the user", ) parser.add_option( "--uninstall", dest="uninstall", action="store_true", default=False, help="Unconfigure automount", ) options, args = parser.parse_args() return options, args def wait_for_sssd(): """ It takes a bit for sssd to get going, lets loop until it is serving data. This function returns nothing. """ n = 0 found = False time.sleep(1) while n < 10 and not found: try: ipautil.run([paths.GETENT, "passwd", "admin@%s" % api.env.realm]) found = True except Exception: time.sleep(1) n = n + 1 # This should never happen but if it does, may as well warn the user if not found: err_msg = ( "Unable to find 'admin' user with " "'getent passwd admin@%s'!" % api.env.realm ) logger.debug('%s', err_msg) print(err_msg) print( "This may mean that sssd didn't re-start properly after " "the configuration changes." ) def configure_autofs_sssd(fstore, statestore, autodiscover, options): try: sssdconfig = SSSDConfig.SSSDConfig() sssdconfig.import_config() domains = sssdconfig.list_active_domains() except Exception as e: sys.exit(e) try: sssdconfig.new_service('autofs') except SSSDConfig.ServiceAlreadyExists: pass except SSSDConfig.ServiceNotRecognizedError: logger.error("Unable to activate the Autofs service in SSSD config.") logger.info( "Please make sure you have SSSD built with autofs support " "installed." ) logger.info( "Configure autofs support manually in /etc/sssd/sssd.conf." ) sys.exit("Cannot create the autofs service in sssd.conf") sssdconfig.activate_service('autofs') domain = None for name in domains: domain = sssdconfig.get_domain(name) try: provider = domain.get_option('id_provider') except SSSDConfig.NoOptionError: continue if provider == "ipa": domain.add_provider('ipa', 'autofs') try: domain.get_option('ipa_automount_location') print('An automount location is already configured') sys.exit(CLIENT_ALREADY_CONFIGURED) except SSSDConfig.NoOptionError: domain.set_option('ipa_automount_location', options.location) break if domain is None: sys.exit('SSSD is not configured.') sssdconfig.save_domain(domain) sssdconfig.write(paths.SSSD_CONF) statestore.backup_state('autofs', 'sssd', True) sssd = services.service('sssd', api) sssd.restart() print("Restarting sssd, waiting for it to become available.") wait_for_sssd() def configure_autofs_common(fstore, statestore, options): autofs = services.knownservices.autofs statestore.backup_state('autofs', 'enabled', autofs.is_enabled()) statestore.backup_state('autofs', 'running', autofs.is_running()) try: autofs.restart() print("Started %s" % autofs.service_name) except Exception as e: logger.error("%s failed to restart: %s", autofs.service_name, e) try: autofs.enable() except Exception as e: print( "Failed to configure automatic startup of the %s daemon" % (autofs.service_name) ) logger.error( "Failed to enable automatic startup of the %s daemon: %s", autofs.service_name, str(e), ) def uninstall(fstore, statestore): RESTORE_FILES = [ paths.SYSCONFIG_AUTOFS, paths.SYSCONFIG_NFS, paths.IDMAPD_CONF, ] STATES = ['autofs', 'rpcidmapd', 'rpcgssd'] if not statestore.get_state('autofs', 'sssd'): tasks.disable_ldap_automount(statestore) if not any(fstore.has_file(f) for f in RESTORE_FILES) or not any( statestore.has_state(s) for s in STATES ): print("IPA automount is not configured on this system") return CLIENT_NOT_CONFIGURED print("Restoring configuration") for filepath in RESTORE_FILES: if fstore.has_file(filepath): fstore.restore_file(filepath) if statestore.has_state('autofs'): enabled = statestore.restore_state('autofs', 'enabled') running = statestore.restore_state('autofs', 'running') sssd = statestore.restore_state('autofs', 'sssd') autofs = services.knownservices.autofs if not enabled: autofs.disable() if not running: autofs.stop() if sssd: try: sssdconfig = SSSDConfig.SSSDConfig() sssdconfig.import_config() sssdconfig.deactivate_service('autofs') domains = sssdconfig.list_active_domains() for name in domains: domain = sssdconfig.get_domain(name) try: provider = domain.get_option('id_provider') except SSSDConfig.NoOptionError: continue if provider == "ipa": domain.remove_option('ipa_automount_location') sssdconfig.save_domain(domain) domain.remove_provider('autofs') sssdconfig.save_domain(domain) break sssdconfig.write(paths.SSSD_CONF) sssd = services.service('sssd', api) sssd.restart() wait_for_sssd() except Exception as e: print('Unable to restore SSSD configuration: %s' % str(e)) logger.debug( 'Unable to restore SSSD configuration: %s', str(e) ) # rpcidmapd and rpcgssd are static units now if statestore.has_state('rpcidmapd'): statestore.delete_state('rpcidmapd', 'enabled') statestore.delete_state('rpcidmapd', 'running') if statestore.has_state('rpcgssd'): statestore.delete_state('rpcgssd', 'enabled') statestore.delete_state('rpcgssd', 'running') nfsutils = services.knownservices['nfs-utils'] try: nfsutils.restart() except Exception as e: logger.error("Failed to restart nfs client services (%s)", str(e)) return 1 return 0 def configure_nfs(fstore, statestore, options): """ Configure secure NFS """ # Newer Fedora releases ship /etc/nfs.conf instead of /etc/sysconfig/nfs # and do not require changes there. On these, SECURE_NFS_VAR == None if constants.SECURE_NFS_VAR: replacevars = {constants.SECURE_NFS_VAR: 'yes'} ipautil.backup_config_and_replace_variables( fstore, paths.SYSCONFIG_NFS, replacevars=replacevars ) tasks.restore_context(paths.SYSCONFIG_NFS) print("Configured %s" % paths.SYSCONFIG_NFS) # Prepare the changes # We need to use IPAChangeConf as simple regexp substitution # does not cut it here conf = ipachangeconf.IPAChangeConf("IPA automount installer") conf.case_insensitive_sections = False conf.setOptionAssignment(" = ") conf.setSectionNameDelimiters(("[", "]")) if options.idmapdomain is None: # Set NFSv4 domain to the IPA domain changes = [conf.setOption('Domain', api.env.domain)] elif options.idmapdomain == 'DNS': # Rely on idmapd auto-detection (DNS) changes = [conf.rmOption('Domain')] else: # Set NFSv4 domain to what was provided changes = [conf.setOption('Domain', options.idmapdomain)] if changes is not None: section_with_changes = [conf.setSection('General', changes)] # Backup the file and apply the changes fstore.backup_file(paths.IDMAPD_CONF) conf.changeConf(paths.IDMAPD_CONF, section_with_changes) tasks.restore_context(paths.IDMAPD_CONF) print("Configured %s" % paths.IDMAPD_CONF) rpcgssd = services.knownservices.rpcgssd try: rpcgssd.restart() except Exception as e: logger.error("Failed to restart rpc-gssd (%s)", str(e)) nfsutils = services.knownservices['nfs-utils'] try: nfsutils.restart() except Exception as e: logger.error("Failed to restart nfs client services (%s)", str(e)) def configure_automount(): statestore = sysrestore.StateFile(paths.IPA_CLIENT_SYSRESTORE) if not statestore.get_state('installation', 'automount'): # not called from ipa-client-install try: check_client_configuration() except ScriptError as e: print(e.msg) sys.exit(e.rval) fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) options, _args = parse_options() standard_logging_setup( paths.IPACLIENT_INSTALL_LOG, verbose=False, debug=options.debug, filemode='a', console_format='%(message)s', ) cfg = dict( context='cli_installer', confdir=paths.ETC_IPA, in_server=False, debug=options.debug, verbose=0, ) # Bootstrap API early so that env object is available api.bootstrap(**cfg) if options.uninstall: return uninstall(fstore, statestore) ca_cert_path = None if os.path.exists(paths.IPA_CA_CRT): ca_cert_path = paths.IPA_CA_CRT if statestore.has_state('autofs'): print('An automount location is already configured') sys.exit(CLIENT_ALREADY_CONFIGURED) autodiscover = False ds = discovery.IPADiscovery() if not options.server: print("Searching for IPA server...") ret = ds.search(ca_cert_path=ca_cert_path) logger.debug('Executing DNS discovery') if ret == discovery.NO_LDAP_SERVER: logger.debug('Autodiscovery did not find LDAP server') s = urlsplit(api.env.xmlrpc_uri) server = [s.netloc] logger.debug('Setting server to %s', s.netloc) else: autodiscover = True if not ds.servers: sys.exit( 'Autodiscovery was successful but didn\'t return a server' ) logger.debug( 'Autodiscovery success, possible servers %s', ','.join(ds.servers), ) server = ds.servers[0] else: server = options.server logger.debug("Verifying that %s is an IPA server", server) ldapret = ds.ipacheckldap(server, api.env.realm, ca_cert_path) if ldapret[0] == discovery.NO_ACCESS_TO_LDAP: print("Anonymous access to the LDAP server is disabled.") print("Proceeding without strict verification.") print( "Note: This is not an error if anonymous access has been " "explicitly restricted." ) elif ldapret[0] == discovery.NO_TLS_LDAP: logger.warning("Unencrypted access to LDAP is not supported.") elif ldapret[0] != 0: sys.exit('Unable to confirm that %s is an IPA server' % server) if not autodiscover: print("IPA server: %s" % server) logger.debug('Using fixed server %s', server) else: print("IPA server: DNS discovery") logger.debug('Configuring to use DNS discovery') print("Location: %s" % options.location) logger.debug('Using automount location %s', options.location) ccache_dir = tempfile.mkdtemp() ccache_name = os.path.join(ccache_dir, 'ccache') try: try: host_princ = str('host/%s@%s' % (api.env.host, api.env.realm)) kinit_keytab(host_princ, paths.KRB5_KEYTAB, ccache_name) os.environ['KRB5CCNAME'] = ccache_name except gssapi.exceptions.GSSError as e: sys.exit("Failed to obtain host TGT: %s" % e) # Finalize API when TGT obtained using host keytab exists api.finalize() # Now we have a TGT, connect to IPA try: api.Backend.rpcclient.connect() except errors.KerberosError as e: sys.exit('Cannot connect to the server due to ' + str(e)) try: # Use the RPC directly so older servers are supported api.Backend.rpcclient.forward( 'automountlocation_show', ipautil.fsdecode(options.location), version=u'2.0', ) except errors.VersionError as e: sys.exit('This client is incompatible: ' + str(e)) except errors.NotFound: sys.exit( "Automount location '%s' does not exist" % options.location ) except errors.PublicError as e: sys.exit( "Cannot connect to the server due to generic error: %s" % str(e) ) finally: shutil.rmtree(ccache_dir) if not options.unattended and not ipautil.user_input( "Continue to configure the system with these values?", False ): sys.exit("Installation aborted") try: configure_nfs(fstore, statestore, options) configure_autofs_sssd(fstore, statestore, autodiscover, options) configure_autofs_common(fstore, statestore, options) except Exception as e: logger.debug('Raised exception %s', e) print("Installation failed. Rolling back changes.") uninstall(fstore, statestore) return 1 return 0 def main(): try: if not os.geteuid() == 0: sys.exit("\nMust be run as root\n") configure_automount() except SystemExit as e: sys.exit(e) except RuntimeError as e: sys.exit(e) except (KeyboardInterrupt, EOFError): sys.exit(1)
16,557
Python
.py
442
28.986425
78
0.628924
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,102
ipa_client_install.py
freeipa_freeipa/ipaclient/install/ipa_client_install.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import from ipaclient.install import client from ipaplatform.paths import paths from ipapython.install import cli from ipapython.install.core import knob, extend_knob class StandaloneClientInstall(client.ClientInstall): no_host_dns = False no_wait_for_dns = False principal = client.ClientInstall.principal principal = extend_knob( principal, cli_names=list(principal.cli_names) + ['-p'], ) password = knob( str, None, sensitive=True, description="password to join the IPA realm (assumes bulk password " "unless principal is also set)", cli_names=[None, '-w'], ) @property def admin_password(self): if self.principal: return self.password return super(StandaloneClientInstall, self).admin_password @property def host_password(self): if not self.principal: return self.password return super(StandaloneClientInstall, self).host_password prompt_password = knob( None, description="Prompt for a password to join the IPA realm", cli_names='-W', ) on_master = knob( None, deprecated=True, ) ClientInstall = cli.install_tool( StandaloneClientInstall, command_name='ipa-client-install', log_file_name=paths.IPACLIENT_INSTALL_LOG, debug_option=True, verbose=True, console_format='%(message)s', uninstall_log_file_name=paths.IPACLIENT_UNINSTALL_LOG, ) def run(): ClientInstall.run_cli()
1,652
Python
.py
53
25.037736
76
0.680985
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,103
ipa_client_samba.py
freeipa_freeipa/ipaclient/install/ipa_client_samba.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # # Configure the Samba suite to operate as domain member in IPA domain from __future__ import print_function import logging import os import gssapi from urllib.parse import urlsplit from optparse import OptionParser # pylint: disable=deprecated-module from contextlib import contextmanager from ipaclient import discovery from ipaclient.install.client import ( CLIENT_NOT_CONFIGURED, CLIENT_ALREADY_CONFIGURED, ) from ipalib import api, errors from ipalib.install import sysrestore from ipalib.util import check_client_configuration from ipalib.request import context from ipapython import ipautil from ipapython.errors import SetseboolError from ipapython.ipa_log_manager import standard_logging_setup from ipapython.dnsutil import DNSName from ipaplatform.tasks import tasks from ipaplatform.paths import paths from ipaplatform.constants import constants from ipaplatform import services from ipapython.admintool import ScriptError from samba import generate_random_password logger = logging.getLogger(os.path.basename(__file__)) logger.setLevel(logging.DEBUG) @contextmanager def use_api_as_principal(principal, keytab): with ipautil.private_ccache() as ccache_file: old_principal = getattr(context, "principal", None) try: name = gssapi.Name(principal, gssapi.NameType.kerberos_principal) store = {"ccache": ccache_file, "client_keytab": keytab} gssapi.Credentials(name=name, usage="initiate", store=store) # Finalize API when TGT obtained using host keytab exists if not api.isdone("finalize"): api.finalize() # Now we have a TGT, connect to IPA try: if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() api.Backend.rpcclient.connect() yield except gssapi.exceptions.GSSError as e: raise Exception( "Unable to bind to IPA server. Error initializing " "principal %s in %s: %s" % (principal, keytab, str(e)) ) finally: if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() setattr(context, "principal", old_principal) def parse_options(): usage = "%prog [options]\n" parser = OptionParser(usage=usage) parser.add_option( "--server", dest="server", help="FQDN of IPA server to connect to", ) parser.add_option( "--netbios-name", dest="netbiosname", help="NetBIOS name of this machine", default=None, ) parser.add_option( "--no-homes", dest="no_homes", action="store_true", default=False, help="Do not add [homes] share to the generated Samba configuration", ) parser.add_option( "--no-nfs", dest="no_nfs", action="store_true", default=False, help="Do not allow NFS integration (SELinux booleans)", ) parser.add_option( "--force", dest="force", action="store_true", default=False, help="force installation by redoing all steps", ) parser.add_option( "-d", "--debug", dest="debug", action="store_true", default=False, help="print debugging information", ) parser.add_option( "-U", "--unattended", dest="unattended", action="store_true", default=False, help="unattended installation never prompts the user", ) parser.add_option( "--uninstall", dest="uninstall", action="store_true", default=False, help="Revert configuration and remove SMB service", ) options, args = parser.parse_args() return options, args domain_information_template = """ Domain name: {domain_name} NetBIOS name: {netbios_name} SID: {domain_sid} ID range: {range_id_min} - {range_id_max} """ def pretty_print_domain_information(info): result = [] for domain in info: result.append(domain_information_template.format(**domain)) return "\n".join(result) trust_keymap = { "netbios_name": "ipantflatname", "domain_sid": "ipantsecurityidentifier", "domain_name": "cn", } trust_keymap_trustdomain = { "netbios_name": "ipantflatname", "domain_sid": "ipanttrusteddomainsid", "domain_name": "cn", } def retrieve_domain_information(api): # Pull down default domain configuration # IPA master might be missing freeipa-server-trust-ad package # or `ipa-adtrust-install` was never run. In such case return # empty list to report an error try: tc_command = api.Command.trustconfig_show except AttributeError: return [] try: result = tc_command()["result"] except errors.PublicError: return [] l_domain = dict() for key, val in trust_keymap.items(): l_domain[key] = result.get(val, [None])[0] # Pull down ID range and other details of our domain # # TODO: make clear how to handle multiple ID ranges for ipa-local range # In Samba only one range can belong to the same idmap domain, # otherwise winbindd's _wbint_Sids2UnixIDs function will not be able # to accept that a mapped Unix ID belongs to the specified domain idrange_local = "{realm}_id_range".format(realm=api.env.realm) result = api.Command.idrange_show(idrange_local)["result"] l_domain["range_id_min"] = int(result["ipabaseid"][0]) l_domain["range_id_max"] = ( int(result["ipabaseid"][0]) + int(result["ipaidrangesize"][0]) - 1 ) domains = [l_domain] # Retrieve list of trusted domains, if they exist # # We flatten the whole trust list because it should be non-overlapping result = api.Command.trust_find()["result"] for forest in result: r = api.Command.trustdomain_find(forest["cn"][0], all=True, raw=True)[ "result" ] # We don't need to process forest root info separately # as trustdomain_find() returns it as well for dom in r: r_dom = dict() for key in trust_keymap: r_dom[key] = dom.get(trust_keymap_trustdomain[key], [None])[0] r_idrange_name = "{realm}_id_range".format( realm=r_dom["domain_name"].upper() ) # TODO: support ipa-ad-trust-posix range as well r_idrange = api.Command.idrange_show(r_idrange_name)["result"] r_dom["range_id_min"] = int(r_idrange["ipabaseid"][0]) r_dom["range_id_max"] = ( int(r_idrange["ipabaseid"][0]) + int(r_idrange["ipaidrangesize"][0]) - 1 ) domains.append(r_dom) return domains smb_conf_template = """ [global] # Limit number of forked processes to avoid SMBLoris attack max smbd processes = 1000 # Use dedicated Samba keytab. The key there must be synchronized # with Samba tdb databases or nothing will work dedicated keytab file = FILE:${samba_keytab} kerberos method = dedicated keytab # Set up logging per machine and Samba process log file = /var/log/samba/log.%m log level = 1 # We force 'member server' role to allow winbind automatically # discover what is supported by the domain controller side server role = member server realm = ${realm} netbios name = ${machine_name} workgroup = ${netbios_name} # Local writable range for IDs not coming from IPA or trusted domains idmap config * : range = 0 - 0 idmap config * : backend = tdb """ idmap_conf_domain_snippet = """ idmap config ${netbios_name} : range = ${range_id_min} - ${range_id_max} idmap config ${netbios_name} : backend = sss """ homes_conf_snippet = """ # Default homes share [homes] read only = no """ def configure_smb_conf(fstore, statestore, options, domains): sub_dict = { "samba_keytab": paths.SAMBA_KEYTAB, "realm": api.env.realm, "machine_name": options.netbiosname, } # First domain in the list is ours, pull our domain name from there sub_dict["netbios_name"] = domains[0]["netbios_name"] # Construct elements of smb.conf by pre-rendering idmap configuration template = [smb_conf_template] for dom in domains: template.extend([ipautil.template_str(idmap_conf_domain_snippet, dom)]) # Add default homes share so that users can log into Samba if not options.no_homes: template.extend([homes_conf_snippet]) fstore.backup_file(paths.SMB_CONF) with open(paths.SMB_CONF, "w") as f: f.write(ipautil.template_str("\n".join(template), sub_dict)) tasks.restore_context(paths.SMB_CONF) def generate_smb_machine_account(fstore, statestore, options, domain): # Ideally, we should be using generate_random_machine_password() # from samba but it uses munged UTF-16 which is not decodable # by the code called from 'net changesecretpw -f'. Thus, we'd limit # password to ASCII only. return generate_random_password(128, 255) def retrieve_service_principal( fstore, statestore, options, domain, principal, password ): # Use explicit encryption types. SMB service must have arcfour-hmac # generated to allow domain member to authenticate to the domain controller args = [ paths.IPA_GETKEYTAB, "-p", principal, "-k", paths.SAMBA_KEYTAB, "-P", "-e", "aes128-cts-hmac-sha1-96,aes256-cts-hmac-sha1-96,arcfour-hmac", ] try: ipautil.run(args, stdin=password + "\n" + password, encoding="utf-8") except ipautil.CalledProcessError as e: logger.error( "Cannot set machine account password at IPA DC. Error: %s", e, ) raise # Once we fetched the keytab, we also need to set ipaNTHash attribute # Use ipa-pwd-extop plugin to regenerate it from the Kerberos key value = "ipaNTHash=MagicRegen" try: api.Command.service_mod(principal, addattr=value) except errors.PublicError as e: logger.error( "Cannot update %s principal NT hash value due to an error: %s", principal, e, ) raise def populate_samba_databases(fstore, statestore, options, domain, password): # First, set domain SID in Samba args = [paths.NET, "setdomainsid", domain["domain_sid"]] try: ipautil.run(args) except ipautil.CalledProcessError as e: logger.error("Cannot set domain SID in Samba. Error: %s", e) raise # Next, make sure we can set machine account credentials # the workaround with tdbtool is temporary until 'net' utility # will not provide us a way to perform 'offline join' procedure secrets_key = "SECRETS/MACHINE_LAST_CHANGE_TIME/{}".format( domain["netbios_name"] ) args = [paths.TDBTOOL, paths.SECRETS_TDB, "store", secrets_key, "2\\00"] try: ipautil.run(args) except ipautil.CalledProcessError as e: logger.error( "Cannot prepare machine account creds in Samba. Error: %s", e, ) raise secrets_key = "SECRETS/MACHINE_PASSWORD/{}".format(domain["netbios_name"]) args = [paths.TDBTOOL, paths.SECRETS_TDB, "store", secrets_key, "2\\00"] try: ipautil.run(args) except ipautil.CalledProcessError as e: logger.error( "Cannot prepare machine account creds in Samba. Error: %s", e, ) raise # Finally, set actual machine account's password args = [paths.NET, "changesecretpw", "-f"] try: ipautil.run(args, stdin=password, encoding="utf-8") except ipautil.CalledProcessError as e: logger.error( "Cannot set machine account creds in Samba. Error: %s", e, ) raise def configure_default_groupmap(fstore, statestore, options, domain): args = [ paths.NET, "groupmap", "add", "sid=S-1-5-32-546", "unixgroup=nobody", "type=builtin", ] logger.info("Map BUILTIN\\Guests to a group 'nobody'") try: ipautil.run(args) except ipautil.CalledProcessError as e: if "already mapped to SID S-1-5-32-546" not in e.stdout: logger.error( 'Cannot map BUILTIN\\Guests to a group "nobody". Error: %s', e ) raise def set_selinux_booleans(booleans, statestore, backup=True): def default_backup_func(name, value): statestore.backup_state("selinux", name, value) backup_func = default_backup_func if backup else None try: tasks.set_selinux_booleans(booleans, backup_func=backup_func) except SetseboolError as e: print("WARNING: " + str(e)) logger.info("WARNING: %s", e) def harden_configuration(fstore, statestore, options, domain): # Add default homes share so that users can log into Samba if not options.no_homes: set_selinux_booleans( constants.SELINUX_BOOLEAN_SMBSERVICE["share_home_dirs"], statestore ) # Allow Samba to access NFS-shared content if not options.no_nfs: set_selinux_booleans( constants.SELINUX_BOOLEAN_SMBSERVICE["reshare_nfs_with_samba"], statestore, ) def uninstall(fstore, statestore, options): # Shut down Samba services and disable them smb = services.service("smb", api) winbind = services.service("winbind", api) for svc in (smb, winbind): if svc.is_running(): svc.stop() svc.disable() # Restore the state of affected selinux booleans boolean_states = {} for usecase in constants.SELINUX_BOOLEAN_SMBSERVICE: for name in usecase: boolean_states[name] = statestore.restore_state("selinux", name) if boolean_states: set_selinux_booleans(boolean_states, statestore, backup=False) # Remove samba's credentials cache ipautil.remove_ccache(ccache_path=paths.KRB5CC_SAMBA) # Remove samba's configuration file if fstore.has_file(paths.SMB_CONF): ipautil.remove_file(paths.SMB_CONF) fstore.restore_file(paths.SMB_CONF) # Remove samba's persistent and temporary tdb files # in /var/lib/samba and /var/lib/samba/private for smbpath in (paths.SAMBA_DIR, os.path.join(paths.SAMBA_DIR, "private"), os.path.join(paths.SAMBA_DIR, "lock")): tdb_files = [ os.path.join(smbpath, tdb_file) for tdb_file in os.listdir(smbpath) if tdb_file.endswith(".tdb") ] for tdb_file in tdb_files: ipautil.remove_file(tdb_file) # Remove our keys from samba's keytab if os.path.exists(paths.SAMBA_KEYTAB): try: ipautil.run( [ paths.IPA_RMKEYTAB, "--principal", api.env.smb_princ, "-k", paths.SAMBA_KEYTAB, ] ) except ipautil.CalledProcessError as e: if e.returncode != 5: logger.critical("Failed to remove old key for %s", api.env.smb_princ) with use_api_as_principal(api.env.host_princ, paths.KRB5_KEYTAB): try: api.Command.service_del(api.env.smb_princ) except errors.VersionError as e: print("This client is incompatible: " + str(e)) except errors.NotFound: logger.debug("No SMB service principal exists, OK to proceed") except errors.PublicError as e: logger.error( "Cannot connect to the server due to " "a generic error: %s", e, ) def run(): try: check_client_configuration() except ScriptError as e: print(e.msg) return e.rval fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) statestore = sysrestore.StateFile(paths.IPA_CLIENT_SYSRESTORE) options, _args = parse_options() logfile = paths.IPACLIENTSAMBA_INSTALL_LOG if options.uninstall: logfile = paths.IPACLIENTSAMBA_UNINSTALL_LOG standard_logging_setup( logfile, verbose=False, debug=options.debug, filemode="a", console_format="%(message)s", ) cfg = dict( context="cli_installer", confdir=paths.ETC_IPA, in_server=False, debug=options.debug, verbose=0, ) # Bootstrap API early so that env object is available api.bootstrap(**cfg) local_config = dict( host_princ=str("host/%s@%s" % (api.env.host, api.env.realm)), smb_princ=str("cifs/%s@%s" % (api.env.host, api.env.realm)), ) # Until api.finalize() is called, we can add our own configuration api.env._merge(**local_config) if options.uninstall: if statestore.has_state("domain_member"): uninstall(fstore, statestore, options) try: keys = ( "configured", "hardening", "groupmap", "tdb", "service.principal", "smb.conf" ) for key in keys: statestore.delete_state("domain_member", key) except Exception as e: print( "Error: Failed to remove the domain_member statestores: " "%s" % e ) return 1 else: print( "Samba configuration is reverted. " "However, Samba databases were fully cleaned and " "old configuration file will not be usable anymore." ) else: print("Samba domain member is not configured yet") return 0 ca_cert_path = None if os.path.exists(paths.IPA_CA_CRT): ca_cert_path = paths.IPA_CA_CRT if statestore.has_state("domain_member") and not options.force: print("Samba domain member is already configured") return CLIENT_ALREADY_CONFIGURED if not os.path.exists(paths.SMBD): print("Samba suite is not installed") return CLIENT_NOT_CONFIGURED autodiscover = False ds = discovery.IPADiscovery() if not options.server: print("Searching for IPA server...") ret = ds.search(ca_cert_path=ca_cert_path) logger.debug("Executing DNS discovery") if ret == discovery.NO_LDAP_SERVER: logger.debug("Autodiscovery did not find LDAP server") s = urlsplit(api.env.xmlrpc_uri) server = [s.netloc] logger.debug("Setting server to %s", s.netloc) else: autodiscover = True if not ds.servers: print( "Autodiscovery was successful but didn't return a server" ) return 1 logger.debug( "Autodiscovery success, possible servers %s", ",".join(ds.servers), ) server = ds.servers[0] else: server = options.server logger.debug("Verifying that %s is an IPA server", server) ldapret = ds.ipacheckldap(server, api.env.realm, ca_cert_path) if ldapret[0] == discovery.NO_ACCESS_TO_LDAP: print("Anonymous access to the LDAP server is disabled.") print("Proceeding without strict verification.") print( "Note: This is not an error if anonymous access has been " "explicitly restricted." ) elif ldapret[0] == discovery.NO_TLS_LDAP: logger.warning("Unencrypted access to LDAP is not supported.") elif ldapret[0] != 0: print("Unable to confirm that %s is an IPA server" % server) return 1 if not autodiscover: print("IPA server: %s" % server) logger.debug("Using fixed server %s", server) else: print("IPA server: DNS discovery") logger.info("Configured to use DNS discovery") if api.env.host == server: logger.error( "Cannot run on IPA master. " "Cannot configure Samba as a domain member on a domain " "controller. Please use ipa-adtrust-install for that!" ) return 1 if not options.netbiosname: options.netbiosname = DNSName.from_text(api.env.host)[0].decode() options.netbiosname = options.netbiosname.upper() with use_api_as_principal(api.env.host_princ, paths.KRB5_KEYTAB): try: # Try to access 'service_add_smb' command, if it throws # AttributeError exception, the IPA server doesn't support # setting up Samba as a domain member. service_add_smb = api.Command.service_add_smb # Now try to see if SMB principal already exists api.Command.service_show(api.env.smb_princ) # If no exception was raised, the object exists. # We cannot continue because we would break existing configuration print( "WARNING: SMB service principal %s already exists. " "Please remove it before proceeding." % (api.env.smb_princ) ) if not options.force: return 1 # For --force, we should then delete cifs/.. service object api.Command.service_del(api.env.smb_princ) except AttributeError: logger.error( "Chosen IPA master %s does not have support to " "set up Samba domain members", server, ) return 1 except errors.VersionError as e: print("This client is incompatible: " + str(e)) return 1 except errors.NotFound: logger.debug("No SMB service principal exists, OK to proceed") except errors.PublicError as e: logger.error( "Cannot connect to the server due to " "a generic error: %s", e, ) return 1 # At this point we have proper setup: # - we connected to IPA API end-point as a host principal # - no cifs/... principal exists so we can create it print("Chosen IPA master: %s" % server) print("SMB principal to be created: %s" % api.env.smb_princ) print("NetBIOS name to be used: %s" % options.netbiosname) logger.info("Chosen IPA master: %s", server) logger.info("SMB principal to be created: %s", api.env.smb_princ) logger.info("NetBIOS name to be used: %s", options.netbiosname) # 1. Pull down ID range and other details of known domains domains = retrieve_domain_information(api) if len(domains) == 0: # logger.error() produces both log file and stderr output logger.error("No configured trust controller detected " "on IPA masters. Use ipa-adtrust-install on an IPA " "master to configure trust controller role.") return 1 str_info = pretty_print_domain_information(domains) logger.info("Discovered domains to use:\n%s", str_info) print("Discovered domains to use:\n%s" % str_info) if not options.unattended and not ipautil.user_input( "Continue to configure the system with these values?", False ): print("Installation aborted") return 1 # 2. Create SMB service principal, if we are here, the command exists if ( not statestore.get_state("domain_member", "service.principal") or options.force ): service_add_smb(api.env.host, options.netbiosname) statestore.backup_state( "domain_member", "service.principal", "configured" ) # 3. Generate machine account password for reuse password = generate_smb_machine_account( fstore, statestore, options, domains[0] ) # 4. Now that we have all domains retrieved, we can generate smb.conf if ( not statestore.get_state("domain_member", "smb.conf") or options.force ): configure_smb_conf(fstore, statestore, options, domains) statestore.backup_state("domain_member", "smb.conf", "configured") # 5. Create SMB service if statestore.get_state("domain_member", "service.principal") == "configured": retrieve_service_principal( fstore, statestore, options, domains[0], api.env.smb_princ, password ) statestore.backup_state( "domain_member", "service.principal", "configured" ) # 6. Configure databases to contain proper details if not statestore.get_state("domain_member", "tdb") or options.force: populate_samba_databases( fstore, statestore, options, domains[0], password ) statestore.backup_state("domain_member", "tdb", "configured") # 7. Configure default group mapping if ( not statestore.get_state("domain_member", "groupmap") or options.force ): configure_default_groupmap(fstore, statestore, options, domains[0]) statestore.backup_state("domain_member", "groupmap", "configured") # 8. Enable SELinux policies if ( not statestore.get_state("domain_member", "hardening") or options.force ): harden_configuration(fstore, statestore, options, domains[0]) statestore.backup_state("domain_member", "hardening", "configured") # 9. Finally, store the state of upgrade statestore.backup_state("domain_member", "configured", True) # Suggest service start only after validating smb.conf print( "Samba domain member is configured. " "Please check configuration at %s and " "start smb and winbind services" % paths.SMB_CONF ) logger.info( "Samba domain member is configured. " "Please check configuration at %s and " "start smb and winbind services", paths.SMB_CONF, ) return 0
26,665
Python
.py
673
30.580981
79
0.61785
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,104
stageuser.py
freeipa_freeipa/ipaclient/plugins/stageuser.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # from ipaclient.plugins.baseuser import baseuser_add_passkey from ipalib.plugable import Registry from ipalib import _ register = Registry() @register(override=True, no_fail=True) class stageuser_add_passkey(baseuser_add_passkey): __doc__ = _("Add one or more passkey mappings to the user entry.")
376
Python
.py
10
35.8
70
0.787293
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,105
automount.py
freeipa_freeipa/ipaclient/plugins/automount.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import six from ipaclient.frontend import MethodOverride from ipalib import api, errors from ipalib import Flag, Str from ipalib.frontend import Command, Method, Object from ipalib.plugable import Registry from ipalib.util import classproperty from ipalib import _ from ipapython.dn import DN if six.PY3: unicode = str register = Registry() DEFAULT_MAPS = (u'auto.direct', ) DEFAULT_KEYS = (u'/-', ) @register(no_fail=True) class _fake_automountlocation(Object): name = 'automountlocation' @register(no_fail=True) class _fake_automountlocation_show(Method): name = 'automountlocation_show' NO_CLI = True @register(override=True, no_fail=True) class automountlocation_tofiles(MethodOverride): @classmethod def __NO_CLI_getter(cls): return (api.Command.get_plugin('automountlocation_show') is _fake_automountlocation_show) NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.automountlocation_show.api_version def output_for_cli(self, textui, result, *keys, **options): maps = result['result']['maps'] keys = result['result']['keys'] orphanmaps = result['result']['orphanmaps'] orphankeys = result['result']['orphankeys'] textui.print_plain('/etc/auto.master:') for m in maps: if m['automountinformation'][0].startswith('-'): textui.print_plain( '%s\t%s' % ( m['automountkey'][0], m['automountinformation'][0] ) ) else: textui.print_plain( '%s\t/etc/%s' % ( m['automountkey'][0], m['automountinformation'][0] ) ) for m in maps: if m['automountinformation'][0].startswith('-'): continue info = m['automountinformation'][0] textui.print_plain('---------------------------') textui.print_plain('/etc/%s:' % info) for k in keys[info]: textui.print_plain( '%s\t%s' % ( k['automountkey'][0], k['automountinformation'][0] ) ) textui.print_plain('') textui.print_plain(_('maps not connected to /etc/auto.master:')) for m in orphanmaps: textui.print_plain('---------------------------') textui.print_plain('/etc/%s:' % m['automountmapname']) for k in orphankeys: if len(k) == 0: continue for key in k: dn = DN(key['dn']) if dn['automountmapname'] == m['automountmapname'][0]: textui.print_plain( '%s\t%s' % ( key['automountkey'][0], key['automountinformation'][0] ) ) @register() class automountlocation_import(Command): __doc__ = _('Import automount files for a specific location.') takes_args = ( Str('masterfile', label=_('Master file'), doc=_('Automount master file.'), ), ) takes_options = ( Flag('continue?', cli_name='continue', doc=_('Continuous operation mode. Errors are reported but the process continues.'), ), ) def get_args(self): for arg in self.api.Command.automountlocation_show.args(): yield arg for arg in super(automountlocation_import, self).get_args(): yield arg def __read_mapfile(self, filename): try: fp = open(filename, 'r') map = fp.readlines() fp.close() except IOError as e: if e.errno == 2: raise errors.NotFound( reason=_('File %(file)s not found') % {'file': filename} ) else: raise return map def forward(self, *args, **options): """ The basic idea is to read the master file and create all the maps we need, then read each map file and add all the keys for the map. """ self.api.Command['automountlocation_show'](args[0]) result = {'maps':[], 'keys':[], 'skipped':[], 'duplicatekeys':[], 'duplicatemaps':[]} maps = {} master = self.__read_mapfile(args[1]) for m in master: if m.startswith('#'): continue m = m.rstrip() if m.startswith('+'): result['skipped'].append([m,args[1]]) continue if len(m) == 0: continue am = m.split(None) if len(am) < 2: continue if am[1].startswith('/'): mapfile = am[1].replace('"','') am[1] = os.path.basename(am[1]) maps[am[1]] = mapfile # Add a new key to the auto.master map for the new map file try: api.Command['automountkey_add']( args[0], u'auto.master', automountkey=unicode(am[0]), automountinformation=unicode(' '.join(am[1:]))) result['keys'].append([am[0], u'auto.master']) except errors.DuplicateEntry: if unicode(am[0]) in DEFAULT_KEYS: # ignore conflict when the key was pre-created by the framework pass elif options.get('continue', False): result['duplicatekeys'].append(am[0]) else: raise errors.DuplicateEntry( message=_('key %(key)s already exists') % dict( key=am[0])) # Add the new map if not am[1].startswith('-'): try: api.Command['automountmap_add'](args[0], unicode(am[1])) result['maps'].append(am[1]) except errors.DuplicateEntry: if unicode(am[1]) in DEFAULT_MAPS: # ignore conflict when the map was pre-created by the framework pass elif options.get('continue', False): result['duplicatemaps'].append(am[0]) else: raise errors.DuplicateEntry( message=_('map %(map)s already exists') % dict( map=am[1])) # Now iterate over the map files and add the keys. To handle # continuation lines I'll make a pass through it to skip comments # etc and also to combine lines. for m, filename in maps.items(): map = self.__read_mapfile(filename) lines = [] cont = '' for x in map: if x.startswith('#'): continue x = x.rstrip() if x.startswith('+'): result['skipped'].append([m, filename]) continue if len(x) == 0: continue if x.endswith("\\"): cont = cont + x[:-1] + ' ' else: lines.append(cont + x) cont='' for x in lines: am = x.split(None) key = unicode(am[0].replace('"','')) try: api.Command['automountkey_add']( args[0], unicode(m), automountkey=key, automountinformation=unicode(' '.join(am[1:]))) result['keys'].append([key,m]) except errors.DuplicateEntry as e: if options.get('continue', False): result['duplicatekeys'].append(am[0]) else: raise e return dict(result=result) def output_for_cli(self, textui, result, *keys, **options): maps = result['result']['maps'] keys = result['result']['keys'] duplicatemaps = result['result']['duplicatemaps'] duplicatekeys = result['result']['duplicatekeys'] skipped = result['result']['skipped'] textui.print_plain(_('Imported maps:')) for m in maps: textui.print_plain( _('Added %(map)s') % dict(map=m) ) textui.print_plain('') textui.print_plain(_('Imported keys:')) for k in keys: textui.print_plain( _('Added %(src)s to %(dst)s') % dict( src=k[0], dst=k[1] ) ) textui.print_plain('') if len(skipped) > 0: textui.print_plain(_('Ignored keys:')) for k in skipped: textui.print_plain( _('Ignored %(src)s to %(dst)s') % dict( src=k[0], dst=k[1] ) ) if options.get('continue', False) and len(duplicatemaps) > 0: textui.print_plain('') textui.print_plain(_('Duplicate maps skipped:')) for m in duplicatemaps: textui.print_plain( _('Skipped %(map)s') % dict(map=m) ) if options.get('continue', False) and len(duplicatekeys) > 0: textui.print_plain('') textui.print_plain(_('Duplicate keys skipped:')) for k in duplicatekeys: textui.print_plain( _('Skipped %(key)s') % dict(key=k) )
10,745
Python
.py
268
26.843284
96
0.500862
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,106
sudorule.py
freeipa_freeipa/ipaclient/plugins/sudorule.py
# Authors: # Jr Aquino <jr.aquino@citrixonline.com> # # Copyright (C) 2010-2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib.plugable import Registry from ipalib import _ register = Registry() @register(override=True, no_fail=True) class sudorule_enable(MethodOverride): def output_for_cli(self, textui, result, cn, **options): textui.print_dashed(_('Enabled Sudo Rule "%s"') % cn) @register(override=True, no_fail=True) class sudorule_disable(MethodOverride): def output_for_cli(self, textui, result, cn, **options): textui.print_dashed(_('Disabled Sudo Rule "%s"') % cn) @register(override=True, no_fail=True) class sudorule_add_option(MethodOverride): def output_for_cli(self, textui, result, cn, **options): opts = self.normalize(**options) textui.print_dashed( _('Added option "%(option)s" to Sudo Rule "%(rule)s"') % dict(option=','.join(opts['ipasudoopt']), rule=cn) ) super(sudorule_add_option, self).output_for_cli(textui, result, cn, **options) @register(override=True, no_fail=True) class sudorule_remove_option(MethodOverride): def output_for_cli(self, textui, result, cn, **options): opts = self.normalize(**options) textui.print_dashed( _('Removed option "%(option)s" from Sudo Rule "%(rule)s"') % dict(option=','.join(opts['ipasudoopt']), rule=cn) ) super(sudorule_remove_option, self).output_for_cli(textui, result, cn, **options)
2,331
Python
.py
50
40.22
78
0.673568
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,107
migration.py
freeipa_freeipa/ipaclient/plugins/migration.py
# Authors: # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import six from ipaclient.frontend import CommandOverride from ipalib.parameters import File from ipalib.plugable import Registry from ipalib import _ if six.PY3: unicode = str register = Registry() @register(override=True, no_fail=True) class migrate_ds(CommandOverride): migrate_order = ('user', 'group') migration_disabled_msg = _('''\ Migration mode is disabled. Use \'ipa config-mod --enable-migration=TRUE\' to enable it.''') pwd_migration_msg = _('''\ Passwords have been migrated in pre-hashed format. IPA is unable to generate Kerberos keys unless provided with clear text passwords. All migrated users need to login at https://your.domain/ipa/migration/ before they can use their Kerberos accounts.''') def get_options(self): for option in super(migrate_ds, self).get_options(): if option.name == 'cacertfile': option = option.clone_retype(option.name, File) yield option def output_for_cli(self, textui, result, ldapuri, **options): textui.print_name(self.name) if not result['enabled']: textui.print_plain(self.migration_disabled_msg) return 1 if not result['compat']: textui.print_plain("The compat plug-in is enabled. This can increase the memory requirements during migration. Disable the compat plug-in with \'ipa-compat-manage disable\' or re-run this script with \'--with-compat\' option.") return 1 any_migrated = any(result['result'].values()) textui.print_plain('Migrated:') textui.print_entry1( result['result'], attr_order=self.migrate_order, one_value_per_line=False ) for ldap_obj_name in self.migrate_order: textui.print_plain('Failed %s:' % ldap_obj_name) textui.print_entry1( result['failed'][ldap_obj_name], attr_order=self.migrate_order, one_value_per_line=True, ) textui.print_plain('-' * len(self.name)) if not any_migrated: textui.print_plain('No users/groups were migrated from %s' % ldapuri) return 1 textui.print_plain(unicode(self.pwd_migration_msg)) return None
3,040
Python
.py
70
37.1
239
0.68277
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,108
user.py
freeipa_freeipa/ipaclient/plugins/user.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipaclient.plugins.baseuser import baseuser_add_passkey from ipalib import errors from ipalib import Flag from ipalib import util from ipalib.plugable import Registry from ipalib import _ from ipalib import x509 register = Registry() @register(override=True, no_fail=True) class user_del(MethodOverride): def get_options(self): for option in super(user_del, self).get_options(): yield option yield Flag( 'preserve?', include='cli', doc=_('Delete a user, keeping the entry available for future use'), ) yield Flag( 'no_preserve?', include='cli', doc=_('Delete a user'), ) def forward(self, *keys, **options): if self.api.env.context == 'cli': no_preserve = options.pop('no_preserve', False) preserve = options.pop('preserve', False) if no_preserve and preserve: raise errors.MutuallyExclusiveError( reason=_("preserve and no-preserve cannot be both set")) elif no_preserve: options['preserve'] = False elif preserve: options['preserve'] = True return super(user_del, self).forward(*keys, **options) @register(override=True, no_fail=True) class user_show(MethodOverride): def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(user_show, self).forward(*keys, **options) if 'usercertificate' in result['result']: certs = (x509.load_der_x509_certificate(c) for c in result['result']['usercertificate']) x509.write_certificate_list(certs, options['out']) result['summary'] = ( _('Certificate(s) stored in file \'%(file)s\'') % dict(file=options['out']) ) return result else: raise errors.NoCertificateError(entry=keys[-1]) else: return super(user_show, self).forward(*keys, **options) @register(override=True, no_fail=True) class user_add_passkey(baseuser_add_passkey): __doc__ = _("Add one or more passkey mappings to the user entry.")
3,184
Python
.py
77
33.454545
79
0.639651
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,109
otptoken.py
freeipa_freeipa/ipaclient/plugins/otptoken.py
# Authors: # Nathaniel McCallum <npmccallum@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 print_function import sys from ipaclient.frontend import MethodOverride from ipalib import api, Str, Password, _ from ipalib import errors from ipalib.messages import add_message, ResultFormattingError from ipalib.plugable import Registry from ipalib.frontend import Local from ipalib.util import create_https_connection from ipapython.version import API_VERSION import locale import qrcode import six from io import StringIO import urllib.parse import urllib.request if six.PY3: unicode = str register = Registry() @register(override=True, no_fail=True) class otptoken_add(MethodOverride): def _get_qrcode(self, output, uri, version): # Print QR code to terminal if specified qr_output = StringIO() qr = qrcode.QRCode() qr.add_data(uri) qr.make() qr.print_ascii(out=qr_output, tty=False) encoding = getattr(sys.stdout, 'encoding', None) if encoding is None: encoding = locale.getpreferredencoding(False) try: qr_code = qr_output.getvalue().encode(encoding) except UnicodeError: add_message( version, output, message=ResultFormattingError( message=_("Unable to display QR code using the configured " "output encoding. Please use the token URI to " "configure your OTP device") ) ) return None if sys.stdout.isatty(): output_width = self.api.Backend.textui.get_tty_width() qr_code_width = len(qr_code.splitlines()[0]) if qr_code_width > output_width: add_message( version, output, message=ResultFormattingError( message=_( "QR code width is greater than that of the output " "tty. Please resize your terminal.") ) ) return qr def output_for_cli(self, textui, output, *args, **options): # copy-pasted from ipalib/Frontend.__do_call() # because option handling is broken on client-side if 'version' in options: pass elif self.api.env.skip_version_check: options['version'] = u'2.0' else: options['version'] = API_VERSION uri = output['result'].get('uri', None) if uri is not None and not options.get('no_qrcode', False): qr = self._get_qrcode(output, uri, options['version']) else: qr = None rv = super(otptoken_add, self).output_for_cli( textui, output, *args, **options) if qr is not None: print("\n") qr.print_ascii(tty=sys.stdout.isatty()) print("\n") return rv class HTTPSHandler(urllib.request.HTTPSHandler): "Opens SSL HTTPS connections that perform hostname validation." def __init__(self, **kwargs): self.__kwargs = kwargs # Can't use super() because the parent is an old-style class. urllib.request.HTTPSHandler.__init__(self) def __inner(self, host, **kwargs): tmp = self.__kwargs.copy() tmp.update(kwargs) return create_https_connection(host, **tmp) def https_open(self, req): return self.do_open(self.__inner, req) @register() class otptoken_sync(Local): __doc__ = _('Synchronize an OTP token.') header = 'X-IPA-TokenSync-Result' takes_options = ( Str('user', label=_('User ID')), Password('password', label=_('Password'), confirm=False), Password('first_code', label=_('First Code'), confirm=False), Password('second_code', label=_('Second Code'), confirm=False), ) takes_args = ( Str('token?', label=_('Token ID')), ) def forward(self, *args, **kwargs): status = {'result': {self.header: 'unknown'}} # Get the sync URI. segments = list(urllib.parse.urlparse(self.api.env.xmlrpc_uri)) assert segments[0] == 'https' # Ensure encryption. segments[2] = segments[2].replace('/xml', '/session/sync_token') sync_uri = urllib.parse.urlunparse(segments) # Prepare the query. options = {x.name for x in self.takes_options} query = {k: v for k, v in kwargs.items() if k in options} if args and args[0] is not None: # sync_token converts token name to token DN query['token'] = args[0] query = urllib.parse.urlencode(query) query = query.encode('utf-8') # Sync the token. handler = HTTPSHandler( cafile=api.env.tls_ca_cert, tls_version_min=api.env.tls_version_min, tls_version_max=api.env.tls_version_max) rsp = urllib.request.build_opener(handler).open(sync_uri, query) if rsp.getcode() == 200: status['result'][self.header] = rsp.info().get(self.header, 'unknown') rsp.close() if status['result'][self.header] != "ok": msg = {'error': 'Error contacting server!', 'invalid-credentials': 'Invalid Credentials!', }.get(status['result'][self.header], 'Unknown Error!') raise errors.ExecutionError( message=_("Unable to synchronize token: %s") % msg) return status def output_for_cli(self, textui, result, *keys, **options): textui.print_plain('Token synchronized.')
6,395
Python
.py
155
32.335484
82
0.614244
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,110
baseuser.py
freeipa_freeipa/ipaclient/plugins/baseuser.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # import os import logging import subprocess from ipaclient.frontend import MethodOverride from ipalib import errors from ipalib import Bool, Flag, StrEnum from ipalib.text import _ from ipaplatform.paths import paths logger = logging.getLogger(__name__) class baseuser_add_passkey(MethodOverride): takes_options = ( Flag( 'register', cli_name='register', doc=_('Register the passkey'), ), Bool( 'require_user_verification?', cli_name='require_user_verification', doc=_('Require user verification during authentication with ' 'the passkey') ), StrEnum( 'cosetype?', cli_name='cose_type', doc=_('COSE type to use for registration'), values=('es256', 'rs256', 'eddsa'), ), StrEnum( 'credtype?', cli_name="cred_type", doc=_('Credential type'), values=('server-side', 'discoverable'), ), ) def get_args(self): # ipapasskey is not mandatory as it can be built # from the registration step for arg in super(baseuser_add_passkey, self).get_args(): if arg.name == 'ipapasskey': yield arg.clone(required=False, alwaysask=False) else: yield arg.clone() def forward(self, *args, **options): if self.api.env.context == 'cli': # 2 formats are possible for ipa user-add-passkey: # --register [--require-user-verification] [--cose-type ...] # or # passkey:<key id>,<pub key> for option in super(baseuser_add_passkey, self).get_options(): if args and option in options: raise errors.MutuallyExclusiveError( reason=_("cannot specify both %s and " "passkey mapping").format(option)) # if the first format is used, need to register the key first # and obtained the data if 'register' in options: # Ensure the executable exists if not os.path.exists(paths.PASSKEY_CHILD): raise errors.ValidationError(name="register", error=_( "Missing executable %s, use the command with " "LOGIN PASSKEY instead of LOGIN --register") % paths.PASSKEY_CHILD) options.pop('register') cosetype = options.pop('cosetype', None) require_verif = options.pop('require_user_verification', None) credtype = options.pop('credtype', None) cmd = [paths.PASSKEY_CHILD, "--register", "--domain", self.api.env.domain, "--username", args[0]] if cosetype: cmd.append("--type") cmd.append(cosetype) if require_verif is not None: cmd.append("--user-verification") cmd.append(str(require_verif).lower()) if credtype: cmd.append("--cred-type") cmd.append(credtype) logger.debug("Executing command: %s", cmd) passkey = None with subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as subp: for line in subp.stdout: if line.startswith("passkey:"): passkey = line.strip() else: print(line.strip()) if subp.returncode != 0: raise errors.NotFound(reason="Failed to generate passkey") args = (args[0], [passkey]) return super(baseuser_add_passkey, self).forward(*args, **options)
4,095
Python
.py
96
28.322917
78
0.521063
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,111
rpcclient.py
freeipa_freeipa/ipaclient/plugins/rpcclient.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # Rob Crittenden <rcritten@redhat.com> # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2008-2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ RPC client plugins. """ from ipalib import Registry, api register = Registry() if 'in_server' in api.env and api.env.in_server is False: from ipalib.rpc import xmlclient, jsonclient register()(xmlclient) register()(jsonclient) # FIXME: api.register only looks at the class name, so we need to create # trivial subclasses with the desired name. if api.env.rpc_protocol == 'xmlrpc': class rpcclient(xmlclient): """xmlclient renamed to 'rpcclient'""" register()(rpcclient) elif api.env.rpc_protocol == 'jsonrpc': class rpcclient(jsonclient): """jsonclient renamed to 'rpcclient'""" register()(rpcclient) else: raise ValueError('unknown rpc_protocol: %s' % api.env.rpc_protocol)
1,651
Python
.py
41
36.634146
76
0.725282
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,112
vault.py
freeipa_freeipa/ipaclient/plugins/vault.py
# Authors: # Endi S. Dewata <edewata@redhat.com> # # Copyright (C) 2015 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 print_function import base64 import errno import io import json import logging import os import ssl import tempfile from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.padding import PKCS7 from cryptography.hazmat.primitives.serialization import ( load_pem_public_key, load_pem_private_key) from ipaclient.frontend import MethodOverride from ipalib import x509 from ipalib import constants from ipalib.frontend import Local, Method, Object from ipalib.util import classproperty from ipalib import api, errors from ipalib import Bytes, Flag, Str from ipalib.plugable import Registry from ipalib import _ from ipapython import ipautil from ipapython.dnsutil import DNSName logger = logging.getLogger(__name__) def validated_read(argname, filename, mode='r', encoding=None): """Read file and catch errors IOError and UnicodeError (for text files) are turned into a ValidationError """ try: with io.open(filename, mode=mode, encoding=encoding) as f: data = f.read() except IOError as exc: raise errors.ValidationError( name=argname, error=_("Cannot read file '%(filename)s': %(exc)s") % { 'filename': filename, 'exc': exc.args[1] } ) except UnicodeError as exc: raise errors.ValidationError( name=argname, error=_("Cannot decode file '%(filename)s': %(exc)s") % { 'filename': filename, 'exc': exc } ) return data register = Registry() MAX_VAULT_DATA_SIZE = 2**20 # = 1 MB def generate_symmetric_key(password, salt): """ Generates symmetric key from password and salt. """ kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend() ) return base64.b64encode(kdf.derive(password.encode('utf-8'))) def encrypt(data, symmetric_key=None, public_key=None): """ Encrypts data with symmetric key or public key. """ if symmetric_key is not None: if public_key is not None: raise ValueError( "Either a symmetric or a public key is required, not both." ) fernet = Fernet(symmetric_key) return fernet.encrypt(data) elif public_key is not None: public_key_obj = load_pem_public_key( data=public_key, backend=default_backend() ) return public_key_obj.encrypt( data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) else: raise ValueError("Either a symmetric or a public key is required.") def decrypt(data, symmetric_key=None, private_key=None): """ Decrypts data with symmetric key or public key. """ if symmetric_key is not None: if private_key is not None: raise ValueError( "Either a symmetric or a private key is required, not both." ) try: fernet = Fernet(symmetric_key) return fernet.decrypt(data) except InvalidToken: raise errors.AuthenticationError( message=_('Invalid credentials')) elif private_key is not None: try: private_key_obj = load_pem_private_key( data=private_key, password=None, backend=default_backend() ) return private_key_obj.decrypt( data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) except ValueError: raise errors.AuthenticationError( message=_('Invalid credentials')) else: raise ValueError("Either a symmetric or a private key is required.") @register(no_fail=True) class _fake_vault(Object): name = 'vault' @register(no_fail=True) class _fake_vault_add_internal(Method): name = 'vault_add_internal' NO_CLI = True @register() class vault_add(Local): __doc__ = _('Create a new vault.') takes_options = ( Str( 'password?', cli_name='password', doc=_('Vault password'), ), Str( # TODO: use File parameter 'password_file?', cli_name='password_file', doc=_('File containing the vault password'), ), Str( # TODO: use File parameter 'public_key_file?', cli_name='public_key_file', doc=_('File containing the vault public key'), ), ) @classmethod def __NO_CLI_getter(cls): return (api.Command.get_plugin('vault_add_internal') is _fake_vault_add_internal) NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.vault_add_internal.api_version def get_args(self): for arg in self.api.Command.vault_add_internal.args(): yield arg for arg in super(vault_add, self).get_args(): yield arg def get_options(self): for option in self.api.Command.vault_add_internal.options(): if option.name not in ('ipavaultsalt', 'version'): yield option for option in super(vault_add, self).get_options(): yield option def get_output_params(self): for param in self.api.Command.vault_add_internal.output_params(): yield param for param in super(vault_add, self).get_output_params(): yield param def _iter_output(self): return self.api.Command.vault_add_internal.output() def forward(self, *args, **options): vault_type = options.get('ipavaulttype') if vault_type is None: internal_cmd = self.api.Command.vault_add_internal vault_type = internal_cmd.params.ipavaulttype.default password = options.get('password') password_file = options.get('password_file') public_key = options.get('ipavaultpublickey') public_key_file = options.get('public_key_file') # don't send these parameters to server if 'password' in options: del options['password'] if 'password_file' in options: del options['password_file'] if 'public_key_file' in options: del options['public_key_file'] if vault_type != u'symmetric' and (password or password_file): raise errors.MutuallyExclusiveError( reason=_('Password can be specified only for ' 'symmetric vault') ) if vault_type != u'asymmetric' and (public_key or public_key_file): raise errors.MutuallyExclusiveError( reason=_('Public key can be specified only for ' 'asymmetric vault') ) if self.api.env.in_server: backend = self.api.Backend.ldap2 else: backend = self.api.Backend.rpcclient if not backend.isconnected(): backend.connect() if vault_type == u'standard': pass elif vault_type == u'symmetric': # get password if password and password_file: raise errors.MutuallyExclusiveError( reason=_('Password specified multiple times')) elif password: pass elif password_file: password = validated_read('password-file', password_file, encoding='utf-8') password = password.rstrip('\n') else: password = self.api.Backend.textui.prompt_password( 'New password') # generate vault salt options['ipavaultsalt'] = os.urandom(16) elif vault_type == u'asymmetric': # get new vault public key if public_key and public_key_file: raise errors.MutuallyExclusiveError( reason=_('Public key specified multiple times')) elif public_key: pass elif public_key_file: public_key = validated_read('public-key-file', public_key_file, mode='rb') # store vault public key options['ipavaultpublickey'] = public_key else: raise errors.ValidationError( name='ipavaultpublickey', error=_('Missing vault public key')) # validate public key and prevent users from accidentally # sending a private key to the server. try: load_pem_public_key( data=public_key, backend=default_backend() ) except ValueError as e: raise errors.ValidationError( name='ipavaultpublickey', error=_('Invalid or unsupported vault public key: %s') % e, ) # create vault response = self.api.Command.vault_add_internal(*args, **options) # prepare parameters for archival opts = options.copy() if 'description' in opts: del opts['description'] if 'ipavaulttype' in opts: del opts['ipavaulttype'] if vault_type == u'symmetric': opts['password'] = password del opts['ipavaultsalt'] elif vault_type == u'asymmetric': del opts['ipavaultpublickey'] # archive blank data self.api.Command.vault_archive(*args, **opts) return response @register(no_fail=True) class _fake_vault_mod_internal(Method): name = 'vault_mod_internal' NO_CLI = True @register() class vault_mod(Local): __doc__ = _('Modify a vault.') takes_options = ( Flag( 'change_password?', doc=_('Change password'), ), Str( 'old_password?', cli_name='old_password', doc=_('Old vault password'), ), Str( # TODO: use File parameter 'old_password_file?', cli_name='old_password_file', doc=_('File containing the old vault password'), ), Str( 'new_password?', cli_name='new_password', doc=_('New vault password'), ), Str( # TODO: use File parameter 'new_password_file?', cli_name='new_password_file', doc=_('File containing the new vault password'), ), Bytes( 'private_key?', cli_name='private_key', doc=_('Old vault private key'), ), Str( # TODO: use File parameter 'private_key_file?', cli_name='private_key_file', doc=_('File containing the old vault private key'), ), Str( # TODO: use File parameter 'public_key_file?', cli_name='public_key_file', doc=_('File containing the new vault public key'), ), ) @classmethod def __NO_CLI_getter(cls): return (api.Command.get_plugin('vault_mod_internal') is _fake_vault_mod_internal) NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.vault_mod_internal.api_version def get_args(self): for arg in self.api.Command.vault_mod_internal.args(): yield arg for arg in super(vault_mod, self).get_args(): yield arg def get_options(self): for option in self.api.Command.vault_mod_internal.options(): if option.name != 'version': yield option for option in super(vault_mod, self).get_options(): yield option def get_output_params(self): for param in self.api.Command.vault_mod_internal.output_params(): yield param for param in super(vault_mod, self).get_output_params(): yield param def _iter_output(self): return self.api.Command.vault_mod_internal.output() def forward(self, *args, **options): vault_type = options.pop('ipavaulttype', False) salt = options.pop('ipavaultsalt', False) change_password = options.pop('change_password', False) old_password = options.pop('old_password', None) old_password_file = options.pop('old_password_file', None) new_password = options.pop('new_password', None) new_password_file = options.pop('new_password_file', None) old_private_key = options.pop('private_key', None) old_private_key_file = options.pop('private_key_file', None) new_public_key = options.pop('ipavaultpublickey', None) new_public_key_file = options.pop('public_key_file', None) if self.api.env.in_server: backend = self.api.Backend.ldap2 else: backend = self.api.Backend.rpcclient if not backend.isconnected(): backend.connect() # determine the vault type based on parameters specified if vault_type: pass elif change_password or new_password or new_password_file or salt: vault_type = u'symmetric' elif new_public_key or new_public_key_file: vault_type = u'asymmetric' # if vault type is specified, retrieve existing secret if vault_type: opts = options.copy() opts.pop('description', None) opts['password'] = old_password opts['password_file'] = old_password_file opts['private_key'] = old_private_key opts['private_key_file'] = old_private_key_file response = self.api.Command.vault_retrieve(*args, **opts) data = response['result']['data'] opts = options.copy() # if vault type is specified, update crypto attributes if vault_type: opts['ipavaulttype'] = vault_type if vault_type == u'standard': opts['ipavaultsalt'] = None opts['ipavaultpublickey'] = None elif vault_type == u'symmetric': if salt: opts['ipavaultsalt'] = salt else: opts['ipavaultsalt'] = os.urandom(16) opts['ipavaultpublickey'] = None elif vault_type == u'asymmetric': # get new vault public key if new_public_key and new_public_key_file: raise errors.MutuallyExclusiveError( reason=_('New public key specified multiple times')) elif new_public_key: pass elif new_public_key_file: new_public_key = validated_read('public_key_file', new_public_key_file, mode='rb') else: raise errors.ValidationError( name='ipavaultpublickey', error=_('Missing new vault public key')) opts['ipavaultsalt'] = None opts['ipavaultpublickey'] = new_public_key response = self.api.Command.vault_mod_internal(*args, **opts) # if vault type is specified, rearchive existing secret if vault_type: opts = options.copy() opts.pop('description', None) opts['data'] = data opts['password'] = new_password opts['password_file'] = new_password_file opts['override_password'] = True self.api.Command.vault_archive(*args, **opts) return response class _KraConfigCache: """The KRA config cache stores vaultconfig-show result. """ def __init__(self, api): self._dirname = os.path.join(api.env.cache_dir, 'kra-config') def _get_filename(self, domain): basename = DNSName(domain).ToASCII() + '.json' return os.path.join(self._dirname, basename) def load(self, domain): """Load config from cache :param domain: IPA domain :return: dict or None """ filename = self._get_filename(domain) try: try: with open(filename) as f: return json.load(f) except OSError as e: if e.errno != errno.ENOENT: raise except Exception: logger.warning("Failed to load %s", filename, exc_info=True) return None def store(self, domain, response): """Store config in cache :param domain: IPA domain :param config: ipa vaultconfig-show response :return: True if config was stored successfully """ config = response['result'].copy() # store certificate as PEM-encoded ASCII config['transport_cert'] = ssl.DER_cert_to_PEM_cert( config['transport_cert'] ) filename = self._get_filename(domain) try: try: os.makedirs(self._dirname) except EnvironmentError as e: if e.errno != errno.EEXIST: raise with tempfile.NamedTemporaryFile(dir=self._dirname, delete=False, mode='w') as f: try: json.dump(config, f) ipautil.flush_sync(f) f.close() os.rename(f.name, filename) except Exception: os.unlink(f.name) raise except Exception: logger.warning("Failed to save %s", filename, exc_info=True) return False else: return True def remove(self, domain): """Remove a config from cache, ignores errors :param domain: IPA domain :return: True if cert was found and removed """ filename = self._get_filename(domain) try: os.unlink(filename) except EnvironmentError as e: if e.errno != errno.ENOENT: logger.warning("Failed to remove %s", filename, exc_info=True) return False else: return True _kra_config_cache = _KraConfigCache(api) @register(override=True, no_fail=True) class vaultconfig_show(MethodOverride): def forward(self, *args, **options): file = options.get('transport_out') # don't send these parameters to server if 'transport_out' in options: del options['transport_out'] response = super(vaultconfig_show, self).forward(*args, **options) # cache config _kra_config_cache.store(self.api.env.domain, response) if file: with open(file, 'wb') as f: f.write(response['result']['transport_cert']) return response class ModVaultData(Local): def _generate_session_key(self, name): if name not in constants.VAULT_WRAPPING_SUPPORTED_ALGOS: msg = _("{algo} is not a supported vault wrapping algorithm") raise errors.ValidationError(msg.format(algo=repr(name))) if name == constants.VAULT_WRAPPING_AES128_CBC: return algorithms.AES(os.urandom(128 // 8)) elif name == constants.VAULT_WRAPPING_3DES: return algorithms.TripleDES(os.urandom(196 // 8)) else: # unreachable raise ValueError(name) def _get_vaultconfig(self, force_refresh=False): config = None if not force_refresh: config = _kra_config_cache.load(self.api.env.domain) if config is None: # vaultconfig_show also caches data response = self.api.Command.vaultconfig_show() config = response['result'] transport_cert = x509.load_der_x509_certificate( config['transport_cert'] ) else: # cached JSON uses PEM-encoded ASCII string transport_cert = x509.load_pem_x509_certificate( config['transport_cert'].encode('ascii') ) default_algo = config.get('wrapping_default_algorithm') if default_algo is None: # old server wrapping_algo = constants.VAULT_WRAPPING_3DES elif default_algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS: # try to use server default wrapping_algo = default_algo else: # prefer server's sorting order for algo in config['wrapping_supported_algorithms']: if algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS: wrapping_algo = algo break else: raise errors.ValidationError( "No overlapping wrapping algorithm between server and " "client." ) return transport_cert, wrapping_algo def _do_internal(self, algo, transport_cert, raise_unexpected, use_oaep=False, *args, **options): public_key = transport_cert.public_key() # wrap session key with transport certificate # KRA may be configured using either the default PKCS1v15 or RSA-OAEP. # there is no way to query this info using the REST interface. if not use_oaep: # PKCS1v15() causes an OpenSSL exception when FIPS is enabled # if so, we fallback to RSA-OAEP try: wrapped_session_key = public_key.encrypt( algo.key, padding.PKCS1v15() ) except ValueError: wrapped_session_key = public_key.encrypt( algo.key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) else: wrapped_session_key = public_key.encrypt( algo.key, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None ) ) options['session_key'] = wrapped_session_key name = self.name + '_internal' try: # ipalib.errors.NotFound exception can be propagated return self.api.Command[name](*args, **options) except (errors.InternalError, errors.ExecutionError, errors.GenericError): _kra_config_cache.remove(self.api.env.domain) if raise_unexpected and use_oaep: raise return None def internal(self, algo, transport_cert, *args, **options): """ Calls the internal counterpart of the command. """ # try call with cached transport certificate try: result = self._do_internal(algo, transport_cert, False, False, *args, **options) except errors.EncodingError: result = self._do_internal(algo, transport_cert, False, True, *args, **options) if result is not None: return result # retrieve transport certificate (cached by vaultconfig_show) transport_cert = self._get_vaultconfig(force_refresh=True)[0] # call with the retrieved transport certificate result = self._do_internal(algo, transport_cert, True, False, *args, **options) if result is not None: return result # call and use_oaep this time, last attempt return self._do_internal(algo, transport_cert, True, True, *args, **options) @register(no_fail=True) class _fake_vault_archive_internal(Method): name = 'vault_archive_internal' NO_CLI = True @register() class vault_archive(ModVaultData): __doc__ = _('Archive data into a vault.') takes_options = ( Bytes( 'data?', doc=_('Binary data to archive'), ), Str( # TODO: use File parameter 'in?', doc=_('File containing data to archive'), ), Str( 'password?', cli_name='password', doc=_('Vault password'), ), Str( # TODO: use File parameter 'password_file?', cli_name='password_file', doc=_('File containing the vault password'), ), Flag( 'override_password?', doc=_('Override existing password'), ), ) @classmethod def __NO_CLI_getter(cls): return (api.Command.get_plugin('vault_archive_internal') is _fake_vault_archive_internal) NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.vault_archive_internal.api_version def get_args(self): for arg in self.api.Command.vault_archive_internal.args(): yield arg for arg in super(vault_archive, self).get_args(): yield arg def get_options(self): for option in self.api.Command.vault_archive_internal.options(): if option.name not in ('nonce', 'session_key', 'vault_data', 'version', 'wrapping_algo'): yield option for option in super(vault_archive, self).get_options(): yield option def get_output_params(self): for param in self.api.Command.vault_archive_internal.output_params(): yield param for param in super(vault_archive, self).get_output_params(): yield param def _iter_output(self): return self.api.Command.vault_archive_internal.output() def _wrap_data(self, algo, json_vault_data): """Encrypt data with wrapped session key and transport cert :param algo: wrapping algorithm instance :param bytes json_vault_data: dumped vault data :return: """ nonce = os.urandom(algo.block_size // 8) # wrap vault_data with session key padder = PKCS7(algo.block_size).padder() padded_data = padder.update(json_vault_data) padded_data += padder.finalize() cipher = Cipher(algo, modes.CBC(nonce), backend=default_backend()) encryptor = cipher.encryptor() wrapped_vault_data = encryptor.update(padded_data) + encryptor.finalize() return nonce, wrapped_vault_data def forward(self, *args, **options): data = options.get('data') input_file = options.get('in') password = options.get('password') password_file = options.get('password_file') override_password = options.pop('override_password', False) # don't send these parameters to server if 'data' in options: del options['data'] if 'in' in options: del options['in'] if 'password' in options: del options['password'] if 'password_file' in options: del options['password_file'] # get data if data and input_file: raise errors.MutuallyExclusiveError( reason=_('Input data specified multiple times')) elif data: if len(data) > MAX_VAULT_DATA_SIZE: raise errors.ValidationError(name="data", error=_( "Size of data exceeds the limit. Current vault data size " "limit is %(limit)d B") % {'limit': MAX_VAULT_DATA_SIZE}) elif input_file: try: stat = os.stat(input_file) except OSError as exc: raise errors.ValidationError(name="in", error=_( "Cannot read file '%(filename)s': %(exc)s") % {'filename': input_file, 'exc': exc.args[1]}) if stat.st_size > MAX_VAULT_DATA_SIZE: raise errors.ValidationError(name="in", error=_( "Size of data exceeds the limit. Current vault data size " "limit is %(limit)d B") % {'limit': MAX_VAULT_DATA_SIZE}) data = validated_read('in', input_file, mode='rb') else: data = b'' if self.api.env.in_server: backend = self.api.Backend.ldap2 else: backend = self.api.Backend.rpcclient if not backend.isconnected(): backend.connect() # retrieve vault info vault = self.api.Command.vault_show(*args, **options)['result'] vault_type = vault['ipavaulttype'][0] if vault_type == u'standard': encrypted_key = None elif vault_type == u'symmetric': # get password if password and password_file: raise errors.MutuallyExclusiveError( reason=_('Password specified multiple times')) elif password: pass elif password_file: password = validated_read('password-file', password_file, encoding='utf-8') password = password.rstrip('\n') else: if override_password: password = self.api.Backend.textui.prompt_password( 'New password') else: password = self.api.Backend.textui.prompt_password( 'Password', confirm=False) if not override_password: # verify password by retrieving existing data opts = options.copy() opts['password'] = password try: self.api.Command.vault_retrieve(*args, **opts) except errors.NotFound: pass salt = vault['ipavaultsalt'][0] # generate encryption key from vault password encryption_key = generate_symmetric_key(password, salt) # encrypt data with encryption key data = encrypt(data, symmetric_key=encryption_key) encrypted_key = None elif vault_type == u'asymmetric': public_key = vault['ipavaultpublickey'][0] # generate encryption key encryption_key = base64.b64encode(os.urandom(32)) # encrypt data with encryption key data = encrypt(data, symmetric_key=encryption_key) # encrypt encryption key with public key encrypted_key = encrypt(encryption_key, public_key=public_key) else: raise errors.ValidationError( name='vault_type', error=_('Invalid vault type')) vault_data = { 'data': base64.b64encode(data).decode('utf-8') } if encrypted_key: vault_data[u'encrypted_key'] = base64.b64encode(encrypted_key)\ .decode('utf-8') json_vault_data = json.dumps(vault_data).encode('utf-8') # get config transport_cert, wrapping_algo = self._get_vaultconfig() # let options override wrapping algo # For backwards compatibility do not send old legacy wrapping algo # to server. Only send the option when non-3DES is used. wrapping_algo = options.pop('wrapping_algo', wrapping_algo) if wrapping_algo != constants.VAULT_WRAPPING_3DES: options['wrapping_algo'] = wrapping_algo # generate session key algo = self._generate_session_key(wrapping_algo) # wrap vault data nonce, wrapped_vault_data = self._wrap_data(algo, json_vault_data) options.update( nonce=nonce, vault_data=wrapped_vault_data ) return self.internal(algo, transport_cert, *args, **options) @register(no_fail=True) class _fake_vault_retrieve_internal(Method): name = 'vault_retrieve_internal' NO_CLI = True @register() class vault_retrieve(ModVaultData): __doc__ = _('Retrieve a data from a vault.') takes_options = ( Str( 'out?', doc=_('File to store retrieved data'), ), Str( 'password?', cli_name='password', doc=_('Vault password'), ), Str( # TODO: use File parameter 'password_file?', cli_name='password_file', doc=_('File containing the vault password'), ), Bytes( 'private_key?', cli_name='private_key', doc=_('Vault private key'), ), Str( # TODO: use File parameter 'private_key_file?', cli_name='private_key_file', doc=_('File containing the vault private key'), ), ) has_output_params = ( Bytes( 'data', label=_('Data'), ), ) @classmethod def __NO_CLI_getter(cls): return (api.Command.get_plugin('vault_retrieve_internal') is _fake_vault_retrieve_internal) NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.vault_retrieve_internal.api_version def get_args(self): for arg in self.api.Command.vault_retrieve_internal.args(): yield arg for arg in super(vault_retrieve, self).get_args(): yield arg def get_options(self): for option in self.api.Command.vault_retrieve_internal.options(): if option.name not in ('session_key', 'version', 'wrapping_algo'): yield option for option in super(vault_retrieve, self).get_options(): yield option def get_output_params(self): for param in self.api.Command.vault_retrieve_internal.output_params(): yield param for param in super(vault_retrieve, self).get_output_params(): yield param def _iter_output(self): return self.api.Command.vault_retrieve_internal.output() def _unwrap_response(self, algo, nonce, vault_data): cipher = Cipher(algo, modes.CBC(nonce), backend=default_backend()) # decrypt decryptor = cipher.decryptor() padded_data = decryptor.update(vault_data) padded_data += decryptor.finalize() # remove padding unpadder = PKCS7(algo.block_size).unpadder() json_vault_data = unpadder.update(padded_data) json_vault_data += unpadder.finalize() # load JSON return json.loads(json_vault_data.decode('utf-8')) def forward(self, *args, **options): output_file = options.get('out') password = options.get('password') password_file = options.get('password_file') private_key = options.get('private_key') private_key_file = options.get('private_key_file') # don't send these parameters to server if 'out' in options: del options['out'] if 'password' in options: del options['password'] if 'password_file' in options: del options['password_file'] if 'private_key' in options: del options['private_key'] if 'private_key_file' in options: del options['private_key_file'] if self.api.env.in_server: backend = self.api.Backend.ldap2 else: backend = self.api.Backend.rpcclient if not backend.isconnected(): backend.connect() # retrieve vault info vault = self.api.Command.vault_show(*args, **options)['result'] vault_type = vault['ipavaulttype'][0] # get config transport_cert, wrapping_algo = self._get_vaultconfig() # let options override wrapping algo # For backwards compatibility do not send old legacy wrapping algo # to server. Only send the option when non-3DES is used. wrapping_algo = options.pop('wrapping_algo', wrapping_algo) if wrapping_algo != constants.VAULT_WRAPPING_3DES: options['wrapping_algo'] = wrapping_algo # generate session key algo = self._generate_session_key(wrapping_algo) # send retrieval request to server response = self.internal(algo, transport_cert, *args, **options) # unwrap data with session key vault_data = self._unwrap_response( algo, response['result']['nonce'], response['result']['vault_data'] ) del algo data = base64.b64decode(vault_data[u'data'].encode('utf-8')) encrypted_key = None if 'encrypted_key' in vault_data: encrypted_key = base64.b64decode(vault_data[u'encrypted_key'] .encode('utf-8')) if vault_type == u'standard': pass elif vault_type == u'symmetric': salt = vault['ipavaultsalt'][0] # get encryption key from vault password if password and password_file: raise errors.MutuallyExclusiveError( reason=_('Password specified multiple times')) elif password: pass elif password_file: password = validated_read('password-file', password_file, encoding='utf-8') password = password.rstrip('\n') else: password = self.api.Backend.textui.prompt_password( 'Password', confirm=False) # generate encryption key from password encryption_key = generate_symmetric_key(password, salt) # decrypt data with encryption key data = decrypt(data, symmetric_key=encryption_key) elif vault_type == u'asymmetric': # get encryption key with vault private key if private_key and private_key_file: raise errors.MutuallyExclusiveError( reason=_('Private key specified multiple times')) elif private_key: pass elif private_key_file: private_key = validated_read('private-key-file', private_key_file, mode='rb') else: raise errors.ValidationError( name='private_key', error=_('Missing vault private key')) # decrypt encryption key with private key encryption_key = decrypt(encrypted_key, private_key=private_key) # decrypt data with encryption key data = decrypt(data, symmetric_key=encryption_key) else: raise errors.ValidationError( name='vault_type', error=_('Invalid vault type')) if output_file: with open(output_file, 'wb') as f: f.write(data) else: response['result'] = {'data': data} return response
41,222
Python
.py
1,019
28.672228
81
0.568019
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,113
automember.py
freeipa_freeipa/ipaclient/plugins/automember.py
# Authors: # Jr Aquino <jr.aquino@citrix.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib.frontend import Str from ipalib.plugable import Registry from ipalib.text import _ register = Registry() @register(override=True, no_fail=True) class automember_add_condition(MethodOverride): has_output_params = ( Str( 'failed', label=_('Failed to add'), flags=['suppress_empty'], ), ) @register(override=True, no_fail=True) class automember_rebuild(MethodOverride): def interactive_prompt_callback(self, kw): msg = _('IMPORTANT: In case of a high number of users, hosts or ' 'groups, the operation may require high CPU usage.') self.Backend.textui.print_plain(msg)
1,496
Python
.py
38
35.684211
73
0.730028
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,114
passwd.py
freeipa_freeipa/ipaclient/plugins/passwd.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import CommandOverride from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class passwd(CommandOverride): def get_args(self): for arg in super(passwd, self).get_args(): if arg.name == 'current_password': arg = arg.clone(sortorder=-1) yield arg
441
Python
.py
13
28.615385
66
0.698113
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,115
location.py
freeipa_freeipa/ipaclient/plugins/location.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import MethodOverride from ipalib import _ from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class location_show(MethodOverride): def output_for_cli(self, textui, output, *keys, **options): rv = super(location_show, self).output_for_cli( textui, output, *keys, **options) servers = output.get('servers', {}) first = True for details in servers.values(): if first: textui.print_indented(_("Servers details:"), indent=1) first = False else: textui.print_line("") for param in self.api.Command.server_find.output_params(): if param.name in details: textui.print_indented( u"{}: {}".format( param.label, u', '.join(details[param.name])), indent=2) return rv
1,057
Python
.py
27
28.518519
74
0.577299
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,116
permission.py
freeipa_freeipa/ipaclient/plugins/permission.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import MethodOverride from ipalib.plugable import Registry register = Registry() class PermissionMethodOverride(MethodOverride): def get_options(self): for option in super(PermissionMethodOverride, self).get_options(): if option.name == 'ipapermright': option = option.clone(deprecated_cli_aliases={'permissions'}) yield option @register(override=True, no_fail=True) class permission_add(PermissionMethodOverride): pass @register(override=True, no_fail=True) class permission_mod(PermissionMethodOverride): pass @register(override=True, no_fail=True) class permission_find(PermissionMethodOverride): pass
774
Python
.py
21
32.333333
77
0.764468
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,117
host.py
freeipa_freeipa/ipaclient/plugins/host.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib import errors, util from ipalib.plugable import Registry from ipalib import _ from ipalib import x509 register = Registry() @register(override=True, no_fail=True) class host_show(MethodOverride): def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(host_show, self).forward(*keys, **options) if 'usercertificate' in result['result']: certs = (x509.load_der_x509_certificate(c) for c in result['result']['usercertificate']) x509.write_certificate_list(certs, options['out']) result['summary'] = ( _('Certificate(s) stored in file \'%(file)s\'') % dict(file=options['out']) ) return result else: raise errors.NoCertificateError(entry=keys[-1]) else: return super(host_show, self).forward(*keys, **options)
1,876
Python
.py
44
36.068182
71
0.66849
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,118
trust.py
freeipa_freeipa/ipaclient/plugins/trust.py
# Authors: # Alexander Bokovoy <abokovoy@redhat.com> # Martin Kosek <mkosek@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class trust_add(MethodOverride): def interactive_prompt_callback(self, kw): """ Also ensure that realm_admin is prompted for if --admin or --trust-secret is not specified when 'ipa trust-add' is run on the system. Also ensure that realm_passwd is prompted for if --password or --trust-secret is not specified when 'ipa trust-add' is run on the system. """ trust_secret = kw.get('trust_secret') realm_admin = kw.get('realm_admin') realm_passwd = kw.get('realm_passwd') if trust_secret is None: if realm_admin is None: kw['realm_admin'] = self.prompt_param( self.params['realm_admin']) if realm_passwd is None: kw['realm_passwd'] = self.Backend.textui.prompt_password( self.params['realm_passwd'].label, confirm=False)
1,897
Python
.py
43
38.046512
76
0.685807
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,119
hbactest.py
freeipa_freeipa/ipaclient/plugins/hbactest.py
# Authors: # Alexander Bokovoy <abokovoy@redhat.com> # # Copyright (C) 2011 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import CommandOverride from ipalib.plugable import Registry import six if six.PY3: unicode = str register = Registry() @register(override=True, no_fail=True) class hbactest(CommandOverride): def output_for_cli(self, textui, output, *args, **options): """ Command.output_for_cli() uses --all option to decide whether to print detailed output. We use --detail to allow that, thus we need to redefine output_for_cli(). """ # Note that we don't actually use --detail below to see if details need # to be printed as our execute() method will return None for corresponding # entries and None entries will be skipped. self.log_messages(output) for o in self.output: if o == 'value': continue outp = self.output[o] if 'no_display' in outp.flags: continue result = output[o] if isinstance(result, (list, tuple)): textui.print_attribute(unicode(outp.doc), result, '%s: %s', 1, True) elif isinstance(result, unicode): if o == 'summary': textui.print_summary(result) else: textui.print_indented(result) # Propagate integer value for result. It will give proper command line result for scripts return int(not output['value'])
2,210
Python
.py
51
36.529412
97
0.671781
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,120
internal.py
freeipa_freeipa/ipaclient/plugins/internal.py
# Authors: # Pavel Zuna <pzuna@redhat.com> # Adam Young <ayoung@redhat.com> # Endi S. Dewata <edewata@redhat.com> # # Copyright (c) 2010 Red Hat # See file 'copying' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 print_function import json from ipaclient.frontend import CommandOverride from ipalib.util import json_serialize from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class json_metadata(CommandOverride): def output_for_cli(self, textui, result, *args, **options): print(json.dumps(result, default=json_serialize)) @register(override=True, no_fail=True) class i18n_messages(CommandOverride): def output_for_cli(self, textui, result, *args, **options): print(json.dumps(result, default=json_serialize))
1,443
Python
.py
34
40.5
71
0.770164
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,121
__init__.py
freeipa_freeipa/ipaclient/plugins/__init__.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # """ Sub-package containing all client plugins. """
123
Python
.py
6
19.333333
66
0.767241
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,122
certprofile.py
freeipa_freeipa/ipaclient/plugins/certprofile.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import MethodOverride from ipalib import util from ipalib.parameters import File from ipalib.plugable import Registry from ipalib.text import _ register = Registry() @register(override=True, no_fail=True) class certprofile_show(MethodOverride): def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(certprofile_show, self).forward(*keys, **options) if 'out' in options and 'config' in result['result']: with open(options['out'], 'wb') as f: f.write(result['result'].pop('config')) result['summary'] = ( _("Profile configuration stored in file '%(file)s'") % dict(file=options['out']) ) return result @register(override=True, no_fail=True) class certprofile_import(MethodOverride): def get_options(self): for option in super(certprofile_import, self).get_options(): if option.name == 'file': option = option.clone_retype(option.name, File) yield option @register(override=True, no_fail=True) class certprofile_mod(MethodOverride): def get_options(self): for option in super(certprofile_mod, self).get_options(): if option.name == 'file': option = option.clone_retype(option.name, File) yield option
1,499
Python
.py
37
32.864865
72
0.649449
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,123
hbacrule.py
freeipa_freeipa/ipaclient/plugins/hbacrule.py
# Authors: # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib.plugable import Registry register = Registry() #@register() class hbacrule_add_accesstime(MethodOverride): def output_for_cli(self, textui, result, cn, **options): textui.print_name(self.name) textui.print_dashed( 'Added access time "%s" to HBAC rule "%s"' % ( options['accesstime'], cn ) ) #@register() class hbacrule_remove_accesstime(MethodOverride): def output_for_cli(self, textui, result, cn, **options): textui.print_name(self.name) textui.print_dashed( 'Removed access time "%s" from HBAC rule "%s"' % ( options['accesstime'], cn ) )
1,509
Python
.py
39
34.051282
71
0.698087
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,124
service.py
freeipa_freeipa/ipaclient/plugins/service.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # Rob Crittenden <rcritten@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib import errors from ipalib.plugable import Registry from ipalib import x509 from ipalib import _ from ipalib import util register = Registry() @register(override=True, no_fail=True) class service_show(MethodOverride): def forward(self, *keys, **options): if 'out' in options: util.check_writable_file(options['out']) result = super(service_show, self).forward(*keys, **options) if 'usercertificate' in result['result']: certs = (x509.load_der_x509_certificate(c) for c in result['result']['usercertificate']) x509.write_certificate_list(certs, options['out']) result['summary'] = ( _('Certificate(s) stored in file \'%(file)s\'') % dict(file=options['out']) ) return result else: raise errors.NoCertificateError(entry=keys[-1]) else: return super(service_show, self).forward(*keys, **options)
1,948
Python
.py
46
36.021739
72
0.674394
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,125
otptoken_yubikey.py
freeipa_freeipa/ipaclient/plugins/otptoken_yubikey.py
# Authors: # Nathaniel McCallum <npmccallum@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import six from ipalib import _, api, IntEnum from ipalib.errors import NotFound, SkipPluginModule from ipalib.frontend import Command, Method, Object from ipalib.plugable import Registry from ipalib.util import classproperty try: import usb.core import yubico except ImportError: # python-yubico depends on pyusb raise SkipPluginModule(reason=_("python-yubico is not installed.")) if six.PY3: unicode = str __doc__ = _(""" YubiKey Tokens """) + _(""" Manage YubiKey tokens. """) + _(""" This code is an extension to the otptoken plugin and provides support for reading/writing YubiKey tokens directly. """) + _(""" EXAMPLES: """) + _(""" Add a new token: ipa otptoken-add-yubikey --owner=jdoe --desc="My YubiKey" """) register = Registry() topic = 'otp' @register(no_fail=True) class _fake_otptoken(Object): name = 'otptoken' @register(no_fail=True) class _fake_otptoken_add(Method): name = 'otptoken_add' NO_CLI = True @register() class otptoken_add_yubikey(Command): __doc__ = _('Add a new YubiKey OTP token.') takes_options = ( IntEnum('slot?', cli_name='slot', label=_('YubiKey slot'), values=(1, 2), ), ) has_output_params = takes_options @classmethod def __NO_CLI_getter(cls): return api.Command.get_plugin('otptoken_add') is _fake_otptoken_add NO_CLI = classproperty(__NO_CLI_getter) @property def api_version(self): return self.api.Command.otptoken_add.api_version def get_args(self): for arg in self.api.Command.otptoken_add.args(): yield arg for arg in super(otptoken_add_yubikey, self).get_args(): yield arg def get_options(self): for option in self.api.Command.otptoken_add.options(): if option.name not in ('type', 'ipatokenvendor', 'ipatokenmodel', 'ipatokenserial', 'ipatokenotpalgorithm', 'ipatokenhotpcounter', 'ipatokenotpkey', 'ipatokentotpclockoffset', 'ipatokentotptimestep', 'no_qrcode', 'qrcode', 'version'): yield option for option in super(otptoken_add_yubikey, self).get_options(): yield option def get_output_params(self): for param in self.api.Command.otptoken_add.output_params(): yield param for param in super(otptoken_add_yubikey, self).get_output_params(): yield param def _iter_output(self): return self.api.Command.otptoken_add.output() def forward(self, *args, **kwargs): # Open the YubiKey try: yk = yubico.find_yubikey() except usb.core.USBError as e: raise NotFound(reason="No YubiKey found: %s" % e.strerror) except yubico.yubikey.YubiKeyError as e: raise NotFound(reason=e.reason) except ValueError as e: raise NotFound(reason=str(e) + ". Please install 'libyubikey' " "and 'libusb' packages first.") assert yk.version_num() >= (2, 1) # If no slot is specified, find the first free slot. if kwargs.get('slot', None) is None: try: used = yk.status().valid_configs() kwargs['slot'] = sorted({1, 2}.difference(used))[0] except IndexError: raise NotFound(reason=_('No free YubiKey slot!')) # Create the key (NOTE: the length is fixed). key = os.urandom(20) # Write the config. cfg = yk.init_config() cfg.mode_oath_hotp(key, kwargs.get( 'ipatokenotpdigits', self.get_default_of('ipatokenotpdigits') )) cfg.extended_flag('SERIAL_API_VISIBLE', True) yk.write_config(cfg, slot=kwargs['slot']) # Filter the options we want to pass. options = {k: v for k, v in kwargs.items() if k in ( 'version', 'description', 'ipatokenowner', 'ipatokendisabled', 'ipatokennotbefore', 'ipatokennotafter', 'ipatokenotpdigits', )} # Run the command. answer = self.Backend.rpcclient.forward('otptoken_add', *args, type=u'hotp', ipatokenvendor=u'YubiCo', ipatokenmodel=unicode(yk.model), ipatokenserial=unicode(yk.serial()), ipatokenotpalgorithm=u'sha1', ipatokenhotpcounter=0, ipatokenotpkey=key, no_qrcode=True, **options) # Suppress values we don't want to return. for k in (u'uri', u'ipatokenotpkey'): if k in answer.get('result', {}): del answer['result'][k] # Return which slot was used for writing. answer.get('result', {})['slot'] = kwargs['slot'] return answer
6,365
Python
.py
160
28.20625
84
0.557913
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,126
certmap.py
freeipa_freeipa/ipaclient/plugins/certmap.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import MethodOverride from ipalib import errors, x509 from ipalib.parameters import BinaryFile from ipalib.plugable import Registry from ipalib.text import _ register = Registry() @register(override=True, no_fail=True) class certmap_match(MethodOverride): takes_args = ( BinaryFile( 'file?', label=_("Input file"), doc=_("File to load the certificate from"), include='cli', ), ) def get_args(self): for arg in super(certmap_match, self).get_args(): if arg.name != 'certificate' or self.api.env.context != 'cli': yield arg def get_options(self): for arg in super(certmap_match, self).get_args(): if arg.name == 'certificate' and self.api.env.context == 'cli': yield arg.clone(required=False) for option in super(certmap_match, self).get_options(): yield option def forward(self, *args, **options): if self.api.env.context == 'cli': if args and 'certificate' in options: raise errors.MutuallyExclusiveError( reason=_("cannot specify both raw certificate and file")) if args: args = [x509.load_unknown_x509_certificate(args[0])] elif 'certificate' in options: args = [options.pop('certificate')] else: args = [] return super(certmap_match, self).forward(*args, **options)
1,596
Python
.py
41
29.829268
77
0.606335
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,127
cert.py
freeipa_freeipa/ipaclient/plugins/cert.py
# Authors: # Andrew Wnuk <awnuk@redhat.com> # Jason Gerard DeRose <jderose@redhat.com> # John Dennis <jdennis@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import base64 from ipaclient.frontend import MethodOverride from ipalib import errors from ipalib import x509 from ipalib import util from ipalib.parameters import BinaryFile, File, Flag, Str from ipalib.plugable import Registry from ipalib.text import _ register = Registry() class CertRetrieveOverride(MethodOverride): takes_options = ( Str( 'certificate_out?', doc=_('Write certificate (chain if --chain used) to file'), include='cli', cli_metavar='FILE', ), ) def forward(self, *args, **options): filename = None if 'certificate_out' in options: filename = options.pop('certificate_out') result = super(CertRetrieveOverride, self).forward(*args, **options) if filename is not None: try: util.check_writable_file(filename) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) if options.get('chain', False): certs = result['result']['certificate_chain'] else: certs = [base64.b64decode(result['result']['certificate'])] certs = (x509.load_der_x509_certificate(cert) for cert in certs) x509.write_certificate_list(certs, filename) return result @register(override=True, no_fail=True) class cert_request(CertRetrieveOverride): def get_args(self): for arg in super(cert_request, self).get_args(): if arg.name == 'csr': arg = arg.clone_retype(arg.name, File, required=False) yield arg @register(override=True, no_fail=True) class cert_show(CertRetrieveOverride): def get_options(self): for option in super(cert_show, self).get_options(): if option.name == 'out': # skip server-defined --out continue if option.name == 'certificate_out': # add --out as a deprecated alias of --certificate-out option = option.clone_rename( 'out', cli_name='certificate_out', deprecated_cli_aliases={'out'}, ) yield option def forward(self, *args, **options): try: options['certificate_out'] = options.pop('out') except KeyError: pass return super(cert_show, self).forward(*args, **options) @register(override=True, no_fail=True) class cert_remove_hold(MethodOverride): has_output_params = ( Flag('unrevoked', label=_('Unrevoked'), ), Str('error_string', label=_('Error'), ), ) @register(override=True, no_fail=True) class cert_find(MethodOverride): takes_options = ( BinaryFile( 'file?', label=_("Input filename"), doc=_('File to load the certificate from.'), include='cli', ), ) def forward(self, *args, **options): if self.api.env.context == 'cli': if 'certificate' in options and 'file' in options: raise errors.MutuallyExclusiveError( reason=_("cannot specify both raw certificate and file")) if 'certificate' not in options and 'file' in options: options['certificate'] = x509.load_unknown_x509_certificate( options.pop('file')) return super(cert_find, self).forward(*args, **options)
4,463
Python
.py
113
30.548673
77
0.613999
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,128
ca.py
freeipa_freeipa/ipaclient/plugins/ca.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # import base64 from ipaclient.frontend import MethodOverride from ipalib import errors, util, x509, Str from ipalib.plugable import Registry from ipalib.text import _ register = Registry() class WithCertOutArgs(MethodOverride): takes_options = ( Str( 'certificate_out?', doc=_('Write certificate (chain if --chain used) to file'), include='cli', cli_metavar='FILE', ), ) def forward(self, *keys, **options): filename = None if 'certificate_out' in options: filename = options.pop('certificate_out') result = super(WithCertOutArgs, self).forward(*keys, **options) if filename: try: util.check_writable_file(filename) except errors.FileError as e: raise errors.ValidationError(name='certificate-out', error=str(e)) # if result certificate / certificate_chain not present in result, # it means Dogtag did not provide it (probably due to LWCA key # replication lag or failure. The server transmits a warning # message in this case, which the client automatically prints. # So in this section we just ignore it and move on. certs = None if options.get('chain', False): if 'certificate_chain' in result['result']: certs = result['result']['certificate_chain'] else: if 'certificate' in result['result']: certs = [base64.b64decode(result['result']['certificate'])] if certs: x509.write_certificate_list( (x509.load_der_x509_certificate(cert) for cert in certs), filename) return result @register(override=True, no_fail=True) class ca_add(WithCertOutArgs): pass @register(override=True, no_fail=True) class ca_show(WithCertOutArgs): pass
2,088
Python
.py
52
29.788462
79
0.602374
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,129
misc.py
freeipa_freeipa/ipaclient/plugins/misc.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipalib.misc import env as _env from ipalib.misc import plugins as _plugins from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class env(_env): def output_for_cli(self, textui, output, *args, **options): output = dict(output) output.pop('count', None) output.pop('total', None) options['all'] = True return super(env, self).output_for_cli(textui, output, *args, **options) @register(override=True, no_fail=True) class plugins(_plugins): def output_for_cli(self, textui, output, *args, **options): options['all'] = True return super(plugins, self).output_for_cli(textui, output, *args, **options)
886
Python
.py
22
31.636364
68
0.61655
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,130
server.py
freeipa_freeipa/ipaclient/plugins/server.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipaclient.frontend import MethodOverride from ipalib import _, errors from ipalib.plugable import Registry register = Registry() @register(override=True, no_fail=True) class server_del(MethodOverride): def interactive_prompt_callback(self, kw): server_list = kw.get('cn') if not server_list: raise errors.RequirementError(name='cn') self.api.Backend.textui.print_plain( _("Removing %(servers)s from replication topology, " "please wait...") % {'servers': ', '.join(server_list)})
626
Python
.py
16
33.6875
70
0.695868
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,131
idrange.py
freeipa_freeipa/ipaclient/plugins/idrange.py
# Authors: # Sumit Bose <sbose@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 ipaclient.frontend import MethodOverride from ipalib.plugable import Registry from ipalib import api register = Registry() @register(override=True, no_fail=True) class idrange_add(MethodOverride): def interactive_prompt_callback(self, kw): """ Ensure that rid-base is prompted for when dom-sid is specified. Also ensure that secondary-rid-base is prompted for when rid-base is specified and vice versa, in case that dom-sid was not specified. Also ensure that rid-base and secondary-rid-base is prompted for if ipa-adtrust-install has been run on the system. """ # dom-sid can be specified using dom-sid or dom-name options # it can be also set using --setattr or --addattr, in these cases # we will not prompt, but raise an ValidationError later dom_sid_set = any(dom_id in kw for dom_id in ('ipanttrusteddomainname', 'ipanttrusteddomainsid')) rid_base = kw.get('ipabaserid', None) secondary_rid_base = kw.get('ipasecondarybaserid', None) range_type = kw.get('iparangetype', None) def set_from_prompt(param): value = self.prompt_param(self.params[param]) update = {param: value} kw.update(update) if dom_sid_set: # This is a trusted range # Prompt for RID base if domain SID / name was given if rid_base is None and range_type != u'ipa-ad-trust-posix': set_from_prompt('ipabaserid') else: # This is a local range # Find out whether ipa-adtrust-install has been ran adtrust_is_enabled = api.Command['adtrust_is_enabled']()['result'] if adtrust_is_enabled: # If ipa-adtrust-install has been ran, all local ranges # require both RID base and secondary RID base if rid_base is None: set_from_prompt('ipabaserid') if secondary_rid_base is None: set_from_prompt('ipasecondarybaserid') else: # This is a local range on a server with no adtrust support # Prompt for secondary RID base only if RID base was given if rid_base is not None and secondary_rid_base is None: set_from_prompt('ipasecondarybaserid') # Symetrically, prompt for RID base if secondary RID base was # given if rid_base is None and secondary_rid_base is not None: set_from_prompt('ipabaserid')
3,404
Python
.py
69
40.014493
78
0.65098
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,132
topology.py
freeipa_freeipa/ipaclient/plugins/topology.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import six from ipaclient.frontend import MethodOverride from ipalib.plugable import Registry from ipalib import _ if six.PY3: unicode = str register = Registry() @register(override=True, no_fail=True) class topologysuffix_verify(MethodOverride): def output_for_cli(self, textui, output, *args, **options): connect_errors = output['result']['connect_errors'] max_agmts_errors = output['result']['max_agmts_errors'] if not connect_errors and not max_agmts_errors: header = _('Replication topology of suffix "%(suffix)s" ' 'is in order.') textui.print_h1(header % {'suffix': args[0]}) if connect_errors: header = _('Replication topology of suffix "%(suffix)s" contains ' 'errors.') textui.print_h1(header % {'suffix': args[0]}) textui.print_dashed(unicode(_('Topology is disconnected'))) for err in connect_errors: msg = _("Server %(srv)s can't contact servers: %(replicas)s") msg = msg % {'srv': err[0], 'replicas': ', '.join(err[2])} textui.print_indented(msg) if max_agmts_errors: textui.print_dashed(unicode(_('Recommended maximum number of ' 'agreements per replica exceeded'))) textui.print_attribute( unicode(_("Maximum number of agreements per replica")), [output['result']['max_agmts']] ) for err in max_agmts_errors: msg = _('Server "%(srv)s" has %(n)d agreements with servers:') msg = msg % {'srv': err[0], 'n': len(err[1])} textui.print_indented(msg) for replica in err[1]: textui.print_indented(replica, 2) return 0
1,937
Python
.py
42
34.666667
78
0.572187
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,133
dns.py
freeipa_freeipa/ipaclient/plugins/dns.py
# Authors: # Martin Kosek <mkosek@redhat.com> # Pavel Zuna <pzuna@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # 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 print_function import six import copy import re from ipaclient.frontend import MethodOverride from ipalib import errors from ipalib.dns import (get_record_rrtype, has_cli_options, iterate_rrparams_by_parts, part_name_format, record_name_format) from ipalib.frontend import Command from ipalib.parameters import Bool, Str from ipalib.plugable import Registry from ipalib import _, ngettext from ipalib import util from ipapython.dnsutil import DNSName if six.PY3: unicode = str register = Registry() # most used record types, always ask for those in interactive prompt _top_record_types = ('A', 'AAAA', ) _rev_top_record_types = ('PTR', ) _zone_top_record_types = ('NS', 'MX', 'LOC', ) def __get_part_param(rrtype, cmd, part, output_kw, default=None): name = part_name_format % (rrtype.lower(), part.name) label = unicode(cmd.params[name].label) optional = not part.required output_kw[name] = cmd.prompt_param(part, optional=optional, label=label) def prompt_parts(rrtype, cmd, mod_dnsvalue=None): mod_parts = None if mod_dnsvalue is not None: name = record_name_format % unicode(rrtype.lower()) mod_parts = cmd.api.Command.dnsrecord_split_parts( name, mod_dnsvalue)['result'] user_options = {} try: rrobj = cmd.api.Object['dns{}record'.format(rrtype.lower())] except KeyError: return user_options for part_id, part in enumerate(rrobj.params()): name = part_name_format % (rrtype.lower(), part.name) if name not in cmd.params: continue if mod_parts: default = mod_parts[part_id] else: default = None __get_part_param(rrtype, cmd, part, user_options, default) return user_options def prompt_missing_parts(rrtype, cmd, kw, prompt_optional=False): user_options = {} try: rrobj = cmd.api.Object['dns{}record'.format(rrtype.lower())] except KeyError: return user_options for part in rrobj.params(): name = part_name_format % (rrtype.lower(), part.name) if name not in cmd.params: continue if name in kw: continue optional = not part.required if optional and not prompt_optional: continue default = part.get_default(**kw) __get_part_param(rrtype, cmd, part, user_options, default) return user_options class DNSZoneMethodOverride(MethodOverride): def get_options(self): for option in super(DNSZoneMethodOverride, self).get_options(): if option.name == 'idnsallowdynupdate': option = option.clone_retype(option.name, Bool) yield option @register(override=True, no_fail=True) class dnszone_add(DNSZoneMethodOverride): pass @register(override=True, no_fail=True) class dnszone_mod(DNSZoneMethodOverride): pass # Support old servers without dnsrecord_split_parts # Do not add anything new here! @register(no_fail=True) class dnsrecord_split_parts(Command): __doc__ = _('Split DNS record to parts') NO_CLI = True takes_args = ( Str('name'), Str('value'), ) def execute(self, name, value, *args, **options): def split_exactly(count): values = value.split() if len(values) != count: return None return tuple(values) result = () rrtype = get_record_rrtype(name) if rrtype in ('A', 'AAAA', 'CNAME', 'DNAME', 'NS', 'PTR'): result = split_exactly(1) elif rrtype in ('AFSDB', 'KX', 'MX'): result = split_exactly(2) elif rrtype in ('CERT', 'DLV', 'DS', 'SRV', 'TLSA'): result = split_exactly(4) elif rrtype in ('NAPTR'): result = split_exactly(6) elif rrtype in ('A6', 'TXT'): result = (value,) elif rrtype == 'LOC': regex = re.compile( r'(?P<d1>\d{1,2}\s+)' r'(?:(?P<m1>\d{1,2}\s+)' r'(?P<s1>\d{1,2}(?:\.\d{1,3})?\s+)?)?' r'(?P<dir1>[NS])\s+' r'(?P<d2>\d{1,3}\s+)' r'(?:(?P<m2>\d{1,2}\s+)' r'(?P<s2>\d{1,2}(?:\.\d{1,3})?\s+)?)?' r'(?P<dir2>[WE])\s+' r'(?P<alt>-?\d{1,8}(?:\.\d{1,2})?)m?' r'(?:\s+(?P<siz>\d{1,8}(?:\.\d{1,2})?)m?' r'(?:\s+(?P<hp>\d{1,8}(?:\.\d{1,2})?)m?' r'(?:\s+(?P<vp>\d{1,8}(?:\.\d{1,2})?)m?\s*)?)?)?$') m = regex.match(value) if m is not None: result = tuple( x.strip() if x is not None else x for x in m.groups()) elif rrtype == 'SSHFP': values = value.split(None, 2) if len(values) == 3: result = tuple(values) return dict(result=result) @register(override=True, no_fail=True) class dnsrecord_add(MethodOverride): no_option_msg = 'No options to add a specific record provided.\n' \ "Command help may be consulted for all supported record types." def interactive_prompt_callback(self, kw): try: has_cli_options(self, kw, self.no_option_msg) # Some DNS records were entered, do not use full interactive help # We should still ask user for required parts of DNS parts he is # trying to add in the same way we do for standard LDAP parameters # # Do not ask for required parts when any "extra" option is used, # it can be used to fill all required params by itself new_kw = {} for rrparam in iterate_rrparams_by_parts(self, kw, skip_extra=True): rrtype = get_record_rrtype(rrparam.name) user_options = prompt_missing_parts(rrtype, self, kw, prompt_optional=False) new_kw.update(user_options) kw.update(new_kw) return except errors.OptionError: pass try: idnsname = DNSName(kw['idnsname']) except Exception as e: raise errors.ValidationError(name='idnsname', error=unicode(e)) try: zonename = DNSName(kw['dnszoneidnsname']) except Exception as e: raise errors.ValidationError(name='dnszoneidnsname', error=unicode(e)) # check zone type if idnsname.is_empty(): common_types = u', '.join(_zone_top_record_types) elif zonename.is_reverse(): common_types = u', '.join(_rev_top_record_types) else: common_types = u', '.join(_top_record_types) self.Backend.textui.print_plain(_(u'Please choose a type of DNS resource record to be added')) self.Backend.textui.print_plain(_(u'The most common types for this type of zone are: %s\n') %\ common_types) ok = False while not ok: rrtype = self.Backend.textui.prompt(_(u'DNS resource record type')) if rrtype is None: return rrtype = rrtype.upper() try: name = record_name_format % rrtype.lower() param = self.params[name] if 'no_option' in param.flags: raise ValueError() except (KeyError, ValueError): all_types = u', '.join(get_record_rrtype(p.name) for p in self.params() if (get_record_rrtype(p.name) and 'no_option' not in p.flags)) self.Backend.textui.print_plain(_(u'Invalid or unsupported type. Allowed values are: %s') % all_types) continue ok = True user_options = prompt_parts(rrtype, self) kw.update(user_options) @register(override=True, no_fail=True) class dnsrecord_mod(MethodOverride): no_option_msg = 'No options to modify a specific record provided.' def interactive_prompt_callback(self, kw): try: has_cli_options(self, kw, self.no_option_msg, True) except errors.OptionError: pass else: # some record type entered, skip this helper return # get DNS record first so that the NotFound exception is raised # before the helper would start dns_record = self.api.Command['dnsrecord_show'](kw['dnszoneidnsname'], kw['idnsname'])['result'] self.Backend.textui.print_plain(_("No option to modify specific record provided.")) # ask user for records to be removed self.Backend.textui.print_plain(_(u'Current DNS record contents:\n')) record_params = [] for attr in dns_record: try: param = self.params[attr] except KeyError: continue rrtype = get_record_rrtype(param.name) if not rrtype: continue record_params.append((param, rrtype)) rec_type_content = u', '.join(dns_record[param.name]) self.Backend.textui.print_plain(u'%s: %s' % (param.label, rec_type_content)) self.Backend.textui.print_plain(u'') # ask what records to remove for param, rrtype in record_params: rec_values = list(dns_record[param.name]) for rec_value in dns_record[param.name]: rec_values.remove(rec_value) mod_value = self.Backend.textui.prompt_yesno( _("Modify %(name)s '%(value)s'?") % dict(name=param.label, value=rec_value), default=False) if mod_value is True: user_options = prompt_parts(rrtype, self, mod_dnsvalue=rec_value) kw[param.name] = [rec_value] kw.update(user_options) if rec_values: self.Backend.textui.print_plain(ngettext( u'%(count)d %(type)s record skipped. Only one value per DNS record type can be modified at one time.', u'%(count)d %(type)s records skipped. Only one value per DNS record type can be modified at one time.', 0) % dict(count=len(rec_values), type=rrtype)) break @register(override=True, no_fail=True) class dnsrecord_del(MethodOverride): no_option_msg = _('Neither --del-all nor options to delete a specific record provided.\n'\ "Command help may be consulted for all supported record types.") def interactive_prompt_callback(self, kw): if kw.get('del_all', False): return try: has_cli_options(self, kw, self.no_option_msg) except errors.OptionError: pass else: # some record type entered, skip this helper return # get DNS record first so that the NotFound exception is raised # before the helper would start dns_record = self.api.Command['dnsrecord_show'](kw['dnszoneidnsname'], kw['idnsname'])['result'] self.Backend.textui.print_plain(_("No option to delete specific record provided.")) user_del_all = self.Backend.textui.prompt_yesno(_("Delete all?"), default=False) if user_del_all is True: kw['del_all'] = True return # ask user for records to be removed self.Backend.textui.print_plain(_(u'Current DNS record contents:\n')) present_params = [] for attr in dns_record: try: param = self.params[attr] except KeyError: continue if not get_record_rrtype(param.name): continue present_params.append(param) rec_type_content = u', '.join(dns_record[param.name]) self.Backend.textui.print_plain(u'%s: %s' % (param.label, rec_type_content)) self.Backend.textui.print_plain(u'') # ask what records to remove for param in present_params: deleted_values = [] for rec_value in dns_record[param.name]: user_del_value = self.Backend.textui.prompt_yesno( _("Delete %(name)s '%(value)s'?") % dict(name=param.label, value=rec_value), default=False) if user_del_value is True: deleted_values.append(rec_value) if deleted_values: kw[param.name] = tuple(deleted_values) @register(override=True, no_fail=True) class dnsconfig_mod(MethodOverride): def interactive_prompt_callback(self, kw): # show informative message on client side # server cannot send messages asynchronous if kw.get('idnsforwarders', False): self.Backend.textui.print_plain( _("Server will check DNS forwarder(s).")) self.Backend.textui.print_plain( _("This may take some time, please wait ...")) @register(override=True, no_fail=True) class dnsforwardzone_add(MethodOverride): def interactive_prompt_callback(self, kw): if ('idnsforwarders' not in kw and kw.get('idnsforwardpolicy') != u'none'): kw['idnsforwarders'] = self.Backend.textui.prompt( _(u'DNS forwarder')) # show informative message on client side # server cannot send messages asynchronous if kw.get('idnsforwarders', False): self.Backend.textui.print_plain( _("Server will check DNS forwarder(s).")) self.Backend.textui.print_plain( _("This may take some time, please wait ...")) @register(override=True, no_fail=True) class dnsforwardzone_mod(MethodOverride): def interactive_prompt_callback(self, kw): # show informative message on client side # server cannot send messages asynchronous if kw.get('idnsforwarders', False): self.Backend.textui.print_plain( _("Server will check DNS forwarder(s).")) self.Backend.textui.print_plain( _("This may take some time, please wait ...")) @register(override=True, no_fail=True) class dns_update_system_records(MethodOverride): record_groups = ('ipa_records', 'location_records') takes_options = ( Str( 'out?', include='cli', doc=_('file to store DNS records in nsupdate format') ), ) def _standard_output(self, textui, result, labels): """Print output in standard format common across the other plugins""" for key in self.record_groups: if result.get(key): textui.print_indented(u'{}:'.format(labels[key]), indent=1) for val in sorted(result[key]): textui.print_indented(val, indent=2) textui.print_line(u'') def _nsupdate_output_file(self, out_f, result): """Store data in nsupdate format in file""" def parse_rname_rtype(record): """Get rname and rtype from textual representation of record""" l = record.split(' ', 4) return l[0], l[3] labels = { p.name: unicode(p.label) for p in self.output_params() } already_removed = set() for key in self.record_groups: if result.get(key): # process only non-empty out_f.write("; {}\n".format(labels[key])) # comment for val in sorted(result[key]): # delete old first r_name_type = parse_rname_rtype(val) if r_name_type not in already_removed: # remove it only once already_removed.add(r_name_type) out_f.write("update delete {rname} {rtype}\n".format( rname=r_name_type[0], rtype=r_name_type[1] )) # add new out_f.write("update add {}\n".format(val)) out_f.write("send\n\n") def forward(self, *keys, **options): # pop `out` before sending to server as it is only client side option out = options.pop('out', None) if out: util.check_writable_file(out) res = super(dns_update_system_records, self).forward(*keys, **options) if out and 'result' in res: try: with open(out, "w") as f: self._nsupdate_output_file(f, res['result']) except (OSError, IOError) as e: raise errors.FileError(reason=unicode(e)) return res def output_for_cli(self, textui, output, *args, **options): output_super = copy.deepcopy(output) super_res = output_super.get('result', {}) super_res.pop('ipa_records', None) super_res.pop('location_records', None) super(dns_update_system_records, self).output_for_cli( textui, output_super, *args, **options) labels = { p.name: unicode(p.label) for p in self.output_params() } result = output.get('result', {}) self._standard_output(textui, result, labels) return int(not output['value'])
18,526
Python
.py
413
33.358354
131
0.573427
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,134
lite-setup.py
freeipa_freeipa/contrib/lite-setup.py
#!/usr/bin/python3 # # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Configure lite-server environment. See README.md for more details. """ import argparse import os import socket from urllib.request import urlopen DEFAULT_CONF = """\ [global] host = {args.hostname} server = {args.servername} basedn = {args.basedn} realm = {args.realm} domain = {args.domain} xmlrpc_uri = {args.xmlrpc_uri} ldap_uri = ldap://{args.servername} debug = {args.debug} enable_ra = False ra_plugin = dogtag dogtag_version = 10 """ KRB5_CONF = """\ [libdefaults] default_realm = {args.realm} dns_lookup_realm = false dns_lookup_kdc = false rdns = false ticket_lifetime = 24h forwardable = true udp_preference_limit = 0 default_ccache_name = FILE:{args.ccache} [realms] {args.realm} = {{ kdc = {args.kdc} master_kdc = {args.kdc} admin_server = {args.kadmin} default_domain = ipa.example pkinit_anchors = FILE:{args.ca_crt} pkinit_pool = FILE:{args.ca_crt} http_anchors = FILE:{args.ca_crt} }} [domain_realm] .ipa.example = {args.realm} ipa.example = {args.realm} {args.servername} = {args.realm} """ LDAP_CONF = """\ URI ldaps://{args.servername} BASE {args.basedn} TLS_CACERT {args.ca_crt} SASL_MECH GSSAPI SASL_NOCANON on """ IPA_BIN = """\ #!/bin/sh exec python3 -m ipaclient $* """ ACTIVATE = """\ deactivate_ipaenv () {{ export PS1="${{_OLD_IPAENV_PS1}}" export PATH="${{_OLD_IPAENV_PATH}}" unset _OLD_IPAENV_PS1 unset _OLD_IPAENV_PATH unset KRB5_CONFIG unset KRB5CCNAME unset LDAPCONF unset IPA_CONFDIR unset PYTHONPATH unset -f deactivate_ipaenv }} export _OLD_IPAENV_PS1="${{PS1:-}}" export _OLD_IPAENV_PATH="${{PATH:-}}" export PS1="(ipaenv) ${{PS1:-}}" export PATH="{args.dot_ipa}:${{PATH:-}}" export KRB5_CONFIG="{args.krb5_conf}" export KRB5CCNAME="{args.ccache}" {args.tracecomment}export KRB5_TRACE=/dev/stderr export LDAPCONF="{args.ldap_conf}" export IPA_CONFDIR="{args.dot_ipa}" export PYTHONPATH="{args.basedir}" """ MSG = """\ Configured for server '{args.servername}' and realm '{args.realm}'. To activate the IPA test env: source {args.activate} kinit make lite-server To deactivate the IPA test env and to unset the env vars: deactivate_ipaenv The source file configures the env vars: export KRB5_CONFIG="{args.krb5_conf}" export KRB5CCNAME="{args.ccache}" export LDAPCONF="{args.ldap_conf}" export IPA_CONFDIR="{args.dot_ipa}" export PYTHONPATH="{args.basedir}" """ parser = argparse.ArgumentParser() parser.add_argument("servername", help="IPA server name") parser.add_argument("domain", default=None, nargs="?") parser.add_argument( "--kdcproxy", action="store_true", help="Use KRB5 over HTTPS (KDC-Proxy)" ) parser.add_argument( "--debug", action="store_true", help="Enable debug mode for lite-server and KRB5", ) parser.add_argument( "--remote-server", action="store_true", help="Configure client to use a remote server instead of lite-server", ) def main(): args = parser.parse_args() if args.domain is None: args.domain = args.servername.lower().split(".", 1)[1] else: args.domain = args.domain.lower().rstrip(".") args.realm = args.domain.upper() args.hostname = socket.gethostname() args.basedn = ",".join(f"dc={part}" for part in args.domain.split(".")) args.tracecomment = "" if args.debug else "#" if args.kdcproxy: args.kdc = f"https://{args.servername}/KdcProxy" args.kadmin = f"https://{args.servername}/KdcProxy" else: args.kdc = f"{args.servername}:88" args.kadmin = f"{args.servername}:749" if args.remote_server: args.xmlrpc_uri = f"https://{args.servername}/ipa/xml" else: args.xmlrpc_uri = f"http://localhost:8888/ipa/xml" args.basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) args.dot_ipa = os.path.expanduser("~/.ipa") args.default_conf = os.path.join(args.dot_ipa, "default.conf") args.ca_crt = os.path.join(args.dot_ipa, "ca.crt") args.krb5_conf = os.path.join(args.dot_ipa, "krb5.conf") args.ldap_conf = os.path.join(args.dot_ipa, "ldap.conf") args.ccache = os.path.join(args.dot_ipa, "ccache") args.ipa_bin = os.path.join(args.dot_ipa, "ipa") args.activate = os.path.join(args.dot_ipa, "activate.sh") if not os.path.isdir(args.dot_ipa): os.makedirs(args.dot_ipa, mode=0o750) with urlopen(f"http://{args.servername}/ipa/config/ca.crt") as req: ca_data = req.read() with open(args.ca_crt, "wb") as f: f.write(ca_data) with open(args.default_conf, "w") as f: f.write(DEFAULT_CONF.format(args=args)) with open(args.krb5_conf, "w") as f: f.write(KRB5_CONF.format(args=args)) with open(args.ldap_conf, "w") as f: f.write(LDAP_CONF.format(args=args)) with open(args.ipa_bin, "w") as f: f.write(IPA_BIN.format(args=args)) os.fchmod(f.fileno(), 0o755) with open(args.activate, "w") as f: f.write(ACTIVATE.format(args=args)) print(MSG.format(args=args)) if __name__ == "__main__": main()
5,161
Python
.py
165
27.775758
78
0.677199
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,135
copy-schema-to-ca-RHEL6.py
freeipa_freeipa/contrib/copy-schema-to-ca-RHEL6.py
#!/usr/bin/python2 """Copy the IPA schema to the CA directory server instance You need to run this script to prepare a 2.2 or 3.0 IPA master for installation of a 3.1 replica. Once a 3.1 replica is in the domain, every older CA master will emit schema replication errors until this script is run on it. """ # DO NOT TOUCH THIS CODE, IT MUST BE COMPATIBLE WITH RHEL6 # disable pylint because current codebase didn't match RHEL6 code # pylint: disable=all import os import sys import pwd import shutil from hashlib import sha1 from ipapython import ipautil from ipapython.ipa_log_manager import root_logger, standard_logging_setup from ipaserver.install.dsinstance import schema_dirname from ipalib import api # oh dear, this is an old IPA (3.0+) from ipaserver.install.dsinstance import DS_USER from ipaserver.install.cainstance import PKI_USER from ipapython import services # for mod_nss from ipaserver.install.httpinstance import NSS_CONF from ipaserver.install.httpinstance import HTTPInstance from ipaserver.install import installutils from ipapython import sysrestore SERVERID = "PKI-IPA" SCHEMA_FILENAMES = ( "60kerberos.ldif", "60samba.ldif", "60ipaconfig.ldif", "60basev2.ldif", "60basev3.ldif", "60ipadns.ldif", "61kerberos-ipav3.ldif", "65ipacertstore.ldif", "65ipasudo.ldif", "70ipaotp.ldif", "05rfc2247.ldif", ) def _sha1_file(filename): with open(filename, 'rb') as f: return sha1(f.read()).hexdigest() def add_ca_schema(): """Copy IPA schema files into the CA DS instance """ pki_pent = pwd.getpwnam(PKI_USER) ds_pent = pwd.getpwnam(DS_USER) for schema_fname in SCHEMA_FILENAMES: source_fname = os.path.join(ipautil.SHARE_DIR, schema_fname) target_fname = os.path.join(schema_dirname(SERVERID), schema_fname) if not os.path.exists(source_fname): root_logger.debug('File does not exist: %s', source_fname) continue if os.path.exists(target_fname): target_sha1 = _sha1_file(target_fname) source_sha1 = _sha1_file(source_fname) if target_sha1 != source_sha1: target_size = os.stat(target_fname).st_size source_size = os.stat(source_fname).st_size root_logger.info('Target file %s exists but the content is ' 'different', target_fname) root_logger.info('\tTarget file: sha1: %s, size: %s B', target_sha1, target_size) root_logger.info('\tSource file: sha1: %s, size: %s B', source_sha1, source_size) if not ipautil.user_input("Do you want replace %s file?" % target_fname, True): continue else: root_logger.info( 'Target exists, not overwriting: %s', target_fname) continue try: shutil.copyfile(source_fname, target_fname) except IOError as e: root_logger.warning('Could not install %s: %s', target_fname, e) else: root_logger.info('Installed %s', target_fname) os.chmod(target_fname, 0o440) # read access for dirsrv user/group os.chown(target_fname, pki_pent.pw_uid, ds_pent.pw_gid) def restart_pki_ds(): """Restart the CA DS instance to pick up schema changes """ root_logger.info('Restarting CA DS') services.service('dirsrv').restart(SERVERID) # The ipa-3-0 set_directive() has very loose comparision of directive # which would cause multiple NSSCipherSuite to be added so provide # a custom function for it. def set_directive(filename, directive, value, quotes=True, separator=' '): """Set a name/value pair directive in a configuration file. A value of None means to drop the directive. This has only been tested with nss.conf """ valueset = False st = os.stat(filename) fd = open(filename) newfile = [] for line in fd: if line.lstrip().startswith(directive): valueset = True if value is not None: if quotes: newfile.append('%s%s"%s"\n' % (directive, separator, value)) else: newfile.append('%s%s%s\n' % (directive, separator, value)) else: newfile.append(line) fd.close() if not valueset: if value is not None: if quotes: newfile.append('%s%s"%s"\n' % (directive, separator, value)) else: newfile.append('%s%s%s\n' % (directive, separator, value)) fd = open(filename, "w") fd.write("".join(newfile)) fd.close() os.chown(filename, st.st_uid, st.st_gid) # reset perms def update_mod_nss_cipher_suite(): add_ciphers = ['ecdhe_rsa_aes_128_sha', 'ecdhe_rsa_aes_256_sha'] ciphers = installutils.get_directive(NSS_CONF, 'NSSCipherSuite') # Run through once to see if any of the new ciphers are there but # disabled. If they are then enable them. lciphers = ciphers.split(',') new_ciphers = [] for cipher in lciphers: for add in add_ciphers: if cipher.endswith(add): if cipher.startswith('-'): cipher = '+%s' % add new_ciphers.append(cipher) # Run through again and add remaining ciphers as enabled. for add in add_ciphers: if add not in ciphers: new_ciphers.append('+%s' % add) ciphers = ','.join(new_ciphers) set_directive(NSS_CONF, 'NSSCipherSuite', ciphers, False) root_logger.info('Updated Apache cipher list') def restart_http(): root_logger.info('Restarting HTTP') fstore = sysrestore.FileStore('/var/lib/ipa/sysrestore') http = HTTPInstance(fstore) http.restart() def main(): if os.getegid() != 0: sys.exit("Must be root to run this script") standard_logging_setup(verbose=True) # In 3.0, restarting needs access to api.env api.bootstrap_with_global_options(context='server') add_ca_schema() restart_pki_ds() update_mod_nss_cipher_suite() restart_http() root_logger.info('Schema updated successfully') if __name__ == '__main__': main()
6,360
Python
.py
160
31.85625
78
0.636054
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,136
lite-server.py
freeipa_freeipa/contrib/lite-server.py
#!/usr/bin/python3 # # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """In-tree development server See README.md for more details. """ import logging import linecache import os import optparse # pylint: disable=deprecated-module import ssl import sys import time import tracemalloc import warnings # Don't import any ipa modules here so tracemalloc can trace memory usage. import gssapi # pylint: disable=import-error from werkzeug.middleware.profiler import ProfilerMiddleware from werkzeug.exceptions import NotFound from werkzeug.serving import run_simple from werkzeug.utils import redirect, append_slash_redirect from werkzeug.middleware.dispatcher import DispatcherMiddleware from werkzeug.middleware.shared_data import SharedDataMiddleware # pylint: enable=import-error logger = logging.getLogger(os.path.basename(__file__)) BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_FILES = { '/ipa/ui': os.path.join(BASEDIR, 'install/ui'), '/ipa/ui/js': os.path.join(BASEDIR, 'install/ui/src'), '/ipa/ui/js/dojo': os.path.join(BASEDIR, 'install/ui/build/dojo'), '/ipa/ui/fonts': '/usr/share/fonts', } def display_tracemalloc(snapshot, key_type='lineno', limit=10): snapshot = snapshot.filter_traces(( tracemalloc.Filter(False, "<frozen importlib._bootstrap*"), tracemalloc.Filter(False, "<unknown>"), tracemalloc.Filter(False, "*/idna/*.py"), )) top_stats = snapshot.statistics(key_type) print("Top {} lines".format(limit)) for index, stat in enumerate(top_stats[:limit], 1): frame = stat.traceback[0] # replace "/path/to/module/file.py" with "module/file.py" filename = os.sep.join(frame.filename.split(os.sep)[-2:]) print("#{}: {}:{}: {:.1f} KiB".format( index, filename, frame.lineno, stat.size // 1024)) line = linecache.getline(frame.filename, frame.lineno).strip() if line: print(' {}'.format(line)) other = top_stats[limit:] if other: size = sum(stat.size for stat in other) print("{} other: {:.1f} KiB".format(len(other), size // 1024)) total = sum(stat.size for stat in top_stats) current, peak = tracemalloc.get_traced_memory() print("Total allocated size: {:8.1f} KiB".format(total // 1024)) print("Current size: {:8.1f} KiB".format(current // 1024)) print("Peak size: {:8.1f} KiB".format(peak // 1024)) def get_ccname(): """Retrieve and validate Kerberos credential cache Only FILE schema is supported. """ from ipalib import krb_utils ccname = os.environ.get('KRB5CCNAME') if ccname is None: raise ValueError("KRB5CCNAME env var is not set.") scheme, location = krb_utils.krb5_parse_ccache(ccname) if scheme != 'FILE': # MEMORY makes no sense raise ValueError("Unsupported KRB5CCNAME scheme {}".format(scheme)) if not os.path.isfile(location): raise ValueError("KRB5CCNAME file '{}' does not exit".format(location)) return krb_utils.krb5_unparse_ccache(scheme, location) class KRBCheater: """Add KRB5CCNAME and GSS_NAME to WSGI environ """ def __init__(self, app, ccname): self.app = app self.ccname = ccname self.creds = gssapi.Credentials( usage='initiate', store={'ccache': ccname} ) def __call__(self, environ, start_response): environ['KRB5CCNAME'] = self.ccname environ['GSS_NAME'] = self.creds.name return self.app(environ, start_response) class TracemallocMiddleware: def __init__(self, app, api): self.app = app self.api = api def __call__(self, environ, start_response): # We are only interested in request traces. # Each request is handled in a new process. tracemalloc.clear_traces() try: return self.app(environ, start_response) finally: snapshot = tracemalloc.take_snapshot() display_tracemalloc(snapshot, limit=self.api.env.lite_tracemalloc) class StaticFilesMiddleware(SharedDataMiddleware): def get_directory_loader(self, directory): # override directory loader to support index.html def loader(path): if path is not None: path = os.path.join(directory, path) else: path = directory # use index.html for directory views if os.path.isdir(path): path = os.path.join(path, 'index.html') if os.path.isfile(path): return os.path.basename(path), self._opener(path) return None, None return loader def init_api(ccname): """Initialize FreeIPA API from command line """ from ipalib import __file__ as ipalib_file from ipalib import api from ipalib.errors import NetworkError importdir = os.path.dirname(os.path.dirname(os.path.abspath(ipalib_file))) if importdir != BASEDIR: warnings.warn( "ipalib was imported from '{}' instead of '{}'!".format( importdir, BASEDIR), RuntimeWarning ) parser = optparse.OptionParser() parser.add_option( '--dev', help='Run WebUI in development mode', default=True, action='store_false', dest='prod', ) parser.add_option( '--host', help='Listen on address HOST (default 127.0.0.1)', default='127.0.0.1', ) parser.add_option( '--port', help='Listen on PORT (default 8888)', default=8888, type='int', ) parser.add_option( '--enable-profiler', help="Path to WSGI profiler directory or '-' for stderr", default=None, type='str', ) parser.add_option( '--enable-tracemalloc', help="Enable memory tracer", default=0, type='int', ) api.env.in_server = True api.env.startup_traceback = True # workaround for RefererError in rpcserver api.env.in_tree = True # workaround: AttributeError: locked: cannot set ldap2.time_limit to None api.env.mode = 'production' start_time = time.time() # pylint: disable=unused-variable options, args = api.bootstrap_with_global_options(parser, context='lite') api.env._merge( lite_port=options.port, lite_host=options.host, webui_prod=options.prod, lite_profiler=options.enable_profiler, lite_tracemalloc=options.enable_tracemalloc, lite_pem=api.env._join('dot_ipa', 'lite.pem'), ) api.finalize() api_time = time.time() logger.info("API initialized in %0.3f sec", api_time - start_time) # Validate LDAP connection and pre-fetch schema # Pre-fetching makes the lite-server behave similar to mod_wsgi. werkzeug's # multi-process WSGI server forks a new process for each request while # mod_wsgi handles multiple request in a daemon process. Without schema # cache, every lite server request would download the LDAP schema and # distort performance profiles. ldap2 = api.Backend.ldap2 try: if not ldap2.isconnected(): ldap2.connect(ccache=ccname) except NetworkError as e: logger.error("Unable to connect to LDAP: %s", e) logger.error("lite-server needs a working LDAP connect. Did you " "configure ldap_uri in '%s'?", api.env.conf_default) sys.exit(2) else: # prefetch schema assert ldap2.schema # Disconnect main process, each WSGI request handler subprocess will # must have its own connection. ldap2.disconnect() ldap_time = time.time() logger.info("LDAP schema retrieved %0.3f sec", ldap_time - api_time) return api def redirect_ui(app): """Redirects for UI """ def wsgi(environ, start_response): path_info = environ['PATH_INFO'] if path_info in {'/', '/ipa', '/ipa/'}: response = redirect('/ipa/ui/') return response(environ, start_response) # Redirect to append slash to some routes if path_info in {'/ipa/ui', '/ipa/ui/test'}: response = append_slash_redirect(environ) return response(environ, start_response) if path_info == '/favicon.ico': response = redirect('/ipa/ui/favicon.ico') return response(environ, start_response) return app(environ, start_response) return wsgi def main(): # workaround, start tracing IPA imports and API init ASAP if any('--enable-tracemalloc' in arg for arg in sys.argv): tracemalloc.start() try: ccname = get_ccname() except ValueError as e: print("ERROR:", e, file=sys.stderr) print("\nliteserver requires a KRB5CCNAME env var and " "a valid Kerberos TGT:\n", file=sys.stderr) print(" export KRB5CCNAME=~/.ipa/ccache", file=sys.stderr) print(" kinit\n", file=sys.stderr) sys.exit(1) api = init_api(ccname) if api.env.lite_tracemalloc: # print memory snapshot of import + init snapshot = tracemalloc.take_snapshot() display_tracemalloc(snapshot, limit=api.env.lite_tracemalloc) del snapshot # From here on, only trace requests. tracemalloc.clear_traces() if os.path.isfile(api.env.lite_pem): ctx = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH) ctx.load_cert_chain(api.env.lite_pem) else: ctx = None app = NotFound() app = DispatcherMiddleware(app, { '/ipa': KRBCheater(api.Backend.wsgi_dispatch, ccname), }) # only profile api calls if api.env.lite_profiler == '-': print('Profiler enable, stats are written to stderr.') app = ProfilerMiddleware(app, stream=sys.stderr, restrictions=(30,)) elif api.env.lite_profiler: profile_dir = os.path.abspath(api.env.lite_profiler) print("Profiler enable, profiles are stored in '{}'.".format( profile_dir )) app = ProfilerMiddleware(app, profile_dir=profile_dir) if api.env.lite_tracemalloc: app = TracemallocMiddleware(app, api) app = StaticFilesMiddleware(app, STATIC_FILES) app = redirect_ui(app) run_simple( hostname=api.env.lite_host, port=api.env.lite_port, application=app, processes=5, ssl_context=ctx, use_reloader=True, # debugger doesn't work because framework catches all exceptions # use_debugger=not api.env.webui_prod, # use_evalex=not api.env.webui_prod, ) if __name__ == '__main__': main()
10,760
Python
.py
278
31.557554
79
0.644979
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,137
lgtm_container.py
freeipa_freeipa/contrib/lgtm_container.py
#!/usr/bin/python3 """Helper script to test LGTM config $ contrib/lgtm_container.py > Dockerfile $ docker build -t lgtm . """ import os import yaml LGTM_YML = os.path.join(os.path.dirname(__file__), '..', '.lgtm.yml') def main(): with open(LGTM_YML) as f: cfg = yaml.safe_load(f) python = cfg['extraction']['python'] print("""\ FROM ubuntu:bionic RUN apt-get update && \ apt-get install -y {dpkg} python3-venv && \ apt-get clean RUN python3 -m venv /venv RUN /venv/bin/pip install wheel RUN /venv/bin/pip install {pypkg} ADD . /freeipa RUN cd /freeipa && ./autogen.sh --with-ipaplatform=debian """.format( dpkg=' '.join(python['prepare']['packages']), pypkg=' '.join(python['python_setup']['requirements']) )) if __name__ == '__main__': main()
844
Python
.py
28
25.571429
69
0.616337
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,138
setup.py
freeipa_freeipa/ipaplatform/setup.py
# Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """FreeIPA platform FreeIPA is a server for identity, policy, and audit. """ from os.path import abspath, dirname import sys if __name__ == '__main__': # include ../ for ipasetup.py sys.path.append(dirname(dirname(abspath(__file__)))) from ipasetup import ipasetup # noqa: E402 ipasetup( name="ipaplatform", doc=__doc__, package_dir={'ipaplatform': ''}, packages=[ "ipaplatform", "ipaplatform.base", "ipaplatform.debian", "ipaplatform.fedora", "ipaplatform.fedora_container", "ipaplatform.nixos", "ipaplatform.redhat", "ipaplatform.rhel", "ipaplatform.rhel_container", "ipaplatform.suse", "ipaplatform.opencloudos", "ipaplatform.tencentos" ], install_requires=[ "cffi", # "ipalib", # circular dependency "ipapython", "pyasn1", "six", ], )
1,747
Python
.py
51
27.686275
71
0.637707
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,139
constants.py
freeipa_freeipa/ipaplatform/constants.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """IpaMetaImporter replaces this module with ipaplatform.$NAME.constants. """ from __future__ import absolute_import import ipaplatform._importhook ipaplatform._importhook.fixup_module('ipaplatform.constants')
283
Python
.py
8
34.125
73
0.81685
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,140
tasks.py
freeipa_freeipa/ipaplatform/tasks.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """IpaMetaImporter replaces this module with ipaplatform.$NAME.tasks. """ from __future__ import absolute_import import ipaplatform._importhook ipaplatform._importhook.fixup_module('ipaplatform.tasks')
275
Python
.py
8
33.125
69
0.811321
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,141
__init__.py
freeipa_freeipa/ipaplatform/__init__.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ipaplatform package """ NAME = None # initialized by ipaplatform.osinfo
147
Python
.py
6
23.5
66
0.77305
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,142
_importhook.py
freeipa_freeipa/ipaplatform/_importhook.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import importlib import sys from ipaplatform.osinfo import osinfo class IpaMetaImporter: modules = { 'ipaplatform.constants', 'ipaplatform.paths', 'ipaplatform.services', 'ipaplatform.tasks' } def __init__(self, platform): self.platform = platform def find_spec(self, fullname, path=None, target=None): """Meta importer hook""" if fullname in self.modules: module = self.load_module(fullname) return module.__spec__ return None def load_module(self, fullname): """Meta importer hook""" suffix = fullname.split('.', 1)[1] alias = 'ipaplatform.{}.{}'.format(self.platform, suffix) platform_mod = importlib.import_module(alias) base_mod = sys.modules.get(fullname) if base_mod is not None: # module has been imported before, update its __dict__ base_mod.__dict__.update(platform_mod.__dict__) for key in list(base_mod.__dict__): if not hasattr(platform_mod, key): delattr(base_mod, key) else: sys.modules[fullname] = platform_mod return platform_mod metaimporter = IpaMetaImporter(osinfo.platform) sys.meta_path.insert(0, metaimporter) fixup_module = metaimporter.load_module
1,450
Python
.py
40
28.575
66
0.634739
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,143
paths.py
freeipa_freeipa/ipaplatform/paths.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """IpaMetaImporter replaces this module with ipaplatform.$NAME.paths. """ from __future__ import absolute_import import ipaplatform._importhook ipaplatform._importhook.fixup_module('ipaplatform.paths')
275
Python
.py
8
33.125
69
0.811321
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,144
osinfo.py
freeipa_freeipa/ipaplatform/osinfo.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """Distribution information Known Linux distros with /etc/os-release ---------------------------------------- - alpine - centos (like rhel, fedora) - debian - fedora - rhel - ubuntu (like debian) The platform ids for ipaplatform providers are based on: 1) IPAPLATFORM_OVERRIDE env var 2) ipaplatform.override.OVERRIDE value 3) ID field of /etc/os-release (Linux) 4) ID_LIKE fields of /etc/os-release (Linux) """ from __future__ import absolute_import from collections.abc import Mapping import importlib import re import os import sys import warnings import ipaplatform try: from ipaplatform.override import OVERRIDE except ImportError: OVERRIDE = None _osrelease_line = re.compile( u"^(?!#)(?P<name>[a-zA-Z0-9_]+)=" u"(?P<quote>[\"\']?)(?P<value>.+)(?P=quote)$" ) def _parse_osrelease(filename='/etc/os-release'): """Parser for /etc/os-release for Linux distributions https://www.freedesktop.org/software/systemd/man/os-release.html """ release = {} with open(filename) as f: for line in f: mo = _osrelease_line.match(line) if mo is not None: release[mo.group('name')] = mo.group('value') if 'ID_LIKE' in release: release['ID_LIKE'] = tuple( v.strip() for v in release['ID_LIKE'].split(' ') if v.strip() ) else: release["ID_LIKE"] = () # defaults release.setdefault('NAME', 'Linux') release.setdefault('ID', 'linux') release.setdefault('VERSION', '') release.setdefault('VERSION_ID', '') return release class OSInfo(Mapping): __slots__ = ('_info', '_platform', '_container') bsd_family = ( 'freebsd', 'openbsd', 'netbsd', 'dragonfly', 'gnukfreebsd' ) def __init__(self): if sys.platform.startswith('linux'): # Linux, get distribution from /etc/os-release info = self._handle_linux() elif sys.platform == 'win32': info = self._handle_win32() elif sys.platform == 'darwin': info = self._handle_darwin() elif sys.platform.startswith(self.bsd_family): info = self._handle_bsd() else: raise ValueError("Unsupported platform: {}".format(sys.platform)) self._info = info self._platform = None self._container = None def _handle_linux(self): """Detect Linux distribution from /etc/os-release """ try: return _parse_osrelease() except Exception as e: warnings.warn("Failed to read /etc/os-release: {}".format(e)) return { 'NAME': 'Linux', 'ID': 'linux', } def _handle_win32(self): """Windows 32 or 64bit platform """ return { 'NAME': 'Windows', 'ID': 'win32', } def _handle_darwin(self): """Handle macOS / Darwin platform """ return { 'NAME': 'macOS', 'ID': 'macos', } def _handle_bsd(self): """Handle BSD-like platforms """ platform = sys.platform simple = platform.rstrip('0123456789') id_like = [] if simple != platform: id_like.append(simple) return { 'NAME': platform, 'ID': platform, 'ID_LIKE': tuple(id_like), } def __getitem__(self, item): return self._info[item] def __iter__(self): return iter(self._info) def __len__(self): return len(self._info) @property def name(self): """OS name (user) """ return self._info['NAME'] @property def id(self): """Lower case OS identifier """ return self._info['ID'] @property def id_like(self): """Related / similar OS """ return self._info.get('ID_LIKE', ()) @property def version(self): """Version number and name of OS (for user) """ return self._info.get('VERSION') @property def version_number(self): """Version number tuple based on version_id """ version_id = self._info.get('VERSION_ID') if not version_id: return () return tuple(int(p) for p in version_id.split('.')) @property def platform_ids(self): """Ordered tuple of detected platforms (including override) """ platforms = [] # env var first env = os.environ.get("IPAPLATFORM_OVERRIDE") if env: platforms.append(env) # override from package definition if OVERRIDE is not None and OVERRIDE not in platforms: # allow RPM and Debian packages to override platform platforms.append(OVERRIDE) if self.id not in platforms: platforms.append(self.id) platforms.extend(self.id_like) return tuple(platforms) @property def platform(self): if self._platform is not None: return self._platform for platform in self.platform_ids: try: importlib.import_module('ipaplatform.{}'.format(platform)) except ImportError: pass else: self._platform = platform return platform raise ImportError('No ipaplatform available for "{}"'.format( ', '.join(self.platform_ids))) @property def container(self): if self._container is not None: return self._container from ipaplatform.tasks import tasks # pylint: disable=cyclic-import try: self._container = tasks.detect_container() except NotImplementedError: raise NotImplementedError( 'Platform does not support detecting containers') return self._container osinfo = OSInfo() ipaplatform.NAME = osinfo.platform if __name__ == '__main__': import pprint pprint.pprint(dict(osinfo))
6,170
Python
.py
201
22.736318
77
0.571765
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,145
services.py
freeipa_freeipa/ipaplatform/services.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """IpaMetaImporter replaces this module with ipaplatform.$NAME.services. """ from __future__ import absolute_import import ipaplatform._importhook ipaplatform._importhook.fixup_module('ipaplatform.services')
281
Python
.py
8
33.875
72
0.815498
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,146
constants.py
freeipa_freeipa/ipaplatform/suse/constants.py
# # Copyright (C) 2020 FreeIPA Contributors, see COPYING for license # """ This SUSE OS family base platform module exports default platform related constants for the SUSE OS family-based systems. """ # Fallback to default path definitions from ipaplatform.base.constants import BaseConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class SuseConstantsNamespace(BaseConstantsNamespace): HTTPD_USER = User("wwwrun") HTTPD_GROUP = Group("www") # Don't have it yet SSSD_USER = User("root") TLS_HIGH_CIPHERS = None constants = SuseConstantsNamespace()
599
Python
.py
17
32.588235
74
0.761324
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,147
tasks.py
freeipa_freeipa/ipaplatform/suse/tasks.py
# # Copyright (C) 2020 FreeIPA Contributors, see COPYING for license # """ This module contains default SUSE OS family-specific implementations of system tasks. """ import logging from ipaplatform.paths import paths from ipaplatform.base.tasks import BaseTaskNamespace as BaseTask from ipaplatform.redhat.tasks import RedHatTaskNamespace from ipapython import ipautil logger = logging.getLogger(__name__) class SuseTaskNamespace(RedHatTaskNamespace): def restore_context(self, filepath, force=False): pass # FIXME: Implement after libexec move def check_selinux_status(self, restorecon=paths.RESTORECON): pass # FIXME: Implement after libexec move def set_nisdomain(self, nisdomain): nis_variable = "NETCONFIG_NIS_STATIC_DOMAIN" try: with open(paths.SYSCONF_NETWORK, "r") as f: content = [ line for line in f if not line.strip().upper().startswith(nis_variable) ] except IOError: content = [] content.append("{}={}\n".format(nis_variable, nisdomain)) with open(paths.SYSCONF_NETWORK, "w") as f: f.writelines(content) def set_selinux_booleans(self, required_settings, backup_func=None): return False # FIXME: Implement after libexec move def modify_nsswitch_pam_stack(self, sssd, mkhomedir, statestore, sudo=True, subid=False): # pylint: disable=ipa-forbidden-import from ipalib import sysrestore # FixMe: break import cycle # pylint: enable=ipa-forbidden-import fstore = sysrestore.FileStore(paths.IPA_CLIENT_SYSRESTORE) logger.debug('Enabling SSSD in nsswitch') BaseTask.configure_nsswitch_database(self, fstore, 'group', ['sss'], default_value=['compat']) BaseTask.configure_nsswitch_database(self, fstore, 'passwd', ['sss'], default_value=['compat']) BaseTask.configure_nsswitch_database(self, fstore, 'shadow', ['sss'], default_value=['compat']) BaseTask.configure_nsswitch_database(self, fstore, 'netgroup', ['files','sss'], preserve=False, default_value=['files','nis']) BaseTask.configure_nsswitch_database(self, fstore, 'automount', ['files','sss'], preserve=False, default_value=['files','nis']) if sudo: BaseTask.enable_sssd_sudo(self,fstore) logger.debug('Enabling sss in PAM') try: ipautil.run([paths.PAM_CONFIG, '--add', '--sss']) if mkhomedir: logger.debug('Enabling mkhomedir in PAM') try: ipautil.run([paths.PAM_CONFIG, '--add', '--mkhomedir', '--mkhomedir-umask=0077']) except ipautil.CalledProcessError: logger.debug('Failed to configure PAM mkhomedir') return False except ipautil.CalledProcessError: logger.debug('Failed to configure PAM to use SSSD') return False return True def restore_pre_ipa_client_configuration(self, fstore, statestore, was_sssd_installed, was_sssd_configured): if fstore.has_file(paths.NSSWITCH_CONF): logger.debug('Restoring nsswitch from fstore') fstore.restore_file(paths.NSSWITCH_CONF) else: logger.info('nsswitch not restored') return False try: logger.debug('Removing sssd from PAM') ipautil.run([paths.PAM_CONFIG, '--delete', '--mkhomedir']) ipautil.run([paths.PAM_CONFIG, '--delete', '--sss']) logger.debug('Removing sssd from PAM successed') except ipautil.CalledProcessError: logger.debug('Faled to remove sssd from PAM') return False return True def disable_ldap_automount(self, statestore): # SUSE does not use authconfig or authselect return BaseTask.disable_ldap_automount(self, statestore) def modify_pam_to_use_krb5(self, statestore): # SUSE doesn't use authconfig, this is handled by pam-config return True def backup_auth_configuration(self, path): # SUSE doesn't use authconfig, nothing to backup return True def restore_auth_configuration(self, path): # SUSE doesn't use authconfig, nothing to restore return True def migrate_auth_configuration(self, statestore): # SUSE doesn't have authselect return True tasks = SuseTaskNamespace()
4,959
Python
.py
104
34.615385
79
0.591605
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,148
__init__.py
freeipa_freeipa/ipaplatform/suse/__init__.py
# # Copyright (C) 2020 FreeIPA Contributors, see COPYING for license # """ This module contains SUSE specific platform files. """
131
Python
.py
6
20.666667
66
0.774194
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,149
paths.py
freeipa_freeipa/ipaplatform/suse/paths.py
# # Copyright (C) 2020 FreeIPA Contributors, see COPYING for license # """ This SUSE OS family base platform module exports default filesystem paths as common in SUSE OS family-based systems. """ from ipaplatform.base.paths import BasePathNamespace class SusePathNamespace(BasePathNamespace): BIN_HOSTNAMECTL = "/usr/bin/hostnamectl" SYSTEMCTL = "/usr/bin/systemctl" ETC_HTTPD_DIR = "/etc/apache2" HTTPD_ALIAS_DIR = "/etc/apache2/ipa" GSSAPI_SESSION_KEY = "/etc/apache2/ipa/ipasession.key" HTTPD_CONF_D_DIR = "/etc/apache2/conf.d/" HTTPD_IPA_KDCPROXY_CONF_SYMLINK = "/etc/apache2/conf.d/ipa-kdc-proxy.conf" HTTPD_IPA_PKI_PROXY_CONF = "/etc/apache2/conf.d/ipa-pki-proxy.conf" HTTPD_IPA_REWRITE_CONF = "/etc/apache2/conf.d/ipa-rewrite.conf" HTTPD_IPA_CONF = "/etc/apache2/conf.d/ipa.conf" HTTPD_NSS_CONF = "/etc/apache2/conf.d/nss.conf" HTTPD_SSL_CONF = "/etc/apache2/conf.d/ssl.conf" HTTPD_SSL_SITE_CONF = "/etc/apache2/conf.d/ssl.conf" HTTPD_PASSWORD_CONF = "/etc/apache2/ipa/password.conf" NAMED_CUSTOM_CONF = "/etc/named.d/ipa-ext.conf" NAMED_CUSTOM_OPTIONS_CONF = "/etc/named.d/ipa-options-ext.conf" NAMED_LOGGING_OPTIONS_CONF = "/etc/named.d/ipa-logging-ext.conf" NAMED_VAR_DIR = "/var/lib/named" NAMED_MANAGED_KEYS_DIR = "/var/lib/named/dyn" OPENSSL_DIR = "/etc/ssl" OPENSSL_CERTS_DIR = "/etc/ssl/certs" OPENSSL_PRIVATE_DIR = "/etc/ssl/private" IPA_P11_KIT = "/etc/pki/trust/ipa.p11-kit" # Those files are only here to be able to configure them, we copy those in # rpm spec to fillupdir SYSCONFIG_HTTPD = "/etc/sysconfig/apache2" SYSCONFIG_NAMED = "/etc/sysconfig/named-named" SYSCONFIG_NTPD = "/etc/sysconfig/ntp" SYSCONF_NETWORK = "/etc/sysconfig/network/config" SYSTEMD_SYSTEM_HTTPD_D_DIR = "/etc/systemd/system/apache2.service.d/" SYSTEMD_SYSTEM_HTTPD_IPA_CONF = ( "/etc/systemd/system/apache2.service.d/ipa.conf" ) CERTMONGER_COMMAND_TEMPLATE = "/usr/lib/ipa/certmonger/%s" CHROMIUM_BROWSER = "/usr/bin/chromium" BIN_NISDOMAINNAME = "/bin/nisdomainname" BIND_LDAP_DNS_IPA_WORKDIR = "/var/lib/named/dyndb-ldap/ipa/" BIND_LDAP_DNS_ZONE_WORKDIR = "/var/lib/named/dyndb-ldap/ipa/master/" PAM_KRB5_SO = "/lib/security/pam_krb5.so" PAM_KRB5_SO_64 = PAM_KRB5_SO # openSUSE still uses lib for libexec, this will change when we don't # anymore LIBEXEC_CERTMONGER_DIR = "/usr/lib/certmonger" DOGTAG_IPA_CA_RENEW_AGENT_SUBMIT = ( "/usr/lib/certmonger/dogtag-ipa-ca-renew-agent-submit" ) DOGTAG_IPA_RENEW_AGENT_SUBMIT = ( "/usr/lib/certmonger/dogtag-ipa-renew-agent-submit" ) CERTMONGER_DOGTAG_SUBMIT = "/usr/lib/certmonger/dogtag-submit" IPA_SERVER_GUARD = "/usr/lib/certmonger/ipa-server-guard" GENERATE_RNDC_KEY = "/usr/lib/generate-rndc-key.sh" LIBEXEC_IPA_DIR = "/usr/lib/ipa" IPA_DNSKEYSYNCD_REPLICA = "/usr/lib/ipa/ipa-dnskeysync-replica" IPA_DNSKEYSYNCD = "/usr/lib/ipa/ipa-dnskeysyncd" IPA_HTTPD_KDCPROXY = "/usr/lib/ipa/ipa-httpd-kdcproxy" IPA_ODS_EXPORTER = "/usr/lib/ipa/ipa-ods-exporter" IPA_PKI_RETRIEVE_KEY = "/usr/lib/ipa/ipa-pki-retrieve-key" IPA_HTTPD_PASSWD_READER = "/usr/lib/ipa/ipa-httpd-pwdreader" IPA_PKI_WAIT_RUNNING = "/usr/lib/ipa/ipa-pki-wait-running" DNSSEC_KEYFROMLABEL = "/usr/sbin/dnssec-keyfromlabel-pkcs11" VAR_KERBEROS_KRB5KDC_DIR = "/var/lib/kerberos/krb5kdc/" VAR_KRB5KDC_K5_REALM = "/var/lib/kerberos/krb5kdc/.k5." CACERT_PEM = "/var/lib/kerberos/krb5kdc/cacert.pem" KRB5KDC_KADM5_ACL = "/var/lib/kerberos/krb5kdc/kadm5.acl" KRB5KDC_KADM5_KEYTAB = "/var/lib/kerberos/krb5kdc/kadm5.keytab" KRB5KDC_KDC_CONF = "/var/lib/kerberos/krb5kdc/kdc.conf" KDC_CERT = "/var/lib/kerberos/krb5kdc/kdc.crt" KDC_KEY = "/var/lib/kerberos/krb5kdc/kdc.key" NAMED_RUN = "/var/lib/named/data/named.run" IPA_CUSTODIA_HANDLER = "/usr/lib/ipa/custodia" WSGI_PREFIX_DIR = "/run/apache2/wsgi" KDESTROY = "/usr/lib/mit/bin/kdestroy" BIN_KVNO = "/usr/lib/mit/bin/kvno" UPDATE_CA_TRUST = "/usr/sbin/update-ca-certificates" PAM_CONFIG = "/usr/sbin/pam-config" paths = SusePathNamespace()
4,216
Python
.py
86
44.27907
78
0.702473
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,150
services.py
freeipa_freeipa/ipaplatform/suse/services.py
# # Copyright (C) 2020 FreeIPA Contributors, see COPYING for license # import os import logging import time import contextlib from ipaplatform.base import services as base_services from ipapython import ipautil, dogtag from ipaplatform.paths import paths logger = logging.getLogger(__name__) suse_system_units = dict( (x, "%s.service" % x) for x in base_services.wellknownservices ) suse_system_units["httpd"] = "apache2.service" suse_system_units["dirsrv"] = "dirsrv@.service" suse_system_units["pki-tomcatd"] = "pki-tomcatd@pki-tomcat.service" suse_system_units["pki_tomcatd"] = suse_system_units["pki-tomcatd"] suse_system_units["ipa-otpd"] = "ipa-otpd.socket" suse_system_units["ipa-dnskeysyncd"] = "ipa-dnskeysyncd.service" suse_system_units["named-regular"] = "named.service" suse_system_units["named-pkcs11"] = "named.service" suse_system_units["named"] = "named.service" suse_system_units["ods-enforcerd"] = "ods-enforcerd.service" suse_system_units["ods_enforcerd"] = suse_system_units["ods-enforcerd"] suse_system_units["ods-signerd"] = "ods-signerd.service" suse_system_units["ods_signerd"] = suse_system_units["ods-signerd"] class SuseService(base_services.SystemdService): system_units = suse_system_units def __init__(self, service_name, api=None): systemd_name = service_name if service_name in self.system_units: systemd_name = self.system_units[service_name] else: if "." not in service_name: systemd_name = "%s.service" % (service_name) super().__init__(service_name, systemd_name, api) class SuseDirectoryService(SuseService): def is_installed(self, instance_name): file_path = "{}/{}-{}".format( paths.ETC_DIRSRV, "slapd", instance_name ) return os.path.exists(file_path) def restart( self, instance_name="", capture_output=True, wait=True, ldapi=False ): # We need to explicitly enable instances to install proper symlinks as # dirsrv.target.wants/ dependencies. Standard systemd service class # does it on enable() method call. Unfortunately, ipa-server-install # does not do explicit dirsrv.enable() because the service startup is # handled by ipactl. # # If we wouldn't do this, our instances will not be started as systemd # would not have any clue about instances (PKI-IPA and the domain we # serve) at all. Thus, hook into dirsrv.restart(). if instance_name: elements = self.systemd_name.split("@") srv_etc = os.path.join( paths.ETC_SYSTEMD_SYSTEM_DIR, self.systemd_name ) srv_tgt = os.path.join( paths.ETC_SYSTEMD_SYSTEM_DIR, self.SYSTEMD_SRV_TARGET % (elements[0]), ) srv_lnk = os.path.join( srv_tgt, self.service_instance(instance_name) ) if not os.path.exists(srv_etc): self.enable(instance_name) elif not os.path.samefile(srv_etc, srv_lnk): os.unlink(srv_lnk) os.symlink(srv_etc, srv_lnk) with self._wait(instance_name, wait, ldapi) as wait: super().restart( instance_name, capture_output=capture_output, wait=wait ) def start( self, instance_name="", capture_output=True, wait=True, ldapi=False ): with self._wait(instance_name, wait, ldapi) as wait: super().start( instance_name, capture_output=capture_output, wait=wait ) @contextlib.contextmanager def _wait(self, instance_name, wait, ldapi): if ldapi: instance_name = self.service_instance(instance_name) if instance_name.endswith(".service"): instance_name = instance_name[:-8] if instance_name.startswith("dirsrv"): # this is intentional, return the empty string if the instance # name is 'dirsrv' instance_name = instance_name[7:] if not instance_name: ldapi = False if ldapi: yield False socket_name = paths.SLAPD_INSTANCE_SOCKET_TEMPLATE % instance_name ipautil.wait_for_open_socket( socket_name, self.api.env.startup_timeout ) else: yield wait class SuseIPAService(SuseService): # Credits to upstream developer def enable(self, instance_name=""): super().enable(instance_name) self.restart(instance_name) class SuseCAService(SuseService): # Credits to upstream developer def wait_until_running(self): logger.debug("Waiting until the CA is running") timeout = float(self.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) except Exception as e: status = "check interrupted due to error: %s" % e logger.debug("The CA status is: %s", status) if status == "running": break logger.debug("Waiting for CA to start...") time.sleep(1) else: raise RuntimeError("CA did not start in %ss" % timeout) def is_running(self, instance_name="", wait=True): if instance_name: return super().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 # For services which have no SUSE counterpart class SuseNoService(base_services.PlatformService): def start(self): pass def stop(self): pass def restart(self): pass def disable(self): pass def suse_service_class_factory(name, api): if name == "dirsrv": return SuseDirectoryService(name, api) if name == 'domainname': return SuseNoService(name, api) if name == "ipa": return SuseIPAService(name, api) if name in ("pki-tomcatd", "pki_tomcatd"): return SuseCAService(name, api) return SuseService(name, api) class SuseServices(base_services.KnownServices): def service_class_factory(self, name, api=None): return suse_service_class_factory(name, api) # Credits to upstream developer def __init__(self): # pylint: disable=ipa-forbidden-import import ipalib # pylint: enable=ipa-forbidden-import services = dict() for s in base_services.wellknownservices: services[s] = self.service_class_factory(s, ipalib.api) super().__init__(services) timedate_services = base_services.timedate_services service = suse_service_class_factory knownservices = SuseServices()
7,270
Python
.py
176
32.460227
78
0.628664
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,151
constants.py
freeipa_freeipa/ipaplatform/debian/constants.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # ''' This Debian family platform module exports platform dependant constants. ''' # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.base.constants import BaseConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class DebianConstantsNamespace(BaseConstantsNamespace): HTTPD_USER = User("www-data") HTTPD_GROUP = Group("www-data") NAMED_USER = User("bind") NAMED_GROUP = Group("bind") NAMED_DATA_DIR = "" NAMED_ZONE_COMMENT = "//" # ntpd init variable used for daemon options NTPD_OPTS_VAR = "NTPD_OPTS" # quote used for daemon options NTPD_OPTS_QUOTE = "\'" ODS_USER = User("opendnssec") ODS_GROUP = Group("opendnssec") SECURE_NFS_VAR = "NEED_GSSD" constants = DebianConstantsNamespace()
882
Python
.py
25
31.88
74
0.71967
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,152
tasks.py
freeipa_freeipa/ipaplatform/debian/tasks.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ This module contains default Debian-specific implementations of system tasks. """ from __future__ import absolute_import import logging import os import shutil from pathlib import Path from ipaplatform.base.tasks import BaseTaskNamespace from ipaplatform.redhat.tasks import RedHatTaskNamespace from ipaplatform.paths import paths from ipapython import directivesetter from ipapython import ipautil from ipapython.dn import DN logger = logging.getLogger(__name__) class DebianTaskNamespace(RedHatTaskNamespace): @staticmethod def restore_pre_ipa_client_configuration(fstore, statestore, was_sssd_installed, was_sssd_configured): try: ipautil.run(["pam-auth-update", "--package", "--remove", "mkhomedir"]) except ipautil.CalledProcessError: return False return True @staticmethod def set_nisdomain(nisdomain): # Debian doesn't use authconfig, nothing to set return True @staticmethod def modify_nsswitch_pam_stack(sssd, mkhomedir, statestore, sudo=True, subid=False): if mkhomedir: try: ipautil.run(["pam-auth-update", "--package", "--enable", "mkhomedir"]) except ipautil.CalledProcessError: return False return True else: return True @staticmethod def modify_pam_to_use_krb5(statestore): # Debian doesn't use authconfig, this is handled by pam-auth-update return True @staticmethod def backup_auth_configuration(path): # Debian doesn't use authconfig, nothing to backup return True @staticmethod def restore_auth_configuration(path): # Debian doesn't use authconfig, nothing to restore return True def migrate_auth_configuration(self, statestore): # Debian doesn't have authselect return True def configure_httpd_wsgi_conf(self): # Debian doesn't require special mod_wsgi configuration pass def configure_httpd_protocol(self): # TLS 1.3 is not yet supported directivesetter.set_directive(paths.HTTPD_SSL_CONF, 'SSLProtocol', 'TLSv1.2', False) def setup_httpd_logging(self): # Debian handles httpd logging differently pass def configure_pkcs11_modules(self, fstore): # Debian doesn't use p11-kit pass def restore_pkcs11_modules(self, fstore): pass def platform_insert_ca_certs(self, ca_certs): # ca-certificates does not use this file, so it doesn't matter if we # fail to create it. try: self.write_p11kit_certs(paths.IPA_P11_KIT, ca_certs), except Exception: logger.exception("""\ Could not create p11-kit anchor trust file. On Debian this file is not used by ca-certificates and is provided for information only.\ """) return any([ self.write_ca_certificates_dir( paths.CA_CERTIFICATES_DIR, ca_certs ), self.remove_ca_certificates_bundle( paths.CA_CERTIFICATES_BUNDLE_PEM ), ]) def write_ca_certificates_dir(self, directory, ca_certs): # pylint: disable=ipa-forbidden-import from ipalib import x509 # FixMe: break import cycle # pylint: enable=ipa-forbidden-import path = Path(directory) try: path.mkdir(mode=0o755, exist_ok=True) except Exception: logger.error("Could not create %s", path) raise for cert, nickname, trusted, _ext_key_usage in ca_certs: if not trusted: continue # I'm not handling errors here because they have already # been checked by the time we get here subject = DN(cert.subject) issuer = DN(cert.issuer) # Construct the certificate filename using the Subject DN so that # the user can see which CA a particular file is for, and include # the serial number to disambiguate clashes where a subordinate CA # had a new certificate issued. # # Strictly speaking, certificates are uniquely idenified by (Issuer # DN, Serial Number). Do we care about the possibility of a clash # where a subordinate CA had two certificates issued by different # CAs who used the same serial number?) filename = f'{subject.ldap_text()} {cert.serial_number}.crt' # pylint: disable=old-division cert_path = path / filename # pylint: enable=old-division try: f = open(cert_path, 'w') except Exception: logger.error("Could not create %s", cert_path) raise with f: try: os.fchmod(f.fileno(), 0o644) except Exception: logger.error("Could not set mode of %s", cert_path) raise try: f.write(f"""\ This file was created by IPA. Do not edit. Description: {nickname} Subject: {subject.ldap_text()} Issuer: {issuer.ldap_text()} Serial Number (dec): {cert.serial_number} Serial Number (hex): {cert.serial_number:#x} """) pem = cert.public_bytes(x509.Encoding.PEM).decode('ascii') f.write(pem) except Exception: logger.error("Could not write to %s", cert_path) raise return True def platform_remove_ca_certs(self): return any([ self.remove_ca_certificates_dir(paths.CA_CERTIFICATES_DIR), self.remove_ca_certificates_bundle(paths.IPA_P11_KIT), self.remove_ca_certificates_bundle( paths.CA_CERTIFICATES_BUNDLE_PEM ), ]) def remove_ca_certificates_dir(self, directory): path = Path(paths.CA_CERTIFICATES_DIR) if not path.exists(): return False try: shutil.rmtree(path) except Exception: logger.error("Could not remove %s", path) raise return True # Debian doesn't use authselect, so call disable_ldap_automount def disable_ldap_automount(self, statestore): return BaseTaskNamespace.disable_ldap_automount(self, statestore) tasks = DebianTaskNamespace()
6,766
Python
.py
172
28.732558
79
0.6054
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,153
__init__.py
freeipa_freeipa/ipaplatform/debian/__init__.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ This module contains Debian specific platform files. """
133
Python
.py
6
21
66
0.777778
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,154
paths.py
freeipa_freeipa/ipaplatform/debian/paths.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ This Debian base platform module exports default filesystem paths as common in Debian-based systems. """ # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.base.paths import BasePathNamespace import sysconfig MULTIARCH = sysconfig.get_config_var('MULTIARCH') class DebianPathNamespace(BasePathNamespace): BIN_HOSTNAMECTL = "/usr/bin/hostnamectl" ETC_HTTPD_DIR = "/etc/apache2" HTTPD_ALIAS_DIR = "/etc/apache2/ipa" HTTPD_CONF_D_DIR = "/etc/apache2/conf-enabled/" HTTPD_IPA_KDCPROXY_CONF_SYMLINK = "/etc/apache2/conf-enabled/ipa-kdc-proxy.conf" HTTPD_IPA_PKI_PROXY_CONF = "/etc/apache2/conf-enabled/ipa-pki-proxy.conf" HTTPD_IPA_REWRITE_CONF = "/etc/apache2/conf-available/ipa-rewrite.conf" HTTPD_IPA_CONF = "/etc/apache2/conf-enabled/ipa.conf" HTTPD_NSS_CONF = "/etc/apache2/mods-available/nss.conf" HTTPD_SSL_CONF = "/etc/apache2/mods-available/ssl.conf" HTTPD_SSL_SITE_CONF = "/etc/apache2/sites-available/default-ssl.conf" OLD_IPA_KEYTAB = "/etc/apache2/ipa.keytab" HTTPD_PASSWORD_CONF = "/etc/apache2/password.conf" NAMED_CONF = "/etc/bind/named.conf" NAMED_CONF_BAK = "/etc/bind/named.conf.ipa-backup" NAMED_CUSTOM_CONF = "/etc/bind/ipa-ext.conf" NAMED_CUSTOM_OPTIONS_CONF = "/etc/bind/ipa-options-ext.conf" NAMED_LOGGING_OPTIONS_CONF = "/etc/bind/ipa-logging-ext.conf" NAMED_VAR_DIR = "/var/cache/bind" NAMED_KEYTAB = "/etc/bind/krb5.keytab" NAMED_RFC1912_ZONES = "/etc/bind/named.conf.default-zones" NAMED_ROOT_KEY = "/etc/bind/bind.keys" NAMED_MANAGED_KEYS_DIR = "/var/cache/bind/dynamic" CHRONY_CONF = "/etc/chrony/chrony.conf" OPENLDAP_LDAP_CONF = "/etc/ldap/ldap.conf" OPENSSL_DIR = "/usr/lib/ssl" OPENSSL_CERTS_DIR = "/usr/lib/ssl/certs" OPENSSL_PRIVATE_DIR = "/usr/lib/ssl/private" ETC_DEBIAN_VERSION = "/etc/debian_version" # Old versions of freeipa wrote all trusted certificates to a single # file, which is not supported by ca-certificates. CA_CERTIFICATES_BUNDLE_PEM = "/usr/local/share/ca-certificates/ipa-ca.crt" CA_CERTIFICATES_DIR = "/usr/local/share/ca-certificates/ipa-ca" # Debian's p11-kit does not use ipa.p11-kit, so the file is provided # for information only. IPA_P11_KIT = "/usr/local/share/ca-certificates/ipa.p11-kit" ETC_SYSCONFIG_DIR = "/etc/default" SYSCONFIG_AUTOFS = "/etc/default/autofs" SYSCONFIG_DIRSRV = "/etc/default/dirsrv" SYSCONFIG_DIRSRV_INSTANCE = "/etc/default/dirsrv-%s" SYSCONFIG_DIRSRV_SYSTEMD = "/etc/default/dirsrv.systemd" SYSCONFIG_IPA_DNSKEYSYNCD = "/etc/default/ipa-dnskeysyncd" SYSCONFIG_IPA_ODS_EXPORTER = "/etc/default/ipa-ods-exporter" SYSCONFIG_KRB5KDC_DIR = "/etc/default/krb5-kdc" SYSCONFIG_NAMED = "/etc/default/named" SYSCONFIG_NFS = "/etc/default/nfs-common" SYSCONFIG_NTPD = "/etc/default/ntp" SYSCONFIG_ODS = "/etc/default/opendnssec" SYSCONFIG_PKI = "/etc/dogtag/" SYSCONFIG_PKI_TOMCAT = "/etc/default/pki-tomcat" SYSCONFIG_PKI_TOMCAT_PKI_TOMCAT_DIR = "/etc/dogtag/tomcat/pki-tomcat" BIN_TOMCAT = "/usr/share/tomcat9/bin/version.sh" SYSTEMD_SYSTEM_HTTPD_D_DIR = "/etc/systemd/system/apache2.service.d/" SYSTEMD_SYSTEM_HTTPD_IPA_CONF = "/etc/systemd/system/apache2.service.d/ipa.conf" DNSSEC_TRUSTED_KEY = "/etc/bind/trusted-key.key" GSSAPI_SESSION_KEY = "/etc/apache2/ipa/ipasession.key" OLD_KRA_AGENT_PEM = "/etc/apache2/nssdb/kra-agent.pem" SBIN_SERVICE = "/usr/sbin/service" CERTMONGER_COMMAND_TEMPLATE = "/usr/lib/ipa/certmonger/%s" ODS_KSMUTIL = None UPDATE_CA_TRUST = "/usr/sbin/update-ca-certificates" BIND_LDAP_DNS_IPA_WORKDIR = "/var/cache/bind/dyndb-ldap/ipa/" BIND_LDAP_DNS_ZONE_WORKDIR = "/var/cache/bind/dyndb-ldap/ipa/master/" BIND_LDAP_SO = "/usr/lib/{0}/bind/ldap.so".format(MULTIARCH) LIBARCH = "/{0}".format(MULTIARCH) LIBSOFTHSM2_SO = "/usr/lib/{0}/softhsm/libsofthsm2.so".format(MULTIARCH) PAM_KRB5_SO = "/usr/lib/{0}/security/pam_krb5.so".format(MULTIARCH) LIB_SYSTEMD_SYSTEMD_DIR = "/lib/systemd/system/" LIBEXEC_CERTMONGER_DIR = "/usr/lib/certmonger" DOGTAG_IPA_CA_RENEW_AGENT_SUBMIT = "/usr/lib/certmonger/dogtag-ipa-ca-renew-agent-submit" DOGTAG_IPA_RENEW_AGENT_SUBMIT = "/usr/lib/certmonger/dogtag-ipa-renew-agent-submit" CERTMONGER_DOGTAG_SUBMIT = "/usr/lib/certmonger/dogtag-submit" IPA_SERVER_GUARD = "/usr/lib/certmonger/ipa-server-guard" GENERATE_RNDC_KEY = "/bin/true" LIBEXEC_IPA_DIR = "/usr/lib/ipa" IPA_DNSKEYSYNCD_REPLICA = "/usr/lib/ipa/ipa-dnskeysync-replica" IPA_DNSKEYSYNCD = "/usr/lib/ipa/ipa-dnskeysyncd" IPA_HTTPD_KDCPROXY = "/usr/lib/ipa/ipa-httpd-kdcproxy" IPA_ODS_EXPORTER = "/usr/lib/ipa/ipa-ods-exporter" IPA_PKI_RETRIEVE_KEY = "/usr/lib/ipa/ipa-pki-retrieve-key" IPA_HTTPD_PASSWD_READER = "/usr/lib/ipa/ipa-httpd-pwdreader" IPA_PKI_WAIT_RUNNING = "/usr/lib/ipa/ipa-pki-wait-running" HTTPD = "/usr/sbin/apache2ctl" FONTS_DIR = "/usr/share/fonts/truetype" FONTS_OPENSANS_DIR = "/usr/share/fonts/truetype/open-sans" FONTS_FONTAWESOME_DIR = "/usr/share/fonts/truetype/font-awesome" VAR_KERBEROS_KRB5KDC_DIR = "/var/lib/krb5kdc/" VAR_KRB5KDC_K5_REALM = "/var/lib/krb5kdc/.k5." CACERT_PEM = "/var/lib/ipa/certs/cacert.pem" KRB5KDC_KADM5_ACL = "/etc/krb5kdc/kadm5.acl" KRB5KDC_KADM5_KEYTAB = "/etc/krb5kdc/kadm5.keytab" KRB5KDC_KDC_CONF = "/etc/krb5kdc/kdc.conf" KDC_CERT = "/var/lib/ipa/certs/kdc.crt" KDC_KEY = "/var/lib/ipa/certs/kdc.key" VAR_LOG_HTTPD_DIR = "/var/log/apache2" VAR_LOG_HTTPD_ERROR = "/var/log/apache2/error.log" NAMED_RUN = "/var/cache/bind/named.run" VAR_OPENDNSSEC_DIR = "/var/lib/opendnssec" OPENDNSSEC_KASP_DB = "/var/lib/opendnssec/db/kasp.db" IPA_ODS_EXPORTER_CCACHE = "/var/lib/opendnssec/tmp/ipa-ods-exporter.ccache" IPA_CUSTODIA_SOCKET = "/run/apache2/ipa-custodia.sock" IPA_CUSTODIA_AUDIT_LOG = '/var/log/ipa-custodia.audit.log' IPA_CUSTODIA_HANDLER = "/usr/lib/ipa/custodia" IPA_CUSTODIA_CHECK = "/usr/lib/ipa/ipa-custodia-check" WSGI_PREFIX_DIR = "/run/apache2/wsgi" paths = DebianPathNamespace()
6,286
Python
.py
119
48.243697
93
0.711735
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,155
services.py
freeipa_freeipa/ipaplatform/debian/services.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # """ Contains Debian-specific service class implementations. """ from __future__ import absolute_import from ipaplatform.base import services as base_services from ipaplatform.redhat import services as redhat_services from ipapython import ipautil from ipaplatform.paths import paths # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names debian_system_units = redhat_services.redhat_system_units.copy() # For beginning just remap names to add .service # As more services will migrate to systemd, unit names will deviate and # mapping will be kept in this dictionary debian_system_units['chronyd'] = 'chrony.service' debian_system_units['httpd'] = 'apache2.service' debian_system_units['kadmin'] = 'krb5-admin-server.service' debian_system_units['krb5kdc'] = 'krb5-kdc.service' debian_system_units['named-regular'] = 'named.service' debian_system_units['named-pkcs11'] = 'bind9-pkcs11.service' debian_system_units['named'] = debian_system_units['named-regular'] debian_system_units['ntpd'] = 'ntp.service' debian_system_units['pki-tomcatd'] = 'pki-tomcatd.service' debian_system_units['pki_tomcatd'] = debian_system_units['pki-tomcatd'] debian_system_units['ods-enforcerd'] = 'opendnssec-enforcer.service' debian_system_units['ods_enforcerd'] = debian_system_units['ods-enforcerd'] debian_system_units['ods-signerd'] = 'opendnssec-signer.service' debian_system_units['ods_signerd'] = debian_system_units['ods-signerd'] debian_system_units['rpcgssd'] = 'rpc-gssd.service' debian_system_units['rpcidmapd'] = 'nfs-idmapd.service' debian_system_units['smb'] = 'smbd.service' # Service classes that implement Debian family-specific behaviour class DebianService(redhat_services.RedHatService): system_units = debian_system_units class DebianSysvService(base_services.PlatformService): def __wait_for_open_ports(self, instance_name=""): """ If this is a service we need to wait for do so. """ ports = None if instance_name in base_services.wellknownports: ports = base_services.wellknownports[instance_name] else: if self.service_name in base_services.wellknownports: ports = base_services.wellknownports[self.service_name] if ports: ipautil.wait_for_open_ports('localhost', ports, self.api.env.startup_timeout) def stop(self, instance_name='', capture_output=True): ipautil.run([paths.SBIN_SERVICE, self.service_name, "stop", instance_name], capture_output=capture_output) super(DebianSysvService, self).stop(instance_name) def start(self, instance_name='', capture_output=True, wait=True): ipautil.run([paths.SBIN_SERVICE, self.service_name, "start", instance_name], capture_output=capture_output) if wait and self.is_running(instance_name): self.__wait_for_open_ports(instance_name) super(DebianSysvService, self).start(instance_name) def restart(self, instance_name='', capture_output=True, wait=True): ipautil.run([paths.SBIN_SERVICE, self.service_name, "restart", instance_name], capture_output=capture_output) if wait and self.is_running(instance_name): self.__wait_for_open_ports(instance_name) def is_running(self, instance_name="", wait=True): ret = True try: result = ipautil.run([paths.SBIN_SERVICE, self.service_name, "status", instance_name], capture_output=True) sout = result.output if sout.find("NOT running") >= 0: ret = False if sout.find("stop") >= 0: ret = False if sout.find("inactive") >= 0: ret = False except ipautil.CalledProcessError: ret = False return ret def is_installed(self): installed = True try: ipautil.run([paths.SBIN_SERVICE, self.service_name, "status"]) except ipautil.CalledProcessError as e: if e.returncode == 1: # service is not installed or there is other serious issue installed = False return installed @staticmethod def is_enabled(instance_name=""): # Services are always assumed to be enabled when installed return True @staticmethod def enable(): return True @staticmethod def disable(): return True @staticmethod def install(): return True @staticmethod def remove(): return True # For services which have no Debian counterpart class DebianNoService(base_services.PlatformService): @staticmethod def start(): return True @staticmethod def stop(): return True @staticmethod def restart(): return True @staticmethod def disable(): return True # Function that constructs proper Debian-specific server classes for services # of specified name def debian_service_class_factory(name, api=None): if name == 'dirsrv': return redhat_services.RedHatDirectoryService(name, api) if name == 'domainname': return DebianNoService(name, api) if name == 'ipa': return redhat_services.RedHatIPAService(name, api) if name in ('pki-tomcatd', 'pki_tomcatd'): return redhat_services.RedHatCAService(name, api) if name == 'ntpd': return DebianSysvService("ntp", api) return DebianService(name, api) # Magicdict containing DebianService instances. class DebianServices(base_services.KnownServices): 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) # Call base class constructor. This will lock services to read-only super(DebianServices, self).__init__(services) @staticmethod def service_class_factory(name, api=None): return debian_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = base_services.timedate_services service = debian_service_class_factory knownservices = DebianServices()
6,574
Python
.py
153
35.679739
89
0.680651
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,156
constants.py
freeipa_freeipa/ipaplatform/nixos/constants.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # ''' This nixos base platform module exports platform related constants. ''' # Fallback to default constant definitions from __future__ import absolute_import from ipaplatform.redhat.constants import ( RedHatConstantsNamespace, User, Group ) HAS_NFS_CONF = True __all__ = ("constants", "User", "Group") class NixosConstantsNamespace(RedHatConstantsNamespace): MOD_WSGI_PYTHON2 = "modules/mod_wsgi.so" MOD_WSGI_PYTHON3 = "modules/mod_wsgi_python3.so" if HAS_NFS_CONF: SECURE_NFS_VAR = None NAMED_OPENSSL_ENGINE = "pkcs11" constants = NixosConstantsNamespace()
669
Python
.py
20
30.45
67
0.759812
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,157
tasks.py
freeipa_freeipa/ipaplatform/nixos/tasks.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # ''' This module contains default nixos-specific implementations of system tasks. ''' from __future__ import absolute_import from ipapython import directivesetter from ipaplatform.redhat.tasks import RedHatTaskNamespace from ipaplatform.paths import paths class NixosTaskNamespace(RedHatTaskNamespace): def configure_httpd_protocol(self): # On nixos 31 and earlier DEFAULT crypto-policy has TLS 1.0 and 1.1 # enabled. directivesetter.set_directive( paths.HTTPD_SSL_CONF, 'SSLProtocol', "all -SSLv3 -TLSv1 -TLSv1.1", False ) tasks = NixosTaskNamespace()
715
Python
.py
21
28.666667
76
0.723032
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,158
__init__.py
freeipa_freeipa/ipaplatform/nixos/__init__.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # ''' This module contains Nixos specific platform files. ''' import sys import warnings NAME = 'nixos' if sys.version_info < (3, 6): warnings.warn( "Support for Python 2.7 and 3.5 is deprecated. Python version " "3.6 or newer will be required in the next major release.", category=DeprecationWarning )
407
Python
.py
15
23.8
71
0.712082
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,159
paths.py
freeipa_freeipa/ipaplatform/nixos/paths.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # from ipaplatform.fedora.paths import FedoraPathNamespace # Note that we cannot use real paths, as they will be meaningless on nixos, as # nixos stores all its packages in the nixstore under version/hash specific # paths. The `@xxx@` are placeholders which will be instantiated to the correct # nixstore paths at build time, by the nixpkgs freeipa derivation. class NixOSPathNamespace(FedoraPathNamespace): SBIN_IPA_JOIN = "@out@/bin/ipa-join" IPA_GETCERT = "@out@/bin/ipa-getcert" IPA_RMKEYTAB = "@out@/bin/ipa-rmkeytab" IPA_GETKEYTAB = "@out@/bin/ipa-getkeytab" NSUPDATE = "@bind@/bin/nsupdate" BIN_CURL = "@curl@/bin/curl" KINIT = "@kerberos@/bin/kinit" KDESTROY = "@kerberos@/bin/kdestroy" paths = NixOSPathNamespace()
831
Python
.py
18
43.055556
79
0.745973
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,160
services.py
freeipa_freeipa/ipaplatform/nixos/services.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # """ Contains Nixos-specific service class implementations. """ from __future__ import absolute_import from ipaplatform.redhat import services as redhat_services # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names nixos_system_units = redhat_services.redhat_system_units.copy() nixos_system_units['named'] = nixos_system_units['named-regular'] nixos_system_units['named-conflict'] = nixos_system_units['named-pkcs11'] # Service classes that implement nixos-specific behaviour class nixosService(redhat_services.RedHatService): system_units = nixos_system_units # Function that constructs proper nixos-specific server classes for services # of specified name def nixos_service_class_factory(name, api=None): if name in ['named', 'named-conflict']: return nixosService(name, api) return redhat_services.redhat_service_class_factory(name, api) # Magicdict containing nixosService instances. class NixosServices(redhat_services.RedHatServices): def service_class_factory(self, name, api=None): return nixos_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = redhat_services.timedate_services service = nixos_service_class_factory knownservices = NixosServices()
1,404
Python
.py
30
44.2
76
0.800442
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,161
constants.py
freeipa_freeipa/ipaplatform/rhel/constants.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # ''' This RHEL base platform module exports platform related constants. ''' # Fallback to default constant definitions from __future__ import absolute_import from ipaplatform.redhat.constants import ( RedHatConstantsNamespace, User, Group ) from ipaplatform.osinfo import osinfo # RHEL 7 and earlier use /etc/sysconfig/nfs # RHEL 8 uses /etc/nfs.conf HAS_NFS_CONF = osinfo.version_number >= (8,) # RHEL 9 uses pkcs11 as openssl engine HAS_PKCS11_OPENSSL_ENGINE = osinfo.version_number >= (9,) __all__ = ("constants", "User", "Group") class RHELConstantsNamespace(RedHatConstantsNamespace): IPA_ADTRUST_PACKAGE_NAME = "ipa-server-trust-ad" IPA_DNS_PACKAGE_NAME = "ipa-server-dns" if HAS_NFS_CONF: SECURE_NFS_VAR = None if HAS_PKCS11_OPENSSL_ENGINE: NAMED_OPENSSL_ENGINE = "pkcs11" constants = RHELConstantsNamespace()
932
Python
.py
26
33.115385
66
0.754738
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,162
tasks.py
freeipa_freeipa/ipaplatform/rhel/tasks.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains default RHEL-specific implementations of system tasks. ''' from __future__ import absolute_import from ipaplatform.redhat.tasks import RedHatTaskNamespace class RHELTaskNamespace(RedHatTaskNamespace): pass tasks = RHELTaskNamespace()
1,042
Python
.py
26
38.653846
75
0.7889
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,163
__init__.py
freeipa_freeipa/ipaplatform/rhel/__init__.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains RHEL-specific platform files. ''' NAME = 'rhel'
846
Python
.py
22
37.409091
71
0.770352
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,164
paths.py
freeipa_freeipa/ipaplatform/rhel/paths.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This RHEL base platform module exports default filesystem paths as common in RHEL-based systems. ''' # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.redhat.paths import RedHatPathNamespace from ipaplatform.rhel.constants import HAS_NFS_CONF class RHELPathNamespace(RedHatPathNamespace): NAMED_CRYPTO_POLICY_FILE = "/etc/crypto-policies/back-ends/bind.config" if HAS_NFS_CONF: SYSCONFIG_NFS = '/etc/nfs.conf' paths = RHELPathNamespace()
1,282
Python
.py
31
39.612903
75
0.782958
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,165
services.py
freeipa_freeipa/ipaplatform/rhel/services.py
# Authors: # Jan Cholasta <jcholast@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Contains RHEL-specific service class implementations. """ from __future__ import absolute_import from ipaplatform.osinfo import osinfo from ipaplatform.redhat import services as redhat_services # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names rhel_system_units = redhat_services.redhat_system_units.copy() if osinfo.version_number >= (9,): rhel_system_units['named'] = rhel_system_units['named-regular'] rhel_system_units['named-conflict'] = rhel_system_units['named-pkcs11'] # Service classes that implement RHEL-specific behaviour class RHELService(redhat_services.RedHatService): system_units = rhel_system_units # Function that constructs proper RHEL-specific server classes for services # of specified name def rhel_service_class_factory(name, api=None): if name in ['named', 'named-conflict']: return RHELService(name, api) return redhat_services.redhat_service_class_factory(name, api) # Magicdict containing RHELService instances. class RHELServices(redhat_services.RedHatServices): def service_class_factory(self, name, api=None): return rhel_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = redhat_services.timedate_services service = rhel_service_class_factory knownservices = RHELServices()
2,172
Python
.py
48
43.083333
75
0.785104
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,166
constants.py
freeipa_freeipa/ipaplatform/fedora/constants.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # ''' This Fedora base platform module exports platform related constants. ''' # Fallback to default constant definitions from __future__ import absolute_import from ipaplatform.redhat.constants import ( RedHatConstantsNamespace, User, Group ) from ipaplatform.osinfo import osinfo # Fedora 28 and earlier use /etc/sysconfig/nfs # Fedora 30 and later use /etc/nfs.conf # Fedora 29 has both HAS_NFS_CONF = osinfo.version_number >= (30,) __all__ = ("constants", "User", "Group") class FedoraConstantsNamespace(RedHatConstantsNamespace): # Fedora allows installation of Python 2 and 3 mod_wsgi, but the modules # can't coexist. For Apache to load correct module. MOD_WSGI_PYTHON2 = "modules/mod_wsgi.so" MOD_WSGI_PYTHON3 = "modules/mod_wsgi_python3.so" if HAS_NFS_CONF: SECURE_NFS_VAR = None NAMED_OPENSSL_ENGINE = "pkcs11" constants = FedoraConstantsNamespace()
976
Python
.py
26
34.730769
76
0.759318
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,167
tasks.py
freeipa_freeipa/ipaplatform/fedora/tasks.py
# Authors: Simo Sorce <ssorce@redhat.com> # Alexander Bokovoy <abokovoy@redhat.com> # Martin Kosek <mkosek@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2007-2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains default Fedora-specific implementations of system tasks. ''' from __future__ import absolute_import from ipapython import directivesetter from ipaplatform.redhat.tasks import RedHatTaskNamespace from ipaplatform.paths import paths class FedoraTaskNamespace(RedHatTaskNamespace): def configure_httpd_protocol(self): # On Fedora 31 and earlier DEFAULT crypto-policy has TLS 1.0 and 1.1 # enabled. directivesetter.set_directive( paths.HTTPD_SSL_CONF, 'SSLProtocol', "all -SSLv3 -TLSv1 -TLSv1.1", False ) tasks = FedoraTaskNamespace()
1,555
Python
.py
38
37.5
77
0.738237
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,168
__init__.py
freeipa_freeipa/ipaplatform/fedora/__init__.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains Fedora specific platform files. ''' import sys import warnings NAME = 'fedora' if sys.version_info < (3, 6): warnings.warn( "Support for Python 2.7 and 3.5 is deprecated. Python version " "3.6 or newer will be required in the next major release.", category=DeprecationWarning )
1,107
Python
.py
30
34.733333
71
0.750466
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,169
paths.py
freeipa_freeipa/ipaplatform/fedora/paths.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This Fedora base platform module exports default filesystem paths as common in Fedora-based systems. ''' # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.redhat.paths import RedHatPathNamespace from ipaplatform.fedora.constants import HAS_NFS_CONF class FedoraPathNamespace(RedHatPathNamespace): HTTPD_IPA_WSGI_MODULES_CONF = ( "/etc/httpd/conf.modules.d/02-ipa-wsgi.conf" ) NAMED_CRYPTO_POLICY_FILE = "/etc/crypto-policies/back-ends/bind.config" if HAS_NFS_CONF: SYSCONFIG_NFS = '/etc/nfs.conf' paths = FedoraPathNamespace()
1,384
Python
.py
34
38.558824
75
0.772152
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,170
services.py
freeipa_freeipa/ipaplatform/fedora/services.py
# Author: Alexander Bokovoy <abokovoy@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2011-2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ Contains Fedora-specific service class implementations. """ from __future__ import absolute_import from ipaplatform.redhat import services as redhat_services # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names fedora_system_units = redhat_services.redhat_system_units.copy() fedora_system_units['named'] = fedora_system_units['named-regular'] fedora_system_units['named-conflict'] = fedora_system_units['named-pkcs11'] # Service classes that implement Fedora-specific behaviour class FedoraService(redhat_services.RedHatService): system_units = fedora_system_units # Function that constructs proper Fedora-specific server classes for services # of specified name def fedora_service_class_factory(name, api=None): if name in ['named', 'named-conflict']: return FedoraService(name, api) return redhat_services.redhat_service_class_factory(name, api) # Magicdict containing FedoraService instances. class FedoraServices(redhat_services.RedHatServices): def service_class_factory(self, name, api=None): return fedora_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = redhat_services.timedate_services service = fedora_service_class_factory knownservices = FedoraServices()
2,174
Python
.py
46
45.217391
77
0.789299
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,171
constants.py
freeipa_freeipa/ipaplatform/tencentos/constants.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This TencentOS base platform module exports platform related constants. """ # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.redhat.constants import RedHatConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class TencentOSConstantsNamespace(RedHatConstantsNamespace): SECURE_NFS_VAR = None NAMED_OPENSSL_ENGINE = "pkcs11" constants = TencentOSConstantsNamespace()
523
Python
.py
14
35.142857
78
0.798
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,172
tasks.py
freeipa_freeipa/ipaplatform/tencentos/tasks.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This module contains default TencentOS-specific implementations of system tasks. """ from __future__ import absolute_import from ipaplatform.redhat.tasks import RedHatTaskNamespace class TencentOSTaskNamespace(RedHatTaskNamespace): pass tasks = TencentOSTaskNamespace()
356
Python
.py
11
30.363636
80
0.831361
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,173
__init__.py
freeipa_freeipa/ipaplatform/tencentos/__init__.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This module contains TencentOS specific platform files. """ NAME = "tencentos"
157
Python
.py
7
21
66
0.77551
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,174
paths.py
freeipa_freeipa/ipaplatform/tencentos/paths.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This TencentOS base platform module exports default filesystem paths as common in TencentOS-based systems. """ from __future__ import absolute_import from ipaplatform.redhat.paths import RedHatPathNamespace class TencentOSPathNamespace(RedHatPathNamespace): NAMED_CRYPTO_POLICY_FILE = "/etc/crypto-policies/back-ends/bind.config" SYSCONFIG_NFS = "/etc/nfs.conf" paths = TencentOSPathNamespace()
485
Python
.py
13
35.153846
75
0.808602
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,175
services.py
freeipa_freeipa/ipaplatform/tencentos/services.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ Contains TencentOS specific service class implementations. """ from __future__ import absolute_import from ipaplatform.redhat import services as redhat_services # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names tencentos_system_units = redhat_services.redhat_system_units.copy() tencentos_system_units["named"] = tencentos_system_units["named-regular"] tencentos_system_units["named-conflict"] = \ tencentos_system_units["named-pkcs11"] # Service classes that implement TencentOS-specific behaviour class TencentOSService(redhat_services.RedHatService): system_units = tencentos_system_units # Function that constructs proper TencentOS-specific server classes for # services of specified name def tencentos_service_class_factory(name, api=None): if name in ["named", "named-conflict"]: return TencentOSService(name, api) return redhat_services.redhat_service_class_factory(name, api) # Magicdict containing TencentOSService instances. class TencentOSServices(redhat_services.RedHatServices): def service_class_factory(self, name, api=None): return tencentos_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = redhat_services.timedate_services service = tencentos_service_class_factory knownservices = TencentOSServices()
1,482
Python
.py
31
45
74
0.807128
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,176
constants.py
freeipa_freeipa/ipaplatform/base/constants.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # ''' This base platform module exports platform dependant constants. ''' import grp import os import pwd import sys class _Entity(str): __slots__ = ("_entity", ) def __new__(cls, name): # if 'name' is already an instance of cls, return identical name if isinstance(name, cls): return name else: return super().__new__(cls, name) def __init__(self, name): super().__init__() self._entity = None def __str__(self): return super().__str__() def __repr__(self): return f'<{self.__class__.__name__} "{self!s}">' class User(_Entity): __slots__ = () @property def entity(self): """User information struct :return: pwd.struct_passwd instance """ entity = self._entity if entity is None: try: self._entity = entity = pwd.getpwnam(self) except KeyError: raise ValueError(f"user '{self!s}' not found") from None return entity @property def uid(self): """Numeric user id (int) """ return self.entity.pw_uid @property def pgid(self): """Primary group id (int)""" return self.entity.pw_gid def chown(self, path, gid=None, **kwargs): """chown() file by path or file descriptor gid defaults to user's primary gid. Use -1 to keep gid. """ if gid is None: gid = self.pgid elif isinstance(gid, Group): gid = gid.gid os.chown(path, self.uid, gid, **kwargs) class Group(_Entity): __slots__ = () @property def entity(self): """Group information :return: grp.struct_group instance """ entity = self._entity if entity is None: try: self._entity = entity = grp.getgrnam(self) except KeyError: raise ValueError(f"group '{self!s}' not found") from None return entity @property def gid(self): """Numeric group id (int) """ return self.entity.gr_gid def chgrp(self, path, **kwargs): """change group owner file by path or file descriptor """ os.chown(path, -1, self.gid, **kwargs) class BaseConstantsNamespace: IS_64BITS = sys.maxsize > 2 ** 32 DEFAULT_ADMIN_SHELL = '/bin/bash' DEFAULT_SHELL = '/bin/sh' IPAAPI_USER = User("ipaapi") IPAAPI_GROUP = Group("ipaapi") DS_USER = User("dirsrv") DS_GROUP = Group("dirsrv") HTTPD_USER = User("apache") HTTPD_GROUP = Group("apache") GSSPROXY_USER = User("root") IPA_ADTRUST_PACKAGE_NAME = "freeipa-server-trust-ad" IPA_DNS_PACKAGE_NAME = "freeipa-server-dns" KDCPROXY_USER = User("kdcproxy") NAMED_USER = User("named") NAMED_GROUP = Group("named") NAMED_DATA_DIR = "data/" NAMED_OPTIONS_VAR = "OPTIONS" NAMED_OPENSSL_ENGINE = None NAMED_ZONE_COMMENT = "" PKI_USER = User("pkiuser") PKI_GROUP = Group("pkiuser") # ntpd init variable used for daemon options NTPD_OPTS_VAR = "OPTIONS" # quote used for daemon options NTPD_OPTS_QUOTE = "\"" ODS_USER = User("ods") ODS_GROUP = Group("ods") # nfsd init variable used to enable kerberized NFS SECURE_NFS_VAR = "SECURE_NFS" SELINUX_BOOLEAN_ADTRUST = { 'samba_portmapper': 'on', } SELINUX_BOOLEAN_HTTPD = { 'httpd_can_network_connect': 'on', 'httpd_manage_ipa': 'on', 'httpd_run_ipa': 'on', 'httpd_dbus_sssd': 'on', } # Unlike above, there are multiple use cases for SMB sharing # SELINUX_BOOLEAN_SMBSERVICE is a dictionary of dictionaries # to define set of booleans for each use case SELINUX_BOOLEAN_SMBSERVICE = { 'share_home_dirs': { 'samba_enable_home_dirs': 'on', }, 'reshare_nfs_with_samba': { 'samba_share_nfs': 'on', }, } SELINUX_BOOLEAN_SSSD = { 'sssd_use_usb': 'on', } SELINUX_MCS_MAX = 1023 SELINUX_MCS_REGEX = r"^c(\d+)([.,-]c(\d+))*$" SELINUX_MLS_MAX = 15 SELINUX_MLS_REGEX = r"^s(\d+)(-s(\d+))?$" SELINUX_USER_REGEX = r"^[a-zA-Z][a-zA-Z_\.]*$" SELINUX_USERMAP_DEFAULT = "unconfined_u:s0-s0:c0.c1023" SELINUX_USERMAP_ORDER = ( "guest_u:s0" "$xguest_u:s0" "$user_u:s0" "$staff_u:s0-s0:c0.c1023" "$sysadm_u:s0-s0:c0.c1023" "$unconfined_u:s0-s0:c0.c1023" ) SSSD_USER = User("sssd") # WSGI module override, only used on Fedora MOD_WSGI_PYTHON2 = None MOD_WSGI_PYTHON3 = None # WSGIDaemonProcess process count. On 64bit platforms, each process # consumes about 110 MB RSS, from which are about 35 MB shared. WSGI_PROCESSES = 4 if IS_64BITS else 2 # high ciphers without RC4, MD5, TripleDES, pre-shared key, secure # remote password, and DSA cert authentication. TLS_HIGH_CIPHERS = "HIGH:!aNULL:!eNULL:!MD5:!RC4:!3DES:!PSK:!SRP:!aDSS" constants = BaseConstantsNamespace()
5,136
Python
.py
158
25.601266
75
0.590955
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,177
tasks.py
freeipa_freeipa/ipaplatform/base/tasks.py
# Authors: # Alexander Bokovoy <abokovoy@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2011-2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains default platform-specific implementations of system tasks. ''' from __future__ import absolute_import import os import logging import textwrap from pkg_resources import parse_version from ipaplatform.paths import paths from ipapython import ipautil from ipapython.ipachangeconf import IPAChangeConf logger = logging.getLogger(__name__) # TODO: Add other masters as FallbackDNS ? RESOLVE1_IPA_CONF = textwrap.dedent(""" # auto-generated by IPA installer [Resolve] # use local BIND instance DNS=127.0.0.1 # make local BIND default DNS server, add search suffixes Domains=~. {searchdomains} """) class BaseTaskNamespace: def restore_context(self, filepath, force=False): """Restore SELinux security context on the given filepath. No return value expected. """ raise NotImplementedError() def backup_hostname(self, fstore, statestore): """ Backs up the current hostname in the statestore (so that it can be restored by the restore_hostname platform task). No return value expected. """ raise NotImplementedError() def reload_systemwide_ca_store(self): """ Reloads the systemwide CA store. Returns True if the operation succeeded, False otherwise. """ raise NotImplementedError() def insert_ca_certs_into_systemwide_ca_store(self, ca_certs): """ Adds CA certificates from 'ca_certs' to the systemwide CA store (if available on the platform). Returns True if the operation succeeded, False otherwise. """ try: if self.platform_insert_ca_certs(ca_certs): return self.reload_systemwide_ca_store() except Exception: logger.exception('Could not populate systemwide CA store') return False def platform_insert_ca_certs(self, ca_certs): """ Platform implementations override this method to implement population of the systemwide CA store. Returns True if changes were made to the CA store, False otherwise. Raises Exception if something went wrong. """ raise NotImplementedError() def remove_ca_certs_from_systemwide_ca_store(self): """ Removes IPA CA certificates from the systemwide CA store (if available on the platform). Returns True if the operation succeeded, False otherwise. """ try: if self.platform_remove_ca_certs(): return self.reload_systemwide_ca_store() except Exception: logger.exception( 'Could not remove certificates from systemwide CA store' ) return False def platform_remove_ca_certs(self): """ Platform implementations override this method to implement removal of certificates from the systemwide CA store. Returns True if changes were made to the CA store, False otherwise. Raises Exception if something went wrong. """ raise NotImplementedError() def get_svc_list_file(self): """ Returns the path to the IPA service list file. """ return paths.SVC_LIST_FILE def is_selinux_enabled(self): """Check if SELinux is available and enabled :return: True if SELinux is available and enabled """ return False def check_selinux_status(self): """Checks if SELinux is available on the platform. If it is, this task also makes sure that restorecon tool is available. If SELinux is available, but restorcon tool is not installed, raises an RuntimeError, which suggest installing the package containing restorecon and rerunning the installation. :return: True if SELinux is available and enabled """ raise NotImplementedError() def check_ipv6_stack_enabled(self): """Check whether IPv6 kernel module is loaded""" raise NotImplementedError() def detect_container(self): """Check if running inside a container :returns: container runtime or None :rtype: str, None """ raise NotImplementedError def restore_hostname(self, fstore, statestore): """ Restores the original hostname as backed up in the backup_hostname platform task. """ raise NotImplementedError() def restore_pre_ipa_client_configuration(self, fstore, statestore, was_sssd_installed, was_sssd_configured): """ Restores the pre-ipa-client configuration that was modified by the following platform tasks: modify_nsswitch_pam_stack modify_pam_to_use_krb5 """ raise NotImplementedError() def set_nisdomain(self, nisdomain): """ Sets the NIS domain name to 'nisdomain'. """ raise NotImplementedError() def modify_nsswitch_pam_stack(self, sssd, mkhomedir, statestore, sudo=True, subid=False): """ If sssd flag is true, configure pam and nsswitch so that SSSD is used for retrieving user information and authentication. Otherwise, configure pam and nsswitch to leverage pure LDAP. """ raise NotImplementedError() def modify_pam_to_use_krb5(self, statestore): """ Configure pam stack to allow kerberos authentication. """ raise NotImplementedError() def is_nosssd_supported(self): """ Check if the flag --no-sssd is supported for client install. """ return True def is_mkhomedir_supported(self): """ Check if the flag --mkhomedir is supported for client install. """ return True def backup_auth_configuration(self, path): """ Create backup of access control configuration. :param path: store the backup here. This will be passed to restore_auth_configuration as well. """ raise NotImplementedError() def restore_auth_configuration(self, path): """ Restore backup of access control configuration. :param path: restore the backup from here. """ raise NotImplementedError() def migrate_auth_configuration(self, statestore): """ Migrate pam stack configuration to authselect. """ def set_selinux_booleans(self, required_settings, backup_func=None): """Set the specified SELinux booleans :param required_settings: A dictionary mapping the boolean names to desired_values. The desired value can be 'on' or 'off', or None to leave the setting unchanged. :param backup_func: A function called for each boolean with two arguments: the name and the previous value If SELinux is disabled, return False; on success returns True. If setting the booleans fails, an ipapython.errors.SetseboolError is raised. """ raise NotImplementedError() @staticmethod def parse_ipa_version(version): """ :param version: textual version :return: object implementing proper __cmp__ method for version compare """ return parse_version(version) def set_hostname(self, hostname): """ Set hostname for the system No return value expected, raise CalledProcessError when error occurred """ raise NotImplementedError() def configure_httpd_service_ipa_conf(self): """Configure httpd service to work with IPA""" raise NotImplementedError() def configure_http_gssproxy_conf(self, ipauser): raise NotImplementedError() def remove_httpd_service_ipa_conf(self): """Remove configuration of httpd service of IPA""" raise NotImplementedError() def configure_httpd_wsgi_conf(self): """Configure WSGI for correct Python version""" raise NotImplementedError() def configure_httpd_protocol(self): """Configure TLS protocols in Apache""" raise NotImplementedError() def is_fips_enabled(self): return False def add_user_to_group(self, user, group): logger.debug('Adding user %s to group %s', user, group) args = [paths.USERMOD, '-a', '-G', group, user] try: ipautil.run(args) logger.debug('Done adding user to group') except ipautil.CalledProcessError as e: logger.debug('Failed to add user to group: %s', e) def setup_httpd_logging(self): raise NotImplementedError() def systemd_daemon_reload(self): """Tell systemd to reload config files""" raise NotImplementedError def configure_dns_resolver(self, nameservers, searchdomains, *, resolve1_enabled=False, fstore=None): """Configure global DNS resolver (e.g. /etc/resolv.conf) :param nameservers: list of IP addresses :param searchdomains: list of search domaons :param resolve1_enabled: is systemd-resolved enabled? :param fstore: optional file store for backup """ if resolve1_enabled: # break circular import from ipaplatform.services import knownservices confd = os.path.dirname(paths.SYSTEMD_RESOLVED_IPA_CONF) if not os.path.isdir(confd): os.mkdir(confd) # owned by root, readable by systemd-resolve user os.chmod(confd, 0o755) self.restore_context(confd, force=True) cfg = RESOLVE1_IPA_CONF.format( searchdomains=" ".join(searchdomains) ) with open(paths.SYSTEMD_RESOLVED_IPA_CONF, "w") as f: os.fchmod(f.fileno(), 0o644) f.write(cfg) self.restore_context( paths.SYSTEMD_RESOLVED_IPA_CONF, force=True ) knownservices["systemd-resolved"].reload_or_restart() def unconfigure_dns_resolver(self, fstore=None): """Unconfigure global DNS resolver (e.g. /etc/resolv.conf) :param fstore: optional file store for restore """ if fstore is not None and fstore.has_file(paths.RESOLV_CONF): fstore.restore_file(paths.RESOLV_CONF) if os.path.isfile(paths.SYSTEMD_RESOLVED_IPA_CONF): # break circular import from ipaplatform.services import knownservices os.unlink(paths.SYSTEMD_RESOLVED_IPA_CONF) knownservices["systemd-resolved"].reload_or_restart() ipautil.remove_directory(paths.SYSTEMD_RESOLVED_CONF_DIR) def configure_pkcs11_modules(self, fstore): """Disable p11-kit modules The p11-kit configuration injects p11-kit-proxy into all NSS databases. Amongst other p11-kit loads SoftHSM2 PKCS#11 provider. This interferes with 389-DS, certmonger, Dogtag and other services. For example certmonger tries to open OpenDNSSEC's SoftHSM2 token, although it doesn't use it at all. It also breaks Dogtag HSM support testing with SoftHSM2. IPA server does neither need nor use SoftHSM2 proxied by p11-kit. """ raise NotImplementedError def restore_pkcs11_modules(self, fstore): """Restore global p11-kit modules for NSS """ raise NotImplementedError def get_pkcs11_modules(self): """Return the list of module config files setup by IPA. """ return () def configure_nsswitch_database(self, fstore, database, services, preserve=True, append=True, default_value=()): """ Edits the specified nsswitch.conf database (e.g. passwd, group, sudoers) to use the specified service(s). Arguments: fstore - FileStore to backup the nsswitch.conf database - database configuration that should be ammended, e.g. 'sudoers' service - list of services that should be added, e.g. ['sss'] preserve - if True, the already configured services will be preserved The next arguments modify the behaviour if preserve=True: append - if True, the services will be appended, if False, prepended default_value - list of services that are considered as default (if the database is not mentioned in nsswitch.conf), e.g. ['files'] """ # Backup the original version of nsswitch.conf, we're going to edit it # now if not fstore.has_file(paths.NSSWITCH_CONF): fstore.backup_file(paths.NSSWITCH_CONF) conf = IPAChangeConf("IPA Installer") conf.setOptionAssignment(':') if preserve: # Read the existing configuration with open(paths.NSSWITCH_CONF, 'r') as f: opts = conf.parse(f) raw_database_entry = conf.findOpts(opts, 'option', database)[1] # Detect the list of already configured services if not raw_database_entry: # If there is no database entry, database is not present in # the nsswitch.conf. Set the list of services to the # default list, if passed. configured_services = list(default_value) else: configured_services = raw_database_entry[ 'value'].strip().split() # Make sure no service is added if already mentioned in the list added_services = [s for s in services if s not in configured_services] # Prepend / append the list of new services if append: new_value = ' ' + ' '.join(configured_services + added_services) else: new_value = ' ' + ' '.join(added_services + configured_services) else: # Preserve not set, let's rewrite existing configuration new_value = ' ' + ' '.join(services) # Set new services as sources for database opts = [ conf.setOption(database, new_value), conf.emptyLine(), ] conf.changeConf(paths.NSSWITCH_CONF, opts) logger.info("Configured %s in %s", database, paths.NSSWITCH_CONF) def enable_sssd_sudo(self, fstore): """Configure nsswitch.conf to use sssd for sudo""" self.configure_nsswitch_database( fstore, 'sudoers', ['sss'], default_value=['files']) def disable_ldap_automount(self, statestore): """Disable automount using LDAP""" if statestore.get_state( 'ipa-client-automount-nsswitch', 'previous-automount' ) is False: # Previous nsswitch.conf had no automount database configured # so remove it. conf = IPAChangeConf("IPA automount installer") conf.setOptionAssignment(':') changes = [conf.rmOption('automount')] conf.changeConf(paths.NSSWITCH_CONF, changes) self.restore_context(paths.NSSWITCH_CONF) statestore.delete_state( 'ipa-client-automount-nsswitch', 'previous-automount' ) elif statestore.get_state( 'ipa-client-automount-nsswitch', 'previous-automount' ) is not None: nss_value = statestore.get_state( 'ipa-client-automount-nsswitch', 'previous-automount' ) opts = [ { 'name': 'automount', 'type': 'option', 'action': 'set', 'value': nss_value, }, {'name': 'empty', 'type': 'empty'}, ] conf = IPAChangeConf("IPA automount installer") conf.setOptionAssignment(':') conf.changeConf(paths.NSSWITCH_CONF, opts) self.restore_context(paths.NSSWITCH_CONF) statestore.delete_state( 'ipa-client-automount-nsswitch', 'previous-automount' ) tasks = BaseTaskNamespace()
17,528
Python
.py
406
32.635468
79
0.620783
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,178
__init__.py
freeipa_freeipa/ipaplatform/base/__init__.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module should contain generic default implementations and definitions of all the objects that a platform module is expected to export. '''
918
Python
.py
22
40.681818
74
0.779888
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,179
paths.py
freeipa_freeipa/ipaplatform/base/paths.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This base platform module exports default filesystem paths. ''' import os class BasePathNamespace: BIN_HOSTNAMECTL = "/bin/hostnamectl" CRYPTO_POLICY_OPENSSLCNF_FILE = None ECHO = "/bin/echo" FIPS_MODE_SETUP = "/bin/fips-mode-setup" GZIP = "/bin/gzip" LS = "/bin/ls" SYSTEMCTL = "/bin/systemctl" SYSTEMD_RUN = "/bin/systemd-run" SYSTEMD_DETECT_VIRT = "/usr/bin/systemd-detect-virt" SYSTEMD_TMPFILES = "/bin/systemd-tmpfiles" TAR = "/bin/tar" ETC_FEDORA_RELEASE = "/etc/fedora-release" GROUP = "/etc/group" ETC_HOSTNAME = "/etc/hostname" HOSTS = "/etc/hosts" ETC_HTTPD_DIR = "/etc/httpd" HTTPD_ALIAS_DIR = "/etc/httpd/alias" GSSAPI_SESSION_KEY = "/etc/httpd/alias/ipasession.key" OLD_KRA_AGENT_PEM = "/etc/httpd/alias/kra-agent.pem" HTTPD_CONF_D_DIR = "/etc/httpd/conf.d/" HTTPD_IPA_KDCPROXY_CONF = "/etc/ipa/kdcproxy/ipa-kdc-proxy.conf" HTTPD_IPA_KDCPROXY_CONF_SYMLINK = "/etc/httpd/conf.d/ipa-kdc-proxy.conf" HTTPD_IPA_PKI_PROXY_CONF = "/etc/httpd/conf.d/ipa-pki-proxy.conf" HTTPD_IPA_REWRITE_CONF = "/etc/httpd/conf.d/ipa-rewrite.conf" HTTPD_IPA_CONF = "/etc/httpd/conf.d/ipa.conf" HTTPD_NSS_CONF = "/etc/httpd/conf.d/nss.conf" HTTPD_SSL_CONF = "/etc/httpd/conf.d/ssl.conf" HTTPD_SSL_SITE_CONF = "/etc/httpd/conf.d/ssl.conf" HTTPD_CERT_FILE = "/var/lib/ipa/certs/httpd.crt" HTTPD_KEY_FILE = "/var/lib/ipa/private/httpd.key" HTTPD_PASSWD_FILE_FMT = "/var/lib/ipa/passwds/{host}-443-RSA" # only used on Fedora HTTPD_IPA_WSGI_MODULES_CONF = None OLD_IPA_KEYTAB = "/etc/httpd/conf/ipa.keytab" HTTP_KEYTAB = "/var/lib/ipa/gssproxy/http.keytab" HTTPD_PASSWORD_CONF = "/etc/httpd/conf/password.conf" IDMAPD_CONF = "/etc/idmapd.conf" ETC_IPA = "/etc/ipa" CONNCHECK_CCACHE = "/etc/ipa/.conncheck_ccache" IPA_DNS_CCACHE = "/etc/ipa/.dns_ccache" IPA_DNS_UPDATE_TXT = "/etc/ipa/.dns_update.txt" IPA_CA_CRT = "/etc/ipa/ca.crt" IPA_DEFAULT_CONF = "/etc/ipa/default.conf" IPA_DNSKEYSYNCD_KEYTAB = "/etc/ipa/dnssec/ipa-dnskeysyncd.keytab" IPA_ODS_EXPORTER_KEYTAB = "/etc/ipa/dnssec/ipa-ods-exporter.keytab" IPA_SERVER_CONF = "/etc/ipa/server.conf" DNSSEC_OPENSSL_CONF = "/etc/ipa/dnssec/openssl.cnf" DNSSEC_SOFTHSM2_CONF = "/etc/ipa/dnssec/softhsm2.conf" DNSSEC_SOFTHSM_PIN_SO = "/etc/ipa/dnssec/softhsm_pin_so" IPA_NSSDB_DIR = "/etc/ipa/nssdb" IPA_NSSDB_PWDFILE_TXT = "/etc/ipa/nssdb/pwdfile.txt" COMMON_KRB5_CONF_DIR = "/etc/krb5.conf.d/" KRB5_CONF = "/etc/krb5.conf" KRB5_FREEIPA = COMMON_KRB5_CONF_DIR + "freeipa" KRB5_FREEIPA_SERVER = COMMON_KRB5_CONF_DIR + "freeipa-server" KRB5_KEYTAB = "/etc/krb5.keytab" LDAP_CONF = "/etc/ldap.conf" LIBNSS_LDAP_CONF = "/etc/libnss-ldap.conf" NAMED_CONF = "/etc/named.conf" NAMED_CONF_BAK = "/etc/named.conf.ipa-backup" NAMED_CUSTOM_CONF = "/etc/named/ipa-ext.conf" NAMED_LOGGING_OPTIONS_CONF = "/etc/named/ipa-logging-ext.conf" NAMED_CUSTOM_OPTIONS_CONF = "/etc/named/ipa-options-ext.conf" NAMED_CONF_SRC = '/usr/share/ipa/bind.named.conf.template' NAMED_CUSTOM_CONF_SRC = '/usr/share/ipa/bind.ipa-ext.conf.template' NAMED_CUSTOM_OPTIONS_CONF_SRC = ( '/usr/share/ipa/bind.ipa-options-ext.conf.template' ) NAMED_LOGGING_OPTIONS_CONF_SRC = ( "/usr/share/ipa/bind.ipa-logging-ext.conf.template" ) NAMED_VAR_DIR = "/var/named" NAMED_KEYTAB = "/etc/named.keytab" NAMED_RFC1912_ZONES = "/etc/named.rfc1912.zones" NAMED_ROOT_KEY = "/etc/named.root.key" NAMED_MANAGED_KEYS_DIR = "/var/named/dynamic" NAMED_CRYPTO_POLICY_FILE = None NSLCD_CONF = "/etc/nslcd.conf" NSS_LDAP_CONF = "/etc/nss_ldap.conf" NSSWITCH_CONF = "/etc/nsswitch.conf" CHRONY_CONF = "/etc/chrony.conf" NTP_CONF = "/etc/ntp.conf" NTP_STEP_TICKERS = "/etc/ntp/step-tickers" ETC_OPENDNSSEC_DIR = "/etc/opendnssec" OPENDNSSEC_CONF_FILE = "/etc/opendnssec/conf.xml" OPENDNSSEC_KASP_FILE = "/etc/opendnssec/kasp.xml" OPENDNSSEC_ZONELIST_FILE = "/etc/opendnssec/zonelist.xml" OPENLDAP_LDAP_CONF = "/etc/openldap/ldap.conf" PAM_LDAP_CONF = "/etc/pam_ldap.conf" PASSWD = "/etc/passwd" # Trusted CA certificates used to be written out to this file. In newer # versions of FreeIPA, it has been replaced by IPA_P11_KIT. SYSTEMWIDE_IPA_CA_CRT = "/etc/pki/ca-trust/source/anchors/ipa-ca.crt" IPA_P11_KIT = "/etc/pki/ca-trust/source/ipa.p11-kit" CA_CERTIFICATES_BUNDLE_PEM = None CA_CERTIFICATES_DIR = None NSS_DB_DIR = "/etc/pki/nssdb" PKI_CONFIGURATION = "/etc/pki" PKI_TOMCAT = "/etc/pki/pki-tomcat" PKI_TOMCAT_ALIAS_DIR = "/etc/pki/pki-tomcat/alias" PKI_TOMCAT_ALIAS_PWDFILE_TXT = "/etc/pki/pki-tomcat/alias/pwdfile.txt" PKI_TOMCAT_PASSWORD_CONF = "/etc/pki/pki-tomcat/password.conf" PKI_TOMCAT_SERVER_XML = "/etc/pki/pki-tomcat/server.xml" PKI_ACME_CONFIGSOURCES_CONF = "/etc/pki/pki-tomcat/acme/configsources.conf" PKI_ACME_DATABASE_CONF = "/etc/pki/pki-tomcat/acme/database.conf" PKI_ACME_ENGINE_CONF = "/etc/pki/pki-tomcat/acme/engine.conf" PKI_ACME_ISSUER_CONF = "/etc/pki/pki-tomcat/acme/issuer.conf" PKI_ACME_REALM_CONF = "/etc/pki/pki-tomcat/acme/realm.conf" ETC_REDHAT_RELEASE = "/etc/redhat-release" RESOLV_CONF = "/etc/resolv.conf" SAMBA_KEYTAB = "/etc/samba/samba.keytab" SMB_CONF = "/etc/samba/smb.conf" LIMITS_CONF = "/etc/security/limits.conf" SSH_CONFIG_DIR = "/etc/ssh" SSH_CONFIG = "/etc/ssh/ssh_config" SSH_IPA_CONFIG_TEMPLATE = "/usr/share/ipa/client/ssh_ipa.conf.template" SSH_IPA_CONFIG = "/etc/ssh/ssh_config.d/04-ipa.conf" SSHD_CONFIG = "/etc/ssh/sshd_config" SSHD_IPA_CONFIG = "/etc/ssh/sshd_config.d/04-ipa.conf" SSHD_IPA_CONFIG_TEMPLATE = "/usr/share/ipa/client/sshd_ipa.conf.template" SSSD_CONF = "/etc/sssd/sssd.conf" SSSD_CONF_BKP = "/etc/sssd/sssd.conf.bkp" SSSD_CONF_DELETED = "/etc/sssd/sssd.conf.deleted" ETC_SYSCONFIG_DIR = "/etc/sysconfig" ETC_SYSCONFIG_AUTHCONFIG = "/etc/sysconfig/authconfig" SYSCONFIG_AUTOFS = "/etc/sysconfig/autofs" SYSCONFIG_DIRSRV = "/etc/sysconfig/dirsrv" SYSCONFIG_DIRSRV_INSTANCE = "/etc/sysconfig/dirsrv-%s" SYSCONFIG_DIRSRV_SYSTEMD = "/etc/sysconfig/dirsrv.systemd" SYSCONFIG_IPA_DNSKEYSYNCD = "/etc/sysconfig/ipa-dnskeysyncd" SYSCONFIG_IPA_ODS_EXPORTER = "/etc/sysconfig/ipa-ods-exporter" SYSCONFIG_HTTPD = "/etc/sysconfig/httpd" SYSCONFIG_KRB5KDC_DIR = "/etc/sysconfig/krb5kdc" SYSCONFIG_NAMED = "/etc/sysconfig/named" SYSCONFIG_NFS = "/etc/sysconfig/nfs" SYSCONFIG_NTPD = "/etc/sysconfig/ntpd" SYSCONFIG_ODS = "/etc/sysconfig/ods" SYSCONFIG_PKI = "/etc/sysconfig/pki" SYSCONFIG_PKI_TOMCAT = "/etc/sysconfig/pki-tomcat" SYSCONFIG_PKI_TOMCAT_PKI_TOMCAT_DIR = "/etc/sysconfig/pki/tomcat/pki-tomcat" ETC_SYSTEMD_SYSTEM_DIR = "/etc/systemd/system/" SYSTEMD_SYSTEM_HTTPD_D_DIR = "/etc/systemd/system/httpd.service.d/" SYSTEMD_SYSTEM_HTTPD_IPA_CONF = "/etc/systemd/system/httpd.service.d/ipa.conf" SYSTEMD_CERTMONGER_SERVICE = "/etc/systemd/system/multi-user.target.wants/certmonger.service" SYSTEMD_IPA_SERVICE = "/etc/systemd/system/multi-user.target.wants/ipa.service" SYSTEMD_SSSD_SERVICE = "/etc/systemd/system/multi-user.target.wants/sssd.service" SYSTEMD_PKI_TOMCAT_SERVICE = "/etc/systemd/system/pki-tomcatd.target.wants/pki-tomcatd@pki-tomcat.service" SYSTEMD_PKI_TOMCAT_IPA_CONF = \ "/etc/systemd/system/pki-tomcatd@pki-tomcat.service.d/ipa.conf" ETC_TMPFILESD_DIRSRV = "/etc/tmpfiles.d/dirsrv-%s.conf" DNSSEC_TRUSTED_KEY = "/etc/trusted-key.key" HOME_DIR = "/home" PROC_FIPS_ENABLED = "/proc/sys/crypto/fips_enabled" ROOT_IPA_CACHE = "/root/.ipa_cache" ROOT_PKI = "/root/.pki" DOGTAG_ADMIN_P12 = "/root/ca-agent.p12" RA_AGENT_PEM = "/var/lib/ipa/ra-agent.pem" RA_AGENT_KEY = "/var/lib/ipa/ra-agent.key" CACERT_P12 = "/root/cacert.p12" ROOT_IPA_CSR = "/root/ipa.csr" NAMED_PID = "/run/named/named.pid" NOLOGIN = "/sbin/nologin" SBIN_REBOOT = "/sbin/reboot" SBIN_RESTORECON = "/sbin/restorecon" SBIN_SERVICE = "/sbin/service" TMP = "/tmp" TMP_CA_P12 = "/tmp/ca.p12" TMP_KRB5CC = "/tmp/krb5cc_%d" USR_DIR = "/usr" CERTMONGER_COMMAND_TEMPLATE = "/usr/libexec/ipa/certmonger/%s" PKCS12EXPORT = "/usr/bin/PKCS12Export" CERTUTIL = "/usr/bin/certutil" CHROMIUM_BROWSER = "/usr/bin/chromium-browser" FIREFOX = "/usr/bin/firefox" GETCERT = "/usr/bin/getcert" GPG2 = "/usr/bin/gpg" GPG_CONF = "/usr/bin/gpgconf" GPG_CONNECT_AGENT = "/usr/bin/gpg-connect-agent" GPG_AGENT = "/usr/bin/gpg-agent" IPA_GETCERT = "/usr/bin/ipa-getcert" KADMIN_LOCAL = '/usr/sbin/kadmin.local' KDESTROY = "/usr/bin/kdestroy" KINIT = "/usr/bin/kinit" KLIST = "/usr/bin/klist" KTUTIL = "/usr/bin/ktutil" BIN_KVNO = "/usr/bin/kvno" LDAPMODIFY = "/usr/bin/ldapmodify" LDAPPASSWD = "/usr/bin/ldappasswd" MODUTIL = "/usr/bin/modutil" NET = "/usr/bin/net" BIN_NISDOMAINNAME = "/usr/bin/nisdomainname" NSUPDATE = "/usr/bin/nsupdate" ODS_KSMUTIL = "/usr/bin/ods-ksmutil" ODS_SIGNER = "/usr/sbin/ods-signer" ODS_ENFORCER = "/usr/sbin/ods-enforcer" ODS_ENFORCER_DB_SETUP = "/usr/sbin/ods-enforcer-db-setup" OPENSSL = "/usr/bin/openssl" OPENSSL_DIR = "/etc/pki/tls" OPENSSL_CERTS_DIR = "/etc/pki/tls/certs" OPENSSL_PRIVATE_DIR = "/etc/pki/tls/private" PK12UTIL = "/usr/bin/pk12util" SOFTHSM2_UTIL = "/usr/bin/softhsm2-util" SSLGET = "/usr/bin/sslget" SSS_SSH_AUTHORIZEDKEYS = "/usr/bin/sss_ssh_authorizedkeys" SSS_SSH_KNOWNHOSTS = "/usr/bin/sss_ssh_knownhosts" SSS_SSH_KNOWNHOSTSPROXY = "/usr/bin/sss_ssh_knownhostsproxy" BIN_TIMEOUT = "/usr/bin/timeout" UPDATE_CA_TRUST = "/usr/bin/update-ca-trust" BIN_CURL = "/usr/bin/curl" BIND_LDAP_SO = "/usr/lib/bind/ldap.so" BIND_LDAP_DNS_IPA_WORKDIR = "/var/named/dyndb-ldap/ipa/" BIND_LDAP_DNS_ZONE_WORKDIR = "/var/named/dyndb-ldap/ipa/master/" LIB_FIREFOX = "/usr/lib/firefox" LIBSOFTHSM2_SO = "/usr/lib/pkcs11/libsofthsm2.so" PAM_KRB5_SO = "/usr/lib/security/pam_krb5.so" LIB_SYSTEMD_SYSTEMD_DIR = "/usr/lib/systemd/system/" BIND_LDAP_SO_64 = "/usr/lib64/bind/ldap.so" LIB64_FIREFOX = "/usr/lib64/firefox" LIBSOFTHSM2_SO_64 = "/usr/lib64/pkcs11/libsofthsm2.so" PAM_KRB5_SO_64 = "/usr/lib64/security/pam_krb5.so" LIBEXEC_CERTMONGER_DIR = "/usr/libexec/certmonger" DOGTAG_IPA_CA_RENEW_AGENT_SUBMIT = "/usr/libexec/certmonger/dogtag-ipa-ca-renew-agent-submit" DOGTAG_IPA_RENEW_AGENT_SUBMIT = "/usr/libexec/certmonger/dogtag-ipa-renew-agent-submit" CERTMONGER_DOGTAG_SUBMIT = "/usr/libexec/certmonger/dogtag-submit" IPA_SERVER_GUARD = "/usr/libexec/certmonger/ipa-server-guard" GENERATE_RNDC_KEY = "/usr/libexec/generate-rndc-key.sh" RNDC_KEY = "/etc/rndc.key" LIBEXEC_IPA_DIR = "/usr/libexec/ipa" IPA_DNSKEYSYNCD_REPLICA = "/usr/libexec/ipa/ipa-dnskeysync-replica" IPA_DNSKEYSYNCD = "/usr/libexec/ipa/ipa-dnskeysyncd" IPA_HTTPD_KDCPROXY = "/usr/libexec/ipa/ipa-httpd-kdcproxy" IPA_ODS_EXPORTER = "/usr/libexec/ipa/ipa-ods-exporter" IPA_PKI_RETRIEVE_KEY = "/usr/libexec/ipa/ipa-pki-retrieve-key" IPA_HTTPD_PASSWD_READER = "/usr/libexec/ipa/ipa-httpd-pwdreader" IPA_PKI_WAIT_RUNNING = "/usr/libexec/ipa/ipa-pki-wait-running" DNSSEC_KEYFROMLABEL = "/usr/sbin/dnssec-keyfromlabel" DNSSEC_KEYFROMLABEL_9_17 = "/usr/bin/dnssec-keyfromlabel" GETSEBOOL = "/usr/sbin/getsebool" GROUPADD = "/usr/sbin/groupadd" USERMOD = "/usr/sbin/usermod" HTTPD = "/usr/sbin/httpd" IPA_CLIENT_AUTOMOUNT = "/usr/sbin/ipa-client-automount" IPA_CLIENT_INSTALL = "/usr/sbin/ipa-client-install" IPA_DNS_INSTALL = "/usr/sbin/ipa-dns-install" SBIN_IPA_JOIN = "/usr/sbin/ipa-join" IPA_REPLICA_CONNCHECK = "/usr/sbin/ipa-replica-conncheck" IPA_RMKEYTAB = "/usr/sbin/ipa-rmkeytab" IPACTL = "/usr/sbin/ipactl" CHRONYC = "/usr/bin/chronyc" CHRONYD = "/usr/sbin/chronyd" PKIDESTROY = "/usr/sbin/pkidestroy" PKISPAWN = "/usr/sbin/pkispawn" PKI = "/usr/bin/pki" RESTORECON = "/usr/sbin/restorecon" SELINUXENABLED = "/usr/sbin/selinuxenabled" SETSEBOOL = "/usr/sbin/setsebool" SEMODULE = "/usr/sbin/semodule" SMBD = "/usr/sbin/smbd" USERADD = "/usr/sbin/useradd" FONTS_DIR = "/usr/share/fonts" FONTS_OPENSANS_DIR = "/usr/share/fonts/open-sans" FONTS_FONTAWESOME_DIR = "/usr/share/fonts/fontawesome" USR_SHARE_IPA_DIR = "/usr/share/ipa/" USR_SHARE_IPA_CLIENT_DIR = "/usr/share/ipa/client" CA_TOPOLOGY_ULDIF = "/usr/share/ipa/ca-topology.uldif" IPA_HTML_DIR = "/usr/share/ipa/html" CA_CRT = "/usr/share/ipa/html/ca.crt" KRB_CON = "/usr/share/ipa/html/krb.con" HTML_KRB5_INI = "/usr/share/ipa/html/krb5.ini" HTML_KRBREALM_CON = "/usr/share/ipa/html/krbrealm.con" SCHEMA_COMPAT_ULDIF = "/usr/share/ipa/updates/91-schema_compat.update" SCHEMA_COMPAT_POST_ULDIF = "/usr/share/ipa/schema_compat_post.uldif" IPA_JS_PLUGINS_DIR = "/usr/share/ipa/ui/js/plugins" UPDATES_DIR = "/usr/share/ipa/updates/" DICT_WORDS = "/usr/share/dict/words" VAR_KERBEROS_KRB5KDC_DIR = "/var/kerberos/krb5kdc/" VAR_KRB5KDC_K5_REALM = "/var/kerberos/krb5kdc/.k5." CACERT_PEM = "/var/kerberos/krb5kdc/cacert.pem" KRB5KDC_KADM5_ACL = "/var/kerberos/krb5kdc/kadm5.acl" KRB5KDC_KADM5_KEYTAB = "/var/kerberos/krb5kdc/kadm5.keytab" KRB5KDC_KDC_CONF = "/var/kerberos/krb5kdc/kdc.conf" KDC_CERT = "/var/kerberos/krb5kdc/kdc.crt" KDC_KEY = "/var/kerberos/krb5kdc/kdc.key" VAR_LIB = "/var/lib" AUTHCONFIG_LAST = "/var/lib/authconfig/last" VAR_LIB_CERTMONGER_DIR = "/var/lib/certmonger" CERTMONGER_CAS_DIR = "/var/lib/certmonger/cas/" CERTMONGER_CAS_CA_RENEWAL = "/var/lib/certmonger/cas/ca_renewal" CERTMONGER_REQUESTS_DIR = "/var/lib/certmonger/requests/" VAR_LIB_DIRSRV = "/var/lib/dirsrv" DIRSRV_BOOT_LDIF = "/var/lib/dirsrv/boot.ldif" VAR_LIB_IPA = "/var/lib/ipa" IPA_CLIENT_SYSRESTORE = "/var/lib/ipa-client/sysrestore" SYSRESTORE_INDEX = "/var/lib/ipa-client/sysrestore/sysrestore.index" IPA_BACKUP_DIR = "/var/lib/ipa/backup" IPA_DNSSEC_DIR = "/var/lib/ipa/dnssec" IPA_KASP_DB_BACKUP = "/var/lib/ipa/ipa-kasp.db.backup" DNSSEC_TOKENS_DIR = "/var/lib/ipa/dnssec/tokens" DNSSEC_SOFTHSM_PIN = "/var/lib/ipa/dnssec/softhsm_pin" DNSSEC_ENGINE_SOCK = "/run/opendnssec/engine.sock" IPA_CA_CSR = "/var/lib/ipa/ca.csr" IPA_CACERT_MANAGE = "/usr/sbin/ipa-cacert-manage" IPA_CERTUPDATE = "/usr/sbin/ipa-certupdate" PKI_CA_PUBLISH_DIR = "/var/lib/ipa/pki-ca/publish" REPLICA_INFO_TEMPLATE = "/var/lib/ipa/replica-info-%s" REPLICA_INFO_GPG_TEMPLATE = "/var/lib/ipa/replica-info-%s.gpg" SYSRESTORE = "/var/lib/ipa/sysrestore" STATEFILE_DIR = "/var/lib/ipa/sysupgrade" VAR_LIB_KDCPROXY = "/var/lib/kdcproxy" VAR_LIB_PKI_DIR = "/var/lib/pki" VAR_LIB_PKI_CA_ALIAS_DIR = "/var/lib/pki-ca/alias" VAR_LIB_PKI_TOMCAT_DIR = "/var/lib/pki/pki-tomcat" CA_BACKUP_KEYS_P12 = "/var/lib/pki/pki-tomcat/alias/ca_backup_keys.p12" KRA_BACKUP_KEYS_P12 = "/var/lib/pki/pki-tomcat/alias/kra_backup_keys.p12" CA_CS_CFG_PATH = "/var/lib/pki/pki-tomcat/conf/ca/CS.cfg" CASIGNEDLOGCERT_CFG = ( "/var/lib/pki/pki-tomcat/ca/profiles/ca/caSignedLogCert.cfg") KRA_CS_CFG_PATH = "/var/lib/pki/pki-tomcat/conf/kra/CS.cfg" KRACERT_P12 = "/root/kracert.p12" SAMBA_DIR = "/var/lib/samba" SSSD_DB = "/var/lib/sss/db" SSSD_MC_GROUP = "/var/lib/sss/mc/group" SSSD_MC_PASSWD = "/var/lib/sss/mc/passwd" SSSD_MC_INITGROUPS = "/var/lib/sss/mc/initgroups" SSSD_MC_SID = "/var/lib/sss/mc/sid" SSSD_PIPES = "/var/lib/sss/pipes" SSSD_LDB = "/var/lib/sss/db/sssd.ldb" SSSD_CONFIG_LDB = "/var/lib/sss/db/config.ldb" SSSD_SECRETS = "/var/lib/sss/secrets/secrets.ldb" SSSD_PUBCONF_DIR = "/var/lib/sss/pubconf" SSSD_PUBCONF_KNOWN_HOSTS = "/var/lib/sss/pubconf/known_hosts" SSSD_PUBCONF_KRB5_INCLUDE_D_DIR = "/var/lib/sss/pubconf/krb5.include.d/" SSSD_KEYTABS_DIR = "/var/lib/sss/keytabs" VAR_LOG_AUDIT = "/var/log/audit/audit.log" VAR_LOG_HTTPD_DIR = "/var/log/httpd" VAR_LOG_HTTPD_ERROR = "/var/log/httpd/error_log" IPABACKUP_LOG = "/var/log/ipabackup.log" IPACLIENT_INSTALL_LOG = "/var/log/ipaclient-install.log" IPACLIENT_UNINSTALL_LOG = "/var/log/ipaclient-uninstall.log" IPACLIENTSAMBA_INSTALL_LOG = "/var/log/ipaclientsamba-install.log" IPACLIENTSAMBA_UNINSTALL_LOG = "/var/log/ipaclientsamba-uninstall.log" IPAREPLICA_CA_INSTALL_LOG = "/var/log/ipareplica-ca-install.log" IPAREPLICA_CONNCHECK_LOG = "/var/log/ipareplica-conncheck.log" IPAREPLICA_INSTALL_LOG = "/var/log/ipareplica-install.log" IPARESTORE_LOG = "/var/log/iparestore.log" IPASERVER_ENABLESID_LOG = "/var/log/ipaserver-enable-sid.log" IPASERVER_INSTALL_LOG = "/var/log/ipaserver-install.log" IPASERVER_ADTRUST_INSTALL_LOG = "/var/log/ipaserver-adtrust-install.log" IPASERVER_DNS_INSTALL_LOG = "/var/log/ipaserver-dns-install.log" IPASERVER_KRA_INSTALL_LOG = "/var/log/ipaserver-kra-install.log" IPASERVER_UNINSTALL_LOG = "/var/log/ipaserver-uninstall.log" IPAUPGRADE_LOG = "/var/log/ipaupgrade.log" IPATRUSTENABLEAGENT_LOG = "/var/log/ipatrust-enable-agent.log" IPAEPN_LOG = "/var/log/ipaepn.log" KADMIND_LOG = "/var/log/kadmind.log" KRB5KDC_LOG = "/var/log/krb5kdc.log" MESSAGES = "/var/log/messages" VAR_LOG_PKI_DIR = "/var/log/pki/" BIN_TOMCAT = "/usr/sbin/tomcat" TOMCAT_TOPLEVEL_DIR = "/var/log/pki/pki-tomcat" TOMCAT_CA_DIR = "/var/log/pki/pki-tomcat/ca" TOMCAT_CA_ARCHIVE_DIR = "/var/log/pki/pki-tomcat/ca/archive" TOMCAT_SIGNEDAUDIT_DIR = "/var/log/pki/pki-tomcat/ca/signedAudit" TOMCAT_KRA_DIR = "/var/log/pki/pki-tomcat/kra" TOMCAT_KRA_ARCHIVE_DIR = "/var/log/pki/pki-tomcat/kra/archive" TOMCAT_KRA_SIGNEDAUDIT_DIR = "/var/log/pki/pki-tomcat/kra/signedAudit" LOG_SECURE = "/var/log/secure" VAR_LOG_SSSD_DIR = "/var/log/sssd" NAMED_RUN = "/var/named/data/named.run" VAR_OPENDNSSEC_DIR = "/var/opendnssec" OPENDNSSEC_KASP_DB = "/var/opendnssec/kasp.db" IPA_ODS_EXPORTER_CCACHE = "/var/opendnssec/tmp/ipa-ods-exporter.ccache" VAR_RUN_DIRSRV_DIR = "/run/dirsrv" IPA_CCACHES = "/run/ipa/ccaches" CA_BUNDLE_PEM = "/var/lib/ipa-client/pki/ca-bundle.pem" KDC_CA_BUNDLE_PEM = "/var/lib/ipa-client/pki/kdc-ca-bundle.pem" IPA_RENEWAL_LOCK = "/run/ipa/renewal.lock" SVC_LIST_FILE = "/run/ipa/services.list" KRB5CC_SAMBA = "/run/samba/krb5cc_samba" SLAPD_INSTANCE_SOCKET_TEMPLATE = "/run/slapd-%s.socket" ADMIN_CERT_PATH = '/root/.dogtag/pki-tomcat/ca_admin.cert' ENTROPY_AVAIL = '/proc/sys/kernel/random/entropy_avail' KDCPROXY_CONFIG = '/etc/ipa/kdcproxy/kdcproxy.conf' CERTMONGER = '/usr/sbin/certmonger' NETWORK_MANAGER_CONFIG = '/etc/NetworkManager/NetworkManager.conf' NETWORK_MANAGER_CONFIG_DIR = '/etc/NetworkManager/conf.d' NETWORK_MANAGER_IPA_CONF = '/etc/NetworkManager/conf.d/zzz-ipa.conf' SYSTEMD_RESOLVED_IPA_CONF = '/etc/systemd/resolved.conf.d/zzz-ipa.conf' SYSTEMD_RESOLVED_CONF = '/etc/systemd/resolved.conf' SYSTEMD_RESOLVED_CONF_DIR = '/etc/systemd/resolved.conf.d' IPA_CUSTODIA_CONF_DIR = '/etc/ipa/custodia' IPA_CUSTODIA_CONF = '/etc/ipa/custodia/custodia.conf' IPA_CUSTODIA_KEYS = '/etc/ipa/custodia/server.keys' IPA_CUSTODIA_SOCKET = '/run/httpd/ipa-custodia.sock' IPA_CUSTODIA_AUDIT_LOG = '/var/log/ipa-custodia.audit.log' IPA_CUSTODIA_HANDLER = "/usr/libexec/ipa/custodia" IPA_CUSTODIA_CHECK = "/usr/libexec/ipa/ipa-custodia-check" IPA_GETKEYTAB = '/usr/sbin/ipa-getkeytab' IPA_MIGRATE_LOG = '/var/log/ipa-migrate.log' EXTERNAL_SCHEMA_DIR = '/usr/share/ipa/schema.d' GSSPROXY_CONF = '/etc/gssproxy/10-ipa.conf' KRB5CC_HTTPD = '/tmp/krb5cc-httpd' IF_INET6 = '/proc/net/if_inet6' WSGI_PREFIX_DIR = "/run/httpd/wsgi" AUTHCONFIG = None AUTHSELECT = None SYSCONF_NETWORK = None ETC_PKCS11_MODULES_DIR = "/etc/pkcs11/modules" # 389 DS related commands. DSCREATE = '/usr/sbin/dscreate' DSCTL = '/usr/sbin/dsctl' DSCONF = '/usr/sbin/dsconf' # DS related constants ETC_DIRSRV = "/etc/dirsrv" DS_KEYTAB = "/etc/dirsrv/ds.keytab" ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE = "/etc/dirsrv/slapd-%s" USR_LIB_DIRSRV = "/usr/lib/dirsrv" USR_LIB_DIRSRV_64 = "/usr/lib64/dirsrv" VAR_LIB_DIRSRV_INSTANCE_SCRIPTS_TEMPLATE = "/var/lib/dirsrv/scripts-%s" VAR_LIB_SLAPD_INSTANCE_DIR_TEMPLATE = "/var/lib/dirsrv/slapd-%s" SLAPD_INSTANCE_BACKUP_DIR_TEMPLATE = "/var/lib/dirsrv/slapd-%s/bak/%s" SLAPD_INSTANCE_DB_DIR_TEMPLATE = "/var/lib/dirsrv/slapd-%s/db/%s" SLAPD_INSTANCE_LDIF_DIR_TEMPLATE = "/var/lib/dirsrv/slapd-%s/ldif" DIRSRV_LOCK_DIR = "/run/lock/dirsrv" ALL_SLAPD_INSTANCE_SOCKETS = "/run/slapd-*.socket" VAR_LOG_DIRSRV_INSTANCE_TEMPLATE = "/var/log/dirsrv/slapd-%s" VAR_LOG_DIRSRV = "/var/log/dirsrv/" SLAPD_INSTANCE_ACCESS_LOG_TEMPLATE = "/var/log/dirsrv/slapd-%s/access" SLAPD_INSTANCE_ERROR_LOG_TEMPLATE = "/var/log/dirsrv/slapd-%s/errors" SLAPD_INSTANCE_AUDIT_LOG_TEMPLATE = "/var/log/dirsrv/slapd-%s/audit" SLAPD_INSTANCE_SYSTEMD_IPA_ENV_TEMPLATE = \ "/etc/systemd/system/dirsrv@%s.service.d/ipa-env.conf" IPA_SERVER_UPGRADE = '/usr/sbin/ipa-server-upgrade' KEYCTL = '/bin/keyctl' GETENT = '/usr/bin/getent' SSHD = '/usr/sbin/sshd' SSSCTL = '/usr/sbin/sssctl' LIBARCH = "64" TDBTOOL = '/usr/bin/tdbtool' SECRETS_TDB = '/var/lib/samba/private/secrets.tdb' LETS_ENCRYPT_LOG = '/var/log/letsencrypt/letsencrypt.log' IPA_CCACHE_SWEEPER_GSSPROXY_SOCK = ( "/var/lib/gssproxy/ipa_ccache_sweeper.sock" ) PAM_CONFIG = None PASSKEY_CHILD = '/usr/libexec/sssd/passkey_child' def check_paths(self): """Check paths for missing files python3 -c 'from ipaplatform.paths import paths; paths.check_paths()' """ executables = ( "/bin", "/sbin", "/usr/bin", "/usr/sbin", self.LIBEXEC_IPA_DIR, self.LIBEXEC_CERTMONGER_DIR ) for name in sorted(dir(self)): if not name[0].isupper(): continue value = getattr(self, name) if not value or not isinstance(value, str): # skip empty values continue if "%" in value or "{" in value: # skip templates continue if value.startswith(executables) and value not in executables: if not os.path.isfile(value): print("Missing executable {}={}".format(name, value)) paths = BasePathNamespace()
23,834
Python
.py
491
43.325866
110
0.684095
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,180
services.py
freeipa_freeipa/ipaplatform/base/services.py
# Author: Alexander Bokovoy <abokovoy@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ''' This base module contains default implementations of IPA interface for interacting with system services. ''' from __future__ import absolute_import import os import json import time import logging import warnings import six from ipapython import ipautil from ipaplatform.paths import paths from ipaplatform.tasks import tasks from collections.abc import Mapping logger = logging.getLogger(__name__) # Canonical names of services as IPA wants to see them. As we need to have # *some* naming, set them as in Red Hat distributions. Actual implementation # should make them available through knownservices.<name> and take care of # re-mapping internally, if needed wellknownservices = [ 'certmonger', 'dirsrv', 'httpd', 'ipa', 'krb5kdc', 'dbus', 'nslcd', 'nscd', 'ntpd', 'portmap', 'rpcbind', 'kadmin', 'sshd', 'autofs', 'rpcgssd', 'rpcidmapd', 'pki_tomcatd', 'chronyd', 'domainname', 'named', 'ods_enforcerd', 'ods_signerd', 'gssproxy', 'nfs-utils', 'sssd', 'NetworkManager', 'ipa-custodia', 'ipa-dnskeysyncd', 'ipa-otpd', 'ipa-ods-exporter', 'systemd-resolved', ] # The common ports for these services. This is used to wait for the # service to become available. wellknownports = { 'dirsrv': [389], # only used if the incoming instance name is blank 'pki-tomcatd@pki-tomcat.service': [8080, 8443], 'pki-tomcat': [8080, 8443], 'pki-tomcatd': [8080, 8443], # used if the incoming instance name is blank } SERVICE_POLL_INTERVAL = 0.1 # seconds class KnownServices(Mapping): """ KnownServices is an abstract class factory that should give out instances of well-known platform services. Actual implementation must create these instances as its own attributes on first access (or instance creation) and cache them. """ def __init__(self, d): self.__d = d def __getitem__(self, key): return self.__d[key] def __iter__(self): return iter(self.__d) def __len__(self): return len(self.__d) def __call__(self): return six.itervalues(self.__d) def __getattr__(self, name): try: return self.__d[name] except KeyError: raise AttributeError(name) class PlatformService: """ PlatformService abstracts out external process running on the system which is possible to administer (start, stop, check status, etc). """ def __init__(self, service_name, api=None): # pylint: disable=ipa-forbidden-import import ipalib # FixMe: break import cycle # pylint: enable=ipa-forbidden-import self.service_name = service_name if api is not None: self.api = api else: self.api = ipalib.api warnings.warn( "{s.__class__.__name__}('{s.service_name}', api=None) " "is deprecated.".format(s=self), RuntimeWarning, stacklevel=2) def start(self, instance_name="", capture_output=True, wait=True, update_service_list=True): """ When a service is started record the fact in a special file. This allows ipactl stop to always stop all services that have been started via ipa tools """ if not update_service_list: return svc_list = [] try: with open(paths.SVC_LIST_FILE, 'r') as f: svc_list = json.load(f) except Exception: # not fatal, may be the first service pass if self.service_name not in svc_list: svc_list.append(self.service_name) with open(paths.SVC_LIST_FILE, 'w') as f: json.dump(svc_list, f) def stop(self, instance_name="", capture_output=True, update_service_list=True): """ When a service is stopped remove it from the service list file. """ if not update_service_list: return svc_list = [] try: with open(paths.SVC_LIST_FILE, 'r') as f: svc_list = json.load(f) except Exception: # not fatal, may be the first service pass while self.service_name in svc_list: svc_list.remove(self.service_name) with open(paths.SVC_LIST_FILE, 'w') as f: json.dump(svc_list, f) def reload_or_restart(self, instance_name="", capture_output=True, wait=True): pass def restart(self, instance_name="", capture_output=True, wait=True): pass def try_restart(self, instance_name="", capture_output=True, wait=True): pass def is_running(self, instance_name="", wait=True): return False def is_installed(self): return False def is_enabled(self, instance_name=""): return False def is_masked(self, instance_name=""): return False def enable(self, instance_name=""): pass def disable(self, instance_name=""): pass def mask(self, instance_name=""): pass def unmask(self, instance_name=""): pass def install(self, instance_name=""): pass def remove(self, instance_name=""): pass class SystemdService(PlatformService): SYSTEMD_SRV_TARGET = "%s.target.wants" def __init__(self, service_name, systemd_name, api=None): super(SystemdService, self).__init__(service_name, api=api) self.systemd_name = systemd_name self.lib_path = os.path.join(paths.LIB_SYSTEMD_SYSTEMD_DIR, self.systemd_name) self.lib_path_exists = None def service_instance(self, instance_name, operation=None): if self.lib_path_exists is None: self.lib_path_exists = os.path.exists(self.lib_path) elements = self.systemd_name.split("@") # Make sure the correct DS instance is returned if elements[0] == 'dirsrv' and not instance_name: return ('dirsrv@%s.service' % str(self.api.env.realm.replace('.', '-'))) # Short-cut: if there is already exact service name, return it if self.lib_path_exists and instance_name: if len(elements) == 1: # service name is like pki-tomcatd.target or krb5kdc.service return self.systemd_name if len(elements) > 1 and elements[1][0] != '.': # Service name is like pki-tomcatd@pki-tomcat.service # and that file exists return self.systemd_name if len(elements) > 1: # We have dynamic service if instance_name: # Instanciate dynamic service return "%s@%s.service" % (elements[0], instance_name) else: # No instance name, try with target tgt_name = "%s.target" % (elements[0]) srv_lib = os.path.join(paths.LIB_SYSTEMD_SYSTEMD_DIR, tgt_name) if os.path.exists(srv_lib): return tgt_name return self.systemd_name def parse_variables(self, text, separator=None): """ Parses 'systemctl show' output and returns a dict[variable]=value Arguments: text -- 'systemctl show' output as string separator -- optional (defaults to None), what separates the key/value pairs in the text """ def splitter(x, separator=None): if len(x) > 1: y = x.split(separator) return (y[0], y[-1]) return (None, None) return dict(splitter(x, separator=separator) for x in text.split("\n")) def wait_for_open_ports(self, instance_name=""): """ If this is a service we need to wait for do so. """ ports = None if instance_name in wellknownports: ports = wellknownports[instance_name] else: elements = self.systemd_name.split("@") if elements[0] in wellknownports: ports = wellknownports[elements[0]] if ports: ipautil.wait_for_open_ports('localhost', ports, self.api.env.startup_timeout) def stop(self, instance_name="", capture_output=True): instance = self.service_instance(instance_name) args = [paths.SYSTEMCTL, "stop", instance] # The --ignore-dependencies switch is used to avoid possible # deadlock during the shutdown transaction. For more details, see # https://fedorahosted.org/freeipa/ticket/3729#comment:1 and # https://bugzilla.redhat.com/show_bug.cgi?id=973331#c11 if instance == "ipa-otpd.socket": args.append("--ignore-dependencies") # ipa-ods-exporter is socket-activated, both the service and the # socket have to be stopped if instance == "ipa-ods-exporter.service": args.append("ipa-ods-exporter.socket") ipautil.run(args, skip_output=not capture_output) update_service_list = getattr(self.api.env, 'context', None) in ['ipactl', 'installer'] super(SystemdService, self).stop( instance_name, update_service_list=update_service_list) logger.debug('Stop of %s complete', instance) def start(self, instance_name="", capture_output=True, wait=True): ipautil.run([paths.SYSTEMCTL, "start", self.service_instance(instance_name)], skip_output=not capture_output) update_service_list = getattr(self.api.env, 'context', None) in ['ipactl', 'installer'] if wait and self.is_running(instance_name): self.wait_for_open_ports(self.service_instance(instance_name)) super(SystemdService, self).start( instance_name, update_service_list=update_service_list) logger.debug('Start of %s complete', self.service_instance(instance_name)) def _restart_base(self, instance_name, operation, capture_output=True, wait=False): ipautil.run([paths.SYSTEMCTL, operation, self.service_instance(instance_name)], skip_output=not capture_output) if wait and self.is_running(instance_name): self.wait_for_open_ports(self.service_instance(instance_name)) logger.debug('Restart of %s complete', self.service_instance(instance_name)) def reload_or_restart(self, instance_name="", capture_output=True, wait=True): self._restart_base(instance_name, "reload-or-restart", capture_output, wait) def restart(self, instance_name="", capture_output=True, wait=True): self._restart_base(instance_name, "restart", capture_output, wait) def try_restart(self, instance_name="", capture_output=True, wait=True): self._restart_base(instance_name, "try-restart", capture_output, wait) def is_running(self, instance_name="", wait=True): instance = self.service_instance(instance_name, 'is-active') while True: try: result = ipautil.run( [paths.SYSTEMCTL, "is-active", instance], capture_output=True ) except ipautil.CalledProcessError as e: if e.returncode == 3 and 'activating' in str(e.output): time.sleep(SERVICE_POLL_INTERVAL) continue return False else: # activating if result.returncode == 3 and 'activating' in result.output: time.sleep(SERVICE_POLL_INTERVAL) continue # active if result.returncode == 0: return True # not active return False def is_installed(self): try: result = ipautil.run( [paths.SYSTEMCTL, "list-unit-files", "--full"], capture_output=True) if result.returncode != 0: return False else: svar = self.parse_variables(result.output) if self.service_instance("") not in svar: # systemd doesn't show the service return False except ipautil.CalledProcessError: return False return True def is_enabled(self, instance_name=""): enabled = True try: result = ipautil.run( [paths.SYSTEMCTL, "is-enabled", self.service_instance(instance_name)]) if result.returncode != 0: enabled = False except ipautil.CalledProcessError: enabled = False return enabled def is_masked(self, instance_name=""): masked = False try: result = ipautil.run( [paths.SYSTEMCTL, "is-enabled", self.service_instance(instance_name)], capture_output=True) if result.returncode == 1 and result.output == 'masked': masked = True except ipautil.CalledProcessError: pass return masked def enable(self, instance_name=""): if self.lib_path_exists is None: self.lib_path_exists = os.path.exists(self.lib_path) elements = self.systemd_name.split("@") l = len(elements) if self.lib_path_exists and (l > 1 and elements[1][0] != '.'): # There is explicit service unit supporting this instance, # follow normal systemd enabler self.__enable(instance_name) return if self.lib_path_exists and (l == 1): # There is explicit service unit which does not support # the instances, ignore instance self.__enable() return if len(instance_name) > 0 and l > 1: # New instance, we need to do following: # 1. Make /etc/systemd/system/<service>.target.wants/ # if it is not there # 2. Link /etc/systemd/system/<service>.target.wants/ # <service>@<instance_name>.service to # /lib/systemd/system/<service>@.service srv_tgt = os.path.join(paths.ETC_SYSTEMD_SYSTEM_DIR, self.SYSTEMD_SRV_TARGET % (elements[0])) srv_lnk = os.path.join(srv_tgt, self.service_instance(instance_name)) try: if not os.path.isdir(srv_tgt): os.mkdir(srv_tgt) os.chmod(srv_tgt, 0o755) if os.path.exists(srv_lnk): # Remove old link os.unlink(srv_lnk) if not os.path.exists(srv_lnk): # object does not exist _or_ is a broken link if not os.path.islink(srv_lnk): # if it truly does not exist, make a link os.symlink(self.lib_path, srv_lnk) else: # Link exists and it is broken, make new one os.unlink(srv_lnk) os.symlink(self.lib_path, srv_lnk) tasks.systemd_daemon_reload() except Exception: pass else: self.__enable(instance_name) def disable(self, instance_name=""): elements = self.systemd_name.split("@") if instance_name != "" and len(elements) > 1: # Remove instance, we need to do following: # Remove link from /etc/systemd/system/<service>.target.wants/ # <service>@<instance_name>.service # to /lib/systemd/system/<service>@.service srv_tgt = os.path.join(paths.ETC_SYSTEMD_SYSTEM_DIR, self.SYSTEMD_SRV_TARGET % (elements[0])) srv_lnk = os.path.join(srv_tgt, self.service_instance(instance_name)) try: if os.path.isdir(srv_tgt): if os.path.islink(srv_lnk): os.unlink(srv_lnk) tasks.systemd_daemon_reload() except Exception: pass else: try: ipautil.run([paths.SYSTEMCTL, "disable", self.service_instance(instance_name)]) except ipautil.CalledProcessError: pass def mask(self, instance_name=""): srv_tgt = os.path.join(paths.ETC_SYSTEMD_SYSTEM_DIR, self.service_instance(instance_name)) if os.path.exists(srv_tgt): os.unlink(srv_tgt) try: ipautil.run([paths.SYSTEMCTL, "mask", self.service_instance(instance_name)]) except ipautil.CalledProcessError: pass def unmask(self, instance_name=""): try: ipautil.run([paths.SYSTEMCTL, "unmask", self.service_instance(instance_name)]) except ipautil.CalledProcessError: pass def __enable(self, instance_name=""): try: ipautil.run([paths.SYSTEMCTL, "enable", self.service_instance(instance_name)]) except ipautil.CalledProcessError: pass def install(self): self.enable() def remove(self): self.disable() # Objects below are expected to be exported by platform module def base_service_class_factory(name, api=None): raise NotImplementedError service = base_service_class_factory knownservices = KnownServices({}) # System may support more time&date services. FreeIPA supports chrony only. # Other services will be disabled during IPA installation timedate_services = ['ntpd', 'chronyd', 'systemd-timesyncd']
19,038
Python
.py
444
31.621622
98
0.583446
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,181
constants.py
freeipa_freeipa/ipaplatform/opencloudos/constants.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This OpenCloudOS family base platform module exports platform related constants. """ # Fallback to default path definitions from __future__ import absolute_import from ipaplatform.redhat.constants import RedHatConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class OpenCloudOSConstantsNamespace(RedHatConstantsNamespace): SECURE_NFS_VAR = None NAMED_OPENSSL_ENGINE = "pkcs11" constants = OpenCloudOSConstantsNamespace()
536
Python
.py
14
36.071429
80
0.80117
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,182
tasks.py
freeipa_freeipa/ipaplatform/opencloudos/tasks.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This module contains default OpenCloudOS family-specific implementations of system tasks. """ from __future__ import absolute_import from ipaplatform.redhat.tasks import RedHatTaskNamespace class OpenCloudOSTaskNamespace(RedHatTaskNamespace): pass tasks = OpenCloudOSTaskNamespace()
369
Python
.py
12
28.833333
75
0.837143
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,183
__init__.py
freeipa_freeipa/ipaplatform/opencloudos/__init__.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This module contains OpenCloudOS family-specific platform files. """ NAME = "opencloudos"
167
Python
.py
7
22.571429
66
0.78481
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,184
paths.py
freeipa_freeipa/ipaplatform/opencloudos/paths.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ This OpenCloudOS family base platform module exports default filesystem paths as common in OpenCloudOS family-based systems. """ from __future__ import absolute_import from ipaplatform.redhat.paths import RedHatPathNamespace class OpenCloudOSPathNamespace(RedHatPathNamespace): NAMED_CRYPTO_POLICY_FILE = "/etc/crypto-policies/back-ends/bind.config" SYSCONFIG_NFS = "/etc/nfs.conf" paths = OpenCloudOSPathNamespace()
507
Python
.py
13
36.846154
77
0.813142
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,185
services.py
freeipa_freeipa/ipaplatform/opencloudos/services.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ Contains OpenCloudOS family-specific service class implementations. """ from __future__ import absolute_import from ipaplatform.redhat import services as redhat_services # Mappings from service names as FreeIPA code references to these services # to their actual systemd service names opencloudos_system_units = redhat_services.redhat_system_units.copy() opencloudos_system_units["named"] = opencloudos_system_units["named-regular"] opencloudos_system_units["named-conflict"] = \ opencloudos_system_units["named-pkcs11"] # Service classes that implement OpenCloudOS family-specific behaviour class OpenCloudOSService(redhat_services.RedHatService): system_units = opencloudos_system_units # Function that constructs proper OpenCloudOS family-specific server classes # for services of specified name def opencloudos_service_class_factory(name, api=None): if name in ["named", "named-conflict"]: return OpenCloudOSService(name, api) return redhat_services.redhat_service_class_factory(name, api) # Magicdict containing OpenCloudOSService instances. class OpenCloudOSServices(redhat_services.RedHatServices): def service_class_factory(self, name, api=None): return opencloudos_service_class_factory(name, api) # Objects below are expected to be exported by platform module timedate_services = redhat_services.timedate_services service = opencloudos_service_class_factory knownservices = OpenCloudOSServices()
1,537
Python
.py
31
46.774194
77
0.812248
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,186
constants.py
freeipa_freeipa/ipaplatform/rhel_container/constants.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """RHEL container constants """ from ipaplatform.rhel.constants import RHELConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class RHELContainerConstantsNamespace(RHELConstantsNamespace): pass constants = RHELContainerConstantsNamespace()
343
Python
.py
10
32.3
74
0.804281
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,187
tasks.py
freeipa_freeipa/ipaplatform/rhel_container/tasks.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """RHEL container tasks """ import logging from ipaplatform.rhel.tasks import RHELTaskNamespace logger = logging.getLogger(__name__) class RHELContainerTaskNamespace(RHELTaskNamespace): def modify_nsswitch_pam_stack( self, sssd, mkhomedir, statestore, sudo=True, subid=False ): # freeipa-container images are preconfigured # authselect select sssd with-sudo --force logger.debug("Authselect is pre-configured in container images.") def is_mkhomedir_supported(self): # authselect is not pre-configured with mkhomedir return False def restore_auth_configuration(self, path): # backup is supported but restore is a no-op logger.debug("Authselect is pre-configured in container images.") def migrate_auth_configuration(self, statestore): logger.debug("Authselect is pre-configured in container images.") tasks = RHELContainerTaskNamespace()
1,010
Python
.py
24
36.833333
73
0.742828
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,188
__init__.py
freeipa_freeipa/ipaplatform/rhel_container/__init__.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ This module contains RHEL Container specific platform files. """ NAME = "rhel_container"
164
Python
.py
7
22.428571
66
0.77707
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,189
paths.py
freeipa_freeipa/ipaplatform/rhel_container/paths.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """RHEL container paths """ import os from ipaplatform.rhel.paths import RHELPathNamespace def data(path): return os.path.join("/data", path[1:]) class RHELContainerPathNamespace(RHELPathNamespace): KRB5_CONF = data(RHELPathNamespace.KRB5_CONF) KRB5_KEYTAB = data(RHELPathNamespace.KRB5_KEYTAB) NAMED_KEYTAB = data(RHELPathNamespace.NAMED_KEYTAB) NAMED_CUSTOM_CONF = data(RHELPathNamespace.NAMED_CUSTOM_CONF) NAMED_CUSTOM_OPTIONS_CONF = data( RHELPathNamespace.NAMED_CUSTOM_OPTIONS_CONF ) NAMED_LOGGING_OPTIONS_CONF = data( RHELPathNamespace.NAMED_LOGGING_OPTIONS_CONF ) NSSWITCH_CONF = data(RHELPathNamespace.NSSWITCH_CONF) PKI_CONFIGURATION = data(RHELPathNamespace.PKI_CONFIGURATION) SAMBA_DIR = data(RHELPathNamespace.SAMBA_DIR) HTTPD_IPA_WSGI_MODULES_CONF = None HTTPD_PASSWD_FILE_FMT = data(RHELPathNamespace.HTTPD_PASSWD_FILE_FMT) # In some contexts, filesystem mounts may be owned by unmapped users # (e.g. "emptyDir" mounts in Kubernetes / OpenShift when using user # namespaces). This causes systemd-tmpfiles(8) to fail, as a # consequence of systemd's path processing routines which reject # this scenario. Therefore we provide a way to substitute # systemd-tmpfiles with a "clone" program. # SYSTEMD_TMPFILES = os.environ.get( 'IPA_TMPFILES_PROG', RHELPathNamespace.SYSTEMD_TMPFILES) paths = RHELContainerPathNamespace()
1,526
Python
.py
35
39.171429
73
0.755226
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,190
services.py
freeipa_freeipa/ipaplatform/rhel_container/services.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """RHEL container services """ from ipaplatform.rhel import services as rhel_services rhel_container_system_units = rhel_services.rhel_system_units.copy() class RHELContainerService(rhel_services.RHELService): system_units = rhel_container_system_units def rhel_container_service_class_factory(name, api=None): return rhel_services.rhel_service_class_factory(name, api) class RHELContainerServices(rhel_services.RHELServices): def service_class_factory(self, name, api=None): return rhel_container_service_class_factory(name, api) timedate_services = rhel_services.timedate_services service = rhel_container_service_class_factory knownservices = RHELContainerServices()
771
Python
.py
17
42.588235
68
0.80914
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,191
constants.py
freeipa_freeipa/ipaplatform/fedora_container/constants.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Fedora container constants """ from ipaplatform.fedora.constants import FedoraConstantsNamespace, User, Group __all__ = ("constants", "User", "Group") class FedoraContainerConstantsNamespace(FedoraConstantsNamespace): pass constants = FedoraContainerConstantsNamespace()
355
Python
.py
10
33.5
78
0.811209
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,192
tasks.py
freeipa_freeipa/ipaplatform/fedora_container/tasks.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Fedora container tasks """ import logging from ipaplatform.fedora.tasks import FedoraTaskNamespace logger = logging.getLogger(__name__) class FedoraContainerTaskNamespace(FedoraTaskNamespace): def modify_nsswitch_pam_stack( self, sssd, mkhomedir, statestore, sudo=True, subid=False ): # freeipa-container images are preconfigured # authselect select sssd with-sudo --force logger.debug("Authselect is pre-configured in container images.") def is_mkhomedir_supported(self): # authselect is not pre-configured with mkhomedir return False def restore_auth_configuration(self, path): # backup is supported but restore is a no-op logger.debug("Authselect is pre-configured in container images.") def migrate_auth_configuration(self, statestore): logger.debug("Authselect is pre-configured in container images.") tasks = FedoraContainerTaskNamespace()
1,022
Python
.py
24
37.333333
73
0.745951
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,193
__init__.py
freeipa_freeipa/ipaplatform/fedora_container/__init__.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ This module contains Fedora Container specific platform files. """ NAME = "fedora_container"
168
Python
.py
7
23
66
0.782609
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,194
paths.py
freeipa_freeipa/ipaplatform/fedora_container/paths.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Fedora container paths """ import os from ipaplatform.fedora.paths import FedoraPathNamespace def data(path): return os.path.join("/data", path[1:]) class FedoraContainerPathNamespace(FedoraPathNamespace): KRB5_CONF = data(FedoraPathNamespace.KRB5_CONF) KRB5_KEYTAB = data(FedoraPathNamespace.KRB5_KEYTAB) NAMED_KEYTAB = data(FedoraPathNamespace.NAMED_KEYTAB) NAMED_CUSTOM_CONF = data(FedoraPathNamespace.NAMED_CUSTOM_CONF) NAMED_CUSTOM_OPTIONS_CONF = data( FedoraPathNamespace.NAMED_CUSTOM_OPTIONS_CONF ) NAMED_LOGGING_OPTIONS_CONF = data( FedoraPathNamespace.NAMED_LOGGING_OPTIONS_CONF ) NSSWITCH_CONF = data(FedoraPathNamespace.NSSWITCH_CONF) PKI_CONFIGURATION = data(FedoraPathNamespace.PKI_CONFIGURATION) SAMBA_DIR = data(FedoraPathNamespace.SAMBA_DIR) HTTPD_IPA_WSGI_MODULES_CONF = None HTTPD_PASSWD_FILE_FMT = data(FedoraPathNamespace.HTTPD_PASSWD_FILE_FMT) # In some contexts, filesystem mounts may be owned by unmapped users # (e.g. "emptyDir" mounts in Kubernetes / OpenShift when using user # namespaces). This causes systemd-tmpfiles(8) to fail, as a # consequence of systemd's path processing routines which reject # this scenario. Therefore we provide a way to substitute # systemd-tmpfiles with a "clone" program. # SYSTEMD_TMPFILES = os.environ.get( 'IPA_TMPFILES_PROG', FedoraPathNamespace.SYSTEMD_TMPFILES) paths = FedoraContainerPathNamespace()
1,560
Python
.py
35
40.142857
75
0.760712
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,195
services.py
freeipa_freeipa/ipaplatform/fedora_container/services.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Fedora container services """ from ipaplatform.fedora import services as fedora_services fedora_container_system_units = fedora_services.fedora_system_units.copy() class FedoraContainerService(fedora_services.FedoraService): system_units = fedora_container_system_units def fedora_container_service_class_factory(name, api=None): return fedora_services.fedora_service_class_factory(name, api) class FedoraContainerServices(fedora_services.FedoraServices): def service_class_factory(self, name, api=None): return fedora_container_service_class_factory(name, api) timedate_services = fedora_services.timedate_services service = fedora_container_service_class_factory knownservices = FedoraContainerServices()
811
Python
.py
17
44.941176
74
0.818878
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,196
constants.py
freeipa_freeipa/ipaplatform/redhat/constants.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # ''' This Red Hat OS family base platform module exports default platform 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, User, Group __all__ = ("constants", "User", "Group") class RedHatConstantsNamespace(BaseConstantsNamespace): # Use system-wide crypto policy # see https://fedoraproject.org/wiki/Changes/CryptoPolicy TLS_HIGH_CIPHERS = None constants = RedHatConstantsNamespace()
631
Python
.py
16
37.125
74
0.793729
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,197
tasks.py
freeipa_freeipa/ipaplatform/redhat/tasks.py
# Authors: Simo Sorce <ssorce@redhat.com> # Alexander Bokovoy <abokovoy@redhat.com> # Martin Kosek <mkosek@redhat.com> # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2007-2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains default Red Hat OS family-specific implementations of system tasks. ''' from __future__ import print_function, absolute_import import ctypes import logging import os from pathlib import Path import socket import traceback import errno import urllib import subprocess import sys import textwrap from ctypes.util import find_library from functools import total_ordering from subprocess import CalledProcessError from pyasn1.error import PyAsn1Error from ipapython import directivesetter from ipapython import ipautil import ipapython.errors from ipaplatform.constants import constants from ipaplatform.paths import paths from ipaplatform.redhat.authconfig import get_auth_tool from ipaplatform.base.tasks import BaseTaskNamespace logger = logging.getLogger(__name__) # /etc/pkcs11/modules override # base filename, module, list of disabled-in # 'p11-kit-proxy' disables proxying of module, see man(5) pkcs11.conf PKCS11_MODULES = [ ('softhsm2', paths.LIBSOFTHSM2_SO, ['p11-kit-proxy']), ] NM_IPA_CONF = textwrap.dedent(""" # auto-generated by IPA installer [main] dns={dnsprocessing} [global-dns] searches={searches} [global-dns-domain-*] servers={servers} """) @total_ordering class IPAVersion: _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 def __eq__(self, other): if not isinstance(other, IPAVersion): return NotImplemented return self._rpmvercmp(self._bytes, other._bytes) == 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) class RedHatTaskNamespace(BaseTaskNamespace): def restore_context(self, filepath, force=False): """Restore SELinux security context on the given filepath. 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 self.is_selinux_enabled() or not os.path.exists(restorecon): 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) def is_selinux_enabled(self): """Check if SELinux is available and enabled """ try: ipautil.run([paths.SELINUXENABLED]) except ipautil.CalledProcessError: # selinuxenabled returns 1 if not enabled return False except OSError: # selinuxenabled binary not available return False else: return True def check_selinux_status(self, restorecon=paths.RESTORECON): """ We don't have a specific package requirement for policycoreutils which provides restorecon. This is because we don't require SELinux on client installs. However if SELinux is enabled then this package is required. This function returns nothing but may raise a Runtime exception if SELinux is enabled but restorecon is not available. """ if not self.is_selinux_enabled(): return False if not os.path.exists(restorecon): raise RuntimeError('SELinux is enabled but %s does not exist.\n' 'Install the policycoreutils package and start ' 'the installation again.' % restorecon) return True 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.") 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 detect_container(self): """Check if running inside a container :returns: container runtime or None :rtype: str, None """ try: output = subprocess.check_output( [paths.SYSTEMD_DETECT_VIRT, '--container'], stderr=subprocess.STDOUT ) except subprocess.CalledProcessError as e: if e.returncode == 1: # No container runtime detected return None else: raise else: return output.decode('utf-8').strip() 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 ) 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) def modify_nsswitch_pam_stack(self, sssd, mkhomedir, statestore, sudo=True, subid=False): auth_config = get_auth_tool() auth_config.configure(sssd, mkhomedir, statestore, sudo, subid) def is_nosssd_supported(self): # The flag --no-sssd is not supported any more for rhel-based distros return False def backup_auth_configuration(self, path): auth_config = get_auth_tool() auth_config.backup(path) def restore_auth_configuration(self, path): auth_config = get_auth_tool() 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( "Could not update systemwide CA trust database: %s", e) return False else: logger.info("Systemwide CA database updated.") return True def platform_insert_ca_certs(self, ca_certs): return any([ self.write_p11kit_certs(paths.IPA_P11_KIT, ca_certs), self.remove_ca_certificates_bundle( paths.SYSTEMWIDE_IPA_CA_CRT ), ]) def write_p11kit_certs(self, filename, 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 path = Path(filename) try: f = open(path, 'w') except IOError: logger.error("Failed to open %s", path) raise with f: f.write("# This file was created by IPA. Do not edit.\n" "\n") try: os.fchmod(f.fileno(), 0o644) except IOError: logger.error("Failed to set mode of %s", path) raise has_eku = set() 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): logger.error( "Failed to decode certificate \"%s\"", nickname) raise label = urllib.parse.quote(nickname) subject = urllib.parse.quote(subject) issuer = urllib.parse.quote(issuer) serial_number = urllib.parse.quote(serial_number) public_key_info = urllib.parse.quote(public_key_info) obj = ("[p11-kit-object-v1]\n" "class: certificate\n" "certificate-type: x-509\n" "certificate-category: authority\n" "label: \"%(label)s\"\n" "subject: \"%(subject)s\"\n" "issuer: \"%(issuer)s\"\n" "serial-number: \"%(serial_number)s\"\n" "x-public-key-info: \"%(public_key_info)s\"\n" % dict(label=label, subject=subject, issuer=issuer, serial_number=serial_number, public_key_info=public_key_info)) if trusted is True: 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')) f.write(obj) if (cert.extended_key_usage is not None and public_key_info not in has_eku): try: ext_key_usage = cert.extended_key_usage_bytes except PyAsn1Error: logger.error( "Failed to encode extended key usage for \"%s\"", nickname) raise value = urllib.parse.quote(ext_key_usage) obj = ("[p11-kit-object-v1]\n" "class: x-certificate-extension\n" "label: \"ExtendedKeyUsage for %(label)s\"\n" "x-public-key-info: \"%(public_key_info)s\"\n" "object-id: 2.5.29.37\n" "value: \"%(value)s\"\n\n" % dict(label=label, public_key_info=public_key_info, value=value)) f.write(obj) has_eku.add(public_key_info) return True def platform_remove_ca_certs(self): return any([ self.remove_ca_certificates_bundle(paths.IPA_P11_KIT), self.remove_ca_certificates_bundle(paths.SYSTEMWIDE_IPA_CA_CRT), ]) def remove_ca_certificates_bundle(self, filename): path = Path(filename) if not path.is_file(): return False try: path.unlink() except Exception: logger.error("Could not remove %s", path) raise return True def backup_hostname(self, fstore, statestore): filepath = paths.ETC_HOSTNAME if os.path.exists(filepath): fstore.backup_file(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') 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 ) filepath = paths.ETC_HOSTNAME if fstore.has_file(filepath): fstore.restore_file(filepath) def set_selinux_booleans(self, required_settings, backup_func=None): def get_setsebool_args(changes): args = [paths.SETSEBOOL, "-P"] args.extend(["%s=%s" % update for update in changes.items()]) return args if not self.is_selinux_enabled(): return False updated_vars = {} failed_vars = {} for setting, state in required_settings.items(): if state is None: continue try: result = ipautil.run( [paths.GETSEBOOL, setting], capture_output=True ) original_state = result.output.split()[2] if backup_func is not None: backup_func(setting, original_state) if original_state != state: updated_vars[setting] = state except ipautil.CalledProcessError as e: logger.error("Cannot get SELinux boolean '%s': %s", setting, e) failed_vars[setting] = state if updated_vars: args = get_setsebool_args(updated_vars) try: ipautil.run(args) except ipautil.CalledProcessError: failed_vars.update(updated_vars) if failed_vars: raise ipapython.errors.SetseboolError( failed=failed_vars, command=' '.join(get_setsebool_args(failed_vars))) return True def parse_ipa_version(self, version): """ :param version: textual version :return: object implementing proper __cmp__ method for version compare """ 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) self.systemd_daemon_reload() def systemd_daemon_reload(self): """Tell systemd to reload config files""" ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"]) def configure_http_gssproxy_conf(self, ipauser): ipautil.copy_template_file( os.path.join(paths.USR_SHARE_IPA_DIR, 'gssproxy.conf.template'), paths.GSSPROXY_CONF, dict( HTTP_KEYTAB=paths.HTTP_KEYTAB, HTTPD_USER=constants.HTTPD_USER, IPAAPI_USER=ipauser, SWEEPER_SOCKET=paths.IPA_CCACHE_SWEEPER_GSSPROXY_SOCK, ) ) 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 self.systemd_daemon_reload() def configure_httpd_protocol(self): # use default crypto policy for SSLProtocol directivesetter.set_directive( paths.HTTPD_SSL_CONF, 'SSLProtocol', None, 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) def configure_dns_resolver(self, nameservers, searchdomains, *, resolve1_enabled=False, fstore=None): """Configure global DNS resolver (e.g. /etc/resolv.conf) :param nameservers: list of IP addresses :param searchdomains: list of search domaons :param fstore: optional file store for backup """ assert nameservers and isinstance(nameservers, list) assert searchdomains and isinstance(searchdomains, list) super().configure_dns_resolver( nameservers=nameservers, searchdomains=searchdomains, resolve1_enabled=resolve1_enabled, fstore=fstore ) # break circular import from ipaplatform.services import knownservices if fstore is not None and not fstore.has_file(paths.RESOLV_CONF): fstore.backup_file(paths.RESOLV_CONF) nm = knownservices['NetworkManager'] nm_enabled = nm.is_enabled() if nm_enabled: logger.debug( "Network Manager is enabled, write %s", paths.NETWORK_MANAGER_IPA_CONF ) # write DNS override and reload network manager to have it create # a new resolv.conf. The file is prefixed with ``zzz`` to # make it the last file. Global dns options do not stack and last # man standing wins. if resolve1_enabled: # push DNS configuration to systemd-resolved dnsprocessing = "systemd-resolved" else: # update /etc/resolv.conf dnsprocessing = "default" cfg = NM_IPA_CONF.format( dnsprocessing=dnsprocessing, servers=','.join(nameservers), searches=','.join(searchdomains) ) with open(paths.NETWORK_MANAGER_IPA_CONF, 'w') as f: os.fchmod(f.fileno(), 0o644) f.write(cfg) # reload NetworkManager nm.reload_or_restart() if not resolve1_enabled and not nm_enabled: # no NM running, no systemd-resolved detected # fall back to /etc/resolv.conf logger.debug( "Neither Network Manager nor systemd-resolved are enabled, " "write %s directly.", paths.RESOLV_CONF ) cfg = [ "# auto-generated by IPA installer", "search {}".format(' '.join(searchdomains)), ] for nameserver in nameservers: cfg.append("nameserver {}".format(nameserver)) with open(paths.RESOLV_CONF, 'w') as f: f.write('\n'.join(cfg)) def unconfigure_dns_resolver(self, fstore=None): """Unconfigure global DNS resolver (e.g. /etc/resolv.conf) :param fstore: optional file store for restore """ super().unconfigure_dns_resolver(fstore=fstore) # break circular import from ipaplatform.services import knownservices nm = knownservices['NetworkManager'] if os.path.isfile(paths.NETWORK_MANAGER_IPA_CONF): os.unlink(paths.NETWORK_MANAGER_IPA_CONF) if nm.is_enabled(): nm.reload_or_restart() def configure_pkcs11_modules(self, fstore): """Disable global p11-kit configuration for NSS """ filenames = [] for name, module, disabled_in in PKCS11_MODULES: filename = os.path.join( paths.ETC_PKCS11_MODULES_DIR, "{}.module".format(name) ) if os.path.isfile(filename): # Only back up if file is not yet backed up and it does not # look like a file that is generated by IPA. with open(filename) as f: content = f.read() is_ipa_file = "IPA" in content if not is_ipa_file and not fstore.has_file(filename): logger.debug("Backing up existing '%s'.", filename) fstore.backup_file(filename) with open(filename, "w") as f: f.write("# created by IPA installer\n") f.write("module: {}\n".format(module)) # see man(5) pkcs11.conf f.write("disable-in: {}\n".format(", ".join(disabled_in))) os.fchmod(f.fileno(), 0o644) self.restore_context(filename) logger.debug("Created PKCS#11 module config '%s'.", filename) filenames.append(filename) return filenames def restore_pkcs11_modules(self, fstore): """Restore global p11-kit configuration for NSS """ filenames = [] for name, _module, _disabled_in in PKCS11_MODULES: filename = os.path.join( paths.ETC_PKCS11_MODULES_DIR, "{}.module".format(name) ) try: os.unlink(filename) except OSError: pass else: filenames.append(filename) if fstore.has_file(filename): fstore.restore_file(filename) return filenames def get_pkcs11_modules(self): """Return the list of module config files setup by IPA """ return tuple(os.path.join(paths.ETC_PKCS11_MODULES_DIR, "{}.module".format(name)) for name, _module, _disabled in PKCS11_MODULES) def enable_sssd_sudo(self, _fstore): """sudo enablement is handled by authselect""" def disable_ldap_automount(self, statestore): """Disable ldap-based automount""" super(RedHatTaskNamespace, self).disable_ldap_automount(statestore) authselect_cmd = [paths.AUTHSELECT, "disable-feature", "with-custom-automount"] try: ipautil.run(authselect_cmd) except ipautil.CalledProcessError: logger.info("Unable to disable with-custom-automount feature") logger.info("It may happen if the configuration was done " "using authconfig instead of authselect") tasks = RedHatTaskNamespace()
28,073
Python
.py
654
30.792049
79
0.579221
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,198
__init__.py
freeipa_freeipa/ipaplatform/redhat/__init__.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' This module contains Red Hat OS family specific platform files. '''
842
Python
.py
21
39.047619
71
0.771951
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
17,199
paths.py
freeipa_freeipa/ipaplatform/redhat/paths.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ''' 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 from ipaplatform.base.paths import BasePathNamespace class RedHatPathNamespace(BasePathNamespace): CRYPTO_POLICY_OPENSSLCNF_FILE = ( '/etc/crypto-policies/back-ends/opensslcnf.config' ) # 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' NSSWITCH_CONF = '/etc/authselect/user-nsswitch.conf' paths = RedHatPathNamespace()
1,682
Python
.py
40
39.25
79
0.761934
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)