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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,800
|
fix_replica_agreements.py
|
freeipa_freeipa/ipaserver/install/plugins/fix_replica_agreements.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
import logging
from ipaserver.install import replication
from ipalib import Registry
from ipalib import Updater
from ipalib import errors
logger = logging.getLogger(__name__)
register = Registry()
EXCLUDE_TEMPLATE = '(objectclass=*) $ EXCLUDE %s'
@register()
class update_replica_attribute_lists(Updater):
"""
Run through all replication agreements and ensure that EXCLUDE list
has all the required attributes so that we don't cause replication
storms.
"""
def execute(self, **options):
# We need an LDAPClient connection to the backend
logger.debug("Start replication agreement exclude list update task")
# Find suffixes
suffixes = self.api.Command.topologysuffix_find()['result']
for suffix in suffixes:
suffix_name = suffix['cn'][0]
# Find segments
sgmts = self.api.Command.topologysegment_find(
suffix_name, all=True)['result']
for segment in sgmts:
updates = {}
updates = self._update_attr(
segment, updates,
'nsds5replicatedattributelist',
replication.EXCLUDES, template=EXCLUDE_TEMPLATE)
updates = self._update_attr(
segment, updates,
'nsds5replicatedattributelisttotal',
replication.TOTAL_EXCLUDES, template=EXCLUDE_TEMPLATE)
updates = self._update_attr(
segment, updates,
'nsds5replicastripattrs', replication.STRIP_ATTRS)
if updates:
try:
self.api.Command.topologysegment_mod(
suffix_name, segment['cn'][0],
**updates)
except errors.EmptyModlist:
# No update done
logger.debug("No update required for the segment %s",
segment['cn'][0])
logger.debug("Done updating agreements")
return False, [] # No restart, no updates
def _update_attr(self, segment, updates, attribute, values, template='%s'):
"""Add or update an attribute of a replication agreement
If the attribute doesn't already exist, it is added and set to
`template` with %s substituted by a space-separated `values`.
If the attribute does exist, `values` missing from it are just
appended to the end, also space-separated.
:param: updates: dict containing the updates
:param segment: dict containing segment information
:param attribute: Attribute to add or update
:param values: List of values the attribute should hold
:param template: Template to use when adding attribute
"""
attrlist = segment.get(attribute)
if attrlist is None:
logger.debug("Adding %s", attribute)
# Need to add it altogether
updates[attribute] = template % " ".join(values)
else:
attrlist_normalized = attrlist[0].lower().split()
missing = [a for a in values
if a.lower() not in attrlist_normalized]
if missing:
logger.debug("%s needs updating (missing: %s)", attribute,
', '.join(missing))
updates[attribute] = '%s %s' % (attrlist[0], ' '.join(missing))
else:
logger.debug("%s: No update necessary", attribute)
return updates
| 4,356
|
Python
|
.py
| 95
| 35.284211
| 79
| 0.620462
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,801
|
fix_kra_people_entry.py
|
freeipa_freeipa/ipaserver/install/plugins/fix_kra_people_entry.py
|
#
# Copyright (C) 2019 FreeIPA Contributors see COPYING for license
#
import logging
from ipalib import Registry, Updater, x509
from ipapython.dn import DN
from ipaplatform.paths import paths
from ipaserver.install import krainstance
logger = logging.getLogger(__name__)
register = Registry()
@register()
class fix_kra_people_entry(Updater):
"""
Update the KRA uid=ipakra agent user entry.
There was a bug where this was created with an incorrect
'description' attribute, breaking authentication:
https://pagure.io/freeipa/issue/8084.
"""
def execute(self, **options):
kra = krainstance.KRAInstance(self.api.env.realm)
if not kra.is_installed():
return False, []
cert = x509.load_certificate_from_file(paths.RA_AGENT_PEM)
entry = self.api.Backend.ldap2.get_entry(krainstance.KRA_AGENT_DN)
# check description attribute
description_values = entry.get('description', [])
if len(description_values) < 1:
# missing 'description' attribute is unexpected, but we can
# add it
do_fix = True
else:
# There should only be one value, so we will take the first value.
# But ignore the serial number when comparing, just in case.
description = description_values[0]
parts = description.split(';', 2) # see below for syntax
if len(parts) < 3:
do_fix = True # syntax error (not expected)
elif parts[2] != '{};{}'.format(DN(cert.issuer), DN(cert.subject)):
# issuer/subject does not match cert. THIS is the condition
# caused by issue 8084, which we want to fix.
do_fix = True
else:
do_fix = False # everything is fine
if do_fix:
# If other replicas have a different iteration of the IPA RA
# cert (e.g. renewal was triggered prematurely on some master
# and not on others) then authentication on those replicas will
# fail. But the 'description' attribute needed fixing because
# the issuer value was wrong, meaning authentication was broken
# on ALL replicas. So even for the corner case where different
# replicas have different IPA RA certs, updating the attribute
# will at least mean THIS replica can authenticate to the KRA.
logger.debug("Fixing KRA user entry 'description' attribute")
entry['description'] = [
'2;{};{};{}'.format(
cert.serial_number,
DN(cert.issuer),
DN(cert.subject)
)
]
self.api.Backend.ldap2.update_entry(entry)
return False, [] # don't restart DS; no LDAP updates to perform
| 2,868
|
Python
|
.py
| 62
| 36.064516
| 79
| 0.618553
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,802
|
update_pacs.py
|
freeipa_freeipa/ipaserver/install/plugins/update_pacs.py
|
# Authors:
# Tomas Babej <tbabej@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/>.
import logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_pacs(Updater):
"""
Includes default nfs:None only if no nfs: PAC present in ipakrbauthzdata.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
try:
dn = DN('cn=ipaConfig', 'cn=etc', self.api.env.basedn)
entry = ldap.get_entry(dn, ['ipakrbauthzdata'])
pacs = entry.get('ipakrbauthzdata', [])
except errors.NotFound:
logger.warning('Error retrieving: %s', str(dn))
return False, []
nfs_pac_set = any(pac.startswith('nfs:') for pac in pacs)
if not nfs_pac_set:
logger.debug('Adding nfs:NONE to default PAC types')
updated_pacs = pacs + [u'nfs:NONE']
entry['ipakrbauthzdata'] = updated_pacs
ldap.update_entry(entry)
else:
logger.debug('PAC for nfs is already set, not adding nfs:NONE.')
return False, []
| 1,877
|
Python
|
.py
| 47
| 34.595745
| 77
| 0.683168
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,803
|
update_uniqueness.py
|
freeipa_freeipa/ipaserver/install/plugins/update_uniqueness.py
|
# Authors:
# Alexander Bokovoy <abokovoy@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 logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_uniqueness_plugins_to_new_syntax(Updater):
"""
Migrate uniqueness plugins to new style syntax
* OLD: *
nsslapd-pluginarg0: uid
nsslapd-pluginarg1: dc=people,dc=example,dc=com
nsslapd-pluginarg2: dc=sales, dc=example,dc=com
or
nsslapd-pluginarg0: attribute=uid
nsslapd-pluginarg1: markerobjectclass=organizationalUnit
nsslapd-pluginarg2: requiredobjectclass=person
* NEW: *
uniqueness-attribute-name: uid
uniqueness-subtrees: dc=people,dc=example,dc=com
uniqueness-subtrees: dc=sales, dc=example,dc=com
uniqueness-across-all-subtrees: on
or
uniqueness-attribute-name: uid
uniqueness-top-entry-oc: organizationalUnit
uniqueness-subtree-entries-oc: person
"""
plugins_dn = DN(('cn', 'plugins'), ('cn', 'config'))
def __remove_update(self, update, key, value):
statement = dict(action='remove', attr=key, value=value)
update.setdefault('updates', []).append(statement)
def __add_update(self, update, key, value):
statement = dict(action='add', attr=key, value=value)
update.setdefault('updates', []).append(statement)
def __subtree_style(self, entry):
"""
old attr -> new attr
nsslapd-pluginArg0 -> uniqueness-attribute-name
nsslapd-pluginArg1..N -> uniqueness-subtrees[1..N]
"""
update = {
'dn': entry.dn,
'updates': [],
}
# nsslapd-pluginArg0 -> referint-update-delay
attribute = entry.single_value['nsslapd-pluginArg0']
if not attribute:
raise ValueError("'nsslapd-pluginArg0' not found")
self.__remove_update(update, 'nsslapd-pluginArg0', attribute)
self.__add_update(update, 'uniqueness-attribute-name', attribute)
entry['nsslapd-pluginArg0'] = None
# nsslapd-pluginArg1..N -> uniqueness-subtrees[1..N]
for key in entry.keys():
if key.lower().startswith('nsslapd-pluginarg'):
subtree_dn = entry.single_value[key]
if subtree_dn:
self.__remove_update(update, key, subtree_dn)
self.__add_update(update, 'uniqueness-subtrees', subtree_dn)
return update
def __objectclass_style(self, entry):
"""
old attr -> new attr
nsslapd-pluginArg?[attribute] -> uniqueness-attribute-name
nsslapd-pluginArg?[markerobjectclass] -> uniqueness-top-entry-oc
nsslapd-pluginArg?[requiredobjectclass](optional)
-> uniqueness-subtree-entries-oc
nsslapd-pluginArg?[others] -> ERROR: unexpected args
Single value attributes.
"""
update = {
'dn': entry.dn,
'updates': [],
}
attribute = None
markerobjectclass = None
requiredobjectclass = None
for key in entry.keys():
if key.lower().startswith('nsslapd-pluginarg'):
try:
# split argument name and value
value = entry.single_value[key]
arg_name, arg_val = value.split('=', 1)
except ValueError:
# unable to split
raise ValueError("unexpected argument %s: %s" %
(key, value))
arg_name = arg_name.lower()
if arg_name == 'attribute':
if attribute:
raise ValueError("single value argument 'attribute' "
"is specified mutliple times")
attribute = arg_val
self.__remove_update(update, key, value)
elif arg_name == 'markerobjectclass':
if markerobjectclass:
raise ValueError("single value argument "
"'markerobjectclass' "
"is specified mutliple times")
markerobjectclass = arg_val
self.__remove_update(update, key, value)
elif arg_name == 'requiredobjectclass':
if requiredobjectclass:
raise ValueError("single value argument "
"'requiredobjectclass' "
"is specified mutliple times")
requiredobjectclass = arg_val
self.__remove_update(update, key, value)
else:
raise ValueError("unexpected argument '%s: %s'" %
(key, value))
if not attribute:
raise ValueError("missing required argument 'attribute'")
if not markerobjectclass:
raise ValueError("missing required argument 'markerobjectclass'")
self.__add_update(update, 'uniqueness-attribute-name', attribute)
self.__add_update(update, 'uniqueness-top-entry-oc', markerobjectclass)
if requiredobjectclass:
# optional argument
self.__add_update(update, 'uniqueness-subtree-entries-oc',
requiredobjectclass)
return update
def execute(self, **options):
ldap = self.api.Backend.ldap2
old_style_plugin_search_filter = (
"(&"
"(objectclass=nsSlapdPlugin)"
"(nsslapd-pluginId=NSUniqueAttr)"
"(nsslapd-pluginPath=libattr-unique-plugin)"
"(nsslapd-pluginarg0=*)" # only entries with old configuration
")"
)
try:
entries, _truncated = ldap.find_entries(
filter=old_style_plugin_search_filter,
base_dn=self.plugins_dn,
)
except errors.NotFound:
logger.debug("No uniqueness plugin entries with old style "
"configuration found")
return False, []
update_list = []
new_attributes = [
'uniqueness-subtree-entries-oc',
'uniqueness-top-entry-oc',
'uniqueness-attribute-name',
'uniqueness-subtrees',
'uniqueness-across-all-subtrees',
]
for entry in entries:
# test for mixed configuration
if any(attr in entry for attr in new_attributes):
logger.critical("Mixed old and new style configuration "
"for plugin %s. Plugin will not work. "
"Skipping plugin migration, please fix it "
"manually",
entry.dn)
continue
logger.debug("Configuration of plugin %s will be migrated "
"to new style", entry.dn)
try:
# detect which configuration was used
arg0 = entry.get('nsslapd-pluginarg0')
if '=' in arg0:
update = self.__objectclass_style(entry)
else:
update = self.__subtree_style(entry)
except ValueError as e:
logger.error("Unable to migrate configuration of "
"plugin %s (%s)",
entry.dn, e)
else:
update_list.append(update)
return False, update_list
| 8,492
|
Python
|
.py
| 192
| 31.401042
| 80
| 0.564844
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,804
|
update_services.py
|
freeipa_freeipa/ipaserver/install/plugins/update_services.py
|
# Authors:
# Martin Kosek <mkosek@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/>.
import logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_service_principalalias(Updater):
"""
Update all services which do not have ipakrbprincipalalias attribute
used for case-insensitive principal searches filled. This applies for
all services created prior IPA 3.0.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
base_dn = DN(self.api.env.container_service, self.api.env.basedn)
search_filter = ("(&(objectclass=krbprincipal)(objectclass=ipaservice)"
"(!(objectclass=ipakrbprincipal)))")
logger.debug("update_service_principalalias: search for affected "
"services")
while True:
# run the search in loop to avoid issues when LDAP limits are hit
# during update
try:
(entries, truncated) = ldap.find_entries(search_filter,
['objectclass', 'krbprincipalname'], base_dn,
time_limit=0, size_limit=0)
except errors.NotFound:
logger.debug("update_service_principalalias: no service "
"to update found")
return False, []
except errors.ExecutionError as e:
logger.error("update_service_principalalias: cannot "
"retrieve list of affected services: %s", e)
return False, []
if not entries:
# no entry was returned, rather break than continue cycling
logger.debug("update_service_principalalias: no service "
"was returned")
return False, []
logger.debug("update_service_principalalias: found %d "
"services to update, truncated: %s",
len(entries), truncated)
error = False
for entry in entries:
entry['objectclass'] = (entry['objectclass'] +
['ipakrbprincipal'])
entry['ipakrbprincipalalias'] = entry['krbprincipalname']
try:
ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError as e:
logger.debug("update_service_principalalias: cannot "
"update service: %s", e)
error = True
if error:
# exit loop to avoid infinite cycles
logger.error("update_service_principalalias: error(s)"
"detected during service update")
return False, []
elif not truncated:
# all affected entries updated, exit the loop
logger.debug("update_service_principalalias: all affected"
" services updated")
return False, []
return False, []
| 3,930
|
Python
|
.py
| 85
| 34.023529
| 79
| 0.594418
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,805
|
upload_cacrt.py
|
freeipa_freeipa/ipaserver/install/plugins/upload_cacrt.py
|
# Authors:
# Alexander Bokovoy <abokovoy@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/>.
import logging
from ipalib.install import certstore
from ipaserver.install import certs, dsinstance
from ipapython.ipaldap import realm_to_serverid
from ipalib import Registry, errors
from ipalib import Updater
from ipapython import certdb
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_upload_cacrt(Updater):
"""
Upload public CA certificate to LDAP
"""
def execute(self, **options):
serverid = realm_to_serverid(self.api.env.realm)
db = certs.CertDB(self.api.env.realm,
nssdir=dsinstance.config_dirname(serverid))
ca_cert = None
ca_enabled = self.api.Command.ca_is_enabled()['result']
if ca_enabled:
ca_nickname = certdb.get_ca_nickname(self.api.env.realm)
ca_subject = certstore.get_ca_subject(
self.api.Backend.ldap2,
self.api.env.container_ca,
self.api.env.basedn)
else:
ca_nickname = None
server_certs = db.find_server_certs()
if server_certs:
ca_chain = db.find_root_cert(server_certs[0][0])[:-1]
if ca_chain:
ca_nickname = ca_chain[-1]
ldap = self.api.Backend.ldap2
for nickname, trust_flags in db.list_certs():
if trust_flags.has_key:
continue
cert = db.get_cert_from_db(nickname)
subject = cert.subject
if ca_enabled and subject == ca_subject:
# When ca is enabled, we can have the IPA CA cert stored
# in the nss db with a different nickname (for instance
# when the server was installed with --subject to
# customize the CA cert subject), but it must always be
# stored in LDAP with the DN cn=$DOMAIN IPA CA
# This is why we check the subject instead of the nickname here
nickname = ca_nickname
trust_flags = certdb.IPA_CA_TRUST_FLAGS
trust, _ca, eku = certstore.trust_flags_to_key_policy(trust_flags)
dn = DN(('cn', nickname), ('cn', 'certificates'), ('cn', 'ipa'),
('cn','etc'), self.api.env.basedn)
entry = ldap.make_entry(dn)
try:
certstore.init_ca_entry(entry, cert, nickname, trust, eku)
except Exception as e:
logger.warning("Failed to create entry for %s: %s",
nickname, e)
continue
if nickname == ca_nickname:
ca_cert = cert
config = entry.setdefault('ipaConfigString', [])
if ca_enabled:
config.append('ipaCa')
config.append('compatCA')
try:
ldap.add_entry(entry)
except errors.DuplicateEntry:
if nickname == ca_nickname and ca_enabled:
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
if ca_cert:
dn = DN(('cn', 'CACert'), ('cn', 'ipa'), ('cn','etc'),
self.api.env.basedn)
try:
entry = ldap.get_entry(dn)
except errors.NotFound:
entry = ldap.make_entry(dn)
entry['objectclass'] = ['nsContainer', 'pkiCA']
entry.single_value['cn'] = 'CAcert'
entry.single_value['cACertificate;binary'] = ca_cert
ldap.add_entry(entry)
else:
force_write = False
try:
_cert_bin = entry['cACertificate;binary']
except ValueError:
# BZ 1644874
# sometimes the cert is badly stored, twice encoded
# force write to fix the value
logger.debug('Fixing the value of cACertificate;binary '
'in entry %s', entry.dn)
force_write = True
if force_write or b'' in entry['cACertificate;binary']:
entry.single_value['cACertificate;binary'] = ca_cert
ldap.update_entry(entry)
return False, []
| 5,145
|
Python
|
.py
| 117
| 31.777778
| 79
| 0.570032
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,806
|
__init__.py
|
freeipa_freeipa/ipaserver/install/plugins/__init__.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
"""
Provide a separate api for updates.
"""
| 819
|
Python
|
.py
| 21
| 37.952381
| 71
| 0.770389
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,807
|
adtrust.py
|
freeipa_freeipa/ipaserver/install/plugins/adtrust.py
|
# Copyright (C) 2012-2019 FreeIPA Contributors see COPYING for license
import logging
from collections import namedtuple
from textwrap import dedent
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
from ipapython import ipautil
from ipaplatform.paths import paths
from ipaserver.install import service
from ipaserver.install import sysupgrade
from ipaserver.install.adtrustinstance import (
ADTRUSTInstance, map_Guests_to_nobody)
from ipaserver.dcerpc_common import TRUST_BIDIRECTIONAL
try:
from samba.ndr import ndr_unpack
from samba.dcerpc import lsa, drsblobs
except ImportError:
# If samba.ndr is not available, this machine is not provisioned
# for serving a trust to Active Directory. As result, it does
# not matter what ndr_unpack does but we save on pylint checks
def ndr_unpack(x):
raise NotImplementedError
drsblobs = None
logger = logging.getLogger(__name__)
register = Registry()
DEFAULT_ID_RANGE_SIZE = 200000
trust_read_keys_template = \
["cn=adtrust agents,cn=sysaccounts,cn=etc,{basedn}",
"cn=trust admins,cn=groups,cn=accounts,{basedn}"]
@register()
class update_default_range(Updater):
"""
Create default ID range for upgraded servers.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
dn = DN(self.api.env.container_ranges, self.api.env.basedn)
search_filter = "objectclass=ipaDomainIDRange"
try:
ldap.find_entries(search_filter, [], dn)
except errors.NotFound:
pass
else:
logger.debug("default_range: ipaDomainIDRange entry found, skip "
"plugin")
return False, []
dn = DN(('cn', 'admins'), self.api.env.container_group,
self.api.env.basedn)
try:
admins_entry = ldap.get_entry(dn, ['gidnumber'])
except errors.NotFound:
logger.error("default_range: No local ID range and no admins "
"group found. Cannot create default ID range")
return False, []
id_range_base_id = admins_entry['gidnumber'][0]
id_range_name = '%s_id_range' % self.api.env.realm
id_range_size = DEFAULT_ID_RANGE_SIZE
range_entry = [
dict(attr='objectclass', value='top'),
dict(attr='objectclass', value='ipaIDrange'),
dict(attr='objectclass', value='ipaDomainIDRange'),
dict(attr='cn', value=id_range_name),
dict(attr='ipabaseid', value=id_range_base_id),
dict(attr='ipaidrangesize', value=id_range_size),
dict(attr='iparangetype', value='ipa-local'),
]
dn = DN(('cn', '%s_id_range' % self.api.env.realm),
self.api.env.container_ranges, self.api.env.basedn)
update = {'dn': dn, 'default': range_entry}
# Default range entry has a hard-coded range size to 200000 which is
# a default range size in ipa-server-install. This could cause issues
# if user did not use a default range, but rather defined an own,
# bigger range (option --idmax).
# We should make our best to check if this is the case and provide
# user with an information how to fix it.
dn = DN(self.api.env.container_dna_posix_ids, self.api.env.basedn)
search_filter = "objectclass=dnaSharedConfig"
attrs = ['dnaHostname', 'dnaRemainingValues']
try:
(entries, _truncated) = ldap.find_entries(search_filter, attrs, dn)
except errors.NotFound:
logger.warning("default_range: no dnaSharedConfig object found. "
"Cannot check default range size.")
else:
masters = set()
remaining_values_sum = 0
for entry in entries:
hostname = entry.get('dnahostname', [None])[0]
if hostname is None or hostname in masters:
continue
remaining_values = entry.get('dnaremainingvalues', [''])[0]
try:
remaining_values = int(remaining_values)
except ValueError:
logger.warning("default_range: could not parse "
"remaining values from '%s'",
remaining_values)
continue
else:
remaining_values_sum += remaining_values
masters.add(hostname)
if remaining_values_sum > DEFAULT_ID_RANGE_SIZE:
msg = ['could not verify default ID range size',
'Please use the following command to set correct ID range size',
' $ ipa range-mod %s --range-size=RANGE_SIZE' % id_range_name,
'RANGE_SIZE may be computed from --idstart and --idmax options '
'used during IPA server installation:',
' RANGE_SIZE = (--idmax) - (--idstart) + 1'
]
logger.error("default_range: %s", "\n".join(msg))
return False, [update]
@register()
class update_default_trust_view(Updater):
"""
Create Default Trust View for upgraded servers.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
default_trust_view_dn = DN(('cn', 'Default Trust View'),
self.api.env.container_views,
self.api.env.basedn)
default_trust_view_entry = [
dict(attr='objectclass', value='top'),
dict(attr='objectclass', value='ipaIDView'),
dict(attr='cn', value='Default Trust View'),
dict(attr='description', value='Default Trust View for AD users. '
'Should not be deleted.'),
]
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
# Second, make sure the Default Trust View does not exist yet
try:
ldap.get_entry(default_trust_view_dn)
except errors.NotFound:
pass
else:
logger.debug('Default Trust View already present on this server')
return False, []
# We have a server with AD trust support without Default Trust View.
# Create the Default Trust View entry.
update = {
'dn': default_trust_view_dn,
'default': default_trust_view_entry
}
return False, [update]
@register()
class update_sigden_extdom_broken_config(Updater):
"""Fix configuration of sidgen and extdom plugins
Upgrade to IPA 4.2+ cause that sidgen and extdom plugins have improperly
configured basedn.
All trusts which have been added when config was broken must to be
re-added manually.
https://fedorahosted.org/freeipa/ticket/5665
"""
sidgen_config_dn = DN("cn=IPA SIDGEN,cn=plugins,cn=config")
extdom_config_dn = DN("cn=ipa_extdom_extop,cn=plugins,cn=config")
def _fix_config(self):
"""Due upgrade error configuration of sidgen and extdom plugins may
contain literally "$SUFFIX" value instead of real DN in nsslapd-basedn
attribute
:return: True if config was fixed, False if fix is not needed
"""
ldap = self.api.Backend.ldap2
basedn_attr = 'nsslapd-basedn'
modified = False
for dn in (self.sidgen_config_dn, self.extdom_config_dn):
try:
entry = ldap.get_entry(dn, attrs_list=[basedn_attr])
except errors.NotFound:
logger.debug("configuration for %s not found, skipping", dn)
else:
configured_suffix = entry.single_value.get(basedn_attr)
if configured_suffix is None:
raise RuntimeError(
"Missing attribute {attr} in {dn}".format(
attr=basedn_attr, dn=dn
)
)
elif configured_suffix == "$SUFFIX":
# configured value is wrong, fix it
entry.single_value[basedn_attr] = str(self.api.env.basedn)
logger.debug("updating attribute %s of %s to correct "
"value %s",
basedn_attr, dn, self.api.env.basedn)
ldap.update_entry(entry)
modified = True
else:
logger.debug("configured basedn for %s is okay", dn)
return modified
def execute(self, **options):
if sysupgrade.get_upgrade_state('sidgen', 'config_basedn_updated'):
logger.debug("Already done, skipping")
return False, ()
restart = False
if self._fix_config():
sysupgrade.set_upgrade_state('sidgen', 'update_sids', True)
restart = True # DS has to be restarted to apply changes
sysupgrade.set_upgrade_state('sidgen', 'config_basedn_updated', True)
return restart, ()
@register()
class update_sids(Updater):
"""SIDs may be not created properly if bug with wrong configuration for
sidgen and extdom plugins is effective
This must be run after "update_sigden_extdom_broken_config"
https://fedorahosted.org/freeipa/ticket/5665
"""
sidgen_config_dn = DN("cn=IPA SIDGEN,cn=plugins,cn=config")
def execute(self, **options):
ldap = self.api.Backend.ldap2
if sysupgrade.get_upgrade_state('sidgen', 'update_sids') is not True:
logger.debug("SIDs do not need to be generated")
return False, ()
# check if IPA domain for AD trust has been created, and if we need to
# regenerate missing SIDs if attribute 'ipaNTSecurityIdentifier'
domain_IPA_AD_dn = DN(
('cn', self.api.env.domain),
self.api.env.container_cifsdomains,
self.api.env.basedn)
attr_name = 'ipaNTSecurityIdentifier'
try:
entry = ldap.get_entry(domain_IPA_AD_dn, attrs_list=[attr_name])
except errors.NotFound:
logger.debug("IPA domain object %s is not configured",
domain_IPA_AD_dn)
sysupgrade.set_upgrade_state('sidgen', 'update_sids', False)
return False, ()
else:
if not entry.single_value.get(attr_name):
# we need to run sidgen task
sidgen_task_dn = DN(
"cn=generate domain sid,cn=ipa-sidgen-task,cn=tasks,"
"cn=config")
sidgen_tasks_attr = {
"objectclass": ["top", "extensibleObject"],
"cn": ["sidgen"],
"delay": [0],
"nsslapd-basedn": [self.api.env.basedn],
}
task_entry = ldap.make_entry(sidgen_task_dn,
**sidgen_tasks_attr)
try:
ldap.add_entry(task_entry)
except errors.DuplicateEntry:
logger.debug("sidgen task already created")
else:
logger.debug("sidgen task has been created")
# we have to check all trusts domains which may been affected by the
# bug. Symptom is missing 'ipaNTSecurityIdentifier' attribute
base_dn = DN(self.api.env.container_adtrusts, self.api.env.basedn)
try:
trust_domain_entries, truncated = ldap.find_entries(
base_dn=base_dn,
scope=ldap.SCOPE_ONELEVEL,
attrs_list=["cn"],
# more types of trusts can be stored under cn=trusts, we need
# the type with ipaNTTrustPartner attribute
filter="(&(ipaNTTrustPartner=*)(!(%s=*)))" % attr_name
)
except errors.NotFound:
pass
else:
if truncated:
logger.warning("update_sids: Search results were truncated")
for entry in trust_domain_entries:
domain = entry.single_value["cn"]
logger.error(
"Your trust to %s is broken. Please re-create it by "
"running 'ipa trust-add' again.", domain)
sysupgrade.set_upgrade_state('sidgen', 'update_sids', False)
return False, ()
def get_gidNumber(ldap, env):
# Read the gidnumber of the fallback group and returns a list with it
dn = DN(('cn', ADTRUSTInstance.FALLBACK_GROUP_NAME),
env.container_group,
env.basedn)
try:
entry = ldap.get_entry(dn, ['gidnumber'])
gidNumber = entry.get('gidnumber')
except errors.NotFound:
logger.error("%s not found",
ADTRUSTInstance.FALLBACK_GROUP_NAME)
return None
if gidNumber is None:
logger.error("%s does not have a gidnumber",
ADTRUSTInstance.FALLBACK_GROUP_NAME)
return None
return gidNumber
@register()
class update_tdo_gidnumber(Updater):
"""
Create a gidNumber attribute for Trusted Domain Objects.
The value is taken from the fallback group defined in cn=Default SMB Group.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
gidNumber = get_gidNumber(ldap, self.api.env)
if not gidNumber:
logger.error("%s does not have a gidnumber",
ADTRUSTInstance.FALLBACK_GROUP_NAME)
return False, ()
# For each trusted domain object, add posix attributes
# to allow use of a trusted domain account by AD DCs
# to authenticate against our Samba instance
try:
tdos = ldap.get_entries(
DN(self.api.env.container_adtrusts, self.api.env.basedn),
scope=ldap.SCOPE_ONELEVEL,
filter="(&(objectclass=ipaNTTrustedDomain)"
"(objectclass=ipaIDObject))",
attrs_list=['gidnumber', 'uidnumber', 'objectclass',
'ipantsecurityidentifier',
'ipaNTTrustDirection'
'uid', 'cn', 'ipantflatname'])
for tdo in tdos:
# if the trusted domain object does not contain gidnumber,
# add the default fallback group gidnumber
if not tdo.get('gidnumber'):
tdo['gidnumber'] = gidNumber
# Generate uidNumber and ipaNTSecurityIdentifier if
# uidNumber is missing. We rely on sidgen plugin here
# to generate ipaNTSecurityIdentifier.
if not tdo.get('uidnumber'):
tdo['uidnumber'] = ['-1']
if 'posixAccount' not in tdo.get('objectclass'):
tdo['objectclass'].extend(['posixAccount'])
# Based on the flat name of a TDO,
# add user name FLATNAME$ (note dollar sign)
# to allow SSSD to map this TDO to a POSIX account
if not tdo.get('uid'):
tdo['uid'] = ["{flatname}$".format(
flatname=tdo.single_value['ipantflatname'])]
if not tdo.get('homedirectory'):
tdo['homedirectory'] = ['/dev/null']
# Store resulted entry
try:
ldap.update_entry(tdo)
except errors.ExecutionError as e:
logger.warning(
"Failed to update trusted domain object %s", tdo.dn)
logger.debug("Exception during TDO update: %s", str(e))
except errors.NotFound:
logger.debug("No trusted domain object to update")
return False, ()
return False, ()
@register()
class update_mapping_Guests_to_nobody(Updater):
"""
Map BUILTIN\\Guests group to nobody
Samba 4.9 became more strict on availability of builtin Guests group
"""
def execute(self, **options):
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
map_Guests_to_nobody()
return False, []
@register()
class update_tdo_to_new_layout(Updater):
"""
Transform trusted domain objects into a new layout
There are now two Kerberos principals per direction of trust:
INBOUND:
- krbtgt/<OUR REALM>@<REMOTE REALM>, enabled by default
- <OUR FLATNAME$>@<REMOTE REALM>, disabled by default on our side
as it is only used by SSSD to retrieve TDO creds when operating
as an AD Trust agent across IPA topology
OUTBOUND:
- krbtgt/<REMOTE REALM>@<OUR REALM>, enabled by default
- <REMOTE FLATNAME$>@<OUR REALM>, enabled by default and
used by remote trusted DCs to authenticate against us
This principal also has krbtgt/<REMOTE FLATNAME>@<OUR REALM> defined
as a Kerberos principal alias. This is due to how Kerberos
key salt is derived for cross-realm principals on AD side
Finally, Samba requires <REMOTE FLATNAME$> account to also possess POSIX
and SMB identities. We ensure this by making the trusted domain object to
be this account with 'uid' and 'cn' attributes being '<REMOTE FLATNAME$>'
and uidNumber/gidNumber generated automatically. Also, we ensure the
trusted domain object is given a SID.
The update to <REMOTE FLATNAME$> POSIX/SMB identities is done through
the update plugin update_tdo_gidnumber.
"""
tgt_principal_template = "krbtgt/{remote}@{local}"
nbt_principal_template = "{nbt}$@{realm}"
trust_filter = \
"(&(objectClass=ipaNTTrustedDomain)(objectClass=ipaIDObject))"
trust_attrs = ("ipaNTFlatName", "ipaNTTrustPartner", "ipaNTTrustDirection",
"cn", "ipaNTTrustAttributes", "ipaNTAdditionalSuffixes",
"ipaNTTrustedDomainSID", "ipaNTTrustType",
"ipaNTTrustAuthIncoming", "ipaNTTrustAuthOutgoing")
change_password_template = \
"change_password -pw {password} " \
"-e aes256-cts-hmac-sha1-96,aes128-cts-hmac-sha1-96 " \
"{principal}"
KRB_PRINC_CREATE_DEFAULT = 0x00000000
KRB_PRINC_CREATE_DISABLED = 0x00000001
KRB_PRINC_CREATE_AGENT_PERMISSION = 0x00000002
KRB_PRINC_CREATE_IDENTITY = 0x00000004
KRB_PRINC_MUST_EXIST = 0x00000008
# This is a flag for krbTicketFlags attribute
# to disallow creating any tickets using this principal
KRB_DISALLOW_ALL_TIX = 0x00000040
def retrieve_trust_password(self, packed):
# The structure of the trust secret is described at
# https://github.com/samba-team/samba/blob/master/
# librpc/idl/drsblobs.idl#L516-L569
# In our case in LDAP TDO object stores
# `struct trustAuthInOutBlob` that has `count` and
# the `current` of `AuthenticationInformationArray` struct
# which has own `count` and `array` of `AuthenticationInformation`
# structs that have `AuthType` field which should be equal to
# `LSA_TRUST_AUTH_TYPE_CLEAR`.
# Then AuthInfo field would contain a password as an array of bytes
assert(packed.count != 0)
assert(packed.current.count != 0)
assert(packed.current.array[0].AuthType == lsa.TRUST_AUTH_TYPE_CLEAR)
clear_value = packed.current.array[0].AuthInfo.password
return ''.join(map(chr, clear_value))
def set_krb_principal(self, principals, password, trustdn, flags=None):
ldap = self.api.Backend.ldap2
if isinstance(principals, (list, tuple)):
trust_principal = principals[0]
alias = principals[1]
else:
trust_principal = principals
alias = None
entry = None
en = None
try:
entry = ldap.get_entry(
DN(('krbprincipalname', trust_principal), trustdn))
dn = entry.dn
action = ldap.update_entry
ticket_flags = int(entry.single_value.get('krbticketflags', 0))
logger.debug("Updating Kerberos principal entry for %s",
trust_principal)
except errors.NotFound:
# For a principal that must exist, we re-raise the exception
# to let the caller to handle this situation
if flags & self.KRB_PRINC_MUST_EXIST:
raise
ticket_flags = 0
if alias:
try:
en = ldap.get_entry(
DN(('krbprincipalname', alias), trustdn))
ldap.delete_entry(en.dn)
ticket_flags = int(en.single_value.get(
'krbticketflags', 0))
except errors.NotFound:
logger.debug("Entry for alias TDO does not exist for "
"trusted domain object %s, skip it",
alias)
dn = DN(('krbprincipalname', trust_principal), trustdn)
entry = ldap.make_entry(dn)
logger.debug("Adding Kerberos principal entry for %s",
trust_principal)
action = ldap.add_entry
entry_data = {
'objectclass':
['krbPrincipal', 'krbPrincipalAux',
'krbTicketPolicyAux', 'top'],
'krbcanonicalname': [trust_principal],
'krbprincipalname': [trust_principal],
}
if flags & self.KRB_PRINC_CREATE_DISABLED:
entry_data['krbticketflags'] = (ticket_flags |
self.KRB_DISALLOW_ALL_TIX)
if flags & self.KRB_PRINC_CREATE_AGENT_PERMISSION:
entry_data['objectclass'].extend(['ipaAllowedOperations'])
if alias:
entry_data['krbprincipalname'].extend([alias])
if en:
entry_data['krbprincipalkey'] = en.single_value.get(
'krbprincipalkey')
entry_data['krbextradata'] = en.single_value.get(
'krbextradata')
read_keys = en.get('ipaAllowedToPerform;read_keys', [])
if not read_keys:
# Old style, no ipaAllowedToPerform;read_keys in the entry,
# use defaults that ipasam should have set when creating a
# trust
read_keys = list(map(
lambda x: x.format(basedn=self.api.env.basedn),
trust_read_keys_template))
entry_data['ipaAllowedToPerform;read_keys'] = read_keys
entry.update(entry_data)
try:
action(entry)
except errors.EmptyModlist:
logger.debug("No update was required for Kerberos principal %s",
trust_principal)
# If entry existed, no need to set Kerberos keys on it
if action == ldap.update_entry:
logger.debug("No need to update Kerberos keys for "
"existing Kerberos principal %s",
trust_principal)
return
# Now that entry is updated, set its Kerberos keys.
#
# It would be a complication to use ipa-getkeytab LDAP extended control
# here because we would need to encode the request in ASN.1 sequence
# and we don't have the code to do so exposed in Python bindings.
# Instead, as we run on IPA master, we can use kadmin.local for that
# directly.
# We pass the command as a stdin to both avoid shell interpolation
# of the passwords and also to avoid its exposure to other processes
# Since we don't want to record the output, make also a redacted log
change_password = self.change_password_template.format(
password=password,
principal=trust_principal)
redacted = self.change_password_template.format(
password='<REDACTED OUT>',
principal=trust_principal)
logger.debug("Updating Kerberos keys for %s with the following "
"kadmin command:\n\t%s", trust_principal, redacted)
ipautil.run([paths.KADMIN_LOCAL, "-x",
"ipa-setup-override-restrictions"],
stdin=change_password, skip_output=True)
def execute(self, **options):
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
# If we have no Samba bindings, this master is not a trust controller
if drsblobs is None:
return False, []
ldap = self.api.Backend.ldap2
gidNumber = get_gidNumber(ldap, self.api.env)
if gidNumber is None:
return False, []
result = self.api.Command.trustconfig_show()['result']
our_nbt_name = result.get('ipantflatname', [None])[0]
if not our_nbt_name:
return False, []
trusts_dn = self.api.env.container_adtrusts + self.api.env.basedn
# We might be in a situation when no trusts exist yet
# In such case there is nothing to upgrade but we have to catch
# an exception or it will abort the whole upgrade process
try:
trusts = ldap.get_entries(
base_dn=trusts_dn,
scope=ldap.SCOPE_ONELEVEL,
filter=self.trust_filter,
attrs_list=self.trust_attrs)
except errors.EmptyResult:
trusts = []
# For every trust, retrieve its principals and convert
for t_entry in trusts:
t_dn = t_entry.dn
logger.debug('Processing trust domain object %s', str(t_dn))
t_realm = t_entry.single_value.get('ipaNTTrustPartner').upper()
direction = int(t_entry.single_value.get('ipaNTTrustDirection'))
passwd_incoming = self.retrieve_trust_password(
ndr_unpack(drsblobs.trustAuthInOutBlob,
t_entry.single_value.get('ipaNTTrustAuthIncoming')))
passwd_outgoing = self.retrieve_trust_password(
ndr_unpack(drsblobs.trustAuthInOutBlob,
t_entry.single_value.get('ipaNTTrustAuthOutgoing')))
# For outbound and inbound trusts, process four principals total
if (direction & TRUST_BIDIRECTIONAL) == TRUST_BIDIRECTIONAL:
# 1. OUTBOUND: krbtgt/<REMOTE REALM>@<OUR REALM> must exist
trust_principal = self.tgt_principal_template.format(
remote=t_realm, local=self.api.env.realm)
try:
self.set_krb_principal(trust_principal,
passwd_outgoing,
t_dn,
flags=self.KRB_PRINC_CREATE_DEFAULT)
except errors.NotFound:
# It makes no sense to convert this one, skip the trust
# completely, better to re-establish one
logger.error(
"Broken trust to AD: %s not found, "
"please re-establish the trust to %s",
trust_principal, t_realm)
continue
# 2. Create <REMOTE FLATNAME$>@<OUR REALM>
nbt_name = t_entry.single_value.get('ipaNTFlatName')
nbt_principal = self.nbt_principal_template.format(
nbt=nbt_name, realm=self.api.env.realm)
tgt_principal = self.tgt_principal_template.format(
remote=nbt_name, local=self.api.env.realm)
self.set_krb_principal([tgt_principal, nbt_principal],
passwd_incoming,
t_dn,
flags=self.KRB_PRINC_CREATE_DEFAULT)
# 3. INBOUND: krbtgt/<OUR REALM>@<REMOTE REALM> must exist
trust_principal = self.tgt_principal_template.format(
remote=self.api.env.realm, local=t_realm)
try:
self.set_krb_principal(trust_principal, passwd_outgoing,
t_dn,
flags=self.KRB_PRINC_CREATE_DEFAULT)
except errors.NotFound:
# It makes no sense to convert this one, skip the trust
# completely, better to re-establish one
logger.error(
"Broken trust to AD: %s not found, "
"please re-establish the trust to %s",
trust_principal, t_realm)
continue
# 4. Create krbtgt/<OUR FLATNAME>@<REMOTE REALM>, disabled
nbt_principal = self.nbt_principal_template.format(
nbt=our_nbt_name, realm=t_realm)
tgt_principal = self.tgt_principal_template.format(
remote=our_nbt_name, local=t_realm)
self.set_krb_principal([tgt_principal, nbt_principal],
passwd_incoming,
t_dn,
flags=self.KRB_PRINC_CREATE_DEFAULT |
self.KRB_PRINC_CREATE_AGENT_PERMISSION |
self.KRB_PRINC_CREATE_DISABLED)
return False, []
KeyEntry = namedtuple('KeyEntry',
['kvno', 'principal', 'etype', 'key'])
@register()
class update_host_cifs_keytabs(Updater):
"""Synchronize host keytab and Samba keytab
Samba needs access to host/domain.controller principal keys to allow
validation of DCE RPC requests sent by domain members since those use a
service ticket to host/domain.controller principal because in Active
Directory service keys are the same as the machine account credentials
and services are just aliases to the machine account object.
"""
host_princ_template = "host/{master}@{realm}"
valid_etypes = ['aes256-cts-hmac-sha384-192', 'aes128-cts-hmac-sha256-128',
'aes256-cts-hmac-sha1-96', 'aes128-cts-hmac-sha1-96']
def extract_key_refs(self, keytab):
host_princ = self.host_princ_template.format(
master=self.api.env.host, realm=self.api.env.realm)
result = ipautil.run([paths.KLIST, "-eK", "-k", keytab],
capture_output=True, raiseonerr=False,
nolog_output=True)
if result.returncode != 0:
return None
keys_to_sync = []
for l in result.output.splitlines():
if (host_princ in l and any(e in l for e in self.valid_etypes)):
els = l.split()
els[-2] = els[-2].strip('()')
els[-1] = els[-1].strip('()')
keys_to_sync.append(KeyEntry._make(els))
return keys_to_sync
def copy_key(self, keytab, keyentry):
# keyentry.key is a hex value of the actual key
# prefixed with 0x, as produced by klist -K -k.
# However, ktutil accepts hex value without 0x, so
# we should strip first two characters.
stdin = dedent("""\
rkt {keytab}
addent -key -p {principal} -k {kvno} -e {etype}
{key}
wkt {keytab}
""").format(keytab=keytab, principal=keyentry.principal,
kvno=keyentry.kvno, etype=keyentry.etype,
key=keyentry.key[2:])
result = ipautil.run([paths.KTUTIL], stdin=stdin, raiseonerr=False,
umask=0o077, nolog_output=True)
if result.returncode != 0:
logger.warning('Unable to update %s with new keys', keytab)
def execute(self, **options):
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
# Extract keys from the host and samba keytabs
hostkeys = self.extract_key_refs(paths.KRB5_KEYTAB)
cifskeys = self.extract_key_refs(paths.SAMBA_KEYTAB)
if any([hostkeys is None, cifskeys is None]):
logger.warning('Either %s or %s are missing or unreadable',
paths.KRB5_KEYTAB, paths.SAMBA_KEYTAB)
return False, []
# If there are missing host keys in the samba keytab, copy them over
# Also copy those keys that differ in the content and/or KVNO
for hostkey in hostkeys:
copied = False
uptodate = False
for cifskey in cifskeys:
if all([cifskey.principal == hostkey.principal,
cifskey.etype == hostkey.etype]):
if any([cifskey.key != hostkey.key,
cifskey.kvno != hostkey.kvno]):
self.copy_key(paths.SAMBA_KEYTAB, hostkey)
copied = True
break
uptodate = True
if not (copied or uptodate):
self.copy_key(paths.SAMBA_KEYTAB, hostkey)
return False, []
@register()
class update_tdo_default_read_keys_permissions(Updater):
trust_filter = \
"(&(objectClass=krbPrincipal)(krbPrincipalName=krbtgt/{nbt}@*))"
def execute(self, **options):
ldap = self.api.Backend.ldap2
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
result = self.api.Command.trustconfig_show()['result']
our_nbt_name = result.get('ipantflatname', [None])[0]
if not our_nbt_name:
return False, []
trusts_dn = self.api.env.container_adtrusts + self.api.env.basedn
trust_filter = self.trust_filter.format(nbt=our_nbt_name)
# We might be in a situation when no trusts exist yet
# In such case there is nothing to upgrade but we have to catch
# an exception or it will abort the whole upgrade process
try:
tdos = ldap.get_entries(
base_dn=trusts_dn,
scope=ldap.SCOPE_SUBTREE,
filter=trust_filter,
attrs_list=['*'])
except errors.EmptyResult:
tdos = []
for tdo in tdos:
updates = dict()
oc = tdo.get('objectClass', [])
if 'ipaAllowedOperations' not in oc:
updates['objectClass'] = oc + ['ipaAllowedOperations']
read_keys = tdo.get('ipaAllowedToPerform;read_keys', [])
if not read_keys:
read_keys_values = list(map(
lambda x: x.format(basedn=self.api.env.basedn),
trust_read_keys_template))
updates['ipaAllowedToPerform;read_keys'] = read_keys_values
tdo.update(updates)
try:
ldap.update_entry(tdo)
except errors.EmptyModlist:
logger.debug("No update was required for TDO %s",
tdo.single_value.get('krbCanonicalName'))
return False, []
@register()
class update_adtrust_agents_members(Updater):
""" Ensure that each adtrust agent is a member of the adtrust agents group
cn=adtrust agents,cn=sysaccounts,cn=etc,$BASEDN must contain:
- member: krbprincipalname=cifs/master@realm,cn=services,cn=accounts,base
- member: fqdn=master,cn=computers,cn=accounts,base
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
# First, see if trusts are enabled on the server
if not self.api.Command.adtrust_is_enabled()['result']:
logger.debug('AD Trusts are not enabled on this server')
return False, []
agents_dn = DN(
('cn', 'adtrust agents'), self.api.env.container_sysaccounts,
self.api.env.basedn)
try:
agents_entry = ldap.get_entry(agents_dn, ['member'])
except errors.NotFound:
logger.error("No adtrust agents group found")
return False, []
# Build a list of agents from the cifs/.. members
agents_list = []
members = agents_entry.get('member', [])
suffix = '@{}'.format(self.api.env.realm).lower()
for amember in members:
if amember[0].attr.lower() == 'krbprincipalname':
# Extract krbprincipalname=cifs/hostname@realm from the DN
value = amember[0].value
if (value.lower().startswith('cifs/') and
value.lower().endswith(suffix)):
# 5 = length of 'cifs/'
hostname = value[5:-len(suffix)]
agents_list.append(DN(('fqdn', hostname),
self.api.env.container_host,
self.api.env.basedn))
# Add the fqdn=hostname... to the group
service.add_principals_to_group(
ldap,
agents_dn,
"member",
agents_list)
return False, []
| 38,067
|
Python
|
.py
| 785
| 35.305732
| 87
| 0.579417
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,808
|
rename_managed.py
|
freeipa_freeipa/ipaserver/install/plugins/rename_managed.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
import logging
import six
from ipalib import Registry, errors
from ipalib import Updater
from ipapython import ipautil
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
if six.PY3:
unicode = str
def entry_to_update(entry):
"""
Convert an entry into a name/value pair list that looks like an update.
An entry is a dict.
An update is a list of name/value pairs.
"""
update = []
for attr in entry.keys():
if isinstance(entry[attr], list):
for item in entry[attr]:
update.append(dict(attr=str(attr), value=str(item)))
else:
update.append(dict(attr=str(attr), value=str(entry[attr])))
return update
class GenerateUpdateMixin:
def _dn_suffix_replace(self, dn, old_suffix, new_suffix):
"""Replace all occurences of "old" AVAs in a DN by "new"
If the input DN doesn't end with old_suffix, log, an raise ValueError.
"""
if not dn.endswith(old_suffix):
logger.error("unable to replace suffix '%s' with '%s' in '%s'",
old_suffix, new_suffix, dn)
raise ValueError('no replacement made')
return DN(*dn[:-len(old_suffix)]) + new_suffix
def generate_update(self, deletes=False):
"""
We need to separate the deletes that need to happen from the
new entries that need to be added.
"""
ldap = self.api.Backend.ldap2
suffix = ipautil.realm_to_suffix(self.api.env.realm)
searchfilter = '(objectclass=*)'
definitions_managed_entries = []
old_template_container = DN(('cn', 'etc'), suffix)
new_template_container = DN(('cn', 'Templates'), ('cn', 'Managed Entries'), ('cn', 'etc'), suffix)
old_definition_container = DN(('cn', 'managed entries'), ('cn', 'plugins'), ('cn', 'config'), suffix)
new_definition_container = DN(('cn', 'Definitions'), ('cn', 'Managed Entries'), ('cn', 'etc'), suffix)
update_list = []
restart = False
# If the old entries don't exist the server has already been updated.
try:
definitions_managed_entries, _truncated = ldap.find_entries(
searchfilter, ['*'], old_definition_container,
ldap.SCOPE_ONELEVEL)
except errors.NotFound:
return (False, update_list)
for entry in definitions_managed_entries:
assert isinstance(entry.dn, DN)
if deletes:
old_dn = entry['managedtemplate'][0]
assert isinstance(old_dn, DN)
try:
entry = ldap.get_entry(old_dn, ['*'])
except errors.NotFound:
pass
else:
# Compute the new dn by replacing the old container with the new container
try:
new_dn = self._dn_suffix_replace(
entry.dn,
old_suffix=old_template_container,
new_suffix=new_template_container)
except ValueError:
continue
# The old attributes become defaults for the new entry
new_update = {'dn': new_dn,
'default': entry_to_update(entry)}
# Delete the old entry
old_update = {'dn': entry.dn, 'deleteentry': None}
# Add the delete and replacement updates to the list of all updates
update_list.append(old_update)
update_list.append(new_update)
else:
# Update the template dn by replacing the old containter with the new container
try:
new_dn = self._dn_suffix_replace(
entry['managedtemplate'][0],
old_suffix=old_template_container,
new_suffix=new_template_container)
except ValueError:
continue
entry['managedtemplate'] = new_dn
# Update the entry dn similarly
try:
new_dn = self._dn_suffix_replace(
entry.dn,
old_suffix=old_definition_container,
new_suffix=new_definition_container)
except ValueError:
continue
# The old attributes become defaults for the new entry
new_update = {'dn': new_dn,
'default': entry_to_update(entry)}
# Add the replacement update to the collection of all updates
update_list.append(new_update)
if len(update_list) > 0:
restart = True
update_list.sort(reverse=True, key=lambda x: x['dn'])
return (restart, update_list)
@register()
class update_managed_post_first(Updater, GenerateUpdateMixin):
"""
Update managed entries
"""
def execute(self, **options):
# Never need to restart with the pre-update changes
_ignore, update_list = self.generate_update(False)
return False, update_list
@register()
class update_managed_post(Updater, GenerateUpdateMixin):
"""
Update managed entries
"""
def execute(self, **options):
(restart, update_list) = self.generate_update(True)
return restart, update_list
| 6,317
|
Python
|
.py
| 144
| 32.513889
| 110
| 0.58533
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,809
|
update_dna_shared_config.py
|
freeipa_freeipa/ipaserver/install/plugins/update_dna_shared_config.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
import logging
import time
import ldap
from ipalib.plugable import Registry
from ipalib import errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_dna_shared_config(Updater):
dna_plugin_names = ('posix IDs', 'Subordinate IDs')
dna_plugin_dn = DN(
('cn', 'Distributed Numeric Assignment Plugin'),
('cn', 'plugins'),
('cn', 'config')
)
def is_dna_enabled(self):
"""Check the plugin is enabled
Else it is useless to update the shared entry
"""
try:
entry = self.api.Backend.ldap2.get_entry(self.dna_plugin_dn)
enabled = entry.single_value.get('nsslapd-pluginenabled')
if enabled.lower() == 'off':
return False
else:
return True
except errors.NotFound:
logger.error("Could not find DNA plugin entry: %s",
self.dna_plugin_dn)
return False
def get_shared_cfg(self, plugin_name):
dna_config_base = DN(('cn', plugin_name), self.dna_plugin_dn)
try:
entry = self.api.Backend.ldap2.get_entry(dna_config_base)
except errors.NotFound:
logger.error("Could not find DNA config entry: %s",
dna_config_base)
return False, ()
else:
logger.debug('Found DNA config %s', dna_config_base)
sharedcfgdn = entry.single_value.get("dnaSharedCfgDN")
if sharedcfgdn is not None:
sharedcfgdn = DN(sharedcfgdn)
logger.debug("dnaSharedCfgDN: %s", sharedcfgdn)
return sharedcfgdn
else:
logger.error(
"Could not find DNA shared config DN in entry: %s",
dna_config_base)
return None
def update_shared_cfg(self, sharedcfgdn, **options):
"""Update the shared config entry related to that host
If the shared config entry already exists (like upgrade)
the update occurs immediately without sleep.
If the shared config entry does not exist (fresh install)
DS server waits for 30s after its startup to create it.
Startup likely occurred few sec before this function is
called so this loop will wait for 30s max.
In case the server is not able to create the entry
The loop gives a grace period of slightly more than 60 seconds
before it logs a failure and aborts the update.
"""
method = options.get('method', "SASL/GSSAPI")
protocol = options.get('protocol', "LDAP")
max_wait = 30 # times 2 second sleep
conn = self.api.Backend.ldap2
fqdn = self.api.env.host
for _i in range(0, max_wait + 1):
try:
entries = conn.get_entries(
sharedcfgdn, scope=ldap.SCOPE_ONELEVEL,
filter='dnaHostname=%s' % fqdn
)
# There must be two entries:
# - dnaHostname=fqdn+dnaPortNum=0
# - dnaHostname=fqdn+dnaPortNum=389
if len(entries) >= 2:
break
logger.debug("Got only one entry. Retry again in 2 sec.")
time.sleep(2)
except errors.NotFound:
logger.debug(
"Unable to find DNA shared config entry for "
"dnaHostname=%s (under %s) so far. Retry in 2 sec.",
fqdn, sharedcfgdn
)
time.sleep(2)
else:
logger.error(
"Could not get dnaHostname entries in %s seconds",
max_wait * 2
)
return False
# time to set the bind method and the protocol in the
# shared config entries
for entry in entries:
entry["dnaRemoteBindMethod"] = method
entry["dnaRemoteConnProtocol"] = protocol
try:
conn.update_entry(entry)
except errors.EmptyModlist:
logger.debug("Entry %s is already updated", entry.dn)
except Exception as e:
logger.error(
"Failed to set SASL/GSSAPI bind method/protocol "
"in entry %s: %s", entry, e
)
else:
logger.debug("Updated entry %s", entry.dn)
return True
def execute(self, **options):
if not self.is_dna_enabled():
return False, ()
for plugin_name in self.dna_plugin_names:
sharedcfgdn = self.get_shared_cfg(plugin_name)
if sharedcfgdn is not None:
self.update_shared_cfg(sharedcfgdn, **options)
# no restart, no update
return False, ()
| 4,950
|
Python
|
.py
| 124
| 28.395161
| 73
| 0.57006
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,810
|
update_idranges.py
|
freeipa_freeipa/ipaserver/install/plugins/update_idranges.py
|
# Authors:
# Tomas Babej <tbabej@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/>.
import logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_idrange_type(Updater):
"""
Update all ID ranges that do not have ipaRangeType attribute filled.
This applies to all ID ranges prior to IPA 3.3.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
base_dn = DN(self.api.env.container_ranges, self.api.env.basedn)
search_filter = ("(&(objectClass=ipaIDrange)(!(ipaRangeType=*)))")
logger.debug("update_idrange_type: search for ID ranges with no "
"type set")
while True:
# Run the search in loop to avoid issues when LDAP limits are hit
# during update
try:
(entries, truncated) = ldap.find_entries(search_filter,
['objectclass'], base_dn, time_limit=0, size_limit=0)
except errors.EmptyResult:
logger.debug("update_idrange_type: no ID range without "
"type set found")
return False, []
except errors.ExecutionError as e:
logger.error("update_idrange_type: cannot retrieve list "
"of ranges with no type set: %s", e)
return False, []
logger.debug("update_idrange_type: found %d "
"idranges to update, truncated: %s",
len(entries), truncated)
error = False
# Set the range type
for entry in entries:
objectclasses = [o.lower() for o
in entry.get('objectclass', [])]
if 'ipatrustedaddomainrange' in objectclasses:
# NOTICE: assumes every AD range does not use POSIX
# attributes
entry['ipaRangeType'] = ['ipa-ad-trust']
elif 'ipadomainidrange' in objectclasses:
entry['ipaRangeType'] = ['ipa-local']
else:
entry['ipaRangeType'] = ['unknown']
logger.error("update_idrange_type: could not detect "
"range type for entry: %s", str(entry.dn))
logger.error("update_idrange_type: ID range type set "
"to 'unknown' for entry: %s", str(entry.dn))
try:
ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError as e:
logger.debug("update_idrange_type: cannot "
"update idrange type: %s", e)
error = True
if error:
# Exit loop to avoid infinite cycles
logger.error("update_idrange_type: error(s) "
"detected during idrange type update")
return False, []
elif not truncated:
# All affected entries updated, exit the loop
logger.debug("update_idrange_type: all affected idranges "
"were assigned types")
return False, []
return False, []
@register()
class update_idrange_baserid(Updater):
"""
Update ipa-ad-trust-posix ranges' base RID to 0. This applies to AD trust
posix ranges prior to IPA 4.1.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
base_dn = DN(self.api.env.container_ranges, self.api.env.basedn)
search_filter = ("(&(objectClass=ipaTrustedADDomainRange)"
"(ipaRangeType=ipa-ad-trust-posix)"
"(!(ipaBaseRID=0)))")
logger.debug(
"update_idrange_baserid: search for ipa-ad-trust-posix ID ranges "
"with ipaBaseRID != 0"
)
try:
(entries, _truncated) = ldap.find_entries(
search_filter, ['ipabaserid'], base_dn,
paged_search=True, time_limit=0, size_limit=0)
except errors.NotFound:
logger.debug("update_idrange_baserid: no AD domain "
"range with posix attributes found")
return False, []
except errors.ExecutionError as e:
logger.error("update_idrange_baserid: cannot retrieve "
"list of affected ranges: %s", e)
return False, []
logger.debug("update_idrange_baserid: found %d "
"idranges possible to update",
len(entries))
error = False
# Set the range type
for entry in entries:
entry['ipabaserid'] = 0
try:
logger.debug("Updating existing idrange: %s", entry.dn)
ldap.update_entry(entry)
logger.info("Done")
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError as e:
logger.debug("update_idrange_type: cannot "
"update idrange: %s", e)
error = True
if error:
logger.error("update_idrange_baserid: error(s) "
"detected during idrange baserid update")
else:
# All affected entries updated, exit the loop
logger.debug("update_idrange_baserid: all affected "
"idranges updated")
return False, []
| 6,457
|
Python
|
.py
| 142
| 32.176056
| 78
| 0.55865
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,811
|
update_managed_permissions.py
|
freeipa_freeipa/ipaserver/install/plugins/update_managed_permissions.py
|
# Authors:
# Petr Viktorin <pviktori@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/>.
"""
Plugin for updating managed permissions.
The permissions are declared in Object plugins in the "managed_permissions"
attribute, which is a dictionary mapping permission names to a "template"
for the updater.
For example, an entry could look like this:
managed_permissions = {
'System: Read Object A': {
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'cn', 'description'},
'replaces_global_anonymous_aci': True,
},
}
For permissions not tied to an object plugin, a NONOBJECT_PERMISSIONS
dict of the same format is defined in this module.
The permission name must start with the "System:" prefix.
The template dictionary can have the following keys:
* ipapermtarget, ipapermtargetfilter, ipapermlocation, ipapermright, ,ipapermtargetto, ipapermtargetfrom, objectclass
- Directly used as attributes on the permission.
- Replaced when upgrading an existing permission
- If not specified, these default to the defaults of a permission of the
corresponding --type, or, if non_object is specified, or if not on an
object, to general permission defaults .
- ipapermlocation, ipatargetto, ipapermtargetfrom, ipapermtarget must be DNs
- ipapermtargetfilter and objectclass must be iterables of strings
* ipapermbindruletype
- Directly used as attribute on the permission.
- Not replaced when upgrading an existing permission.
* ipapermdefaultattr
- Used as attribute of the permission.
- When upgrading, only new values are added; all old values are kept.
* default_privileges
- Names of privileges to add the permission to
- Only applied on newly created permissions
* replaces_global_anonymous_aci
- If true, any attributes specified (denied) in the legacy global anonymous
read ACI will be added to excluded_attributes of the new permission.
- Has no effect when existing permissions are updated.
* non_object
- If true, no object-specific defaults are used (e.g. for
ipapermtargetfilter, ipapermlocation).
* replaces
- A list of ACIs corresponding to legacy default permissions replaced
by this permission.
* replaces_system
- A list of names of old SYSTEM permissions this replaces.
* fixup_function
- A callable that may modify the template in-place before it is applied.
- Called with the permission name, template dict, and keyword arguments:
- is_new: true if the permission was previously existing
- anonymous_read_aci: the legacy 'Enable Anonymous access' ACI as
an ipalib.aci.ACI object, or None if it does not exist
Extra keyword arguments must be ignored, since this list may grow
in the future.
No other keys are allowed in the template
The plugin also deletes permissions specified in OBSOLETE_PERMISSIONS.
"""
import logging
import six
from ipalib import api, errors
from ipapython.dn import DN
from ipalib.plugable import Registry
from ipalib.aci import ACI
from ipalib import Updater
from ipapython import ipautil
from ipaserver.plugins import aci
from ipaserver.plugins.permission import permission, permission_del
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
register = Registry()
OBSOLETE_PERMISSIONS = {
# These permissions will be removed on upgrade, if they exist.
# Any modifications the user might have made to them are not taken
# into account. This should be used sparingly.
'System: Read Timestamp and USN Operational Attributes',
'System: Read Creator and Modifier Operational Attributes',
}
NONOBJECT_PERMISSIONS = {
'System: Read IPA Masters': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=masters,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=nscontainer)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipaconfigstring',
},
'default_privileges': {'IPA Masters Readers'},
},
'System: Compat Tree ID View targets': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=*,cn=compat', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipaOverrideTarget)'},
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipaAnchorUUID',
},
},
'System: Read DNA Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=dna,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=dnasharedconfig)'},
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'dnaHostname', 'dnaPortNum',
'dnaSecurePortNum', 'dnaRemoteBindMethod', 'dnaRemoteConnProtocol',
'dnaRemainingValues',
},
},
'System: Read CA Renewal Information': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=ca_renewal,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=pkiuser)'},
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'usercertificate',
},
},
'System: Add CA Certificate For Renewal': {
'ipapermlocation': DN('cn=ca_renewal,cn=ipa,cn=etc', api.env.basedn),
'ipapermtarget': DN(
'cn=caSigningCert cert-pki-ca,cn=ca_renewal,cn=ipa,cn=etc',
api.env.basedn),
'ipapermtargetfilter': {'(objectclass=pkiuser)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'add'},
'default_privileges': {'Certificate Administrators'},
},
'System: Modify CA Certificate For Renewal': {
'ipapermlocation': DN('cn=ca_renewal,cn=ipa,cn=etc', api.env.basedn),
'ipapermtarget': DN(
'cn=caSigningCert cert-pki-ca,cn=ca_renewal,cn=ipa,cn=etc',
api.env.basedn),
'ipapermtargetfilter': {'(objectclass=pkiuser)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {
'usercertificate',
},
'default_privileges': {'Certificate Administrators'},
},
'System: Read CA Certificate': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=CAcert,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=pkica)'},
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'cacertificate', 'certificaterevocationlist',
'authorityrevocationlist', 'crosscertificatepair',
},
},
'System: Modify CA Certificate': {
'ipapermlocation': DN('cn=CAcert,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=pkica)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cacertificate',
},
'default_privileges': {'Certificate Administrators'},
},
'System: Read Certificate Store Entries': {
'ipapermlocation': DN('cn=certificates,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipacertificate)'},
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipacertsubject', 'ipacertissuerserial',
'ipapublickey', 'ipaconfigstring', 'cacertificate', 'ipakeytrust',
'ipakeyusage', 'ipakeyextusage',
},
},
'System: Add Certificate Store Entry': {
'ipapermlocation': DN('cn=certificates,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipacertificate)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'add'},
'default_privileges': {'Certificate Administrators'},
},
'System: Modify Certificate Store Entry': {
'ipapermlocation': DN('cn=certificates,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipacertificate)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {
'ipacertissuerserial', 'ipaconfigstring', 'cacertificate',
'ipakeytrust', 'ipakeyusage', 'ipakeyextusage',
},
'default_privileges': {'Certificate Administrators'},
},
'System: Remove Certificate Store Entry': {
'ipapermlocation': DN('cn=certificates,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipacertificate)'},
'ipapermbindruletype': 'permission',
'ipapermright': {'delete'},
'default_privileges': {'Certificate Administrators'},
},
'System: Read Replication Information': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=replication,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=nsds5replica)'},
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'nsds5replicaroot', 'nsds5replicaid',
'nsds5replicacleanruv', 'nsds5replicaabortcleanruv',
'nsds5replicatype', 'nsds5replicabinddn', 'nsstate',
'nsds5replicaname', 'nsds5flags', 'nsds5task',
'nsds5replicareferral', 'nsds5replicaautoreferral',
'nsds5replicapurgedelay', 'nsds5replicatombstonepurgeinterval',
'nsds5replicachangecount', 'nsds5replicalegacyconsumer',
'nsds5replicaprotocoltimeout', 'nsds5replicabackoffmin',
'nsds5replicabackoffmax',
},
},
'System: Read AD Domains': {
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN('cn=etc', api.env.basedn),
'ipapermtarget': DN('cn=ad,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipantdomainattrs)'},
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipantsecurityidentifier', 'ipantflatname',
'ipantdomainguid', 'ipantfallbackprimarygroup',
},
},
'System: Read DUA Profile': {
'ipapermlocation': DN('ou=profile', api.env.basedn),
'ipapermtargetfilter': {
'(|'
'(objectclass=organizationalUnit)'
'(objectclass=DUAConfigProfile)'
')'
},
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'ou', 'cn', 'defaultServerList',
'preferredServerList', 'defaultSearchBase', 'defaultSearchScope',
'searchTimeLimit', 'bindTimeLimit', 'credentialLevel',
'authenticationMethod', 'followReferrals', 'dereferenceAliases',
'serviceSearchDescriptor', 'serviceCredentialLevel',
'serviceAuthenticationMethod', 'objectclassMap', 'attributeMap',
'profileTTL'
},
},
'System: Read Domain Level': {
'ipapermlocation': DN('cn=Domain Level,cn=ipa,cn=etc', api.env.basedn),
'ipapermtargetfilter': {'(objectclass=ipadomainlevelconfig)'},
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipadomainlevel', 'objectclass',
},
},
}
class IncompatibleACIModification(Exception):
"""User has made a legacy default perm modification we can't handle"""
@register()
class update_managed_permissions(Updater):
"""Update managed permissions after an update.
Update managed permissions according to templates specified in plugins.
For read permissions, puts any attributes specified in the legacy
Anonymous access ACI in the exclude list when creating the permission.
"""
def get_anonymous_read_aci(self, ldap):
aciname = u'Enable Anonymous access'
aciprefix = u'none'
base_entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acistrs = base_entry.get('aci', [])
acilist = aci._convert_strings_to_acis(acistrs)
try:
return aci._find_aci_by_name(acilist, aciprefix, aciname)
except errors.NotFound:
return None
def remove_anonymous_read_aci(self, ldap, anonymous_read_aci):
base_entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acistrs = base_entry.get('aci', [])
for acistr in acistrs:
if ACI(acistr).isequal(anonymous_read_aci):
logger.debug('Removing anonymous ACI: %s', acistr)
acistrs.remove(acistr)
break
else:
return
ldap.update_entry(base_entry)
def get_templates(self):
"""Return (name, template, obj) triples for all managed permissions
If the permission is not defined in an object plugin, obj is None.
Entries with the same obj are returned consecutively.
"""
for obj in sorted(self.api.Object(), key=lambda o: o.name):
managed_permissions = getattr(obj, 'managed_permissions', {})
for name, template in sorted(managed_permissions.items()):
yield name, template, obj
for name, template in sorted(NONOBJECT_PERMISSIONS.items()):
yield name, template, None
def execute(self, **options):
ldap = self.api.Backend.ldap2
anonymous_read_aci = self.get_anonymous_read_aci(ldap)
if anonymous_read_aci:
logger.debug('Anonymous read ACI: %s', anonymous_read_aci)
else:
logger.debug('Anonymous ACI not found')
current_obj = () # initially distinct from any obj value, even None
for name, template, obj in self.get_templates():
if current_obj != obj:
if obj:
logger.debug('Updating managed permissions for %s',
obj.name)
else:
logger.debug('Updating non-object managed permissions')
current_obj = obj
self.update_permission(ldap,
obj,
unicode(name),
template,
anonymous_read_aci)
if anonymous_read_aci:
self.remove_anonymous_read_aci(ldap, anonymous_read_aci)
for obsolete_name in OBSOLETE_PERMISSIONS:
logger.debug('Deleting obsolete permission %s', obsolete_name)
try:
self.api.Command[permission_del](unicode(obsolete_name),
force=True,
version=u'2.101')
except errors.NotFound:
logger.debug('Obsolete permission not found')
else:
logger.debug('Obsolete permission deleted: %s', obsolete_name)
return False, ()
def update_permission(self, ldap, obj, name, template, anonymous_read_aci):
"""Update the given permission and the corresponding ACI"""
assert name.startswith('System:')
dn = self.api.Object[permission].get_dn(name)
permission_plugin = self.api.Object[permission]
try:
attrs_list = list(permission_plugin.default_attributes)
attrs_list.remove('memberindirect')
entry = ldap.get_entry(dn, attrs_list)
is_new = False
except errors.NotFound:
entry = ldap.make_entry(dn)
is_new = True
self.update_entry(obj, entry, template,
anonymous_read_aci, is_new=is_new)
remove_legacy = False
if 'replaces' in template:
sub_dict = {
'SUFFIX': str(self.api.env.basedn),
'REALM': str(self.api.env.realm),
}
legacy_acistrs = [ipautil.template_str(r, sub_dict)
for r in template['replaces']]
legacy_aci = ACI(legacy_acistrs[0])
prefix, sep, legacy_name = legacy_aci.name.partition(':')
assert prefix == 'permission' and sep
legacy_dn = permission_plugin.get_dn(legacy_name)
try:
legacy_entry = ldap.get_entry(legacy_dn,
['ipapermissiontype', 'cn'])
except errors.NotFound:
logger.debug("Legacy permission %s not found", legacy_name)
else:
if 'ipapermissiontype' not in legacy_entry:
if is_new:
_acientry, acistr = (
permission_plugin._get_aci_entry_and_string(
legacy_entry, notfound_ok=True))
try:
included, excluded = self.get_upgrade_attr_lists(
acistr, legacy_acistrs)
except IncompatibleACIModification:
logger.error(
"Permission '%s' has been modified from its "
"default; not updating it to '%s'.",
legacy_name, name)
return
else:
logger.debug("Merging attributes from legacy "
"permission '%s'", legacy_name)
logger.debug("Included attrs: %s",
', '.join(sorted(included)))
logger.debug("Excluded attrs: %s",
', '.join(sorted(excluded)))
entry['ipapermincludedattr'] = list(included)
entry['ipapermexcludedattr'] = list(excluded)
remove_legacy = True
else:
logger.debug("Ignoring attributes in legacy "
"permission '%s' because '%s' exists",
legacy_name, name)
remove_legacy = True
else:
logger.debug("Ignoring V2 permission named '%s'",
legacy_name)
update_aci = True
logger.debug('Updating managed permission: %s', name)
if is_new:
ldap.add_entry(entry)
else:
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
logger.debug('No changes to permission: %s', name)
update_aci = False
if update_aci:
logger.debug('Updating ACI for managed permission: %s', name)
permission_plugin.update_aci(entry)
if remove_legacy:
logger.debug("Removing legacy permission '%s'", legacy_name)
self.api.Command[permission_del](unicode(legacy_name))
for name in template.get('replaces_system', ()):
name = unicode(name)
try:
entry = ldap.get_entry(permission_plugin.get_dn(name),
['ipapermissiontype'])
except errors.NotFound:
logger.debug("Legacy permission '%s' not found", name)
else:
flags = entry.get('ipapermissiontype', [])
if list(flags) == ['SYSTEM']:
logger.debug("Removing legacy permission '%s'", name)
self.api.Command[permission_del](name, force=True)
else:
logger.debug("Ignoring V2 permission '%s'", name)
def get_upgrade_attr_lists(self, current_acistring, default_acistrings):
"""Compute included and excluded attributes for a new permission
:param current_acistring: ACI is in LDAP currently
:param default_acistrings:
List of all default ACIs IPA historically used for this permission
:return:
(ipapermincludedattr, ipapermexcludedattr) for the upgraded
permission
An attribute will be included if the user has it in LDAP but it does
not appear in *any* historic ACI.
It will be excluded if it is in *all* historic ACIs but not in LDAP.
Rationale: When we don't know which version of an ACI the user is
upgrading from, we only consider attributes where all the versions
agree. For other attrs we'll use the default from the new managed perm.
If the ACIs differ in something else than the list of attributes,
raise IncompatibleACIModification. This means manual action is needed
(either delete the old permission or change it to resemble the default
again, then re-run ipa-ldap-updater).
In case there are multiple historic default ACIs, and some of them
are compatible with the current but other ones aren't, we deduce that
the user is upgrading from one of the compatible ones.
The incompatible ones are removed from consideration, both for
compatibility and attribute lists.
"""
assert default_acistrings
def _pop_targetattr(aci):
"""Return the attr list it as a set, clear it in the ACI object
"""
targetattr = aci.target.get('targetattr')
if targetattr:
attrs = targetattr['expression']
targetattr['expression'] = []
return set(t.lower() for t in attrs)
else:
return set()
current_aci = ACI(current_acistring)
current_attrs = _pop_targetattr(current_aci)
logger.debug("Current ACI for '%s': %s",
current_aci.name, current_acistring)
attrs_in_all_defaults = None
attrs_in_any_defaults = set()
all_incompatible = True
for default_acistring in default_acistrings:
default_aci = ACI(default_acistring)
default_attrs = _pop_targetattr(default_aci)
logger.debug("Default ACI for '%s': %s",
default_aci.name, default_acistring)
if current_aci != default_aci:
logger.debug('ACIs not compatible')
continue
all_incompatible = False
if attrs_in_all_defaults is None:
attrs_in_all_defaults = set(default_attrs)
else:
attrs_in_all_defaults &= attrs_in_all_defaults
attrs_in_any_defaults |= default_attrs
if all_incompatible:
logger.debug('All old default ACIs are incompatible')
raise(IncompatibleACIModification())
included = current_attrs - attrs_in_any_defaults
excluded = attrs_in_all_defaults - current_attrs
return included, excluded
def update_entry(self, obj, entry, template,
anonymous_read_aci, is_new):
"""Update the given permission Entry (without contacting LDAP)"""
[name_ava] = entry.dn[0]
assert name_ava.attr == 'cn'
name = name_ava.value
entry.single_value['cn'] = name
template = dict(template)
template.pop('replaces', None)
template.pop('replaces_system', None)
template.pop('replaces_permissions', None)
template.pop('replaces_acis', None)
fixup_function = template.pop('fixup_function', None)
if fixup_function:
fixup_function(name, template,
is_new=is_new,
anonymous_read_aci=anonymous_read_aci)
if template.pop('non_object', False):
obj = None
entry['ipapermissiontype'] = [u'SYSTEM', u'V2', u'MANAGED']
# Attributes with defaults
objectclass = template.pop('objectclass', None)
if objectclass is None:
objectclass = self.api.Object[permission].object_class
entry['objectclass'] = list(objectclass)
ldap_filter = template.pop('ipapermtargetfilter', None)
if obj and ldap_filter is None:
ldap_filter = [self.api.Object[permission].make_type_filter(obj)]
entry['ipapermtargetfilter'] = list(ldap_filter or [])
ipapermlocation = template.pop('ipapermlocation', None)
if ipapermlocation is None:
assert obj
ipapermlocation = DN(obj.container_dn, self.api.env.basedn)
entry.single_value['ipapermlocation'] = ipapermlocation
# Optional attributes
ipapermtarget = template.pop('ipapermtarget', None)
if ipapermtarget is not None:
entry['ipapermtarget'] = ipapermtarget
ipapermtargetto = template.pop('ipapermtargetto', None)
if ipapermtargetto is not None:
entry['ipapermtargetto'] = ipapermtargetto
ipapermtargetfrom = template.pop('ipapermtargetfrom', None)
if ipapermtargetfrom is not None:
entry['ipapermtargetfrom'] = ipapermtargetfrom
# Attributes from template
bindruletype = template.pop('ipapermbindruletype', 'permission')
if bindruletype not in {"all", "anonymous", "self", "permission"}:
raise ValueError(
f"Invalid ipapermbindruletype '{bindruletype}'"
)
if is_new:
entry.single_value['ipapermbindruletype'] = bindruletype
entry['ipapermright'] = list(template.pop('ipapermright'))
default_privileges = template.pop('default_privileges', None)
if is_new and default_privileges:
entry['member'] = list(
DN(('cn', privilege_name),
self.api.env.container_privilege,
self.api.env.basedn)
for privilege_name in default_privileges)
# Add to the set of default attributes
attributes = set(template.pop('ipapermdefaultattr', ()))
attributes.update(entry.get('ipapermdefaultattr', ()))
attributes = set(a.lower() for a in attributes)
entry['ipapermdefaultattr'] = list(attributes)
# Exclude attributes filtered from the global read ACI
replaces_ga_aci = template.pop('replaces_global_anonymous_aci', False)
if replaces_ga_aci and is_new and anonymous_read_aci:
read_blocklist = set(
a.lower() for a in
anonymous_read_aci.target['targetattr']['expression'])
read_blocklist &= attributes
if read_blocklist:
logger.debug('Excluded attributes for %s: %s',
name, ', '.join(read_blocklist))
entry['ipapermexcludedattr'] = list(read_blocklist)
# Sanity check
if template:
raise ValueError(
'Unknown key(s) in managed permission template %s: %s' % (
name, ', '.join(template.keys())))
@register()
class update_read_replication_agreements_permission(Updater):
"""'Read replication agreements' permission must not be managed permission
https://fedorahosted.org/freeipa/ticket/5631
Existing permission "cn=System: Read Replication Agreements" must be moved
to non-managed permission "cn=Read Replication Agreements" using modrdn
ldap operation to keep current membership of the permission set by user.
ACI is updated via update files
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
old_perm_dn = DN(
('cn', 'System: Read Replication Agreements'),
self.api.env.container_permission,
self.api.env.basedn
)
new_perm_dn = DN(
('cn', 'Read Replication Agreements'),
self.api.env.container_permission,
self.api.env.basedn
)
try:
perm_entry = ldap.get_entry(old_perm_dn)
except errors.NotFound:
logger.debug("Old permission not found")
return False, ()
try:
ldap.get_entry(new_perm_dn)
except errors.NotFound:
# we can happily upgrade
pass
else:
logger.error("Permission '%s' cannot be upgraded. "
"Permission with target name '%s' already "
"exists", old_perm_dn, new_perm_dn)
return False, ()
# values are case insensitive
for t in list(perm_entry['ipapermissiontype']):
if t.lower() in ['managed', 'v2']:
perm_entry['ipapermissiontype'].remove(t)
for o in list(perm_entry['objectclass']):
if o.lower() == 'ipapermissionv2':
# remove permission V2 objectclass and related attributes
perm_entry['objectclass'].remove(o)
perm_entry['ipapermdefaultattr'] = []
perm_entry['ipapermright'] = []
perm_entry['ipapermbindruletype'] = []
perm_entry['ipapermlocation'] = []
perm_entry['ipapermtargetfilter'] = []
logger.debug("Removing MANAGED attributes from permission %s",
old_perm_dn)
try:
ldap.update_entry(perm_entry)
except errors.EmptyModlist:
pass
# do modrdn on permission
logger.debug("modrdn: %s -> %s", old_perm_dn, new_perm_dn)
ldap.move_entry(old_perm_dn, new_perm_dn)
return False, ()
| 30,812
|
Python
|
.py
| 654
| 36.012232
| 117
| 0.610485
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,812
|
update_changelog_maxage.py
|
freeipa_freeipa/ipaserver/install/plugins/update_changelog_maxage.py
|
#
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license
#
import logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_changelog_maxage(Updater):
"""
Update the changelog maxage if it is not set
"""
def update_entry(self, cl_entry, conn):
maxage = cl_entry.single_value.get('nsslapd-changelogmaxage')
if maxage is None:
cl_entry['nsslapd-changelogmaxage'] = '30d'
conn.update_entry(cl_entry)
def execute(self, **options):
ldap = self.api.Backend.ldap2
for backend in ('userroot', 'ipaca'):
dn = DN(
('cn', 'changelog'),
('cn', backend),
('cn', 'ldbm database'),
('cn', 'plugins'),
('cn', 'config'))
try:
cl_entry = ldap.get_entry(dn, ['nsslapd-changelogmaxage'])
self.update_entry(cl_entry, ldap)
except errors.NotFound:
# Try the old global changelog, and return
dn = DN(
('cn', 'changelog5'),
('cn', 'config'))
try:
cl_entry = ldap.get_entry(dn, ['nsslapd-changelogmaxage'])
self.update_entry(cl_entry, ldap)
except errors.NotFound:
logger.debug('Error retrieving: %s', str(dn))
return False, []
return False, []
| 1,577
|
Python
|
.py
| 43
| 25.906977
| 78
| 0.541284
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,813
|
update_pwpolicy.py
|
freeipa_freeipa/ipaserver/install/plugins/update_pwpolicy.py
|
#
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license
#
import logging
from ipalib import Registry, errors
from ipalib import Updater
from ipapython.dn import DN
logger = logging.getLogger(__name__)
register = Registry()
@register()
class update_pwpolicy(Updater):
"""
Add new ipapwdpolicy objectclass to all password policies
Otherwise pwpolicy-find will not find them.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
base_dn = DN(('cn', self.api.env.realm), ('cn', 'kerberos'),
self.api.env.basedn)
search_filter = (
"(&(objectClass=krbpwdpolicy)(!(objectclass=ipapwdpolicy)))"
)
while True:
# Run the search in loop to avoid issues when LDAP limits are hit
# during update
try:
(entries, truncated) = ldap.find_entries(
search_filter, ['objectclass'], base_dn, time_limit=0,
size_limit=0)
except errors.EmptyResult:
logger.debug("update_pwpolicy: no policies without "
"objectclass set")
return False, []
except errors.ExecutionError as e:
logger.error("update_pwpolicy: cannot retrieve list "
"of policies missing an objectclass: %s", e)
return False, []
logger.debug("update_pwpolicy: found %d "
"policies to update, truncated: %s",
len(entries), truncated)
error = False
for entry in entries:
entry['objectclass'].append('ipapwdpolicy')
try:
ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError as e:
logger.debug("update_pwpolicy: cannot "
"update policy: %s", e)
error = True
if error:
# Exit loop to avoid infinite cycles
logger.error("update_pwpolicy: error(s) "
"detected during pwpolicy update")
return False, []
elif not truncated:
# All affected entries updated, exit the loop
logger.debug("update_pwpolicy: all policies updated")
return False, []
return False, []
@register()
class update_pwpolicy_grace(Updater):
"""
Ensure all group policies have a grace period set.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
base_dn = DN(('cn', self.api.env.realm), ('cn', 'kerberos'),
self.api.env.basedn)
search_filter = (
"(&(objectClass=krbpwdpolicy)(!(passwordgracelimit=*)))"
)
while True:
# Run the search in loop to avoid issues when LDAP limits are hit
# during update
try:
(entries, truncated) = ldap.find_entries(
search_filter, ['objectclass'], base_dn, time_limit=0,
size_limit=0)
except errors.EmptyResult:
logger.debug("update_pwpolicy: no policies without "
"passwordgracelimit set")
return False, []
except errors.ExecutionError as e:
logger.error("update_pwpolicy: cannot retrieve list "
"of policies missing passwordgracelimit: %s", e)
return False, []
logger.debug("update_pwpolicy: found %d "
"policies to update, truncated: %s",
len(entries), truncated)
error = False
for entry in entries:
# Set unlimited BIND by default
entry['passwordgracelimit'] = -1
try:
ldap.update_entry(entry)
except (errors.EmptyModlist, errors.NotFound):
pass
except errors.ExecutionError as e:
logger.debug("update_pwpolicy: cannot "
"update policy: %s", e)
error = True
if error:
# Exit loop to avoid infinite cycles
logger.error("update_pwpolicy: error(s) "
"detected during pwpolicy update")
return False, []
elif not truncated:
# All affected entries updated, exit the loop
logger.debug("update_pwpolicy: all policies updated")
return False, []
return False, []
| 4,820
|
Python
|
.py
| 113
| 27.964602
| 77
| 0.523748
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,814
|
dns.py
|
freeipa_freeipa/ipaserver/install/plugins/dns.py
|
# Authors:
# Martin Kosek <mkosek@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 __future__ import absolute_import
import logging
import dns.exception
import re
import traceback
import time
from ldif import LDIFWriter
from ipalib import Registry, errors, util
from ipalib import Updater
from ipapython.dn import DN
from ipapython import dnsutil
from ipaserver.install import sysupgrade
from ipaserver.install.bindinstance import ensure_dnsserver_container_exists
from ipaserver.plugins.dns import dns_container_exists
logger = logging.getLogger(__name__)
register = Registry()
class DNSUpdater(Updater):
backup_dir = u'/var/lib/ipa/backup/'
# override backup_filename in subclass, it will be mangled by strftime
backup_filename = None
def __init__(self, api):
super(DNSUpdater, self).__init__(api)
backup_path = u'%s%s' % (self.backup_dir, self.backup_filename)
self.backup_path = time.strftime(backup_path)
self._ldif_writer = None
self._saved_privileges = set() # store privileges only once
self.saved_zone_to_privilege = {}
def version_update_needed(self, target_version):
"""Test if IPA DNS version is smaller than target version."""
assert isinstance(target_version, int)
try:
return int(self.api.Command['dnsconfig_show'](
all=True)['result']['ipadnsversion'][0]) < target_version
except errors.NotFound:
# IPA DNS is not configured
return False
@property
def ldif_writer(self):
if not self._ldif_writer:
logger.info('Original zones will be saved in LDIF format in '
'%s file', self.backup_path)
self._ldif_writer = LDIFWriter(open(self.backup_path, 'w'))
return self._ldif_writer
def backup_zone(self, zone):
"""Backup zone object, its records, permissions, and privileges.
Mapping from zone to privilege (containing zone's permissions)
will be stored in saved_zone_to_privilege dict for further usage.
"""
dn = str(zone['dn'])
del zone['dn'] # dn shouldn't be as attribute in ldif
self.ldif_writer.unparse(dn, zone)
ldap = self.api.Backend.ldap2
if 'managedBy' in zone:
permission = ldap.get_entry(DN(zone['managedBy'][0]))
self.ldif_writer.unparse(str(permission.dn), dict(permission.raw))
for privilege_dn in permission.get('member', []):
# privileges can be shared by multiples zones
if privilege_dn not in self._saved_privileges:
self._saved_privileges.add(privilege_dn)
privilege = ldap.get_entry(privilege_dn)
self.ldif_writer.unparse(str(privilege.dn),
dict(privilege.raw))
# remember privileges referened by permission
if 'member' in permission:
self.saved_zone_to_privilege[
zone['idnsname'][0]
] = permission['member']
if 'idnszone' in zone['objectClass']:
# raw values are required to store into ldif
records = self.api.Command['dnsrecord_find'](zone['idnsname'][0],
all=True,
raw=True,
sizelimit=0)['result']
for record in records:
if record['idnsname'][0] == u'@':
# zone record was saved before
continue
dn = str(record['dn'])
del record['dn']
self.ldif_writer.unparse(dn, record)
@register()
class update_ipaconfigstring_dnsversion_to_ipadnsversion(Updater):
"""
IPA <= 4.3.1 used ipaConfigString "DNSVersion 1" on DNS container.
This was hard to deal with in API so from IPA 4.3.2 we are using
new ipaDNSVersion attribute with integer syntax.
Old ipaConfigString is left there for now so if someone accidentally
executes upgrade on an old replica again it will not re-upgrade the data.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
dns_container_dn = DN(self.api.env.container_dns, self.api.env.basedn)
try:
container_entry = ldap.get_entry(dns_container_dn)
except errors.NotFound:
# DNS container not found, nothing to upgrade
return False, []
if 'ipadnscontainer' in [
o.lower() for o in container_entry['objectclass']
]:
# version data are already migrated
return False, []
logger.debug('Migrating DNS ipaConfigString to ipaDNSVersion')
container_entry['objectclass'].append('ipadnscontainer')
version = 0
for config_option in container_entry.get("ipaConfigString", []):
matched = re.match(r"^DNSVersion\s+(?P<version>\d+)$",
config_option, flags=re.I)
if matched:
version = int(matched.group("version"))
else:
logger.error(
'Failed to parse DNS version from ipaConfigString, '
'defaulting to version %s', version)
container_entry['ipadnsversion'] = version
ldap.update_entry(container_entry)
logger.debug('ipaDNSVersion = %s', version)
return False, []
@register()
class update_dnszones(Updater):
"""
Update all zones to meet requirements in the new IPA versions
1) AllowQuery and AllowTransfer
Set AllowQuery and AllowTransfer ACLs in all zones that may be configured
in an upgraded IPA instance.
Upgrading to new version of bind-dyndb-ldap and having these ACLs empty
would result in a leak of potentially sensitive DNS information as
zone transfers are enabled for all hosts if not disabled in named.conf
or LDAP.
This plugin disables the zone transfer by default so that it needs to be
explicitly enabled by IPA Administrator.
2) Update policy
SSH public key support includes a feature to automatically add/update
client SSH fingerprints in SSHFP records. However, the update won't
work for zones created before this support was added as they don't allow
clients to update SSHFP records in their update policies.
This module extends the original policy to allow the SSHFP updates.
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
if not dns_container_exists(ldap):
return False, []
try:
zones = self.api.Command.dnszone_find(all=True)['result']
except errors.NotFound:
logger.debug('No DNS zone to update found')
return False, []
for zone in zones:
update = {}
if not zone.get('idnsallowquery'):
# allow query from any client by default
update['idnsallowquery'] = u'any;'
if not zone.get('idnsallowtransfer'):
# do not open zone transfers by default
update['idnsallowtransfer'] = u'none;'
old_policy = util.get_dns_forward_zone_update_policy(
self.api.env.realm, ('A', 'AAAA'))
if zone.get('idnsupdatepolicy', [''])[0] == old_policy:
update['idnsupdatepolicy'] = util.get_dns_forward_zone_update_policy(\
self.api.env.realm)
if update:
# FIXME: https://fedorahosted.org/freeipa/ticket/4722
self.api.Command.dnszone_mod(zone[u'idnsname'][0].make_absolute(),
**update)
return False, []
@register()
class update_dns_limits(Updater):
"""
bind-dyndb-ldap persistent search queries LDAP for all DNS records.
The LDAP connection must have no size or time limits to work
properly. This plugin updates limits of the existing DNS service
principal to match there requirements.
"""
limit_attributes = ['nsTimeLimit', 'nsSizeLimit', 'nsIdleTimeout', 'nsLookThroughLimit']
limit_value = '-1'
def execute(self, **options):
ldap = self.api.Backend.ldap2
if not dns_container_exists(ldap):
return False, []
dns_principal = 'DNS/%s@%s' % (self.env.host, self.env.realm)
dns_service_dn = DN(('krbprincipalname', dns_principal),
self.env.container_service,
self.env.basedn)
try:
entry = ldap.get_entry(dns_service_dn, self.limit_attributes)
except errors.NotFound:
# this host may not have DNS service set
logger.debug("DNS: service %s not found, no need to update limits",
dns_service_dn)
return False, []
if all(entry.get(limit.lower(), [None])[0] == self.limit_value for limit in self.limit_attributes):
logger.debug("DNS: limits for service %s already set",
dns_service_dn)
# service is already updated
return False, []
limit_updates = []
for limit in self.limit_attributes:
limit_updates.append(dict(action='only', attr=limit,
value=self.limit_value))
dnsupdate = {'dn': dns_service_dn, 'updates': limit_updates}
logger.debug("DNS: limits for service %s will be updated",
dns_service_dn)
return False, [dnsupdate]
@register()
class update_master_to_dnsforwardzones(DNSUpdater):
"""
Update all zones to meet requirements in the new IPA versions
All masters zones with specified forwarders, and forward-policy different
than none, will be tranformed to forward zones.
Original masters zone will be backed up to ldif file.
This should be applied only once,
and only if original version was lower than 4.0
"""
backup_filename = u'dns-master-to-forward-zones-%Y-%m-%d-%H-%M-%S.ldif'
def execute(self, **options):
# check LDAP if forwardzones already uses new semantics
if not self.version_update_needed(target_version=1):
# forwardzones already uses new semantics,
# no upgrade is required
return False, []
logger.debug('Updating forward zones')
# update the DNSVersion, following upgrade can be executed only once
self.api.Command['dnsconfig_mod'](ipadnsversion=1)
# Updater in IPA version from 4.0 to 4.1.2 doesn't work well, this
# should detect if update in past has been executed, and set proper
# DNSVersion into LDAP
try:
fwzones = self.api.Command.dnsforwardzone_find()['result']
except errors.NotFound:
# No forwardzones found, update probably has not been executed yet
pass
else:
if fwzones:
# fwzones exist, do not execute upgrade again
return False, []
zones = []
try:
# raw values are required to store into ldif
zones = self.api.Command.dnszone_find(all=True,
raw=True,
sizelimit=0)['result']
except errors.NotFound:
pass
if not zones:
logger.debug('No DNS zone to update found')
return False, []
zones_to_transform = []
for zone in zones:
if (
zone.get('idnsforwardpolicy', [u'first'])[0] == u'none' or
zone.get('idnsforwarders', []) == []
):
continue # don't update zone
zones_to_transform.append(zone)
if zones_to_transform:
logger.info('Zones with specified forwarders with policy '
'different than none will be transformed to forward '
'zones.')
# update
for zone in zones_to_transform:
try:
self.backup_zone(zone)
except Exception:
logger.error('Unable to create backup for zone, '
'terminating zone upgrade')
logger.error("%s", traceback.format_exc())
return False, []
# delete master zone
try:
self.api.Command['dnszone_del'](zone['idnsname'])
except Exception as e:
logger.error('Transform to forwardzone terminated: '
'removing zone %s failed (%s)',
zone['idnsname'][0], e)
logger.error("%s", traceback.format_exc())
continue
# create forward zone
try:
kw = {
'idnsforwarders': zone.get('idnsforwarders', []),
'idnsforwardpolicy': zone.get('idnsforwardpolicy',
[u'first'])[0],
'skip_overlap_check': True,
}
self.api.Command['dnsforwardzone_add'](zone['idnsname'][0], **kw)
except Exception:
logger.error('Transform to forwardzone terminated: '
'creating forwardzone %s failed',
zone['idnsname'][0])
logger.error("%s", traceback.format_exc())
continue
# create permission if original zone has one
if 'managedBy' in zone:
try:
perm_name = self.api.Command['dnsforwardzone_add_permission'](
zone['idnsname'][0])['value']
except Exception:
logger.error('Transform to forwardzone terminated: '
'Adding managed by permission to forward '
'zone %s failed', zone['idnsname'])
logger.error("%s", traceback.format_exc())
logger.info('Zone %s was transformed to forward zone '
' without managed permissions',
zone['idnsname'][0])
continue
else:
if zone['idnsname'][0] in self.saved_zone_to_privilege:
privileges = [
dn[0].value for dn in self.saved_zone_to_privilege[zone['idnsname'][0]]
]
try:
self.api.Command['permission_add_member'](perm_name,
privilege=privileges)
except Exception:
logger.error('Unable to restore privileges '
'for permission %s, for zone %s',
perm_name, zone['idnsname'])
logger.error("%s", traceback.format_exc())
logger.info('Zone %s was transformed to '
'forward zone without restored '
'privileges',
zone['idnsname'][0])
continue
logger.debug('Zone %s was sucessfully transformed to forward '
'zone',
zone['idnsname'][0])
return False, []
@register()
class update_dnsforward_emptyzones(DNSUpdater):
"""
Migrate forward policies which conflict with automatic empty zones
(RFC 6303) to use forward policy = only.
BIND ignores conflicting forwarding configuration
when forwarding policy != only.
bind-dyndb-ldap 9.0+ will do the same so we have to adjust IPA zones
accordingly.
"""
backup_filename = u'dns-forwarding-empty-zones-%Y-%m-%d-%H-%M-%S.ldif'
def update_zones(self):
try:
fwzones = self.api.Command.dnsforwardzone_find(all=True,
raw=True)['result']
except errors.NotFound:
# No forwardzones found, we are done
return
logged_once = False
for zone in fwzones:
if not (
dnsutil.related_to_auto_empty_zone(
dnsutil.DNSName(zone.get('idnsname')[0]))
and zone.get('idnsforwardpolicy', [u'first'])[0] != u'only'
and zone.get('idnsforwarders', []) != []
):
# this zone does not conflict with automatic empty zone
continue
if not logged_once:
logger.info('Forward policy for zones conflicting with '
'automatic empty zones will be changed to "only"')
logged_once = True
# backup
try:
self.backup_zone(zone)
except Exception:
logger.error('Unable to create backup for zone %s, '
'terminating zone upgrade',
zone['idnsname'][0])
logger.error("%s", traceback.format_exc())
continue
# change forward policy
try:
self.api.Command['dnsforwardzone_mod'](
zone['idnsname'][0],
idnsforwardpolicy=u'only'
)
except Exception as e:
logger.error('Forward policy update for zone %s failed '
'(%s)', zone['idnsname'][0], e)
logger.error("%s", traceback.format_exc())
continue
logger.debug('Zone %s was sucessfully modified to use forward '
'policy "only"', zone['idnsname'][0])
def update_global_ldap_forwarder(self):
config = self.api.Command['dnsconfig_show'](all=True,
raw=True)['result']
if (
config.get('idnsforwardpolicy', [u'first'])[0] == u'first'
and config.get('idnsforwarders', [])
):
logger.info('Global forward policy in LDAP for all servers will '
'be changed to "only" to avoid conflicts with '
'automatic empty zones')
self.backup_zone(config)
self.api.Command['dnsconfig_mod'](idnsforwardpolicy=u'only')
def execute(self, **options):
# check LDAP if DNS subtree already uses new semantics
if not self.version_update_needed(target_version=2):
# forwardzones already use new semantics, no upgrade is required
return False, []
logger.debug('Updating forwarding policies in LDAP '
'to avoid conflicts with automatic empty zones')
# update the DNSVersion, following upgrade can be executed only once
self.api.Command['dnsconfig_mod'](ipadnsversion=2)
self.update_zones()
try:
if dnsutil.has_empty_zone_addresses(self.api.env.host):
self.update_global_ldap_forwarder()
except dns.exception.DNSException as ex:
logger.error('Skipping update of global DNS forwarder in LDAP: '
'Unable to determine if local server is using an '
'IP address belonging to an automatic empty zone. '
'Consider changing forwarding policy to "only". '
'DNS exception: %s', ex)
return False, []
@register()
class update_dnsserver_configuration_into_ldap(DNSUpdater):
"""
DNS Locations feature requires to have DNS configuration stored in LDAP DB.
Create DNS server configuration in LDAP for each old server
"""
def execute(self, **options):
ldap = self.api.Backend.ldap2
if sysupgrade.get_upgrade_state('dns', 'server_config_to_ldap'):
logger.debug('upgrade is not needed')
return False, []
dns_container_dn = DN(self.api.env.container_dns, self.api.env.basedn)
try:
ldap.get_entry(dns_container_dn)
except errors.NotFound:
logger.debug('DNS container not found, nothing to upgrade')
sysupgrade.set_upgrade_state('dns', 'server_config_to_ldap', True)
return False, []
result = self.api.Command.server_show(self.api.env.host)['result']
if 'DNS server' not in result.get('enabled_role_servrole', []):
logger.debug('This server is not DNS server, nothing to upgrade')
sysupgrade.set_upgrade_state('dns', 'server_config_to_ldap', True)
return False, []
# create container first, if doesn't exist
ensure_dnsserver_container_exists(ldap, self.api)
try:
self.api.Command.dnsserver_add(self.api.env.host)
except errors.DuplicateEntry:
logger.debug("DNS server configuration already exists "
"in LDAP database")
else:
logger.debug("DNS server configuration has been sucessfully "
"created in LDAP database")
sysupgrade.set_upgrade_state('dns', 'server_config_to_ldap', True)
return False, []
@register()
class update_krb_uri_txt_records_for_locations(DNSUpdater):
backup_filename = u'dns-krb-uri-txt-records-for-locations-%Y-%m-%d-%H-%M-'\
u'%S.ldif'
def execute(self, **options):
ldap = self.api.Backend.ldap2
if not dns_container_exists(ldap):
return False, []
locations = []
for location in self.api.Command.location_find()['result']:
locations.append(str(location['idnsname'][0]))
if not locations:
return False, []
tmpl_class_attr = 'objectClass'
tmpl_class_value = 'idnsTemplateObject'
cname_tmpl_attr = 'idnsTemplateAttribute;cnamerecord'
cname_tmpl_value = '_kerberos.\\{substitutionvariable_ipalocation\\}.'\
'_locations'
domain = self.env.domain
realm = self.env.realm
dns_updates = []
main_krb_rec = '_kerberos.' + domain + '.'
main_krb_rec_dn = DN(('idnsname', '_kerberos'),
('idnsname', domain + '.'),
self.env.container_dns, self.env.basedn)
try:
entry = ldap.get_entry(main_krb_rec_dn, [
tmpl_class_attr, cname_tmpl_attr,
])
except errors.NotFound:
logger.debug('DNS: %s does not exist, there is no %s record to '
'convert into CNAME', main_krb_rec_dn, main_krb_rec)
else:
cname_updates = []
if tmpl_class_value not in entry.get(tmpl_class_attr, []):
logger.debug('DNS: convert %s into a CNAME record',
main_krb_rec)
cname_updates.append({
'action': 'add',
'attr': tmpl_class_attr,
'value': tmpl_class_value,
})
if cname_tmpl_value not in entry.get(cname_tmpl_attr, []):
logger.debug('DNS: update %s CNAME record to point to location '
'records', main_krb_rec)
cname_updates.append({
'action': 'add',
'attr': cname_tmpl_attr,
'value': cname_tmpl_value,
})
if cname_updates:
dns_updates.append({
'dn': main_krb_rec_dn,
'updates': cname_updates,
})
else:
logger.debug('DNS: %s is already a valid CNAME record',
main_krb_rec)
for location in locations:
location_krb_rec = '_kerberos.' + location + '._locations.' \
+ domain + '.'
location_krb_rec_dn = DN(('idnsname',
'_kerberos.' + location + '._locations'),
('idnsname', domain + '.'),
self.env.container_dns, self.env.basedn)
try:
entry = ldap.get_entry(location_krb_rec_dn, ['tXTRecord'])
except errors.NotFound:
logger.debug('DNS: %s does not exist, there is no %s URI '
'record to rely on to create a TXT record',
location_krb_rec_dn, location_krb_rec)
else:
if 'tXTRecord' in entry:
logger.debug('DNS: there already is a %s TXT record',
location_krb_rec)
else:
logger.debug('DNS: add %s location-aware TXT record',
location_krb_rec)
dns_updates.append({
'dn': location_krb_rec_dn,
'updates': [
{
'action': 'addifnew',
'attr': 'tXTRecord',
'value': f'"{realm}"',
},
],
})
return False, dns_updates
| 26,624
|
Python
|
.py
| 555
| 33.254054
| 107
| 0.547548
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,815
|
delegation.py
|
freeipa_freeipa/ipaserver/plugins/delegation.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Martin Kosek <mkosek@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 ipalib import _, ngettext
from ipalib import Str
from ipalib import api, crud
from ipalib import output
from ipalib import Object
from ipalib.plugable import Registry
from .baseldap import gen_pkey_only_option, pkey_to_value
__doc__ = _("""
Group to Group Delegation
A permission enables fine-grained delegation of permissions. Access Control
Rules, or instructions (ACIs), grant permission to permissions to perform
given tasks such as adding a user, modifying a group, etc.
Group to Group Delegations grants the members of one group to update a set
of attributes of members of another group.
EXAMPLES:
Add a delegation rule to allow managers to edit employee's addresses:
ipa delegation-add --attrs=street --group=managers --membergroup=employees "managers edit employees' street"
When managing the list of attributes you need to include all attributes
in the list, including existing ones. Add postalCode to the list:
ipa delegation-mod --attrs=street --attrs=postalCode --group=managers --membergroup=employees "managers edit employees' street"
Display our updated rule:
ipa delegation-show "managers edit employees' street"
Delete a rule:
ipa delegation-del "managers edit employees' street"
""")
register = Registry()
ACI_PREFIX=u"delegation"
@register()
class delegation(Object):
"""
Delegation object.
"""
bindable = False
object_name = _('delegation')
object_name_plural = _('delegations')
label = _('Delegations')
label_singular = _('Delegation')
takes_params = (
Str('aciname',
cli_name='name',
label=_('Delegation name'),
doc=_('Delegation name'),
primary_key=True,
),
Str('permissions*',
cli_name='permissions',
label=_('Permissions'),
doc=_('Permissions to grant (read, write). Default is write.'),
),
Str('attrs+',
cli_name='attrs',
label=_('Attributes'),
doc=_('Attributes to which the delegation applies'),
normalizer=lambda value: value.lower(),
),
Str('memberof',
cli_name='membergroup',
label=_('Member user group'),
doc=_('User group to apply delegation to'),
),
Str('group',
cli_name='group',
label=_('User group'),
doc=_('User group ACI grants access to'),
),
Str('aci',
label=_('ACI'),
flags={'no_create', 'no_update', 'no_search'},
),
)
def __json__(self):
json_friendly_attributes = (
'label', 'label_singular', 'takes_params', 'bindable', 'name',
'object_name', 'object_name_plural',
)
json_dict = dict(
(a, getattr(self, a)) for a in json_friendly_attributes
)
json_dict['primary_key'] = self.primary_key.name
json_dict['methods'] = list(self.methods)
return json_dict
def postprocess_result(self, result):
try:
# do not include prefix in result
del result['aciprefix']
except KeyError:
pass
@register()
class delegation_add(crud.Create):
__doc__ = _('Add a new delegation.')
msg_summary = _('Added delegation "%(value)s"')
def execute(self, aciname, **kw):
if 'permissions' not in kw:
kw['permissions'] = (u'write',)
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_add'](aciname, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class delegation_del(crud.Delete):
__doc__ = _('Delete a delegation.')
has_output = output.standard_boolean
msg_summary = _('Deleted delegation "%(value)s"')
def execute(self, aciname, **kw):
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_del'](aciname, **kw)
self.obj.postprocess_result(result)
return dict(
result=True,
value=pkey_to_value(aciname, kw),
)
@register()
class delegation_mod(crud.Update):
__doc__ = _('Modify a delegation.')
msg_summary = _('Modified delegation "%(value)s"')
def execute(self, aciname, **kw):
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_mod'](aciname, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class delegation_find(crud.Search):
__doc__ = _('Search for delegations.')
msg_summary = ngettext(
'%(count)d delegation matched', '%(count)d delegations matched', 0
)
takes_options = (gen_pkey_only_option("name"),)
def execute(self, term=None, **kw):
kw['aciprefix'] = ACI_PREFIX
results = api.Command['aci_find'](term, **kw)['result']
for aci in results:
self.obj.postprocess_result(aci)
return dict(
result=results,
count=len(results),
truncated=False,
)
@register()
class delegation_show(crud.Retrieve):
__doc__ = _('Display information about a delegation.')
def execute(self, aciname, **kw):
result = api.Command['aci_show'](aciname, aciprefix=ACI_PREFIX, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
| 6,381
|
Python
|
.py
| 172
| 30.215116
| 130
| 0.634859
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,816
|
stageuser.py
|
freeipa_freeipa/ipaserver/plugins/stageuser.py
|
# Authors:
# Thierry Bordaz <tbordaz@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/>.
from __future__ import absolute_import
import logging
import posixpath
from copy import deepcopy
import six
from ipalib import api, errors
from ipalib import Bool
from ipalib.plugable import Registry
from .baseldap import (
LDAPCreate,
LDAPQuery,
DN)
from . import baseldap
from .baseuser import (
baseuser,
baseuser_add,
baseuser_del,
baseuser_mod,
baseuser_find,
baseuser_show,
NO_UPG_MAGIC,
baseuser_output_params,
baseuser_add_cert,
baseuser_remove_cert,
baseuser_add_principal,
baseuser_remove_principal,
baseuser_add_manager,
baseuser_remove_manager,
baseuser_add_certmapdata,
baseuser_remove_certmapdata,
baseuser_add_passkey,
baseuser_remove_passkey)
from ipalib.request import context
from ipalib.util import set_krbcanonicalname
from ipalib import _, ngettext
from ipalib import output
from ipaplatform.paths import paths
from ipaplatform.constants import constants as platformconstants
from ipapython.ipautil import ipa_generate_password, TMP_PWD_ENTROPY_BITS
from ipalib.capabilities import client_has_capability
if six.PY3:
unicode = str
__doc__ = _("""
Stageusers
Manage stage user entries.
Stage user entries are directly under the container: "cn=stage users,
cn=accounts, cn=provisioning, SUFFIX".
Users can not authenticate with those entries (even if the entries
contain credentials). Those entries are only candidate to become Active entries.
Active user entries are Posix users directly under the container: "cn=accounts, SUFFIX".
Users can authenticate with Active entries, at the condition they have
credentials.
Deleted user entries are Posix users directly under the container: "cn=deleted users,
cn=accounts, cn=provisioning, SUFFIX".
Users can not authenticate with those entries, even if the entries contain credentials.
The stage user container contains entries:
- created by 'stageuser-add' commands that are Posix users,
- created by external provisioning system.
A valid stage user entry MUST have:
- entry RDN is 'uid',
- ipaUniqueID is 'autogenerate'.
IPA supports a wide range of username formats, but you need to be aware of any
restrictions that may apply to your particular environment. For example,
usernames that start with a digit or usernames that exceed a certain length
may cause problems for some UNIX systems.
Use 'ipa config-mod' to change the username format allowed by IPA tools.
The user name must follow these rules:
- cannot contain only numbers
- must start with a letter, a number, _ or .
- may contain letters, numbers, _, ., or -
- may end with a letter, a number, _, ., - or $
EXAMPLES:
Add a new stageuser:
ipa stageuser-add --first=Tim --last=User --password tuser1
Add a stageuser from the deleted users container:
ipa stageuser-add --first=Tim --last=User --from-delete tuser1
""")
logger = logging.getLogger(__name__)
register = Registry()
stageuser_output_params = baseuser_output_params
@register()
class stageuser(baseuser):
"""
Stage User object
A Stage user is not an Active user and can not be used to bind with.
Stage container is: cn=staged users,cn=accounts,cn=provisioning,SUFFIX
Stage entry conforms the schema
Stage entry RDN attribute is 'uid'
Stage entry are disabled (nsAccountLock: True) through cos
"""
container_dn = baseuser.stage_container_dn
label = _('Stage Users')
label_singular = _('Stage User')
object_name = _('stage user')
object_name_plural = _('stage users')
managed_permissions = {
#
# Stage container
#
# Allowed to create stage user
'System: Add Stage User': {
'ipapermlocation': DN(baseuser.stage_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.stage_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'add'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators', 'Stage User Provisioning'},
},
# Allow to read kerberos/password
'System: Read Stage User password': {
'ipapermlocation': DN(baseuser.stage_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.stage_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'userPassword', 'krbPrincipalKey',
},
'default_privileges': {'Stage User Administrators'},
},
# Allow to update stage user
'System: Modify Stage User': {
'ipapermlocation': DN(baseuser.stage_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.stage_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'write'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
# Allow to delete stage user
'System: Remove Stage User': {
'ipapermlocation': DN(baseuser.stage_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.stage_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'delete'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
# Allow to read any attributes of stage users
'System: Read Stage Users': {
'ipapermlocation': DN(baseuser.stage_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.stage_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
#
# Preserve container
#
# Allow to read Preserved User
'System: Read Preserved Users': {
'ipapermlocation': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=posixaccount)'},
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
# Allow to update Preserved User
'System: Modify Preserved Users': {
'ipapermlocation': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=posixaccount)'},
'ipapermright': {'write'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
# Allow to reset Preserved User password
'System: Reset Preserved User password': {
'ipapermlocation': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=posixaccount)'},
'ipapermright': {'read', 'search', 'write'},
'ipapermdefaultattr': {
'userPassword', 'krbPrincipalKey','krbPasswordExpiration','krbLastPwdChange'
},
'default_privileges': {'Stage User Administrators'},
},
# Allow to delete preserved user
'System: Remove preserved User': {
'ipapermlocation': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=*)'},
'ipapermright': {'delete'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Stage User Administrators'},
},
#
# Active container
#
# Stage user administrators need write right on RDN when
# the active user is deleted (preserved)
'System: Modify User RDN': {
'ipapermlocation': DN(baseuser.active_container_dn, api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtarget': DN('uid=*', baseuser.active_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=posixaccount)'},
'ipapermright': {'write'},
'ipapermdefaultattr': {'uid'},
'default_privileges': {'Stage User Administrators'},
},
#
# Cross containers autorization
#
# Allow to move active user to preserve container (user-del --preserve)
# Note: targetfilter is the target parent container
'System: Preserve User': {
'ipapermlocation': DN(api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtargetfrom': DN(baseuser.active_container_dn, api.env.basedn),
'ipapermtargetto': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=nsContainer)'},
'ipapermright': {'moddn'},
'default_privileges': {'Stage User Administrators'},
},
# Allow to move preserved user to active container (user-undel)
# Note: targetfilter is the target parent container
'System: Undelete User': {
'ipapermlocation': DN(api.env.basedn),
'ipapermbindruletype': 'permission',
'ipapermtargetfrom': DN(baseuser.delete_container_dn, api.env.basedn),
'ipapermtargetto': DN(baseuser.active_container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=nsContainer)'},
'ipapermright': {'moddn'},
'default_privileges': {'Stage User Administrators'},
},
}
@register()
class stageuser_add(baseuser_add):
__doc__ = _('Add a new stage user.')
msg_summary = _('Added stage user "%(value)s"')
has_output_params = baseuser_add.has_output_params + stageuser_output_params
takes_options = LDAPCreate.takes_options + (
Bool(
'from_delete?',
deprecated=True,
doc=_('Create Stage user in from a delete user'),
cli_name='from_delete',
flags={'no_option'},
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# then givenname and sn are required attributes
if 'givenname' not in entry_attrs:
raise errors.RequirementError(name='givenname', error=_('givenname is required'))
if 'sn' not in entry_attrs:
raise errors.RequirementError(name='sn', error=_('sn is required'))
# we don't want an user private group to be created for this user
# add NO_UPG_MAGIC description attribute to let the DS plugin know
entry_attrs.setdefault('description', [])
entry_attrs['description'].append(NO_UPG_MAGIC)
# uidNumber/gidNumber
entry_attrs.setdefault('uidnumber', baseldap.DNA_MAGIC)
entry_attrs.setdefault('gidnumber', baseldap.DNA_MAGIC)
if not client_has_capability(
options['version'], 'optional_uid_params'):
# https://fedorahosted.org/freeipa/ticket/2886
# Old clients say 999 (OLD_DNA_MAGIC) when they really mean
# "assign a value dynamically".
OLD_DNA_MAGIC = 999
if entry_attrs.get('uidnumber') == OLD_DNA_MAGIC:
entry_attrs['uidnumber'] = baseldap.DNA_MAGIC
if entry_attrs.get('gidnumber') == OLD_DNA_MAGIC:
entry_attrs['gidnumber'] = baseldap.DNA_MAGIC
# Check the lenght of the RDN (uid) value
config = ldap.get_ipa_config()
if 'ipamaxusernamelength' in config:
if len(keys[-1]) > int(config.get('ipamaxusernamelength')[0]):
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('can be at most %(len)d characters') % dict(
len = int(config.get('ipamaxusernamelength')[0])
)
)
default_shell = config.get('ipadefaultloginshell',
[platformconstants.DEFAULT_SHELL])[0]
entry_attrs.setdefault('loginshell', default_shell)
# hack so we can request separate first and last name in CLI
full_name = '%s %s' % (entry_attrs['givenname'], entry_attrs['sn'])
entry_attrs.setdefault('cn', full_name)
# Homedirectory
# (order is : option, placeholder (TBD), CLI default value (here in config))
if 'homedirectory' not in entry_attrs:
# get home's root directory from config
homes_root = config.get('ipahomesrootdir', [paths.HOME_DIR])[0]
# build user's home directory based on his uid
entry_attrs['homedirectory'] = posixpath.join(homes_root, keys[-1])
# Kerberos principal
entry_attrs.setdefault('krbprincipalname', '%s@%s' % (entry_attrs['uid'], api.env.realm))
# If requested, generate a userpassword
if 'userpassword' not in entry_attrs and options.get('random'):
entry_attrs['userpassword'] = ipa_generate_password(
entropy_bits=TMP_PWD_ENTROPY_BITS)
# save the password so it can be displayed in post_callback
setattr(context, 'randompassword', entry_attrs['userpassword'])
# Check the email or create it
if 'mail' in entry_attrs:
entry_attrs['mail'] = self.obj.normalize_and_validate_email(entry_attrs['mail'], config)
else:
# No e-mail passed in. If we have a default e-mail domain set
# then we'll add it automatically.
defaultdomain = config.get('ipadefaultemaildomain', [None])[0]
if defaultdomain:
entry_attrs['mail'] = self.obj.normalize_and_validate_email(keys[-1], config)
# If the manager is defined, check it is a ACTIVE user to validate it
if 'manager' in entry_attrs:
entry_attrs['manager'] = self.obj.normalize_manager(entry_attrs['manager'], self.obj.active_container_dn)
if ('objectclass' in entry_attrs
and 'userclass' in entry_attrs
and 'ipauser' not in entry_attrs['objectclass']):
entry_attrs['objectclass'].append('ipauser')
if 'ipatokenradiusconfiglink' in entry_attrs:
cl = entry_attrs['ipatokenradiusconfiglink']
if cl:
if 'objectclass' not in entry_attrs:
_entry = ldap.get_entry(dn, ['objectclass'])
entry_attrs['objectclass'] = _entry['objectclass']
if 'ipatokenradiusproxyuser' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('ipatokenradiusproxyuser')
answer = self.api.Object['radiusproxy'].get_dn_if_exists(cl)
entry_attrs['ipatokenradiusconfiglink'] = answer
if 'ipaidpconfiglink' in entry_attrs:
cl = entry_attrs['ipaidpconfiglink']
if cl:
if 'objectclass' not in entry_attrs:
_entry = ldap.get_entry(dn, ['objectclass'])
entry_attrs['objectclass'] = _entry['objectclass']
if 'ipaidpuser' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('ipaidpuser')
try:
answer = self.api.Object['idp'].get_dn_if_exists(cl)
except errors.NotFound:
reason = "External IdP configuration {} not found"
raise errors.NotFound(reason=_(reason).format(cl))
entry_attrs['ipaidpconfiglink'] = answer
self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys,
**options)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
# Fetch the entry again to update memberof, mep data, etc updated
# at the end of the transaction.
newentry = ldap.get_entry(dn, ['*'])
entry_attrs.update(newentry)
if options.get('random', False):
try:
entry_attrs['randompassword'] = unicode(getattr(context, 'randompassword'))
except AttributeError:
# if both randompassword and userpassword options were used
pass
self.post_common_callback(ldap, dn, entry_attrs, *keys, **options)
return dn
@register()
class stageuser_del(baseuser_del):
__doc__ = _('Delete a stage user.')
msg_summary = _('Deleted stage user "%(value)s"')
@register()
class stageuser_mod(baseuser_mod):
__doc__ = _('Modify a stage user.')
msg_summary = _('Modified stage user "%(value)s"')
has_output_params = baseuser_mod.has_output_params + stageuser_output_params
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys,
**options)
# Make sure it is not possible to authenticate with a Stage user account
if 'nsaccountlock' in entry_attrs:
del entry_attrs['nsaccountlock']
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.post_common_callback(ldap, dn, entry_attrs, **options)
if 'nsaccountlock' in entry_attrs:
del entry_attrs['nsaccountlock']
return dn
@register()
class stageuser_find(baseuser_find):
__doc__ = _('Search for stage users.')
member_attributes = ['memberof']
has_output_params = baseuser_find.has_output_params + stageuser_output_params
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *keys, **options):
assert isinstance(base_dn, DN)
self.pre_common_callback(ldap, filter, attrs_list, base_dn, scope,
*keys, **options)
container_filter = ldap.make_filter_from_attr(
'objectclass', 'posixaccount')
# provisioning system can create non posixaccount stage user
# but then they have to create inetOrgPerson stage user
stagefilter = filter.replace(container_filter,
"(|%s(objectclass=inetOrgPerson))" % container_filter)
logger.debug("stageuser_find: pre_callback new filter=%s ",
stagefilter)
return (stagefilter, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
self.post_common_callback(ldap, entries, lockout=True, **options)
return truncated
msg_summary = ngettext(
'%(count)d user matched', '%(count)d users matched', 0
)
@register()
class stageuser_show(baseuser_show):
__doc__ = _('Display information about a stage user.')
has_output_params = baseuser_show.has_output_params + stageuser_output_params
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
self.pre_common_callback(ldap, dn, attrs_list, *keys, **options)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
entry_attrs['nsaccountlock'] = True
self.post_common_callback(ldap, dn, entry_attrs, *keys, **options)
return dn
@register()
class stageuser_activate(LDAPQuery):
__doc__ = _('Activate a stage user.')
msg_summary = _('Activate a stage user "%(value)s"')
preserved_DN_syntax_attrs = ('manager', 'managedby', 'secretary')
searched_operational_attributes = ['uidNumber', 'gidNumber', 'nsAccountLock', 'ipauniqueid']
has_output = output.standard_entry
has_output_params = LDAPQuery.has_output_params + stageuser_output_params
def _check_validy(self, dn, entry):
if dn[0].attr != 'uid':
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('Entry RDN is not \'uid\''),
)
for attr in ('cn', 'sn', 'uid'):
if attr not in entry:
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('Entry has no \'%(attribute)s\'') % dict(attribute=attr),
)
def _build_new_entry(self, ldap, dn, entry_from, entry_to):
config = ldap.get_ipa_config()
if 'uidnumber' not in entry_from:
entry_to['uidnumber'] = baseldap.DNA_MAGIC
if 'gidnumber' not in entry_from:
entry_to['gidnumber'] = baseldap.DNA_MAGIC
if 'homedirectory' not in entry_from:
# get home's root directory from config
homes_root = config.get('ipahomesrootdir', [paths.HOME_DIR])[0]
# build user's home directory based on his uid
entry_to['homedirectory'] = posixpath.join(homes_root, dn[0].value)
if 'ipamaxusernamelength' in config:
if len(dn[0].value) > int(config.get('ipamaxusernamelength')[0]):
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('can be at most %(len)d characters') % dict(
len = int(config.get('ipamaxusernamelength')[0])
)
)
if 'loginshell' not in entry_from:
default_shell = config.get('ipadefaultloginshell',
[platformconstants.DEFAULT_SHELL])[0]
if default_shell:
entry_to.setdefault('loginshell', default_shell)
if 'givenname' not in entry_from:
entry_to['givenname'] = entry_from['cn'][0].split()[0]
if 'krbprincipalname' not in entry_from:
entry_to['krbprincipalname'] = '%s@%s' % (entry_from['uid'][0], api.env.realm)
set_krbcanonicalname(entry_to)
def __dict_new_entry(self, *args, **options):
ldap = self.obj.backend
entry_attrs = self.args_options_2_entry(*args, **options)
entry_attrs = ldap.make_entry(DN(), entry_attrs)
self.process_attr_options(entry_attrs, None, args, options)
entry_attrs['objectclass'] = deepcopy(self.obj.object_class)
if self.obj.object_class_config:
config = ldap.get_ipa_config()
entry_attrs['objectclass'] = deepcopy(config.get(
self.obj.object_class_config, entry_attrs['objectclass']
))
return(entry_attrs)
def __merge_values(self, args, options, entry_from, entry_to, attr):
'''
This routine merges the values of attr taken from entry_from, into entry_to.
If attr is a syntax DN attribute, it is replaced by an empty value. It is a preferable solution
compare to skiping it because the final entry may no longer conform the schema.
An exception of this is for a limited set of syntax DN attribute that we want to
preserved (defined in preserved_DN_syntax_attrs)
see http://www.freeipa.org/page/V3/User_Life-Cycle_Management#Adjustment_of_DN_syntax_attributes
'''
if attr not in entry_to:
if isinstance(entry_from[attr], (list, tuple)):
# attr is multi value attribute
entry_to[attr] = []
else:
# attr single valued attribute
entry_to[attr] = None
# At this point entry_to contains for all resulting attributes
# either a list (possibly empty) or a value (possibly None)
for value in entry_from[attr]:
# merge all the values from->to
v = self.__value_2_add(args, options, attr, value)
if (isinstance(v, str) and v in ('', None)) or \
(isinstance(v, unicode) and v in (u'', None)):
try:
v.decode('utf-8')
logger.debug("merge: %s:%r wiped", attr, v)
except Exception:
logger.debug("merge %s: [no_print %s]",
attr, v.__class__.__name__)
if isinstance(entry_to[attr], (list, tuple)):
# multi value attribute
if v not in entry_to[attr]:
# it may has been added before in the loop
# so add it only if it not present
entry_to[attr].append(v)
else:
# single value attribute
# keep the value defined in staging
entry_to[attr] = v
else:
try:
v.decode('utf-8')
logger.debug("Add: %s:%r", attr, v)
except Exception:
logger.debug("Add %s: [no_print %s]",
attr, v.__class__.__name__)
if isinstance(entry_to[attr], (list, tuple)):
# multi value attribute
if attr.lower() == 'objectclass':
entry_to[attr] = [oc.lower() for oc in entry_to[attr]]
value = value.lower()
if value not in entry_to[attr]:
entry_to[attr].append(value)
else:
if value not in entry_to[attr]:
entry_to[attr].append(value)
else:
# single value attribute
if value:
entry_to[attr] = value
def __value_2_add(self, args, options, attr, value):
'''
If the attribute is NOT syntax DN it returns its value.
Else it checks if the value can be preserved.
To be preserved:
- attribute must be in preserved_DN_syntax_attrs
- value must be an active user DN (in Active container)
- the active user entry exists
'''
ldap = self.obj.backend
if ldap.has_dn_syntax(attr):
if attr.lower() in self.preserved_DN_syntax_attrs:
# we are about to add a DN syntax value
# Check this is a valid DN
if not isinstance(value, DN):
return u''
if not self.obj.active_user(value):
return u''
# Check that this value is a Active user
try:
self._exc_wrapper(args, options, ldap.get_entry)(
value, ['dn']
)
return value
except errors.NotFound:
return u''
else:
return u''
else:
return value
def execute(self, *args, **options):
ldap = self.obj.backend
staging_dn = self.obj.get_dn(*args, **options)
assert isinstance(staging_dn, DN)
# retrieve the current entry
try:
entry_attrs = self._exc_wrapper(args, options, ldap.get_entry)(
staging_dn, ['*']
)
except errors.NotFound:
raise self.obj.handle_not_found(*args)
entry_attrs = dict((k.lower(), v) for (k, v) in entry_attrs.items())
# Check it does not exist an active entry with the same RDN
active_dn = DN(staging_dn[0], api.env.container_user, api.env.basedn)
try:
self._exc_wrapper(args, options, ldap.get_entry)(
active_dn, ['dn']
)
raise errors.DuplicateEntry(
message=_('active user with name "%(user)s" already exists') %
dict(user=args[-1]))
except errors.NotFound:
pass
# Check the original entry is valid
self._check_validy(staging_dn, entry_attrs)
# Time to build the new entry
result_entry = {'dn' : active_dn}
new_entry_attrs = self.__dict_new_entry()
for (attr, values) in entry_attrs.items():
self.__merge_values(args, options, entry_attrs, new_entry_attrs, attr)
result_entry[attr] = values
# Allow Managed entry plugin to do its work
if 'description' in new_entry_attrs and NO_UPG_MAGIC in new_entry_attrs['description']:
new_entry_attrs['description'].remove(NO_UPG_MAGIC)
if result_entry['description'] == NO_UPG_MAGIC:
del result_entry['description']
for (k, v) in new_entry_attrs.items():
logger.debug("new entry: k=%r and v=%r)", k, v)
self._build_new_entry(ldap, staging_dn, entry_attrs, new_entry_attrs)
# Add the Active entry
entry = ldap.make_entry(active_dn, new_entry_attrs)
self._exc_wrapper(args, options, ldap.add_entry)(entry)
# Now delete the Staging entry
try:
self._exc_wrapper(args, options, ldap.delete_entry)(staging_dn)
except BaseException:
try:
logger.error("Fail to delete the Staging user after "
"activating it %s ", staging_dn)
self._exc_wrapper(args, options, ldap.delete_entry)(active_dn)
except Exception:
logger.error("Fail to cleanup activation. The user remains "
"active %s", active_dn)
raise
# add the user we just created into the default primary group
config = ldap.get_ipa_config()
def_primary_group = config.get('ipadefaultprimarygroup')
group_dn = self.api.Object['group'].get_dn(def_primary_group)
# if the user is already a member of default primary group,
# do not raise error
# this can happen if automember rule or default group is set
try:
ldap.add_entry_to_group(active_dn, group_dn)
except errors.AlreadyGroupMember:
pass
# Now retrieve the activated entry
result = self.api.Command.user_show(
args[-1],
all=options.get('all', False),
raw=options.get('raw', False),
version=options.get('version'),
)
result['summary'] = unicode(
_('Stage user %s activated' % staging_dn[0].value))
return result
@register()
class stageuser_add_manager(baseuser_add_manager):
__doc__ = _("Add a manager to the stage user entry")
@register()
class stageuser_remove_manager(baseuser_remove_manager):
__doc__ = _("Remove a manager to the stage user entry")
@register()
class stageuser_add_cert(baseuser_add_cert):
__doc__ = _("Add one or more certificates to the stageuser entry")
msg_summary = _('Added certificates to stageuser "%(value)s"')
@register()
class stageuser_remove_cert(baseuser_remove_cert):
__doc__ = _("Remove one or more certificates to the stageuser entry")
msg_summary = _('Removed certificates from stageuser "%(value)s"')
@register()
class stageuser_add_principal(baseuser_add_principal):
__doc__ = _('Add new principal alias to the stageuser entry')
msg_summary = _('Added new aliases to stageuser "%(value)s"')
@register()
class stageuser_remove_principal(baseuser_remove_principal):
__doc__ = _('Remove principal alias from the stageuser entry')
msg_summary = _('Removed aliases from stageuser "%(value)s"')
@register()
class stageuser_add_certmapdata(baseuser_add_certmapdata):
__doc__ = _("Add one or more certificate mappings to the stage user"
" entry.")
@register()
class stageuser_remove_certmapdata(baseuser_remove_certmapdata):
__doc__ = _("Remove one or more certificate mappings from the stage user"
" entry.")
@register()
class stageuser_add_passkey(baseuser_add_passkey):
__doc__ = _("Add one or more passkey mappings to the stage user"
" entry.")
@register()
class stageuser_remove_passkey(baseuser_remove_passkey):
__doc__ = _("Remove one or more passkey mappings from the stage user"
" entry.")
| 34,072
|
Python
|
.py
| 703
| 37.620199
| 117
| 0.604159
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,817
|
role.py
|
freeipa_freeipa/ipaserver/plugins/role.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# 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 ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember,
LDAPAddReverseMember,
LDAPRemoveReverseMember)
from ipalib import api, Str, _, ngettext
from ipalib import output
from ipapython.dn import DN
from .idviews import handle_idoverride_memberof
__doc__ = _("""
Roles
A role is used for fine-grained delegation. A permission grants the ability
to perform given low-level tasks (add a user, modify a group, etc.). A
privilege combines one or more permissions into a higher-level abstraction
such as useradmin. A useradmin would be able to add, delete and modify users.
Privileges are assigned to Roles.
Users, groups, hosts and hostgroups may be members of a Role.
Roles can not contain other roles.
EXAMPLES:
Add a new role:
ipa role-add --desc="Junior-level admin" junioradmin
Add some privileges to this role:
ipa role-add-privilege --privileges=addusers junioradmin
ipa role-add-privilege --privileges=change_password junioradmin
ipa role-add-privilege --privileges=add_user_to_default_group junioradmin
Add a group of users to this role:
ipa group-add --desc="User admins" useradmins
ipa role-add-member --groups=useradmins junioradmin
Display information about a role:
ipa role-show junioradmin
The result of this is that any users in the group 'junioradmin' can
add users, reset passwords or add a user to the default IPA user group.
""")
register = Registry()
@register()
class role(LDAPObject):
"""
Role object.
"""
container_dn = api.env.container_rolegroup
object_name = _('role')
object_name_plural = _('roles')
object_class = ['groupofnames', 'nestedgroup']
permission_filter_objectclasses = ['groupofnames']
default_attributes = ['cn', 'description', 'member', 'memberof']
# Role could have a lot of indirect members, but they are not in
# attribute_members therefore they don't have to be in default_attributes
# 'memberindirect', 'memberofindirect',
attribute_members = {
'member': ['user', 'group', 'host', 'hostgroup', 'service',
'idoverrideuser'],
'memberof': ['privilege'],
}
reverse_members = {
'member': ['privilege'],
}
allow_rename = True
managed_permissions = {
'System: Read Roles': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'member', 'memberof',
'o', 'objectclass', 'ou', 'owner', 'seealso', 'memberuser',
'memberhost',
},
'default_privileges': {'RBAC Readers'},
},
'System: Add Roles': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=roles,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Roles";allow (add) groupdn = "ldap:///cn=Add Roles,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Delegation Administrator'},
},
'System: Modify Role Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=roles,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Role membership";allow (write) groupdn = "ldap:///cn=Modify Role membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Delegation Administrator'},
},
'System: Modify Roles': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'cn', 'description'},
'replaces': [
'(targetattr = "cn || description")(target = "ldap:///cn=*,cn=roles,cn=accounts,$SUFFIX")(version 3.0; acl "permission:Modify Roles";allow (write) groupdn = "ldap:///cn=Modify Roles,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Delegation Administrator'},
},
'System: Remove Roles': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=roles,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Roles";allow (delete) groupdn = "ldap:///cn=Remove Roles,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Delegation Administrator'},
},
}
label = _('Roles')
label_singular = _('Role')
takes_params = (
Str('cn',
cli_name='name',
label=_('Role name'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this role-group'),
),
)
@register()
class role_add(LDAPCreate):
__doc__ = _('Add a new role.')
msg_summary = _('Added role "%(value)s"')
@register()
class role_del(LDAPDelete):
__doc__ = _('Delete a role.')
msg_summary = _('Deleted role "%(value)s"')
@register()
class role_mod(LDAPUpdate):
__doc__ = _('Modify a role.')
msg_summary = _('Modified role "%(value)s"')
@register()
class role_find(LDAPSearch):
__doc__ = _('Search for roles.')
msg_summary = ngettext(
'%(count)d role matched', '%(count)d roles matched', 0
)
@register()
class role_show(LDAPRetrieve):
__doc__ = _('Display information about a role.')
@register()
class role_add_member(LDAPAddMember):
__doc__ = _('Add members to a role.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
handle_idoverride_memberof(self, ldap, dn, found, not_found,
*keys, **options)
return dn
@register()
class role_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a role.')
@register()
class role_add_privilege(LDAPAddReverseMember):
__doc__ = _('Add privileges to a role.')
show_command = 'role_show'
member_command = 'privilege_add_member'
reverse_attr = 'privilege'
member_attr = 'role'
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of privileges added'),
),
)
@register()
class role_remove_privilege(LDAPRemoveReverseMember):
__doc__ = _('Remove privileges from a role.')
show_command = 'role_show'
member_command = 'privilege_remove_member'
reverse_attr = 'privilege'
member_attr = 'role'
has_output = (
output.Entry('result'),
output.Output(
'failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output(
'completed',
type=int,
doc=_('Number of privileges removed'),
),
)
| 7,964
|
Python
|
.py
| 209
| 31.354067
| 241
| 0.628668
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,818
|
automount.py
|
freeipa_freeipa/ipaserver/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 six
from ipalib import api, errors
from ipalib import Str, IA5Str
from ipalib.plugable import Registry
from .baseldap import (
pkey_to_value,
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPQuery,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve)
from ipalib import _, ngettext
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Automount
Stores automount(8) configuration for autofs(8) in IPA.
The base of an automount configuration is the configuration file auto.master.
This is also the base location in IPA. Multiple auto.master configurations
can be stored in separate locations. A location is implementation-specific
with the default being a location named 'default'. For example, you can have
locations by geographic region, by floor, by type, etc.
Automount has three basic object types: locations, maps and keys.
A location defines a set of maps anchored in auto.master. This allows you
to store multiple automount configurations. A location in itself isn't
very interesting, it is just a point to start a new automount map.
A map is roughly equivalent to a discrete automount file and provides
storage for keys.
A key is a mount point associated with a map.
When a new location is created, two maps are automatically created for
it: auto.master and auto.direct. auto.master is the root map for all
automount maps for the location. auto.direct is the default map for
direct mounts and is mounted on /-.
An automount map may contain a submount key. This key defines a mount
location within the map that references another map. This can be done
either using automountmap-add-indirect --parentmap or manually
with automountkey-add and setting info to "-type=autofs :<mapname>".
EXAMPLES:
Locations:
Create a named location, "Baltimore":
ipa automountlocation-add baltimore
Display the new location:
ipa automountlocation-show baltimore
Find available locations:
ipa automountlocation-find
Remove a named automount location:
ipa automountlocation-del baltimore
Show what the automount maps would look like if they were in the filesystem:
ipa automountlocation-tofiles baltimore
Import an existing configuration into a location:
ipa automountlocation-import baltimore /etc/auto.master
The import will fail if any duplicate entries are found. For
continuous operation where errors are ignored, use the --continue
option.
Maps:
Create a new map, "auto.share":
ipa automountmap-add baltimore auto.share
Display the new map:
ipa automountmap-show baltimore auto.share
Find maps in the location baltimore:
ipa automountmap-find baltimore
Create an indirect map with auto.share as a submount:
ipa automountmap-add-indirect baltimore --parentmap=auto.share --mount=sub auto.man
This is equivalent to:
ipa automountmap-add-indirect baltimore --mount=/man auto.man
ipa automountkey-add baltimore auto.man --key=sub --info="-fstype=autofs ldap:auto.share"
Remove the auto.share map:
ipa automountmap-del baltimore auto.share
Keys:
Create a new key for the auto.share map in location baltimore. This ties
the map we previously created to auto.master:
ipa automountkey-add baltimore auto.master --key=/share --info=auto.share
Create a new key for our auto.share map, an NFS mount for man pages:
ipa automountkey-add baltimore auto.share --key=man --info="-ro,soft,rsize=8192,wsize=8192 ipa.example.com:/shared/man"
Find all keys for the auto.share map:
ipa automountkey-find baltimore auto.share
Find all direct automount keys:
ipa automountkey-find baltimore --key=/-
Remove the man key from the auto.share map:
ipa automountkey-del baltimore auto.share --key=man
""")
"""
Developer notes:
RFC 2707bis http://www.padl.com/~lukeh/rfc2307bis.txt
A few notes on automount:
- The default parent when adding an indirect map is auto.master
- This uses the short format for automount maps instead of the
URL format. Support for ldap as a map source in nsswitch.conf was added
in autofs version 4.1.3-197. Any version prior to that is not expected
to work.
- An indirect key should not begin with /
As an example, the following automount files:
auto.master:
/- auto.direct
/mnt auto.mnt
auto.mnt:
stuff -ro,soft,rsize=8192,wsize=8192 nfs.example.com:/vol/archive/stuff
are equivalent to the following LDAP entries:
# auto.master, automount, example.com
dn: automountmapname=auto.master,cn=automount,dc=example,dc=com
objectClass: automountMap
objectClass: top
automountMapName: auto.master
# auto.direct, automount, example.com
dn: automountmapname=auto.direct,cn=automount,dc=example,dc=com
objectClass: automountMap
objectClass: top
automountMapName: auto.direct
# /-, auto.master, automount, example.com
dn: automountkey=/-,automountmapname=auto.master,cn=automount,dc=example,dc=co
m
objectClass: automount
objectClass: top
automountKey: /-
automountInformation: auto.direct
# auto.mnt, automount, example.com
dn: automountmapname=auto.mnt,cn=automount,dc=example,dc=com
objectClass: automountMap
objectClass: top
automountMapName: auto.mnt
# /mnt, auto.master, automount, example.com
dn: automountkey=/mnt,automountmapname=auto.master,cn=automount,dc=example,dc=
com
objectClass: automount
objectClass: top
automountKey: /mnt
automountInformation: auto.mnt
# stuff, auto.mnt, automount, example.com
dn: automountkey=stuff,automountmapname=auto.mnt,cn=automount,dc=example,dc=com
objectClass: automount
objectClass: top
automountKey: stuff
automountInformation: -ro,soft,rsize=8192,wsize=8192 nfs.example.com:/vol/arch
ive/stuff
"""
register = Registry()
DIRECT_MAP_KEY = u'/-'
@register()
class automountlocation(LDAPObject):
"""
Location container for automount maps.
"""
container_dn = api.env.container_automount
object_name = _('automount location')
object_name_plural = _('automount locations')
object_class = ['nscontainer']
default_attributes = ['cn']
label = _('Automount Locations')
label_singular = _('Automount Location')
permission_filter_objectclasses = ['nscontainer']
managed_permissions = {
'System: Read Automount Configuration': {
# Single permission for all automount-related entries
'non_object': True,
'ipapermlocation': DN(container_dn, api.env.basedn),
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass',
'automountinformation', 'automountkey', 'description',
'automountmapname',
},
},
'System: Add Automount Locations': {
'ipapermright': {'add'},
'default_privileges': {'Automount Administrators'},
},
'System: Remove Automount Locations': {
'ipapermright': {'delete'},
'default_privileges': {'Automount Administrators'},
},
}
takes_params = (
Str('cn',
cli_name='location',
label=_('Location'),
doc=_('Automount location name.'),
primary_key=True,
),
)
@register()
class automountlocation_add(LDAPCreate):
__doc__ = _('Create a new automount location.')
msg_summary = _('Added automount location "%(value)s"')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
# create auto.master for the new location
self.api.Command['automountmap_add'](keys[-1], u'auto.master')
# add additional pre-created maps and keys
# IMPORTANT: add pre-created maps/keys to DEFAULT_MAPS/DEFAULT_KEYS
# so that they do not cause conflicts during import operation
self.api.Command['automountmap_add_indirect'](
keys[-1], u'auto.direct', key=DIRECT_MAP_KEY
)
return dn
@register()
class automountlocation_del(LDAPDelete):
__doc__ = _('Delete an automount location.')
msg_summary = _('Deleted automount location "%(value)s"')
@register()
class automountlocation_show(LDAPRetrieve):
__doc__ = _('Display an automount location.')
@register()
class automountlocation_find(LDAPSearch):
__doc__ = _('Search for an automount location.')
msg_summary = ngettext(
'%(count)d automount location matched',
'%(count)d automount locations matched', 0
)
@register()
class automountlocation_tofiles(LDAPQuery):
__doc__ = _('Generate automount files for a specific location.')
def execute(self, *args, **options):
self.api.Command['automountlocation_show'](args[0])
result = self.api.Command['automountkey_find'](args[0], u'auto.master')
maps = result['result']
# maps, truncated
# TODO: handle truncated results
# ?use ldap.find_entries instead of automountkey_find?
keys = {}
mapnames = [u'auto.master']
for m in maps:
info = m['automountinformation'][0]
mapnames.append(info)
key = info.split(None)
result = self.api.Command['automountkey_find'](args[0], key[0])
keys[info] = result['result']
# TODO: handle truncated results, same as above
allmaps = self.api.Command['automountmap_find'](args[0])['result']
orphanmaps = []
for m in allmaps:
if m['automountmapname'][0] not in mapnames:
orphanmaps.append(m)
orphankeys = []
# Collect all the keys for the orphaned maps
for m in orphanmaps:
key = m['automountmapname']
result = self.api.Command['automountkey_find'](args[0], key[0])
orphankeys.append(result['result'])
return dict(result=dict(maps=maps, keys=keys,
orphanmaps=orphanmaps, orphankeys=orphankeys))
@register()
class automountmap(LDAPObject):
"""
Automount map object.
"""
parent_object = 'automountlocation'
container_dn = api.env.container_automount
object_name = _('automount map')
object_name_plural = _('automount maps')
object_class = ['automountmap']
permission_filter_objectclasses = ['automountmap']
default_attributes = ['automountmapname', 'description']
takes_params = (
IA5Str('automountmapname',
cli_name='map',
label=_('Map'),
doc=_('Automount map name.'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
)
managed_permissions = {
'System: Add Automount Maps': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Add Automount maps";allow (add) groupdn = "ldap:///cn=Add Automount maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
'System: Modify Automount Maps': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'automountmapname', 'description'},
'replaces': [
'(targetattr = "automountmapname || description")(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Modify Automount maps";allow (write) groupdn = "ldap:///cn=Modify Automount maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
'System: Remove Automount Maps': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Remove Automount maps";allow (delete) groupdn = "ldap:///cn=Remove Automount maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
}
label = _('Automount Maps')
label_singular = _('Automount Map')
@register()
class automountmap_add(LDAPCreate):
__doc__ = _('Create a new automount map.')
msg_summary = _('Added automount map "%(value)s"')
@register()
class automountmap_del(LDAPDelete):
__doc__ = _('Delete an automount map.')
msg_summary = _('Deleted automount map "%(value)s"')
def post_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
# delete optional parental connection (direct maps may not have this)
try:
entry_attrs = ldap.find_entry_by_attr(
'automountinformation', keys[1], 'automount',
base_dn=DN(self.obj.container_dn, api.env.basedn)
)
ldap.delete_entry(entry_attrs)
except errors.NotFound:
pass
return True
@register()
class automountmap_mod(LDAPUpdate):
__doc__ = _('Modify an automount map.')
msg_summary = _('Modified automount map "%(value)s"')
@register()
class automountmap_find(LDAPSearch):
__doc__ = _('Search for an automount map.')
msg_summary = ngettext(
'%(count)d automount map matched',
'%(count)d automount maps matched', 0
)
@register()
class automountmap_show(LDAPRetrieve):
__doc__ = _('Display an automount map.')
@register()
class automountkey(LDAPObject):
__doc__ = _('Automount key object.')
parent_object = 'automountmap'
container_dn = api.env.container_automount
object_name = _('automount key')
object_name_plural = _('automount keys')
object_class = ['automount']
permission_filter_objectclasses = ['automount']
default_attributes = [
'automountkey', 'automountinformation', 'description'
]
allow_rename = True
rdn_separator = ' '
takes_params = (
IA5Str('automountkey',
cli_name='key',
label=_('Key'),
doc=_('Automount key name.'),
flags=('req_update',),
),
IA5Str('automountinformation',
cli_name='info',
label=_('Mount information'),
),
Str('description',
label=_('description'),
primary_key=True,
required=False,
flags=['no_create', 'no_update', 'no_search', 'no_output'],
exclude='webui',
),
)
managed_permissions = {
'System: Add Automount Keys': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///automountkey=*,automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Add Automount keys";allow (add) groupdn = "ldap:///cn=Add Automount keys,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(objectclass=automount)")(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Add Automount keys";allow (add) groupdn = "ldap:///cn=Add Automount keys,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
'System: Modify Automount Keys': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'automountinformation', 'automountkey', 'description',
},
'replaces': [
'(targetattr = "automountkey || automountinformation || description")(targetfilter = "(objectclass=automount)")(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Modify Automount keys";allow (write) groupdn = "ldap:///cn=Modify Automount keys,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
'System: Remove Automount Keys': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///automountkey=*,automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Remove Automount keys";allow (delete) groupdn = "ldap:///cn=Remove Automount keys,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(objectclass=automount)")(target = "ldap:///automountmapname=*,cn=automount,$SUFFIX")(version 3.0;acl "permission:Remove Automount keys";allow (delete) groupdn = "ldap:///cn=Remove Automount keys,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Automount Administrators'},
},
}
num_parents = 2
label = _('Automount Keys')
label_singular = _('Automount Key')
already_exists_msg = _('The key,info pair must be unique. A key named %(key)s with info %(info)s already exists')
key_already_exists_msg = _('key named %(key)s already exists')
object_not_found_msg = _('The automount key %(key)s with info %(info)s does not exist')
def get_dn(self, *keys, **kwargs):
# all commands except for create send pk in keys, too
# create cannot due to validation in frontend.py
ldap = self.backend
if len(keys) == self.num_parents:
try:
pkey = kwargs[self.primary_key.name]
except KeyError:
raise ValueError('Not enough keys and pkey not in kwargs')
parent_keys = keys
else:
pkey = keys[-1]
parent_keys = keys[:-1]
parent_dn = self.api.Object[self.parent_object].get_dn(*parent_keys)
dn = self.backend.make_dn_from_attr(
self.primary_key.name,
pkey,
parent_dn
)
# If we're doing an add then just return the dn we created, there
# is no need to check for it.
if kwargs.get('add_operation', False):
return dn
# We had an older mechanism where description consisted of
# 'automountkey automountinformation' so we could support multiple
# direct maps. This made showing keys nearly impossible since it
# required automountinfo to show, which if you had you didn't need
# to look at the key. We still support existing entries but now
# only create this type of dn when the key is /-
#
# First we look with the information given, then try to search for
# the right entry.
try:
dn = ldap.get_entry(dn, ['*']).dn
except errors.NotFound:
if kwargs.get('automountinformation', False):
sfilter = '(&(automountkey=%s)(automountinformation=%s))' % \
(kwargs['automountkey'], kwargs['automountinformation'])
else:
sfilter = '(automountkey=%s)' % kwargs['automountkey']
basedn = DN(('automountmapname', parent_keys[1]),
('cn', parent_keys[0]), self.container_dn,
api.env.basedn)
attrs_list = ['*']
entries = ldap.get_entries(
basedn, ldap.SCOPE_ONELEVEL, sfilter, attrs_list)
if len(entries) > 1:
raise errors.NotFound(reason=_('More than one entry with key %(key)s found, use --info to select specific entry.') % dict(key=pkey))
dn = entries[0].dn
return dn
def handle_not_found(self, *keys):
pkey = keys[-1]
key = pkey.split(self.rdn_separator)[0]
info = self.rdn_separator.join(pkey.split(self.rdn_separator)[1:])
raise errors.NotFound(
reason=self.object_not_found_msg % {
'key': key, 'info': info,
}
)
def handle_duplicate_entry(self, *keys):
pkey = keys[-1]
key = pkey.split(self.rdn_separator)[0]
info = self.rdn_separator.join(pkey.split(self.rdn_separator)[1:])
if info:
raise errors.DuplicateEntry(
message=self.already_exists_msg % {
'key': key, 'info': info,
}
)
else:
raise errors.DuplicateEntry(
message=self.key_already_exists_msg % {
'key': key,
}
)
def get_pk(self, key, info=None):
if key == DIRECT_MAP_KEY and info:
return self.rdn_separator.join((key,info))
else:
return key
def check_key_uniqueness(self, location, map, **keykw):
info = None
key = keykw.get('automountkey')
if key is None:
return
entries = self.methods.find(location, map, automountkey=key)['result']
if len(entries) > 0:
if key == DIRECT_MAP_KEY:
info = keykw.get('automountinformation')
entries = self.methods.find(location, map, **keykw)['result']
if len(entries) > 0:
self.handle_duplicate_entry(location, map, self.get_pk(key, info))
else: return
self.handle_duplicate_entry(location, map, self.get_pk(key, info))
@register()
class automountkey_add(LDAPCreate):
__doc__ = _('Create a new automount key.')
msg_summary = _('Added automount key "%(value)s"')
internal_options = ['description', 'add_operation']
def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
options.pop('add_operation', None)
options.pop('description', None)
self.obj.check_key_uniqueness(keys[-2], keys[-1], **options)
return dn
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
def execute(self, *keys, **options):
key = options['automountkey']
info = options.get('automountinformation', None)
options[self.obj.primary_key.name] = self.obj.get_pk(key, info)
options['add_operation'] = True
result = super(automountkey_add, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['automountkey'], options)
return result
@register()
class automountmap_add_indirect(LDAPCreate):
__doc__ = _('Create a new indirect mount point.')
msg_summary = _('Added automount indirect map "%(value)s"')
takes_options = LDAPCreate.takes_options + (
Str('key',
cli_name='mount',
label=_('Mount point'),
),
Str('parentmap?',
cli_name='parentmap',
label=_('Parent map'),
doc=_('Name of parent automount map (default: auto.master).'),
default=u'auto.master',
autofill=True,
),
)
def execute(self, *keys, **options):
parentmap = options.pop('parentmap', None)
key = options.pop('key')
result = self.api.Command['automountmap_add'](*keys, **options)
try:
if parentmap != u'auto.master':
if key.startswith('/'):
raise errors.ValidationError(name='mount',
error=_('mount point is relative to parent map, '
'cannot begin with /'))
location = keys[0]
map = keys[1]
options['automountinformation'] = map
# Ensure the referenced map exists
self.api.Command['automountmap_show'](location, parentmap)
# Add a submount key
self.api.Command['automountkey_add'](
location, parentmap, automountkey=key,
automountinformation='-fstype=autofs ldap:%s' % map)
else: # adding to auto.master
# Ensure auto.master exists
self.api.Command['automountmap_show'](keys[0], parentmap)
self.api.Command['automountkey_add'](
keys[0], u'auto.master', automountkey=key,
automountinformation=keys[1])
except Exception:
# The key exists, drop the map
self.api.Command['automountmap_del'](*keys)
raise
return result
@register()
class automountkey_del(LDAPDelete):
__doc__ = _('Delete an automount key.')
msg_summary = _('Deleted automount key "%(value)s"')
takes_options = LDAPDelete.takes_options + (
IA5Str('automountkey',
cli_name='key',
label=_('Key'),
doc=_('Automount key name.'),
),
IA5Str('automountinformation?',
cli_name='info',
label=_('Mount information'),
),
)
def get_options(self):
for option in super(automountkey_del, self).get_options():
if option.name == 'continue':
# TODO: hide for now - remove in future major release
yield option.clone(exclude='webui',
flags=['no_option', 'no_output'])
else:
yield option
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
def execute(self, *keys, **options):
keys += (self.obj.get_pk(options['automountkey'],
options.get('automountinformation', None)),)
options[self.obj.primary_key.name] = self.obj.get_pk(
options['automountkey'],
options.get('automountinformation', None))
result = super(automountkey_del, self).execute(*keys, **options)
result['value'] = pkey_to_value([options['automountkey']], options)
return result
@register()
class automountkey_mod(LDAPUpdate):
__doc__ = _('Modify an automount key.')
msg_summary = _('Modified automount key "%(value)s"')
internal_options = ['newautomountkey']
takes_options = LDAPUpdate.takes_options + (
IA5Str('newautomountinformation?',
cli_name='newinfo',
label=_('New mount information'),
),
)
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if 'newautomountkey' in options:
entry_attrs['automountkey'] = options['newautomountkey']
if 'newautomountinformation' in options:
entry_attrs['automountinformation'] = options['newautomountinformation']
return dn
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
key = options['automountkey']
info = options.get('automountinformation', None)
keys += (self.obj.get_pk(key, info), )
# handle RDN changes
if 'rename' in options or 'newautomountinformation' in options:
new_key = options.get('rename', key)
new_info = options.get('newautomountinformation', info)
if new_key == DIRECT_MAP_KEY and not new_info:
# automountinformation attribute of existing LDAP object needs
# to be retrieved so that RDN can be generated
dn = self.obj.get_dn(*keys, **options)
entry_attrs_ = ldap.get_entry(dn, ['automountinformation'])
new_info = entry_attrs_.get('automountinformation', [])[0]
# automounkey attribute cannot be overwritten so that get_dn()
# still works right
options['newautomountkey'] = new_key
new_rdn = self.obj.get_pk(new_key, new_info)
if new_rdn != keys[-1]:
options['rename'] = new_rdn
result = super(automountkey_mod, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['automountkey'], options)
return result
@register()
class automountkey_find(LDAPSearch):
__doc__ = _('Search for an automount key.')
msg_summary = ngettext(
'%(count)d automount key matched',
'%(count)d automount keys matched', 0
)
@register()
class automountkey_show(LDAPRetrieve):
__doc__ = _('Display an automount key.')
takes_options = LDAPRetrieve.takes_options + (
IA5Str('automountkey',
cli_name='key',
label=_('Key'),
doc=_('Automount key name.'),
),
IA5Str('automountinformation?',
cli_name='info',
label=_('Mount information'),
),
)
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
def execute(self, *keys, **options):
keys += (self.obj.get_pk(options['automountkey'],
options.get('automountinformation', None)), )
options[self.obj.primary_key.name] = self.obj.get_pk(
options['automountkey'],
options.get('automountinformation', None))
result = super(automountkey_show, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['automountkey'], options)
return result
| 29,930
|
Python
|
.py
| 691
| 34.696093
| 332
| 0.627763
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,819
|
baseldap.py
|
freeipa_freeipa/ipaserver/plugins/baseldap.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/>.
"""
Base classes for LDAP plugins.
"""
import re
import time
from copy import deepcopy
import base64
import six
from ipalib import api, crud, errors
from ipalib import Method, Object
from ipalib import Flag, Int, Str
from ipalib.cli import to_cli
from ipalib import output
from ipalib.text import _
from ipalib.util import json_serialize, validate_hostname
from ipalib.capabilities import client_has_capability
from ipalib.messages import add_message, SearchResultTruncated
from ipalib.plugable import Registry
from ipapython.dn import DN, RDN
from ipapython.version import API_VERSION
if six.PY3:
unicode = str
DNA_MAGIC = -1
global_output_params = (
Flag('has_password',
label=_('Password'),
),
Str('member',
label=_('Failed members'),
),
Str('member_user?',
label=_('Member users'),
),
Str('member_group?',
label=_('Member groups'),
),
Str('memberof_group?',
label=_('Member of groups'),
),
Str('member_host?',
label=_('Member hosts'),
),
Str('member_hostgroup?',
label=_('Member host-groups'),
),
Str('memberof_hostgroup?',
label=_('Member of host-groups'),
),
Str('memberof_permission?',
label=_('Permissions'),
),
Str('memberof_privilege?',
label='Privileges',
),
Str('memberof_role?',
label=_('Roles'),
),
Str('memberof_sudocmdgroup?',
label=_('Sudo Command Groups'),
),
Str('member_privilege?',
label='Granted to Privilege',
),
Str('member_role?',
label=_('Granting privilege to roles'),
),
Str('member_netgroup?',
label=_('Member netgroups'),
),
Str('memberof_netgroup?',
label=_('Member of netgroups'),
),
Str('member_service?',
label=_('Member services'),
),
Str('member_servicegroup?',
label=_('Member service groups'),
),
Str('memberof_servicegroup?',
label='Member of service groups',
),
Str('member_hbacsvc?',
label=_('Member HBAC service'),
),
Str('member_hbacsvcgroup?',
label=_('Member HBAC service groups'),
),
Str('memberof_hbacsvcgroup?',
label='Member of HBAC service groups',
),
Str('member_sudocmd?',
label='Member Sudo commands',
),
Str('memberof_sudorule?',
label='Member of Sudo rule',
),
Str('memberof_hbacrule?',
label='Member of HBAC rule',
),
Str('memberof_subid?',
label='Subordinate ids',),
Str('member_idoverrideuser?',
label=_('Member ID user overrides'),),
Str('memberindirect_idoverrideuser?',
label=_('Indirect Member ID user overrides'),),
Str('memberindirect_user?',
label=_('Indirect Member users'),
),
Str('memberindirect_group?',
label=_('Indirect Member groups'),
),
Str('memberindirect_host?',
label=_('Indirect Member hosts'),
),
Str('memberindirect_hostgroup?',
label=_('Indirect Member host-groups'),
),
Str('memberindirect_role?',
label=_('Indirect Member of roles'),
),
Str('memberindirect_permission?',
label=_('Indirect Member permissions'),
),
Str('memberindirect_hbacsvc?',
label=_('Indirect Member HBAC service'),
),
Str('memberindirect_hbacsvcgrp?',
label=_('Indirect Member HBAC service group'),
),
Str('memberindirect_netgroup?',
label=_('Indirect Member netgroups'),
),
Str('memberofindirect_group?',
label='Indirect Member of group',
),
Str('memberofindirect_netgroup?',
label='Indirect Member of netgroup',
),
Str('memberofindirect_hostgroup?',
label='Indirect Member of host-group',
),
Str('memberofindirect_role?',
label='Indirect Member of role',
),
Str('memberofindirect_sudorule?',
label='Indirect Member of Sudo rule',
),
Str('memberofindirect_hbacrule?',
label='Indirect Member of HBAC rule',
),
Str('sourcehost',
label=_('Failed source hosts/hostgroups'),
),
Str('memberhost',
label=_('Failed hosts/hostgroups'),
),
Str('memberuser',
label=_('Failed users/groups'),
),
Str('memberservice',
label=_('Failed service/service groups'),
),
Str('failed',
label=_('Failed to remove'),
flags=['suppress_empty'],
),
Str('ipasudorunas',
label=_('Failed RunAs'),
),
Str('ipasudorunasgroup',
label=_('Failed RunAsGroup'),
),
)
def validate_add_attribute(ugettext, attr):
validate_attribute(ugettext, 'addattr', attr)
def validate_set_attribute(ugettext, attr):
validate_attribute(ugettext, 'setattr', attr)
def validate_del_attribute(ugettext, attr):
validate_attribute(ugettext, 'delattr', attr)
def validate_attribute(ugettext, name, attr):
m = re.match(r"\s*(.*?)\s*=\s*(.*?)\s*$", attr)
if not m or len(m.groups()) != 2:
raise errors.ValidationError(
name=name, error=_('Invalid format. Should be name=value'))
def get_effective_rights(ldap, dn, attrs=None):
assert isinstance(dn, DN)
if attrs is None:
attrs = ['*', 'nsaccountlock', 'cospriority']
rights = ldap.get_effective_rights(dn, attrs)
rdict = {}
if 'attributelevelrights' in rights:
rights = rights['attributelevelrights']
rights = rights[0].split(', ')
for r in rights:
(k,v) = r.split(':')
if v == 'none':
# the string "none" means "no rights found"
# see https://fedorahosted.org/freeipa/ticket/4359
v = u''
rdict[k.strip().lower()] = v
return rdict
def entry_from_entry(entry, newentry):
"""
Python is more or less pass-by-value except for immutable objects. So if
you pass in a dict to a function you are free to change members of that
dict but you can't create a new dict in the function and expect to replace
what was passed in.
In some post-op plugins that is exactly what we want to do, so here is a
clumsy way around the problem.
"""
# Wipe out the current data
for e in list(entry):
del entry[e]
# Re-populate it with new wentry
for e in newentry.keys():
entry[e] = newentry[e]
def entry_to_dict(entry, **options):
if options.get('raw', False):
result = {}
for attr in entry:
if attr.lower() == 'attributelevelrights':
value = entry[attr]
elif entry.conn.get_attribute_type(attr) is bytes:
value = entry.raw[attr]
else:
value = list(entry.raw[attr])
for (i, v) in enumerate(value):
try:
value[i] = v.decode('utf-8')
except UnicodeDecodeError:
pass
result[attr] = value
else:
result = dict((k.lower(), v) for (k, v) in entry.items())
if options.get('all', False):
result['dn'] = entry.dn
return result
def pkey_to_unicode(key):
if key is None:
key = []
elif not isinstance(key, (tuple, list)):
key = [key]
key = u','.join(unicode(k) for k in key)
return key
def pkey_to_value(key, options):
version = options.get('version', API_VERSION)
if client_has_capability(version, 'primary_key_types'):
return key
return pkey_to_unicode(key)
def wait_for_value(ldap, dn, attr, value):
"""
389-ds postoperation plugins are executed after the data has been
returned to a client. This means that plugins that add data in a
postop are not included in data returned to the user.
The downside of waiting is that this increases the time of the
command.
The updated entry is returned.
"""
# Loop a few times to give the postop-plugin a chance to complete
# Don't sleep for more than 6 seconds.
x = 0
while x < 20:
# sleep first because the first search, even on a quiet system,
# almost always fails.
time.sleep(.3)
x = x + 1
# FIXME: put a try/except around here? I think it is probably better
# to just let the exception filter up to the caller.
entry_attrs = ldap.get_entry(dn, ['*'])
if attr in entry_attrs:
if isinstance(entry_attrs[attr], (list, tuple)):
values = [y.lower() for y in entry_attrs[attr]]
if value.lower() in values:
break
else:
if value.lower() == entry_attrs[attr].lower():
break
return entry_attrs
def validate_externalhost(ugettext, hostname):
try:
validate_hostname(hostname, check_fqdn=False, allow_underscore=True)
except ValueError as e:
return unicode(e)
return None
external_host_param = Str('externalhost*', validate_externalhost,
label=_('External host'),
flags=['no_option'],
)
# Registry to store member validators called through add_external_pre_callback
# Each validator should be defined as foo(ldap, dn, keys, options, value)
# where (ldap, dn, keys, options) are part of the signature for the
# add_external_pre_callback()
member_validator = Registry()
# validate hostname with allowed underscore characters, non-fqdn
# hostnames are allowed
@member_validator(membertype='host')
def validate_host(ldap, dn, keys, options, hostname):
validate_hostname(hostname, check_fqdn=False, allow_underscore=True)
def add_external_pre_callback(membertype, ldap, dn, keys, options):
"""
Pre callback to validate external members.
This should be called by a command pre callback directly.
membertype is the type of member
"""
assert isinstance(dn, DN)
if options.get(membertype):
validator = None
for cb in member_validator:
if 'membertype' in cb and cb['membertype'] == membertype:
validator = cb['plugin']
if validator is None:
param = api.Object[membertype].primary_key
def generic_validator(ldap, dn, keys, options, value):
value = param(value)
param.validate(value)
validator = generic_validator
for value in options[membertype]:
try:
validator(ldap, dn, keys, options, value)
except errors.ValidationError as e:
raise errors.ValidationError(name=membertype, error=e.error)
except ValueError as e:
raise errors.ValidationError(name=membertype, error=e)
return dn
EXTERNAL_OBJ_PREFIX = 'external '
def pre_callback_process_external_objects(member_attr, object_desc,
ldap, dn, found, not_found,
*keys, **options):
"""
Takes the following arguments:
member_attr - member attribute to process external members for
object_desc - a tuple (type, prefix) to identify a type of an object
('user', 'group', ...) to associate and a prefix to skip
when comparing with an external object. Prefix should be
None for objects that do not have prefixes.
found - the dictionary with all members that were found
not_found - the dictionary with all members which weren't found
keys - list of arguments to the command where this callback is used
options - list of options to the command where this callback is used.
The callback performs validation of objects as external (not existing in
IPA LDAP) and then adds them to a list of not found objects with a mark
'external ..' object if they were resolved as an object from a trusted
domain.
Returns a DN object used for processing dn.
"""
(o_type, o_prefix) = object_desc
if o_type not in options:
return dn
dn = add_external_pre_callback(o_type, ldap, dn, keys, options)
if 'trusted_objects' in options:
trusted_objects = options.pop('trusted_objects')
found_members = found.get(member_attr, {})
found_objects = found_members.get(o_type, [])
filtered_objects = []
for o_id in found_objects:
for obj in trusted_objects:
m = obj
if o_prefix is not None and obj.startswith(o_prefix):
m = obj[len(o_prefix):]
if o_id[0].value.lower() == m.lower():
filtered_objects.append(o_id)
found[member_attr][o_type] = list(
set(found_objects) - set(filtered_objects))
notfound_members = not_found.get(member_attr, {})
notfound_objects = notfound_members.get(o_type, [])
notfound_objects.extend(
[(m, EXTERNAL_OBJ_PREFIX + o_type) for m in trusted_objects])
notfound_members[o_type] = notfound_objects
return dn
def add_external_post_callback(ldap, dn, entry_attrs, failed, completed,
memberattr, membertype, externalattr,
normalize=True, reject_failures=False):
"""
Takes the following arguments:
failed - the list of failed entries, these are candidates for possible
external entries to add
completed - the number of successfully added entries so far
memberattr - the attribute name that IPA uses for membership natively
(e.g. memberhost)
membertype - the object type of the member (e.g. host)
externalattr - the attribute name that IPA uses to store the membership
of the entries that are not managed by IPA
(e.g. externalhost)
Returns the number of completed entries so far (the number of entries
handled by IPA incremented by the number of handled external entries) and
dn.
"""
assert isinstance(dn, DN)
completed_external = 0
# Sift through the failures. We assume that these are all
# entries that aren't stored in IPA, aka external entries.
if memberattr in failed and membertype in failed[memberattr]:
entry_attrs_ = ldap.get_entry(dn, [externalattr])
dn = entry_attrs_.dn
members = entry_attrs.get(memberattr, [])
external_entries = entry_attrs_.get(externalattr, [])
lc_external_entries = set(e.lower() for e in external_entries)
failed_entries = []
for entry in failed[memberattr][membertype]:
# entry is a tuple (name, error)
membername = entry[0].lower()
member_dn = api.Object[membertype].get_dn(membername)
assert isinstance(member_dn, DN)
if (membername not in lc_external_entries and
member_dn not in members):
# Not an IPA entry, only add if it has been marked
# as an external entry during the pre-callback validation
# or if we are not asked to reject failures
if (reject_failures and not entry[1].startswith(
EXTERNAL_OBJ_PREFIX)):
failed_entries.append(membername)
continue
if normalize:
external_entries.append(membername)
else:
external_entries.append(entry[0])
lc_external_entries.add(membername)
completed_external += 1
elif (membername in lc_external_entries and
member_dn not in members):
# Already an external member, reset the error message
msg = unicode(errors.AlreadyGroupMember())
newerror = (entry[0], msg)
ind = failed[memberattr][membertype].index(entry)
failed[memberattr][membertype][ind] = newerror
failed_entries.append(membername)
else:
# Really a failure
failed_entries.append(membername)
if completed_external:
entry_attrs_[externalattr] = external_entries
try:
ldap.update_entry(entry_attrs_)
except errors.EmptyModlist:
pass
failed[memberattr][membertype] = failed_entries
entry_attrs[externalattr] = external_entries
return (completed + completed_external, dn)
def remove_external_post_callback(ldap, dn, entry_attrs, failed, completed,
memberattr, membertype, externalattr):
"""
Takes the following arguments:
failed - the list of failed entries, these are candidates for possible
external entries to remove
completed - the number of successfully removed entries so far
memberattr - the attribute name that IPA uses for membership natively
(e.g. memberhost)
membertype - the object type of the member (e.g. host)
externalattr - the attribute name that IPA uses to store the membership
of the entries that are not managed by IPA
(e.g. externalhost)
Returns the number of completed entries so far (the number of entries
handled by IPA incremented by the number of handled external entries) and
dn.
"""
assert isinstance(dn, DN)
# Run through the failures and gracefully remove any member defined
# as an external member.
completed_external = 0
if memberattr in failed and membertype in failed[memberattr]:
entry_attrs_ = ldap.get_entry(dn, [externalattr])
dn = entry_attrs_.dn
external_entries = entry_attrs_.get(externalattr, [])
failed_entries = []
for entry in failed[memberattr][membertype]:
membername = entry[0].lower()
if membername in external_entries or entry[0] in external_entries:
try:
external_entries.remove(membername)
except ValueError:
external_entries.remove(entry[0])
completed_external += 1
else:
msg = unicode(errors.NotGroupMember())
newerror = (entry[0], msg)
ind = failed[memberattr][membertype].index(entry)
failed[memberattr][membertype][ind] = newerror
failed_entries.append(membername)
if completed_external:
entry_attrs_[externalattr] = external_entries
try:
ldap.update_entry(entry_attrs_)
except errors.EmptyModlist:
pass
failed[memberattr][membertype] = failed_entries
entry_attrs[externalattr] = external_entries
return (completed + completed_external, dn)
def host_is_master(ldap, fqdn):
"""
Check to see if this host is a master.
Raises an exception if a master, otherwise returns nothing.
"""
master_dn = DN(('cn', fqdn), api.env.container_masters, api.env.basedn)
try:
ldap.get_entry(master_dn, ['objectclass'])
raise errors.ValidationError(name='hostname', error=_('An IPA master host cannot be deleted or disabled'))
except errors.NotFound:
# Good, not a master
return
def add_missing_object_class(ldap, objectclass, dn, entry_attrs=None, update=True):
"""
Add object class if missing into entry. Fetches entry if not passed. Updates
the entry by default.
Returns the entry
"""
if not entry_attrs:
entry_attrs = ldap.get_entry(dn, ['objectclass'])
if (objectclass.lower() not in (o.lower() for o in entry_attrs['objectclass'])):
entry_attrs['objectclass'].append(objectclass)
if update:
ldap.update_entry(entry_attrs)
return entry_attrs
class LDAPObject(Object):
"""
Object representing a LDAP entry.
"""
backend_name = 'ldap2'
parent_object = ''
container_dn = ''
object_name = _('entry')
object_name_plural = _('entries')
object_class = []
object_class_config = None
# If an objectclass is possible but not default in an entry. Needed for
# collecting attributes for ACI UI.
possible_objectclasses = []
limit_object_classes = [] # Only attributes in these are allowed
disallow_object_classes = [] # Disallow attributes in these
permission_filter_objectclasses = None
search_attributes = []
search_attributes_config = None
default_attributes = []
search_display_attributes = [] # attributes displayed in LDAPSearch
hidden_attributes = ['objectclass', 'aci']
# set rdn_attribute only if RDN attribute differs from primary key!
rdn_attribute = ''
uuid_attribute = ''
attribute_members = {}
allow_rename = False
password_attributes = []
# Can bind as this entry (has userPassword or krbPrincipalKey)
bindable = False
relationships = {
# attribute: (label, inclusive param prefix, exclusive param prefix)
'member': ('Member', '', 'no_'),
'memberof': ('Member Of', 'in_', 'not_in_'),
'memberindirect': (
'Indirect Member', None, 'no_indirect_'
),
'memberofindirect': (
'Indirect Member Of', None, 'not_in_indirect_'
),
'membermanager': (
'Group membership managed by',
'membermanager_',
'not_membermanager_'
),
}
label = _('Entry')
label_singular = _('Entry')
managed_permissions = {}
container_not_found_msg = _('container entry (%(container)s) not found')
parent_not_found_msg = _('%(parent)s: %(oname)s not found')
object_not_found_msg = _('%(pkey)s: %(oname)s not found')
already_exists_msg = _('%(oname)s with name "%(pkey)s" already exists')
def get_dn(self, *keys, **kwargs):
if self.parent_object:
parent_dn = self.api.Object[self.parent_object].get_dn(*keys[:-1])
else:
parent_dn = DN(self.container_dn, api.env.basedn)
if self.rdn_attribute:
try:
entry_attrs = self.backend.find_entry_by_attr(
self.primary_key.name, keys[-1], self.object_class, [''],
DN(self.container_dn, api.env.basedn)
)
except errors.NotFound:
pass
else:
return entry_attrs.dn
if self.primary_key and keys[-1] is not None:
return self.backend.make_dn_from_attr(
self.primary_key.name, keys[-1], parent_dn
)
assert isinstance(parent_dn, DN)
return parent_dn
def get_dn_if_exists(self, *keys, **kwargs):
dn = self.get_dn(*keys, **kwargs)
entry = self.backend.get_entry(dn, [''])
return entry.dn
def get_primary_key_from_dn(self, dn):
assert isinstance(dn, DN)
try:
if self.rdn_attribute:
entry_attrs = self.backend.get_entry(
dn, [self.primary_key.name]
)
try:
return entry_attrs[self.primary_key.name][0]
except (KeyError, IndexError):
return ''
except errors.NotFound:
pass
try:
return dn[self.primary_key.name]
except KeyError:
# The primary key is not in the DN.
# This shouldn't happen, but we don't want a "show" command to
# crash.
# Just return the entire DN, it's all we have if the entry
# doesn't exist
return unicode(dn)
def get_ancestor_primary_keys(self):
if self.parent_object:
parent_obj = self.api.Object[self.parent_object]
for key in parent_obj.get_ancestor_primary_keys():
yield key
if parent_obj.primary_key:
pkey = parent_obj.primary_key
yield pkey.clone_rename(
parent_obj.name + pkey.name, required=True, query=True,
cli_name=parent_obj.name, label=pkey.label
)
def has_objectclass(self, classes, objectclass):
oc = [x.lower() for x in classes]
return objectclass.lower() in oc
def convert_attribute_members(self, entry_attrs, *keys, **options):
if options.get('raw', False):
return
container_dns = {}
new_attrs = {}
for attr, members in self.attribute_members.items():
try:
value = entry_attrs.raw[attr]
except KeyError:
continue
del entry_attrs[attr]
for member in value:
memberdn = DN(member.decode('utf-8'))
for ldap_obj_name in members:
ldap_obj = self.api.Object[ldap_obj_name]
try:
container_dn = container_dns[ldap_obj_name]
except KeyError:
container_dn = DN(ldap_obj.container_dn, api.env.basedn)
container_dns[ldap_obj_name] = container_dn
if memberdn.endswith(container_dn):
new_value = ldap_obj.get_primary_key_from_dn(memberdn)
new_attr_name = '%s_%s' % (attr, ldap_obj.name)
try:
new_attr = new_attrs[new_attr_name]
except KeyError:
new_attr = entry_attrs.setdefault(new_attr_name, [])
new_attrs[new_attr_name] = new_attr
new_attr.append(new_value)
break
def get_indirect_members(self, entry_attrs, attrs_list):
if 'memberindirect' in attrs_list:
self.get_memberindirect(entry_attrs)
if 'memberofindirect' in attrs_list:
self.get_memberofindirect(entry_attrs)
def get_memberindirect(self, group_entry):
"""
Get indirect members
"""
mo_filter = self.backend.make_filter({'memberof': group_entry.dn})
filter = self.backend.combine_filters(
('(member=*)', mo_filter), self.backend.MATCH_ALL)
try:
result = self.backend.get_entries(
self.api.env.basedn,
filter=filter,
attrs_list=['member'],
size_limit=-1, # paged search will get everything anyway
paged_search=True)
except errors.NotFound:
result = []
indirect = set()
for entry in result:
indirect.update(entry.raw.get('member', []))
indirect.difference_update(group_entry.raw.get('member', []))
if indirect:
group_entry.raw['memberindirect'] = list(indirect)
def get_memberofindirect(self, entry):
dn = entry.dn
filter = self.backend.make_filter(
{
'member': dn,
'memberuser': dn,
'memberhost': dn,
'ipaowner': dn
}
)
try:
result = self.backend.get_entries(
self.api.env.basedn,
filter=filter,
attrs_list=[''],
size_limit=-1, # paged search will get everything anyway
paged_search=True)
except errors.NotFound:
result = []
direct = set()
indirect = set(entry.raw.get('memberof', []))
for group_entry in result:
dn = str(group_entry.dn).encode('utf-8')
if dn in indirect:
indirect.remove(dn)
direct.add(dn)
entry.raw['memberof'] = list(direct)
if indirect:
entry.raw['memberofindirect'] = list(indirect)
def get_password_attributes(self, ldap, dn, entry_attrs):
"""
Search on the entry to determine if it has a password or
keytab set.
A tuple is used to determine which attribute is set
in entry_attrs. The value is set to True/False whether a
given password type is set.
"""
for (pwattr, attr) in self.password_attributes:
search_filter = '(%s=*)' % pwattr
try:
ldap.find_entries(
search_filter, [pwattr], dn, ldap.SCOPE_BASE
)
entry_attrs[attr] = True
except errors.NotFound:
entry_attrs[attr] = False
def handle_not_found(self, *keys):
"""Handle NotFound exception
Must raise errors.NotFound again.
"""
pkey = ''
if self.primary_key:
pkey = keys[-1]
raise errors.NotFound(
reason=self.object_not_found_msg % {
'pkey': pkey, 'oname': self.object_name,
}
)
def handle_duplicate_entry(self, *keys):
try:
pkey = keys[-1]
except IndexError:
pkey = ''
raise errors.DuplicateEntry(
message=self.already_exists_msg % {
'pkey': pkey, 'oname': self.object_name,
}
)
# list of attributes we want exported to JSON
json_friendly_attributes = (
'parent_object', 'container_dn', 'object_name', 'object_name_plural',
'object_class', 'object_class_config', 'default_attributes', 'label', 'label_singular',
'hidden_attributes', 'uuid_attribute', 'attribute_members', 'name',
'takes_params', 'rdn_attribute', 'bindable', 'relationships',
)
def __json__(self):
ldap = self.backend
json_dict = dict(
(a, json_serialize(getattr(self, a))) for a in self.json_friendly_attributes
)
if self.primary_key:
json_dict['primary_key'] = self.primary_key.name
objectclasses = self.object_class
if self.object_class_config:
config = ldap.get_ipa_config()
objectclasses = deepcopy(config.get(
self.object_class_config, objectclasses
))
objectclasses = objectclasses + self.possible_objectclasses
# Get list of available attributes for this object for use
# in the ACI UI.
attrs = self.api.Backend.ldap2.schema.attribute_types(objectclasses)
attrlist = []
# Go through the MUST first
for attr in attrs[0].values():
attrlist.append(attr.names[0].lower())
# And now the MAY
for attr in attrs[1].values():
attrlist.append(attr.names[0].lower())
json_dict['aciattrs'] = attrlist
attrlist.sort()
json_dict['methods'] = list(self.methods)
json_dict['can_have_permissions'] = bool(
self.permission_filter_objectclasses)
return json_dict
# addattr can cause parameters to have more than one value even if not defined
# as multivalue, make sure this isn't the case
def _check_single_value_attrs(params, entry_attrs):
for (a, v) in entry_attrs.items():
if isinstance(v, (list, tuple)) and len(v) > 1:
if a in params and not params[a].multivalue:
raise errors.OnlyOneValueAllowed(attr=a)
# setattr or --option='' can cause parameters to be empty that are otherwise
# required, make sure we enforce that.
def _check_empty_attrs(params, entry_attrs):
for (a, v) in entry_attrs.items():
if v is None or (isinstance(v, str) and len(v) == 0):
if a in params and params[a].required:
raise errors.RequirementError(name=a)
def _check_limit_object_class(attributes, attrs, allow_only):
"""
If the set of objectclasses is limited enforce that only those
are updated in entry_attrs (plus dn)
allow_only tells us what mode to check in:
If True then we enforce that the attributes must be in the list of
allowed.
If False then those attributes are not allowed.
"""
if len(attributes[0]) == 0 and len(attributes[1]) == 0:
return
# Remove options from the attributes names before validating
# LDAP schema does not enforce any of LDAP attribute options
# (e.g. attribute;option), thus we should avoid comparing
# attribute names with options directly.
limitattrs = {x.split(';')[0].lower() for x in attrs}
# Go through the MUST first
for attr in attributes[0].values():
if attr.names[0].lower() in limitattrs:
if not allow_only:
raise errors.ObjectclassViolation(
info=_('attribute "%(attribute)s" not allowed') % dict(
attribute=attr.names[0].lower()))
limitattrs.remove(attr.names[0].lower())
# And now the MAY
for attr in attributes[1].values():
if attr.names[0].lower() in limitattrs:
if not allow_only:
raise errors.ObjectclassViolation(
info=_('attribute "%(attribute)s" not allowed') % dict(
attribute=attr.names[0].lower()))
limitattrs.remove(attr.names[0].lower())
if len(limitattrs) > 0 and allow_only:
raise errors.ObjectclassViolation(
info=_('these attributes are not allowed: %(attrs)s') % dict(
attrs=", ".join(sorted(limitattrs))))
class BaseLDAPCommand(Method):
"""
Base class for Base LDAP Commands.
"""
setattr_option = Str('setattr*', validate_set_attribute,
cli_name='setattr',
doc=_("""Set an attribute to a name/value pair. Format is attr=value.
For multi-valued attributes, the command replaces the values already present."""),
exclude='webui',
)
addattr_option = Str('addattr*', validate_add_attribute,
cli_name='addattr',
doc=_("""Add an attribute/value pair. Format is attr=value. The attribute
must be part of the schema."""),
exclude='webui',
)
delattr_option = Str('delattr*', validate_del_attribute,
cli_name='delattr',
doc=_("""Delete an attribute/value pair. The option will be evaluated
last, after all sets and adds."""),
exclude='webui',
)
callback_types = Method.callback_types + ('pre',
'post',
'exc')
def get_summary_default(self, output):
if 'value' in output:
output = dict(output)
output['value'] = pkey_to_unicode(output['value'])
return super(BaseLDAPCommand, self).get_summary_default(output)
def _convert_2_dict(self, ldap, attrs):
"""
Convert a string in the form of name/value pairs into a dictionary.
:param attrs: A list of name/value pair strings, in the "name=value"
format. May also be a single string, or None.
"""
newdict = {}
if attrs is None:
attrs = []
elif type(attrs) not in (list, tuple):
attrs = [attrs]
for a in attrs:
m = re.match(r"\s*(.*?)\s*=\s*(.*?)\s*$", a)
attr = str(m.group(1)).lower()
value = m.group(2)
if attr in self.obj.params and attr not in self.params:
# The attribute is managed by IPA, but it didn't get cloned
# to the command. This happens with no_update/no_create attrs.
raise errors.ValidationError(
name=attr, error=_('attribute is not configurable'))
if len(value) == 0:
# None means "delete this attribute"
value = None
if attr in newdict:
if type(value) in (tuple,):
newdict[attr] += list(value)
else:
newdict[attr].append(value)
else:
if type(value) in (tuple,):
newdict[attr] = list(value)
else:
newdict[attr] = [value]
return newdict
def process_attr_options(self, entry_attrs, dn, keys, options):
"""
Process all --setattr, --addattr, and --delattr options and add the
resulting value to the list of attributes. --setattr is processed first,
then --addattr and finally --delattr.
When --setattr is not used then the original LDAP object is looked up
(of course, not when dn is None) and the changes are applied to old
object values.
Attribute values deleted by --delattr may be deleted from attribute
values set or added by --setattr, --addattr. For example, the following
attributes will result in a NOOP:
--addattr=attribute=foo --delattr=attribute=foo
AttrValueNotFound exception may be raised when an attribute value was
not found either by --setattr and --addattr nor in existing LDAP object.
:param entry_attrs: A list of attributes that will be updated
:param dn: dn of updated LDAP object or None if a new object is created
:param keys: List of command arguments
:param options: List of options
"""
if all(k not in options for k in ("setattr", "addattr", "delattr")):
return
ldap = self.obj.backend
adddict = self._convert_2_dict(ldap, options.get('addattr', []))
setdict = self._convert_2_dict(ldap, options.get('setattr', []))
deldict = self._convert_2_dict(ldap, options.get('delattr', []))
setattrs = set(setdict)
addattrs = set(adddict)
delattrs = set(deldict)
if dn is None:
direct_add = addattrs
direct_del = delattrs
needldapattrs = []
else:
assert isinstance(dn, DN)
direct_add = setattrs & addattrs
direct_del = setattrs & delattrs
needldapattrs = list((addattrs | delattrs) - setattrs)
for attr, val in setdict.items():
entry_attrs[attr] = val
for attr in direct_add:
try:
val = entry_attrs[attr]
except KeyError:
val = []
else:
if not isinstance(val, (list, tuple)):
val = [val]
elif isinstance(val, tuple):
val = list(val)
val.extend(adddict[attr])
entry_attrs[attr] = val
for attr in direct_del:
for delval in deldict[attr]:
try:
entry_attrs[attr].remove(delval)
except ValueError:
raise errors.AttrValueNotFound(attr=attr, value=delval)
if needldapattrs:
try:
old_entry = self._exc_wrapper(keys, options, ldap.get_entry)(
dn, needldapattrs
)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
# Provide a nice error message when user tries to delete an
# attribute that does not exist on the entry (and user is not
# adding it)
names = set(n.lower() for n in old_entry)
del_nonexisting = delattrs - (names | setattrs | addattrs)
if del_nonexisting:
raise errors.ValidationError(name=del_nonexisting.pop(),
error=_('No such attribute on this entry'))
for attr in needldapattrs:
entry_attrs[attr] = old_entry.get(attr, [])
if attr in addattrs:
entry_attrs[attr].extend(adddict.get(attr, []))
for delval in deldict.get(attr, []):
try:
try:
val = ldap.decode(delval.encode('utf-8'), attr)
entry_attrs[attr].remove(val)
except ValueError:
entry_attrs[attr].remove(delval)
except ValueError:
if isinstance(delval, bytes):
# This is a Binary value, base64 encode it
delval = base64.b64encode(delval).decode('ascii')
raise errors.AttrValueNotFound(attr=attr, value=delval)
# normalize all values
changedattrs = setattrs | addattrs | delattrs
for attr in changedattrs:
if attr in self.params and self.params[attr].attribute:
# convert single-value params to scalars
param = self.params[attr]
value = entry_attrs[attr]
if not param.multivalue:
if len(value) == 1:
value = value[0]
elif not value:
value = None
else:
raise errors.OnlyOneValueAllowed(attr=attr)
# validate, convert and encode params
try:
value = param(value)
param.validate(value)
except errors.ValidationError as err:
raise errors.ValidationError(name=attr, error=err.error)
except errors.ConversionError as err:
raise errors.ConversionError(name=attr, error=err.error)
if isinstance(value, tuple):
value = list(value)
entry_attrs[attr] = value
else:
# unknown attribute: remove duplicite and invalid values
entry_attrs[attr] = list(
{val for val in entry_attrs[attr] if val}
)
if not entry_attrs[attr]:
entry_attrs[attr] = None
elif isinstance(entry_attrs[attr], (tuple, list)) and len(entry_attrs[attr]) == 1:
entry_attrs[attr] = entry_attrs[attr][0]
@classmethod
def register_pre_callback(cls, callback, first=False):
"""Shortcut for register_callback('pre', ...)"""
cls.register_callback('pre', callback, first)
@classmethod
def register_post_callback(cls, callback, first=False):
"""Shortcut for register_callback('post', ...)"""
cls.register_callback('post', callback, first)
@classmethod
def register_exc_callback(cls, callback, first=False):
"""Shortcut for register_callback('exc', ...)"""
cls.register_callback('exc', callback, first)
def _exc_wrapper(self, keys, options, call_func):
"""Function wrapper that automatically calls exception callbacks"""
def wrapped(*call_args, **call_kwargs):
# call call_func first
func = call_func
callbacks = list(self.get_callbacks('exc'))
while True:
try:
return func(*call_args, **call_kwargs)
except errors.ExecutionError as exc:
e = exc
if not callbacks:
raise
# call exc_callback in the next loop
callback = callbacks.pop(0)
def exc_func(*args, **kwargs):
return callback(
self, keys, options, e, call_func, *args, **kwargs)
func = exc_func
return wrapped
def get_options(self):
for param in super(BaseLDAPCommand, self).get_options():
yield param
if self.obj.attribute_members:
for o in self.has_output:
if isinstance(o, (output.Entry, output.ListOfEntries)):
yield Flag('no_members',
doc=_('Suppress processing of membership attributes.'),
exclude='webui',
flags={'no_output'},
)
break
class LDAPCreate(BaseLDAPCommand, crud.Create):
"""
Create a new entry in LDAP.
"""
takes_options = (BaseLDAPCommand.setattr_option, BaseLDAPCommand.addattr_option)
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
for arg in super(LDAPCreate, self).get_args():
yield arg
has_output_params = global_output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
entry_attrs = ldap.make_entry(
dn, self.args_options_2_entry(*keys, **options))
entry_attrs['objectclass'] = deepcopy(self.obj.object_class)
self.process_attr_options(entry_attrs, None, keys, options)
if self.obj.object_class_config:
config = ldap.get_ipa_config()
entry_attrs['objectclass'] = deepcopy(config.get(
self.obj.object_class_config, entry_attrs['objectclass']
))
if self.obj.uuid_attribute:
entry_attrs[self.obj.uuid_attribute] = 'autogenerate'
if self.obj.rdn_attribute:
try:
dn_attr = dn[0].attr
except (IndexError, KeyError):
dn_attr = None
if dn_attr != self.obj.primary_key.name:
self.obj.handle_duplicate_entry(*keys)
entry_attrs.dn = ldap.make_dn(
entry_attrs, self.obj.rdn_attribute,
DN(self.obj.container_dn, api.env.basedn))
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
attrs_list.update(entry_attrs.keys())
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
for callback in self.get_callbacks('pre'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, attrs_list,
*keys, **options)
_check_single_value_attrs(self.params, entry_attrs)
_check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), list(entry_attrs), allow_only=True)
_check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), list(entry_attrs), allow_only=False)
try:
self._exc_wrapper(keys, options, ldap.add_entry)(entry_attrs)
except errors.NotFound:
parent = self.obj.parent_object
if parent:
raise errors.NotFound(
reason=self.obj.parent_not_found_msg % {
'parent': keys[-2],
'oname': self.api.Object[parent].object_name,
}
)
raise errors.NotFound(
reason=self.obj.container_not_found_msg % {
'container': self.obj.container_dn,
}
)
except errors.DuplicateEntry:
self.obj.handle_duplicate_entry(*keys)
try:
if self.obj.rdn_attribute:
# make sure objectclass is either set or None
if self.obj.object_class:
object_class = self.obj.object_class
else:
object_class = None
entry_attrs = self._exc_wrapper(keys, options, ldap.find_entry_by_attr)(
self.obj.primary_key.name, keys[-1], object_class, attrs_list,
DN(self.obj.container_dn, api.env.basedn)
)
else:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
entry_attrs.dn, attrs_list)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.obj.get_indirect_members(entry_attrs, attrs_list)
for callback in self.get_callbacks('post'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, *keys, **options)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
if self.obj.primary_key:
pkey = keys[-1]
else:
pkey = None
return dict(result=entry_attrs, value=pkey_to_value(pkey, options))
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPQuery(BaseLDAPCommand, crud.PKQuery):
"""
Base class for commands that need to retrieve an existing entry.
"""
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
for arg in super(LDAPQuery, self).get_args():
yield arg
class LDAPMultiQuery(LDAPQuery):
"""
Base class for commands that need to retrieve one or more existing entries.
"""
takes_options = (
Flag('continue',
cli_name='continue',
doc=_('Continuous mode: Don\'t stop on errors.'),
),
)
def get_args(self):
for arg in super(LDAPMultiQuery, self).get_args():
if self.obj.primary_key and arg.name == self.obj.primary_key.name:
yield arg.clone(multivalue=True)
else:
yield arg
class LDAPRetrieve(LDAPQuery):
"""
Retrieve an LDAP entry.
"""
has_output = output.standard_entry
has_output_params = global_output_params
takes_options = (
Flag('rights',
label=_('Rights'),
doc=_('Display the access rights of this entry (requires --all). See ipa man page for details.'),
),
)
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
assert isinstance(dn, DN)
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, attrs_list, *keys, **options)
assert isinstance(dn, DN)
try:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
dn, attrs_list
)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.obj.get_indirect_members(entry_attrs, attrs_list)
if options.get('rights', False) and options.get('all', False):
entry_attrs['attributelevelrights'] = get_effective_rights(
ldap, entry_attrs.dn)
for callback in self.get_callbacks('post'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, *keys, **options)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
if self.obj.primary_key:
pkey = keys[-1]
else:
pkey = None
return dict(result=entry_attrs, value=pkey_to_value(pkey, options))
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPUpdate(LDAPQuery, crud.Update):
"""
Update an LDAP entry.
"""
takes_options = (
BaseLDAPCommand.setattr_option,
BaseLDAPCommand.addattr_option,
BaseLDAPCommand.delattr_option,
Flag('rights',
label=_('Rights'),
doc=_('Display the access rights of this entry (requires --all). See ipa man page for details.'),
),
)
has_output_params = global_output_params
def _get_rename_option(self):
rdnparam = getattr(self.obj.params, self.obj.primary_key.name)
return rdnparam.clone_rename('rename',
cli_name='rename', required=False, label=_('Rename'),
doc=_('Rename the %(ldap_obj_name)s object') % dict(
ldap_obj_name=self.obj.object_name
)
)
def get_options(self):
for option in super(LDAPUpdate, self).get_options():
yield option
if self.obj.allow_rename:
yield self._get_rename_option()
def execute(self, *keys, **options):
ldap = self.obj.backend
if len(options) == 2: # 'all' and 'raw' are always sent
raise errors.EmptyModlist()
dn = self.obj.get_dn(*keys, **options)
entry_attrs = ldap.make_entry(dn, self.args_options_2_entry(**options))
self.process_attr_options(entry_attrs, dn, keys, options)
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
attrs_list.update(entry_attrs.keys())
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
_check_single_value_attrs(self.params, entry_attrs)
_check_empty_attrs(self.obj.params, entry_attrs)
for callback in self.get_callbacks('pre'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, attrs_list,
*keys, **options)
_check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.limit_object_classes), list(entry_attrs), allow_only=True)
_check_limit_object_class(self.api.Backend.ldap2.schema.attribute_types(self.obj.disallow_object_classes), list(entry_attrs), allow_only=False)
rdnupdate = False
if 'rename' in options:
if not options['rename']:
raise errors.ValidationError(
name='rename', error=u'can\'t be empty')
entry_attrs[self.obj.primary_key.name] = options['rename']
# if setattr was used to change the RDN, the primary_key.name is
# already in entry_attrs
if self.obj.allow_rename and self.obj.primary_key.name in entry_attrs:
# perform RDN change if the primary key is also RDN
if (RDN((self.obj.primary_key.name, keys[-1])) ==
entry_attrs.dn[0]):
try:
new_dn = DN((self.obj.primary_key.name,
entry_attrs[self.obj.primary_key.name]),
*entry_attrs.dn[1:])
self._exc_wrapper(keys, options, ldap.move_entry)(
entry_attrs.dn,
new_dn)
rdnkeys = (keys[:-1] +
(entry_attrs[self.obj.primary_key.name], ))
entry_attrs.dn = self.obj.get_dn(*rdnkeys)
options['rdnupdate'] = True
rdnupdate = True
except errors.EmptyModlist:
# Attempt to rename to the current name, ignore
pass
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
finally:
# Delete the primary_key from entry_attrs either way
del entry_attrs[self.obj.primary_key.name]
try:
# Exception callbacks will need to test for options['rdnupdate']
# to decide what to do. An EmptyModlist in this context doesn't
# mean an error occurred, just that there were no other updates to
# perform.
update = self._exc_wrapper(keys, options, ldap.get_entry)(
entry_attrs.dn, list(entry_attrs))
update.update(entry_attrs)
self._exc_wrapper(keys, options, ldap.update_entry)(update)
except errors.EmptyModlist as e:
if not rdnupdate:
raise e
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
try:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
entry_attrs.dn, attrs_list)
except errors.NotFound:
raise errors.MidairCollision(
message=_('the entry was deleted while being modified')
)
self.obj.get_indirect_members(entry_attrs, attrs_list)
if options.get('rights', False) and options.get('all', False):
entry_attrs['attributelevelrights'] = get_effective_rights(
ldap, entry_attrs.dn)
for callback in self.get_callbacks('post'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, *keys, **options)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
entry_attrs = entry_to_dict(entry_attrs, **options)
if self.obj.primary_key:
pkey = keys[-1]
else:
pkey = None
return dict(result=entry_attrs, value=pkey_to_value(pkey, options))
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPDelete(LDAPMultiQuery):
"""
Delete an LDAP entry and all of its direct subentries.
"""
has_output = output.standard_multi_delete
has_output_params = global_output_params
subtree_delete = True
def execute(self, *keys, **options):
ldap = self.obj.backend
def delete_entry(pkey):
nkeys = keys[:-1] + (pkey, )
dn = self.obj.get_dn(*nkeys, **options)
assert isinstance(dn, DN)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, *nkeys, **options)
assert isinstance(dn, DN)
def delete_subtree(base_dn):
assert isinstance(base_dn, DN)
truncated = True
while truncated:
try:
(subentries, truncated) = ldap.find_entries(
None, [''], base_dn, ldap.SCOPE_ONELEVEL
)
except errors.NotFound:
break
else:
for entry_attrs in subentries:
delete_subtree(entry_attrs.dn)
try:
self._exc_wrapper(nkeys, options, ldap.delete_entry)(
base_dn
)
except errors.NotFound:
raise self.obj.handle_not_found(*nkeys)
try:
self._exc_wrapper(nkeys, options, ldap.delete_entry)(dn)
except errors.NotFound:
raise self.obj.handle_not_found(*nkeys)
except errors.NotAllowedOnNonLeaf:
if not self.subtree_delete:
raise
# this entry is not a leaf entry, delete all child nodes
delete_subtree(dn)
for callback in self.get_callbacks('post'):
result = callback(self, ldap, dn, *nkeys, **options)
return result
if self.obj.primary_key and isinstance(keys[-1], (list, tuple)):
pkeyiter = keys[-1]
elif keys[-1] is not None:
pkeyiter = [keys[-1]]
else:
pkeyiter = []
deleted = []
failed = []
for pkey in pkeyiter:
try:
delete_entry(pkey)
except errors.ExecutionError:
if not options.get('continue', False):
raise
failed.append(pkey)
else:
deleted.append(pkey)
deleted = pkey_to_value(deleted, options)
failed = pkey_to_value(failed, options)
return dict(result=dict(failed=failed), value=deleted)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
return True
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPModMember(LDAPQuery):
"""
Base class for member manipulation.
"""
member_attributes = ['member']
member_param_doc = _('%s')
member_param_label = _('member %s')
member_count_out = ('%i member processed.', '%i members processed.')
def get_options(self):
for option in super(LDAPModMember, self).get_options():
yield option
for attr in self.member_attributes:
for ldap_obj_name in self.obj.attribute_members[attr]:
ldap_obj = self.api.Object[ldap_obj_name]
name = to_cli(ldap_obj_name)
doc = self.member_param_doc % ldap_obj.object_name_plural
label = self.member_param_label % ldap_obj.object_name
yield Str('%s*' % name, cli_name='%ss' % name, doc=doc,
label=label, alwaysask=True)
def get_member_dns(self, **options):
dns = {}
failed = {}
for attr in self.member_attributes:
dns[attr] = {}
failed[attr] = {}
for ldap_obj_name in self.obj.attribute_members[attr]:
dns[attr][ldap_obj_name] = []
failed[attr][ldap_obj_name] = []
names = options.get(to_cli(ldap_obj_name), [])
if not names:
continue
for name in names:
if not name:
continue
ldap_obj = self.api.Object[ldap_obj_name]
try:
dns[attr][ldap_obj_name].append(ldap_obj.get_dn(name))
except errors.PublicError as e:
failed[attr][ldap_obj_name].append((name, unicode(e)))
return (dns, failed)
class LDAPAddMember(LDAPModMember):
"""
Add other LDAP entries to members.
"""
member_param_doc = _('%s to add')
member_count_out = ('%i member added.', '%i members added.')
allow_same = False
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of members added'),
),
)
has_output_params = global_output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
(member_dns, failed) = self.get_member_dns(**options)
dn = self.obj.get_dn(*keys, **options)
assert isinstance(dn, DN)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, member_dns, failed, *keys, **options)
assert isinstance(dn, DN)
completed = 0
for (attr, objs) in member_dns.items():
for ldap_obj_name in objs:
for m_dn in objs[ldap_obj_name]:
assert isinstance(m_dn, DN)
if not m_dn:
continue
try:
ldap.add_entry_to_group(m_dn, dn, attr, allow_same=self.allow_same)
except errors.PublicError as e:
ldap_obj = self.api.Object[ldap_obj_name]
failed[attr][ldap_obj_name].append((
ldap_obj.get_primary_key_from_dn(m_dn),
unicode(e),)
)
else:
completed += 1
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
attrs_list.update(member_dns.keys())
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
try:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
dn, attrs_list
)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.obj.get_indirect_members(entry_attrs, attrs_list)
for callback in self.get_callbacks('post'):
(completed, entry_attrs.dn) = callback(
self, ldap, completed, failed, entry_attrs.dn, entry_attrs,
*keys, **options)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
return dict(
completed=completed,
failed=failed,
result=entry_attrs,
)
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return (completed, dn)
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPRemoveMember(LDAPModMember):
"""
Remove LDAP entries from members.
"""
member_param_doc = _('%s to remove')
member_count_out = ('%i member removed.', '%i members removed.')
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be removed'),
),
output.Output('completed',
type=int,
doc=_('Number of members removed'),
),
)
has_output_params = global_output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
(member_dns, failed) = self.get_member_dns(**options)
dn = self.obj.get_dn(*keys, **options)
assert isinstance(dn, DN)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, member_dns, failed, *keys, **options)
assert isinstance(dn, DN)
completed = 0
for (attr, objs) in member_dns.items():
for ldap_obj_name, m_dns in objs.items():
for m_dn in m_dns:
assert isinstance(m_dn, DN)
if not m_dn:
continue
try:
ldap.remove_entry_from_group(m_dn, dn, attr)
except errors.PublicError as e:
ldap_obj = self.api.Object[ldap_obj_name]
failed[attr][ldap_obj_name].append((
ldap_obj.get_primary_key_from_dn(m_dn),
unicode(e),)
)
else:
completed += 1
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
attrs_list.update(member_dns.keys())
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
# Give memberOf a chance to update entries
time.sleep(.3)
try:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
dn, attrs_list
)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.obj.get_indirect_members(entry_attrs, attrs_list)
for callback in self.get_callbacks('post'):
(completed, entry_attrs.dn) = callback(
self, ldap, completed, failed, entry_attrs.dn, entry_attrs,
*keys, **options)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
return dict(
completed=completed,
failed=failed,
result=entry_attrs,
)
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return (completed, dn)
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
def gen_pkey_only_option(cli_name):
return Flag('pkey_only?',
label=_('Primary key only'),
doc=_('Results should contain primary key attribute only ("%s")') \
% to_cli(cli_name),)
class LDAPSearch(BaseLDAPCommand, crud.Search):
"""
Retrieve all LDAP entries matching the given criteria.
"""
member_attributes = []
member_param_incl_doc = _('Search for %(searched_object)s with these %(relationship)s %(ldap_object)s.')
member_param_excl_doc = _('Search for %(searched_object)s without these %(relationship)s %(ldap_object)s.')
# LDAPSearch sorts all matched records in the end using their primary key
# as a key attribute
# Set the following attribute to False to turn sorting off
sort_result_entries = True
takes_options = (
Int('timelimit?',
label=_('Time Limit'),
doc=_('Time limit of search in seconds (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
Int('sizelimit?',
label=_('Size Limit'),
doc=_('Maximum number of entries returned (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
)
def get_args(self):
for key in self.obj.get_ancestor_primary_keys():
yield key
for arg in super(LDAPSearch, self).get_args():
yield arg
def get_member_options(self, attr):
for ldap_obj_name in self.obj.attribute_members[attr]:
ldap_obj = self.api.Object[ldap_obj_name]
relationship = self.obj.relationships.get(
attr, ['member', '', 'no_']
)
doc = self.member_param_incl_doc % dict(
searched_object=self.obj.object_name_plural,
relationship=relationship[0].lower(),
ldap_object=ldap_obj.object_name_plural
)
name = '%s%s' % (relationship[1], to_cli(ldap_obj_name))
yield ldap_obj.primary_key.clone_rename(
'%s' % name, cli_name='%ss' % name, doc=doc,
label=ldap_obj.object_name, multivalue=True, query=True,
required=False, primary_key=False
)
doc = self.member_param_excl_doc % dict(
searched_object=self.obj.object_name_plural,
relationship=relationship[0].lower(),
ldap_object=ldap_obj.object_name_plural
)
name = '%s%s' % (relationship[2], to_cli(ldap_obj_name))
yield ldap_obj.primary_key.clone_rename(
'%s' % name, cli_name='%ss' % name, doc=doc,
label=ldap_obj.object_name, multivalue=True, query=True,
required=False, primary_key=False
)
def get_options(self):
for option in super(LDAPSearch, self).get_options():
if option.name == 'no_members':
# no_members are always true for find commands, do not
# show option in CLI but keep API compatibility
option = option.clone(
default=True, flags=option.flags | {"no_option"})
yield option
if self.obj.primary_key and \
'no_output' not in self.obj.primary_key.flags:
yield gen_pkey_only_option(self.obj.primary_key.cli_name)
for attr in self.member_attributes:
for option in self.get_member_options(attr):
yield option
def get_attr_filter(self, ldap, **options):
"""
Returns a MATCH_ALL filter containing all required attributes from the
options
"""
search_kw = self.args_options_2_entry(**options)
search_kw['objectclass'] = self.obj.object_class
filters = []
for name, value in search_kw.items():
default = self.get_default_of(name, **options)
fltr = ldap.make_filter_from_attr(name, value, ldap.MATCH_ALL)
if default is not None and value == default:
fltr = ldap.combine_filters([fltr, '(!({}=*))'.format(name)])
filters.append(fltr)
return ldap.combine_filters(filters, rules=ldap.MATCH_ALL)
def get_term_filter(self, ldap, term):
"""
Returns a filter to search for a value (term) in any of the
search attributes of an entry.
"""
if self.obj.search_attributes:
search_attrs = self.obj.search_attributes
else:
search_attrs = self.obj.default_attributes
if self.obj.search_attributes_config:
config = ldap.get_ipa_config()
config_attrs = config.get(
self.obj.search_attributes_config, [])
if len(config_attrs) == 1 and (
isinstance(config_attrs[0], str)):
search_attrs = config_attrs[0].split(',')
search_kw = {}
for a in search_attrs:
search_kw[a] = term
return ldap.make_filter(search_kw, exact=False)
def get_member_filter(self, ldap, **options):
filter = ''
for attr in self.member_attributes:
for ldap_obj_name in self.obj.attribute_members[attr]:
ldap_obj = self.api.Object[ldap_obj_name]
relationship = self.obj.relationships.get(
attr, ['member', '', 'no_']
)
# Handle positive (MATCH_ALL) and negative (MATCH_NONE)
# searches similarly
param_prefixes = relationship[1:] # e.g. ('in_', 'not_in_')
rules = ldap.MATCH_ALL, ldap.MATCH_NONE
for param_prefix, rule in zip(param_prefixes, rules):
param_name = '%s%s' % (param_prefix, to_cli(ldap_obj_name))
if options.get(param_name):
dns = []
for pkey in options[param_name]:
dns.append(ldap_obj.get_dn(pkey))
flt = ldap.make_filter_from_attr(attr, dns, rule)
filter = ldap.combine_filters(
(filter, flt), ldap.MATCH_ALL
)
return filter
has_output_params = global_output_params
def execute(self, *args, **options):
ldap = self.obj.backend
index = tuple(self.args).index('criteria')
keys = args[:index]
try:
term = args[index]
except IndexError:
term = None
if self.obj.parent_object:
base_dn = self.api.Object[self.obj.parent_object].get_dn(*keys)
else:
base_dn = DN(self.obj.container_dn, api.env.basedn)
assert isinstance(base_dn, DN)
search_kw = self.args_options_2_entry(**options)
if self.obj.search_display_attributes:
defattrs = self.obj.search_display_attributes
else:
defattrs = self.obj.default_attributes
if options.get('pkey_only', False):
attrs_list = [self.obj.primary_key.name]
elif options.get('all', False):
attrs_list = ['*'] + defattrs
else:
attrs_list = set(defattrs)
attrs_list.update(search_kw.keys())
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
attr_filter = self.get_attr_filter(ldap, **options)
term_filter = self.get_term_filter(ldap, term)
member_filter = self.get_member_filter(ldap, **options)
filter = ldap.combine_filters(
(term_filter, attr_filter, member_filter), rules=ldap.MATCH_ALL
)
scope = ldap.SCOPE_ONELEVEL
for callback in self.get_callbacks('pre'):
(filter, base_dn, scope) = callback(
self, ldap, filter, attrs_list, base_dn, scope, *args, **options)
assert isinstance(base_dn, DN)
try:
(entries, truncated) = self._exc_wrapper(args, options, ldap.find_entries)(
filter, attrs_list, base_dn, scope,
time_limit=options.get('timelimit', None),
size_limit=options.get('sizelimit', None)
)
except errors.EmptyResult:
(entries, truncated) = ([], False)
except errors.NotFound:
return self.api.Object[self.obj.parent_object].handle_not_found(
*keys)
for callback in self.get_callbacks('post'):
truncated = callback(
self, ldap, entries, truncated, *args, **options
)
if self.sort_result_entries:
if self.obj.primary_key:
def sort_key(x):
return self.obj.primary_key.sort_key(
x[self.obj.primary_key.name][0])
entries.sort(key=sort_key)
if not options.get('raw', False):
for entry in entries:
self.obj.get_indirect_members(entry, attrs_list)
self.obj.convert_attribute_members(entry, *args, **options)
for (i, e) in enumerate(entries):
entries[i] = entry_to_dict(e, **options)
entries[i]['dn'] = e.dn
result = dict(
result=entries,
count=len(entries),
truncated=bool(truncated),
)
try:
ldap.handle_truncated_result(truncated)
except errors.LimitsExceeded as exc:
add_message(options['version'], result, SearchResultTruncated(
reason=exc))
return result
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
return (filters, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
return truncated
def exc_callback(self, args, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPModReverseMember(LDAPQuery):
"""
Base class for reverse member manipulation.
"""
reverse_attributes = ['member']
reverse_param_doc = _('%s')
reverse_count_out = ('%i member processed.', '%i members processed.')
has_output_params = global_output_params
def get_options(self):
for option in super(LDAPModReverseMember, self).get_options():
yield option
for attr in self.reverse_attributes:
for ldap_obj_name in self.obj.reverse_members[attr]:
ldap_obj = self.api.Object[ldap_obj_name]
name = to_cli(ldap_obj_name)
doc = self.reverse_param_doc % ldap_obj.object_name_plural
yield Str('%s*' % name, cli_name='%ss' % name, doc=doc,
label=ldap_obj.object_name, alwaysask=True)
class LDAPAddReverseMember(LDAPModReverseMember):
"""
Add other LDAP entries to members in reverse.
The call looks like "add A to B" but in fact executes
add B to A to handle reverse membership.
"""
member_param_doc = _('%s to add')
member_count_out = ('%i member added.', '%i members added.')
show_command = None
member_command = None
reverse_attr = None
member_attr = None
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of members added'),
),
)
has_output_params = global_output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
# Ensure our target exists
result = self.api.Command[self.show_command](keys[-1])['result']
dn = result['dn']
assert isinstance(dn, DN)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, *keys, **options)
assert isinstance(dn, DN)
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
completed = 0
failed = {'member': {self.reverse_attr: []}}
for attr in options.get(self.reverse_attr) or []:
try:
options = {'%s' % self.member_attr: keys[-1]}
try:
result = self._exc_wrapper(keys, options, self.api.Command[self.member_command])(attr, **options)
if result['completed'] == 1:
completed = completed + 1
else:
failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1]))
except errors.NotFound as e:
msg = str(e)
(attr, msg) = msg.split(':', 1)
failed['member'][self.reverse_attr].append((attr, unicode(msg.strip())))
except errors.PublicError as e:
failed['member'][self.reverse_attr].append((attr, unicode(e)))
# Update the member data.
entry_attrs = ldap.get_entry(dn, attrs_list)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
for callback in self.get_callbacks('post'):
(completed, entry_attrs.dn) = callback(
self, ldap, completed, failed, entry_attrs.dn, entry_attrs,
*keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
return dict(
completed=completed,
failed=failed,
result=entry_attrs,
)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return (completed, dn)
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class LDAPRemoveReverseMember(LDAPModReverseMember):
"""
Remove other LDAP entries from members in reverse.
The call looks like "remove A from B" but in fact executes
remove B from A to handle reverse membership.
"""
member_param_doc = _('%s to remove')
member_count_out = ('%i member removed.', '%i members removed.')
show_command = None
member_command = None
reverse_attr = None
member_attr = None
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be removed'),
),
output.Output('completed',
type=int,
doc=_('Number of members removed'),
),
)
has_output_params = global_output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
# Ensure our target exists
result = self.api.Command[self.show_command](keys[-1])['result']
dn = result['dn']
assert isinstance(dn, DN)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, *keys, **options)
assert isinstance(dn, DN)
if options.get('all', False):
attrs_list = ['*'] + self.obj.default_attributes
else:
attrs_list = set(self.obj.default_attributes)
if options.get('no_members', False):
attrs_list.difference_update(self.obj.attribute_members)
attrs_list = list(attrs_list)
completed = 0
failed = {'member': {self.reverse_attr: []}}
for attr in options.get(self.reverse_attr) or []:
try:
options = {'%s' % self.member_attr: keys[-1]}
try:
result = self._exc_wrapper(keys, options, self.api.Command[self.member_command])(attr, **options)
if result['completed'] == 1:
completed = completed + 1
else:
failed['member'][self.reverse_attr].append((attr, result['failed']['member'][self.member_attr][0][1]))
except errors.NotFound as e:
msg = str(e)
(attr, msg) = msg.split(':', 1)
failed['member'][self.reverse_attr].append((attr, unicode(msg.strip())))
except errors.PublicError as e:
failed['member'][self.reverse_attr].append((attr, unicode(e)))
# Update the member data.
entry_attrs = ldap.get_entry(dn, attrs_list)
self.obj.convert_attribute_members(entry_attrs, *keys, **options)
for callback in self.get_callbacks('post'):
(completed, entry_attrs.dn) = callback(
self, ldap, completed, failed, entry_attrs.dn, entry_attrs,
*keys, **options)
dn = entry_attrs.dn
entry_attrs = entry_to_dict(entry_attrs, **options)
entry_attrs['dn'] = dn
return dict(
completed=completed,
failed=failed,
result=entry_attrs,
)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return (completed, dn)
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
raise exc
class BaseLDAPModAttribute(LDAPQuery):
attribute = None
has_output = output.standard_entry
def _get_attribute_param(self):
arg = self.obj.params[self.attribute]
attribute = 'virtual_attribute' not in arg.flags
return arg.clone(required=True, attribute=attribute, alwaysask=True)
def _update_attrs(self, update, entry_attrs):
raise NotImplementedError(
"%s.update_attrs()" % self.__class__.__name__
)
def execute(self, *keys, **options):
ldap = self.obj.backend
try:
index = tuple(self.args).index(self.attribute)
except ValueError:
obj_keys = keys
else:
obj_keys = keys[:index]
dn = self.obj.get_dn(*obj_keys, **options)
entry_attrs = ldap.make_entry(dn, self.args_options_2_entry(
*keys, **options))
entry_attrs.pop(self.obj.primary_key.name, None)
if options.get('all', False):
attrs_list = ['*', self.obj.primary_key.name]
else:
attrs_list = {self.obj.primary_key.name}
attrs_list.update(entry_attrs.keys())
attrs_list = list(attrs_list)
for callback in self.get_callbacks('pre'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, attrs_list,
*keys, **options)
try:
update = self._exc_wrapper(keys, options, ldap.get_entry)(
entry_attrs.dn, list(entry_attrs))
self._update_attrs(update, entry_attrs)
self._exc_wrapper(keys, options, ldap.update_entry)(update)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
try:
entry_attrs = self._exc_wrapper(keys, options, ldap.get_entry)(
entry_attrs.dn, attrs_list)
except errors.NotFound:
raise errors.MidairCollision(
message=_('the entry was deleted while being modified')
)
for callback in self.get_callbacks('post'):
entry_attrs.dn = callback(
self, ldap, entry_attrs.dn, entry_attrs, *keys, **options)
entry_attrs = entry_to_dict(entry_attrs, **options)
if self.obj.primary_key:
pkey = obj_keys[-1]
else:
pkey = None
return dict(result=entry_attrs, value=pkey_to_value(pkey, options))
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
assert isinstance(dn, DN)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args,
**call_kwargs):
raise exc
class BaseLDAPAddAttribute(BaseLDAPModAttribute):
msg_summary = _('added attribute value to entry %(value)s')
def _update_attrs(self, update, entry_attrs):
for name, value in entry_attrs.items():
old_value = set(update.get(name, []))
value_to_add = set(value)
if not old_value.isdisjoint(value_to_add):
raise errors.AlreadyContainsValueError(attr=name)
update[name] = list(old_value | value_to_add)
class BaseLDAPRemoveAttribute(BaseLDAPModAttribute):
msg_summary = _('removed attribute values from entry %(value)s')
def _update_attrs(self, update, entry_attrs):
for name, value in entry_attrs.items():
old_value = set(update.get(name, []))
value_to_remove = set(value)
if not value_to_remove.issubset(old_value):
raise errors.AttrValueNotFound(
attr=name, value=_("one or more values to remove"))
update[name] = list(old_value - value_to_remove)
class LDAPModAttribute(BaseLDAPModAttribute):
def get_args(self):
for arg in super(LDAPModAttribute, self).get_args():
yield arg
yield self._get_attribute_param()
class LDAPAddAttribute(LDAPModAttribute, BaseLDAPAddAttribute):
pass
class LDAPRemoveAttribute(LDAPModAttribute, BaseLDAPRemoveAttribute):
pass
class LDAPModAttributeViaOption(BaseLDAPModAttribute):
def get_options(self):
for option in super(LDAPModAttributeViaOption, self).get_options():
yield option
yield self._get_attribute_param()
class LDAPAddAttributeViaOption(LDAPModAttributeViaOption,
BaseLDAPAddAttribute):
pass
class LDAPRemoveAttributeViaOption(LDAPModAttributeViaOption,
BaseLDAPRemoveAttribute):
pass
| 93,201
|
Python
|
.py
| 2,179
| 31.397889
| 151
| 0.574894
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,820
|
selfservice.py
|
freeipa_freeipa/ipaserver/plugins/selfservice.py
|
# Authors:
# Rob Crittenden <rcritten@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 ipalib import _, ngettext
from ipalib import Str
from ipalib import api, crud, errors
from ipalib import output
from ipalib import Object
from ipalib.plugable import Registry
from .baseldap import gen_pkey_only_option, pkey_to_value
__doc__ = _("""
Self-service Permissions
A permission enables fine-grained delegation of permissions. Access Control
Rules, or instructions (ACIs), grant permission to permissions to perform
given tasks such as adding a user, modifying a group, etc.
A Self-service permission defines what an object can change in its own entry.
EXAMPLES:
Add a self-service rule to allow users to manage their address (using Bash
brace expansion):
ipa selfservice-add --permissions=write --attrs={street,postalCode,l,c,st} "Users manage their own address"
When managing the list of attributes you need to include all attributes
in the list, including existing ones.
Add telephoneNumber to the list (using Bash brace expansion):
ipa selfservice-mod --attrs={street,postalCode,l,c,st,telephoneNumber} "Users manage their own address"
Display our updated rule:
ipa selfservice-show "Users manage their own address"
Delete a rule:
ipa selfservice-del "Users manage their own address"
""")
register = Registry()
ACI_PREFIX=u"selfservice"
@register()
class selfservice(Object):
"""
Selfservice object.
"""
bindable = False
object_name = _('self service permission')
object_name_plural = _('self service permissions')
label = _('Self Service Permissions')
label_singular = _('Self Service Permission')
takes_params = (
Str('aciname',
cli_name='name',
label=_('Self-service name'),
doc=_('Self-service name'),
primary_key=True,
pattern='^[-_ a-zA-Z0-9]+$',
pattern_errmsg="May only contain letters, numbers, -, _, and space",
),
Str('permissions*',
cli_name='permissions',
label=_('Permissions'),
doc=_('Permissions to grant (read, write). Default is write.'),
),
Str('attrs+',
cli_name='attrs',
label=_('Attributes'),
doc=_('Attributes to which the permission applies.'),
normalizer=lambda value: value.lower(),
),
Str('aci',
label=_('ACI'),
flags={'no_create', 'no_update', 'no_search'},
),
)
def __json__(self):
json_friendly_attributes = (
'label', 'label_singular', 'takes_params', 'bindable', 'name',
'object_name', 'object_name_plural',
)
json_dict = dict(
(a, getattr(self, a)) for a in json_friendly_attributes
)
json_dict['primary_key'] = self.primary_key.name
json_dict['methods'] = list(self.methods)
return json_dict
def postprocess_result(self, result):
try:
# do not include prefix in result
del result['aciprefix']
except KeyError:
pass
@register()
class selfservice_add(crud.Create):
__doc__ = _('Add a new self-service permission.')
msg_summary = _('Added selfservice "%(value)s"')
def execute(self, aciname, **kw):
if 'permissions' not in kw:
kw['permissions'] = (u'write',)
kw['selfaci'] = True
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_add'](aciname, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class selfservice_del(crud.Delete):
__doc__ = _('Delete a self-service permission.')
has_output = output.standard_boolean
msg_summary = _('Deleted selfservice "%(value)s"')
def execute(self, aciname, **kw):
result = api.Command['aci_del'](aciname, aciprefix=ACI_PREFIX)
self.obj.postprocess_result(result)
return dict(
result=True,
value=pkey_to_value(aciname, kw),
)
@register()
class selfservice_mod(crud.Update):
__doc__ = _('Modify a self-service permission.')
msg_summary = _('Modified selfservice "%(value)s"')
def execute(self, aciname, **kw):
if 'attrs' in kw and kw['attrs'] is None:
raise errors.RequirementError(name='attrs')
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_mod'](aciname, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class selfservice_find(crud.Search):
__doc__ = _('Search for a self-service permission.')
msg_summary = ngettext(
'%(count)d selfservice matched', '%(count)d selfservices matched', 0
)
takes_options = (gen_pkey_only_option("name"),)
def execute(self, term=None, **kw):
kw['selfaci'] = True
kw['aciprefix'] = ACI_PREFIX
result = api.Command['aci_find'](term, **kw)['result']
for aci in result:
self.obj.postprocess_result(aci)
return dict(
result=result,
count=len(result),
truncated=False,
)
@register()
class selfservice_show(crud.Retrieve):
__doc__ = _('Display information about a self-service permission.')
def execute(self, aciname, **kw):
result = api.Command['aci_show'](aciname, aciprefix=ACI_PREFIX, **kw)['result']
self.obj.postprocess_result(result)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
| 6,424
|
Python
|
.py
| 167
| 31.694611
| 110
| 0.643686
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,821
|
sudorule.py
|
freeipa_freeipa/ipaserver/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/>.
import netaddr
import six
from ipalib import api, errors
from ipalib import Str, StrEnum, Bool, Int
from ipalib.plugable import Registry
from .baseldap import (LDAPObject, LDAPCreate, LDAPDelete,
LDAPUpdate, LDAPSearch, LDAPRetrieve,
LDAPQuery, LDAPAddMember, LDAPRemoveMember,
add_external_pre_callback,
pre_callback_process_external_objects,
add_external_post_callback,
remove_external_post_callback,
output, entry_to_dict, pkey_to_value,
external_host_param)
from .hbacrule import is_all
from ipalib import _, ngettext
from ipalib.util import validate_hostmask
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Sudo Rules
""") + _("""
Sudo (su "do") allows a system administrator to delegate authority to
give certain users (or groups of users) the ability to run some (or all)
commands as root or another user while providing an audit trail of the
commands and their arguments.
""") + _("""
IPA provides a means to configure the various aspects of Sudo:
Users: The user(s)/group(s) allowed to invoke Sudo.
Hosts: The host(s)/hostgroup(s) which the user is allowed to to invoke Sudo.
Allow Command: The specific command(s) permitted to be run via Sudo.
Deny Command: The specific command(s) prohibited to be run via Sudo.
RunAsUser: The user(s) or group(s) of users whose rights Sudo will be invoked with.
RunAsGroup: The group(s) whose gid rights Sudo will be invoked with.
Options: The various Sudoers Options that can modify Sudo's behavior.
""") + _("""
Each option needs to be added separately and no validation is done whether
the option is known by sudo or is in a valid format. Environment variables
also need to be set individually. For example env_keep="FOO BAR" in sudoers
needs be represented as --sudooption env_keep=FOO --sudooption env_keep+=BAR.
""") + _("""
An order can be added to a sudorule to control the order in which they
are evaluated (if the client supports it). This order is an integer and
must be unique.
""") + _("""
IPA provides a designated binddn to use with Sudo located at:
uid=sudo,cn=sysaccounts,cn=etc,dc=example,dc=com
""") + _("""
To enable the binddn run the following command to set the password:
LDAPTLS_CACERT=/etc/ipa/ca.crt /usr/bin/ldappasswd -S -W \
-H ldap://ipa.example.com -ZZ -D "cn=Directory Manager" \
uid=sudo,cn=sysaccounts,cn=etc,dc=example,dc=com
""") + _("""
EXAMPLES:
""") + _("""
Create a new rule:
ipa sudorule-add readfiles
""") + _("""
Add sudo command object and add it as allowed command in the rule:
ipa sudocmd-add /usr/bin/less
ipa sudorule-add-allow-command readfiles --sudocmds /usr/bin/less
""") + _("""
Add a host to the rule:
ipa sudorule-add-host readfiles --hosts server.example.com
""") + _("""
Add a user to the rule:
ipa sudorule-add-user readfiles --users jsmith
""") + _("""
Add a special Sudo rule for default Sudo server configuration:
ipa sudorule-add defaults
""") + _("""
Set a default Sudo option:
ipa sudorule-add-option defaults --sudooption '!authenticate'
""") + _("""
Set multiple default Sudo options:
ipa sudorule-add-option defaults --sudooption '!authenticate' \
--sudooption mail_badpass
""") + _("""
Set SELinux type and role transitions on a rule:
ipa sudorule-add-option sysadmin_sudo --sudooption type=unconfined_t
ipa sudorule-add-option sysadmin_sudo --sudooption role=unconfined_r
""")
register = Registry()
topic = 'sudo'
# used to process external object references in SUDO rules
USER_OBJ_SPEC = ('user', None)
GROUP_OBJ_SPEC = ('group', '%')
def deprecated(attribute):
raise errors.ValidationError(
name=attribute,
error=_('this option has been deprecated.'))
hostmask_membership_param = Str('hostmask?', validate_hostmask,
label=_('host masks of allowed hosts'),
flags=['no_create', 'no_update', 'no_search'],
multivalue=True,
)
def validate_externaluser(ugettext, value):
deprecated('externaluser')
def validate_runasextuser(ugettext, value):
deprecated('runasexternaluser')
def validate_runasextgroup(ugettext, value):
deprecated('runasexternalgroup')
@register()
class sudorule(LDAPObject):
"""
Sudo Rule object.
"""
container_dn = api.env.container_sudorule
object_name = _('sudo rule')
object_name_plural = _('sudo rules')
object_class = ['ipaassociation', 'ipasudorule']
permission_filter_objectclasses = ['ipasudorule']
default_attributes = [
'cn', 'ipaenabledflag', 'externaluser',
'description', 'usercategory', 'hostcategory',
'cmdcategory', 'memberuser', 'memberhost',
'memberallowcmd', 'memberdenycmd', 'ipasudoopt',
'ipasudorunas', 'ipasudorunasgroup',
'ipasudorunasusercategory', 'ipasudorunasgroupcategory',
'sudoorder', 'hostmask', 'externalhost', 'ipasudorunasextusergroup',
'ipasudorunasextgroup', 'ipasudorunasextuser'
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
allow_rename = True
attribute_members = {
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
'memberallowcmd': ['sudocmd', 'sudocmdgroup'],
'memberdenycmd': ['sudocmd', 'sudocmdgroup'],
'ipasudorunas': ['user', 'group'],
'ipasudorunasgroup': ['group'],
}
managed_permissions = {
'System: Read Sudo Rules': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cmdcategory', 'cn', 'description', 'externalhost',
'externaluser', 'hostcategory', 'hostmask', 'ipaenabledflag',
'ipasudoopt', 'ipasudorunas', 'ipasudorunasextgroup',
'ipasudorunasextuser', 'ipasudorunasextusergroup',
'ipasudorunasgroup',
'ipasudorunasgroupcategory', 'ipasudorunasusercategory',
'ipauniqueid', 'memberallowcmd', 'memberdenycmd',
'memberhost', 'memberuser', 'sudonotafter', 'sudonotbefore',
'sudoorder', 'usercategory', 'objectclass', 'member',
},
},
'System: Read Sudoers compat tree': {
'non_object': True,
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('ou=sudoers', api.env.basedn),
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'ou',
'sudouser', 'sudohost', 'sudocommand', 'sudorunas',
'sudorunasuser', 'sudorunasgroup', 'sudooption',
'sudonotbefore', 'sudonotafter', 'sudoorder', 'description',
},
},
'System: Add Sudo rule': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=sudorules,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Add Sudo rule";allow (add) groupdn = "ldap:///cn=Add Sudo rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Delete Sudo rule': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=sudorules,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Delete Sudo rule";allow (delete) groupdn = "ldap:///cn=Delete Sudo rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Modify Sudo rule': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'description', 'ipaenabledflag', 'usercategory',
'hostcategory', 'cmdcategory', 'ipasudorunasusercategory',
'ipasudorunasgroupcategory', 'externaluser',
'ipasudorunasextusergroup',
'ipasudorunasextuser', 'ipasudorunasextgroup', 'memberdenycmd',
'memberallowcmd', 'memberuser', 'memberhost', 'externalhost',
'sudonotafter', 'hostmask', 'sudoorder', 'sudonotbefore',
'ipasudorunas', 'ipasudorunasgroup',
'ipasudoopt',
},
'replaces': [
'(targetattr = "description || ipaenabledflag || usercategory || hostcategory || cmdcategory || ipasudorunasusercategory || ipasudorunasgroupcategory || externaluser || ipasudorunasextuser || ipasudorunasextgroup || memberdenycmd || memberallowcmd || memberuser")(target = "ldap:///ipauniqueid=*,cn=sudorules,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Modify Sudo rule";allow (write) groupdn = "ldap:///cn=Modify Sudo rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
}
label = _('Sudo Rules')
label_singular = _('Sudo Rule')
takes_params = (
Str('cn',
cli_name='sudorule_name',
label=_('Rule name'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Bool('ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
),
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the rule applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the rule applies to'),
values=(u'all', ),
),
StrEnum('cmdcategory?',
cli_name='cmdcat',
label=_('Command category'),
doc=_('Command category the rule applies to'),
values=(u'all', ),
),
StrEnum('ipasudorunasusercategory?',
cli_name='runasusercat',
label=_('RunAs User category'),
doc=_('RunAs User category the rule applies to'),
values=(u'all', ),
),
StrEnum('ipasudorunasgroupcategory?',
cli_name='runasgroupcat',
label=_('RunAs Group category'),
doc=_('RunAs Group category the rule applies to'),
values=(u'all', ),
),
Int('sudoorder?',
cli_name='order',
label=_('Sudo order'),
doc=_('integer to order the Sudo rules'),
default=0,
minvalue=0,
),
Str('memberuser_user?',
label=_('Users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_group?',
label=_('User Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('externaluser?', validate_externaluser,
cli_name='externaluser',
label=_('External User'),
doc=_('External User the rule applies to (sudorule-find only)'),
),
Str('memberhost_host?',
label=_('Hosts'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_hostgroup?',
label=_('Host Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('hostmask', validate_hostmask,
normalizer=lambda x: unicode(netaddr.IPNetwork(x).cidr),
label=_('Host Masks'),
flags=['no_create', 'no_update', 'no_search'],
multivalue=True,
),
external_host_param,
Str('memberallowcmd_sudocmd?',
label=_('Sudo Allow Commands'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberdenycmd_sudocmd?',
label=_('Sudo Deny Commands'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberallowcmd_sudocmdgroup?',
label=_('Sudo Allow Command Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberdenycmd_sudocmdgroup?',
label=_('Sudo Deny Command Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipasudorunas_user?',
label=_('RunAs Users'),
doc=_('Run as a user'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipasudorunas_group?',
label=_('Groups of RunAs Users'),
doc=_('Run as any user within a specified group'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipasudorunasextuser?', validate_runasextuser,
cli_name='runasexternaluser',
label=_('RunAs External User'),
doc=_('External User the commands can run as (sudorule-find only)'),
),
Str('ipasudorunasextusergroup?',
cli_name='runasexternalusergroup',
label=_('External Groups of RunAs Users'),
doc=_('External Groups of users that the command can run as'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipasudorunasgroup_group?',
label=_('RunAs Groups'),
doc=_('Run with the gid of a specified POSIX group'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipasudorunasextgroup?', validate_runasextgroup,
cli_name='runasexternalgroup',
label=_('RunAs External Group'),
doc=_('External Group the commands can run as (sudorule-find only)'),
),
Str('ipasudoopt*',
label=_('Sudo Option'),
flags=['no_create', 'no_update', 'no_search'],
),
)
order_not_unique_msg = _(
'order must be a unique value (%(order)d already used by %(rule)s)'
)
def check_order_uniqueness(self, *keys, **options):
if options.get('sudoorder') is not None:
entries = self.methods.find(
sudoorder=options['sudoorder']
)['result']
if len(entries) > 0:
rule_name = entries[0]['cn'][0]
raise errors.ValidationError(
name='order',
error=self.order_not_unique_msg % {
'order': options['sudoorder'],
'rule': rule_name,
}
)
@register()
class sudorule_add(LDAPCreate):
__doc__ = _('Create new Sudo Rule.')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
self.obj.check_order_uniqueness(*keys, **options)
# Sudo Rules are enabled by default
entry_attrs['ipaenabledflag'] = True
return dn
msg_summary = _('Added Sudo Rule "%(value)s"')
@register()
class sudorule_del(LDAPDelete):
__doc__ = _('Delete Sudo Rule.')
msg_summary = _('Deleted Sudo Rule "%(value)s"')
@register()
class sudorule_mod(LDAPUpdate):
__doc__ = _('Modify Sudo Rule.')
msg_summary = _('Modified Sudo Rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if 'sudoorder' in options:
new_order = options.get('sudoorder')
if 'sudoorder' in _entry_attrs:
old_order = int(_entry_attrs['sudoorder'][0])
if old_order != new_order:
self.obj.check_order_uniqueness(*keys, **options)
else:
self.obj.check_order_uniqueness(*keys, **options)
error = _("%(type)s category cannot be set to 'all' "
"while there are allowed %(objects)s")
category_info = [(
'usercategory',
['memberuser', 'externaluser'],
error % {'type': _('user'), 'objects': _('users')}
),
(
'hostcategory',
['memberhost', 'externalhost', 'hostmask'],
error % {'type': _('host'), 'objects': _('hosts')}
),
(
'cmdcategory',
['memberallowcmd'],
error % {'type': _('command'), 'objects': _('commands')}
),
(
'ipasudorunasusercategory',
['ipasudorunas', 'ipasudorunasextuser',
'ipasudorunasextusergroup'],
error % {'type': _('runAs user'), 'objects': _('runAs users')}
),
(
'ipasudorunasgroupcategory',
['ipasudorunasgroup', 'ipasudorunasextgroup'],
error % {'type': _('group runAs'), 'objects': _('runAs groups')}
),
]
# Enforce the checks for all the categories
for category, member_attrs, error in category_info:
any_member_attrs_set = any(attr in _entry_attrs
for attr in member_attrs)
if is_all(options, category) and any_member_attrs_set:
raise errors.MutuallyExclusiveError(reason=error)
return dn
@register()
class sudorule_find(LDAPSearch):
__doc__ = _('Search for Sudo Rule.')
msg_summary = ngettext(
'%(count)d Sudo Rule matched', '%(count)d Sudo Rules matched', 0
)
@register()
class sudorule_show(LDAPRetrieve):
__doc__ = _('Display Sudo Rule.')
@register()
class sudorule_enable(LDAPQuery):
__doc__ = _('Enable a Sudo Rule.')
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [True]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(result=True)
@register()
class sudorule_disable(LDAPQuery):
__doc__ = _('Disable a Sudo Rule.')
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [False]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(result=True)
@register()
class sudorule_add_allow_command(LDAPAddMember):
__doc__ = _('Add commands and sudo command groups affected by Sudo Rule.')
member_attributes = ['memberallowcmd']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(_entry_attrs, 'cmdcategory'):
raise errors.MutuallyExclusiveError(
reason=_("commands cannot be added when command "
"category='all'"))
return dn
@register()
class sudorule_remove_allow_command(LDAPRemoveMember):
__doc__ = _('Remove commands and sudo command groups affected by Sudo Rule.')
member_attributes = ['memberallowcmd']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class sudorule_add_deny_command(LDAPAddMember):
__doc__ = _('Add commands and sudo command groups affected by Sudo Rule.')
member_attributes = ['memberdenycmd']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
return dn
@register()
class sudorule_remove_deny_command(LDAPRemoveMember):
__doc__ = _('Remove commands and sudo command groups affected by Sudo Rule.')
member_attributes = ['memberdenycmd']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class sudorule_add_user(LDAPAddMember):
__doc__ = _('Add users and groups affected by Sudo Rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(_entry_attrs, 'usercategory'):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when user category='all'"))
for o_desc in (USER_OBJ_SPEC, GROUP_OBJ_SPEC):
dn = pre_callback_process_external_objects(
'memberuser', o_desc,
ldap, dn, found, not_found, *keys, **options)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
completed_ex = {}
completed_ex['user'] = 0
completed_ex['group'] = 0
# Since external_post_callback returns the total number of completed
# entries yet (that is, any external users it added plus the value of
# passed variable 'completed', we need to pass 0 as completed,
# so that the entries added by the framework are not counted twice
# (once in each call of add_external_post_callback)
for o_type in ('user', 'group'):
if o_type not in options:
continue
(completed_ex[o_type], dn) = \
add_external_post_callback(ldap, dn,
entry_attrs=entry_attrs,
failed=failed,
completed=0,
memberattr='memberuser',
membertype=o_type,
externalattr='externaluser',
)
return (completed + sum(completed_ex.values()), dn)
@register()
class sudorule_remove_user(LDAPRemoveMember):
__doc__ = _('Remove users and groups affected by Sudo Rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object removed.', '%i objects removed.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
for o_desc in (USER_OBJ_SPEC, GROUP_OBJ_SPEC):
dn = pre_callback_process_external_objects(
'memberuser', o_desc,
ldap, dn, found, not_found, *keys, **options)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
# Since external_post_callback returns the total number of completed
# entries yet (that is, any external users it removed plus the value of
# passed variable 'completed', we need to pass 0 as completed,
# so that the entries removed by the framework are not counted twice
# (once in each call of remove_external_post_callback)
(completed_ex_users, dn) = remove_external_post_callback(
ldap, dn, entry_attrs,
failed=failed,
completed=0,
memberattr='memberuser',
membertype='user',
externalattr='externaluser')
(completed_ex_groups, dn) = remove_external_post_callback(
ldap, dn, entry_attrs,
failed=failed,
completed=0,
memberattr='memberuser',
membertype='group',
externalattr='externaluser')
return (completed + completed_ex_users + completed_ex_groups, dn)
@register()
class sudorule_add_host(LDAPAddMember):
__doc__ = _('Add hosts and hostgroups affected by Sudo Rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object added.', '%i objects added.')
def get_options(self):
for option in super(sudorule_add_host, self).get_options():
yield option
yield hostmask_membership_param
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(_entry_attrs, 'hostcategory'):
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be added when host category='all'"))
return add_external_pre_callback('host', ldap, dn, keys, options)
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if 'hostmask' in options:
def norm(x):
return unicode(netaddr.IPNetwork(x).cidr)
old_masks = set(norm(m) for m in _entry_attrs.get('hostmask', []))
new_masks = set(norm(m) for m in options['hostmask'])
num_added = len(new_masks - old_masks)
if num_added:
entry_attrs['hostmask'] = list(old_masks | new_masks)
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
completed = completed + num_added
return add_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='memberhost',
membertype='host',
externalattr='externalhost')
@register()
class sudorule_remove_host(LDAPRemoveMember):
__doc__ = _('Remove hosts and hostgroups affected by Sudo Rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object removed.', '%i objects removed.')
def get_options(self):
for option in super(sudorule_remove_host, self).get_options():
yield option
yield hostmask_membership_param
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if 'hostmask' in options:
def norm(x):
return unicode(netaddr.IPNetwork(x).cidr)
old_masks = set(norm(m) for m in _entry_attrs.get('hostmask', []))
removed_masks = set(norm(m) for m in options['hostmask'])
num_added = len(removed_masks & old_masks)
if num_added:
entry_attrs['hostmask'] = list(old_masks - removed_masks)
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
completed = completed + num_added
return remove_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='memberhost',
membertype='host',
externalattr='externalhost')
@register()
class sudorule_add_runasuser(LDAPAddMember):
__doc__ = _('Add users and groups for Sudo to execute as.')
member_attributes = ['ipasudorunas']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
def check_validity(runas):
v = unicode(runas)
if v.upper() == u'ALL':
return False
return True
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if any((is_all(_entry_attrs, 'ipasudorunasusercategory'),
is_all(_entry_attrs, 'ipasudorunasgroupcategory'))):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when runAs user or runAs "
"group category='all'"))
if 'user' in options:
for name in options['user']:
if not check_validity(name):
raise errors.ValidationError(name='runas-user',
error=unicode(_("RunAsUser does not accept "
"'%(name)s' as a user name")) %
dict(name=name))
if 'group' in options:
for name in options['group']:
if not check_validity(name):
raise errors.ValidationError(name='runas-user',
error=unicode(_("RunAsUser does not accept "
"'%(name)s' as a group name")) %
dict(name=name))
for o_desc in (USER_OBJ_SPEC, GROUP_OBJ_SPEC):
dn = pre_callback_process_external_objects(
'ipasudorunas', o_desc,
ldap, dn, found, not_found, *keys, **options)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
completed_ex = {}
completed_ex['user'] = 0
completed_ex['group'] = 0
# Since external_post_callback returns the total number of completed
# entries yet (that is, any external users it added plus the value of
# passed variable 'completed', we need to pass 0 as completed,
# so that the entries added by the framework are not counted twice
# (once in each call of add_external_post_callback)
for (o_type, ext_attr) in (('user', 'ipasudorunasextuser'),
('group', 'ipasudorunasextusergroup')):
if o_type not in options:
continue
(completed_ex[o_type], dn) = \
add_external_post_callback(ldap, dn,
entry_attrs=entry_attrs,
failed=failed,
completed=0,
memberattr='ipasudorunas',
membertype=o_type,
externalattr=ext_attr,
)
return (completed + sum(completed_ex.values()), dn)
@register()
class sudorule_remove_runasuser(LDAPRemoveMember):
__doc__ = _('Remove users and groups for Sudo to execute as.')
member_attributes = ['ipasudorunas']
member_count_out = ('%i object removed.', '%i objects removed.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
for o_desc in (USER_OBJ_SPEC, GROUP_OBJ_SPEC):
dn = pre_callback_process_external_objects(
'ipasudorunas', o_desc,
ldap, dn, found, not_found, *keys, **options)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
completed_ex = {}
completed_ex['user'] = 0
completed_ex['group'] = 0
# Since external_post_callback returns the total number of completed
# entries yet (that is, any external users it added plus the value of
# passed variable 'completed', we need to pass 0 as completed,
# so that the entries added by the framework are not counted twice
# (once in each call of add_external_post_callback)
for (o_type, ext_attr) in (('user', 'ipasudorunasextuser'),
('group', 'ipasudorunasextusergroup')):
if o_type not in options:
continue
(completed_ex[o_type], dn) = \
remove_external_post_callback(ldap, dn,
entry_attrs=entry_attrs,
failed=failed,
completed=0,
memberattr='ipasudorunas',
membertype=o_type,
externalattr=ext_attr,
)
return (completed + sum(completed_ex.values()), dn)
@register()
class sudorule_add_runasgroup(LDAPAddMember):
__doc__ = _('Add group for Sudo to execute as.')
member_attributes = ['ipasudorunasgroup']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
def check_validity(runas):
v = unicode(runas)
if v.upper() == u'ALL':
return False
return True
try:
_entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if (is_all(_entry_attrs, 'ipasudorunasusercategory') or
is_all(_entry_attrs, 'ipasudorunasgroupcategory')):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when runAs user or runAs "
"group category='all'"))
if 'group' in options:
for name in options['group']:
if not check_validity(name):
raise errors.ValidationError(name='runas-group',
error=unicode(_("RunAsGroup does not accept "
"'%(name)s' as a group name")) %
dict(name=name))
return pre_callback_process_external_objects(
'ipasudorunasgroup', GROUP_OBJ_SPEC,
ldap, dn, found, not_found, *keys, **options)
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
return add_external_post_callback(
ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='ipasudorunasgroup',
membertype='group',
externalattr='ipasudorunasextgroup',
)
@register()
class sudorule_remove_runasgroup(LDAPRemoveMember):
__doc__ = _('Remove group for Sudo to execute as.')
member_attributes = ['ipasudorunasgroup']
member_count_out = ('%i object removed.', '%i objects removed.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
return pre_callback_process_external_objects(
'ipasudorunasgroup', GROUP_OBJ_SPEC,
ldap, dn, found, not_found, *keys, **options)
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
return remove_external_post_callback(
ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='ipasudorunasgroup',
membertype='group',
externalattr='ipasudorunasextgroup',
)
@register()
class sudorule_add_option(LDAPQuery):
__doc__ = _('Add an option to the Sudo Rule.')
has_output = output.standard_entry
takes_options = (
Str('ipasudoopt+',
cli_name='sudooption',
label=_('Sudo Option'),
),
)
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
if len(options.get('ipasudoopt',[])) == 0:
raise errors.EmptyModlist()
entry_attrs = ldap.get_entry(dn, ['ipasudoopt'])
try:
entry_attrs.setdefault('ipasudoopt', [])
for option in options['ipasudoopt']:
if option not in entry_attrs['ipasudoopt']:
entry_attrs['ipasudoopt'].append(option)
else:
raise errors.DuplicateEntry
except KeyError:
entry_attrs.setdefault('ipasudoopt', []).append(
options['ipasudoopt'])
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
except errors.NotFound:
raise self.obj.handle_not_found(cn)
attrs_list = self.obj.default_attributes
entry_attrs = ldap.get_entry(dn, attrs_list)
self.obj.get_indirect_members(entry_attrs, attrs_list)
self.obj.convert_attribute_members(entry_attrs, [cn], **options)
entry_attrs = entry_to_dict(entry_attrs, **options)
return dict(result=entry_attrs, value=pkey_to_value(cn, options))
@register()
class sudorule_remove_option(LDAPQuery):
__doc__ = _('Remove an option from Sudo Rule.')
has_output = output.standard_entry
takes_options = (
Str('ipasudoopt+',
cli_name='sudooption',
label=_('Sudo Option'),
),
)
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
if len(options.get('ipasudoopt',[])) == 0:
raise errors.EmptyModlist()
entry_attrs = ldap.get_entry(dn, ['ipasudoopt'])
try:
entry_attrs.setdefault('ipasudoopt', [])
for option in options['ipasudoopt']:
if option in entry_attrs['ipasudoopt']:
entry_attrs['ipasudoopt'].remove(option)
else:
raise errors.AttrValueNotFound(
attr='ipasudoopt',
value=option)
except ValueError:
pass
except KeyError:
raise errors.AttrValueNotFound(
attr='ipasudoopt',
value=options['ipasudoopt']
)
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
except errors.NotFound:
raise self.obj.handle_not_found(cn)
attrs_list = self.obj.default_attributes
entry_attrs = ldap.get_entry(dn, attrs_list)
self.obj.get_indirect_members(entry_attrs, attrs_list)
self.obj.convert_attribute_members(entry_attrs, [cn], **options)
entry_attrs = entry_to_dict(entry_attrs, **options)
return dict(result=entry_attrs, value=pkey_to_value(cn, options))
| 40,824
|
Python
|
.py
| 913
| 33.096386
| 477
| 0.570317
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,822
|
migration.py
|
freeipa_freeipa/ipaserver/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/>.
from __future__ import absolute_import
import logging
import re
from ldap import MOD_ADD
from ldap import SCOPE_BASE, SCOPE_ONELEVEL, SCOPE_SUBTREE
import six
from ipalib import api, errors, output
from ipalib import Command, Password, Str, Flag, StrEnum, DNParam, Bool
from ipalib.cli import to_cli
from ipalib.plugable import Registry
from ipaserver.plugins.user import NO_UPG_MAGIC
from ipalib import _
from ipapython.dn import DN
from ipapython.ipaldap import LDAPClient
from ipapython.ipautil import write_tmp_file
from ipapython.kerberos import Principal
import datetime
from ipaplatform.paths import paths
from ipaplatform.constants import constants as platformconstants
if six.PY3:
unicode = str
__doc__ = _("""
Migration to IPA
Migrate users and groups from an LDAP server to IPA.
This performs an LDAP query against the remote server searching for
users and groups in a container. In order to migrate passwords you need
to bind as a user that can read the userPassword attribute on the remote
server. This is generally restricted to high-level admins such as
cn=Directory Manager in 389-ds (this is the default bind user).
The default user container is ou=People.
The default group container is ou=Groups.
Users and groups that already exist on the IPA server are skipped.
Two LDAP schemas define how group members are stored: RFC2307 and
RFC2307bis. RFC2307bis uses member and uniquemember to specify group
members, RFC2307 uses memberUid. The default schema is RFC2307bis.
The schema compat feature allows IPA to reformat data for systems that
do not support RFC2307bis. It is recommended that this feature is disabled
during migration to reduce system overhead. It can be re-enabled after
migration. To migrate with it enabled use the "--with-compat" option.
Migrated users do not have Kerberos credentials, they have only their
LDAP password. To complete the migration process, users need to go
to http://ipa.example.com/ipa/migration and authenticate using their
LDAP password in order to generate their Kerberos credentials.
Migration is disabled by default. Use the command ipa config-mod to
enable it:
ipa config-mod --enable-migration=TRUE
If a base DN is not provided with --basedn then IPA will use either
the value of defaultNamingContext if it is set or the first value
in namingContexts set in the root of the remote LDAP server.
Users are added as members to the default user group. This can be a
time-intensive task so during migration this is done in a batch
mode for every 100 users. As a result there will be a window in which
users will be added to IPA but will not be members of the default
user group.
EXAMPLES:
The simplest migration, accepting all defaults:
ipa migrate-ds ldap://ds.example.com:389
Specify the user and group container. This can be used to migrate user
and group data from an IPA v1 server:
ipa migrate-ds --user-container='cn=users,cn=accounts' \\
--group-container='cn=groups,cn=accounts' \\
ldap://ds.example.com:389
Since IPA v2 server already contain predefined groups that may collide with
groups in migrated (IPA v1) server (for example admins, ipausers), users
having colliding group as their primary group may happen to belong to
an unknown group on new IPA v2 server.
Use --group-overwrite-gid option to overwrite GID of already existing groups
to prevent this issue:
ipa migrate-ds --group-overwrite-gid \\
--user-container='cn=users,cn=accounts' \\
--group-container='cn=groups,cn=accounts' \\
ldap://ds.example.com:389
Migrated users or groups may have object class and accompanied attributes
unknown to the IPA v2 server. These object classes and attributes may be
left out of the migration process:
ipa migrate-ds --user-container='cn=users,cn=accounts' \\
--group-container='cn=groups,cn=accounts' \\
--user-ignore-objectclass=radiusprofile \\
--user-ignore-attribute=radiusgroupname \\
ldap://ds.example.com:389
LOGGING
Migration will log warnings and errors to the Apache error log. This
file should be evaluated post-migration to correct or investigate any
issues that were discovered.
For every 100 users migrated an info-level message will be displayed to
give the current progress and duration to make it possible to track
the progress of migration.
If the log level is debug, either by setting debug = True in
/etc/ipa/default.conf or /etc/ipa/server.conf, then an entry will be printed
for each user added plus a summary when the default user group is
updated.
""")
logger = logging.getLogger(__name__)
register = Registry()
# USER MIGRATION CALLBACKS AND VARS
_krb_err_msg = _('Kerberos principal %s already exists. Use \'ipa user-mod\' to set it manually.')
_krb_failed_msg = _('Unable to determine if Kerberos principal %s already exists. Use \'ipa user-mod\' to set it manually.')
_grp_err_msg = _('Failed to add user to the default group. Use \'ipa group-add-member\' to add manually.')
_ref_err_msg = _('Migration of LDAP search reference is not supported.')
_dn_err_msg = _('Malformed DN')
_supported_schemas = (u'RFC2307bis', u'RFC2307')
# search scopes for users and groups when migrating
_supported_scopes = {u'base': SCOPE_BASE, u'onelevel': SCOPE_ONELEVEL, u'subtree': SCOPE_SUBTREE}
_default_scope = u'onelevel'
def _create_kerberos_principals(ldap, pkey, entry_attrs, failed):
"""
Create 'krbprincipalname' and 'krbcanonicalname' attributes for incoming
user entry or skip it if there already is a user with such principal name.
The code does not search for `krbcanonicalname` since we assume that the
canonical principal name is always contained among values of
`krbprincipalname` attribute.Both `krbprincipalname` and `krbcanonicalname`
are set to default value generated from uid and realm.
Note: the migration does not currently preserve principal aliases
"""
principal = Principal((pkey,), realm=api.env.realm)
try:
ldap.find_entry_by_attr(
'krbprincipalname', principal, 'krbprincipalaux', [''],
DN(api.env.container_user, api.env.basedn)
)
except errors.NotFound:
entry_attrs['krbprincipalname'] = principal
entry_attrs['krbcanonicalname'] = principal
except errors.LimitsExceeded:
failed[pkey] = unicode(_krb_failed_msg % unicode(principal))
else:
failed[pkey] = unicode(_krb_err_msg % unicode(principal))
def _pre_migrate_user(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwargs):
assert isinstance(dn, DN)
attr_blocklist = ['krbprincipalkey','memberofindirect','memberindirect']
attr_blocklist.extend(kwargs.get('attr_blocklist', []))
ds_ldap = ctx['ds_ldap']
search_bases = kwargs.get('search_bases', None)
valid_gids = kwargs['valid_gids']
invalid_gids = kwargs['invalid_gids']
if 'gidnumber' not in entry_attrs:
raise errors.NotFound(reason=_('%(user)s is not a POSIX user') % dict(user=pkey))
else:
# See if the gidNumber at least points to a valid group on the remote
# server.
if entry_attrs['gidnumber'][0] in invalid_gids:
logger.warning('GID number %s of migrated user %s does not point '
'to a known group.',
entry_attrs['gidnumber'][0], pkey)
elif entry_attrs['gidnumber'][0] not in valid_gids:
try:
remote_entry = ds_ldap.find_entry_by_attr(
'gidnumber', entry_attrs['gidnumber'][0], 'posixgroup',
[''], search_bases['group']
)
valid_gids.add(entry_attrs['gidnumber'][0])
except errors.NotFound:
logger.warning('GID number %s of migrated user %s does not '
'point to a known group.',
entry_attrs['gidnumber'][0], pkey)
invalid_gids.add(entry_attrs['gidnumber'][0])
except errors.SingleMatchExpected as e:
# GID number matched more groups, this should not happen
logger.warning('GID number %s of migrated user %s should '
'match 1 group, but it matched %d groups',
entry_attrs['gidnumber'][0], pkey, e.found)
except errors.LimitsExceeded:
logger.warning('Search limit exceeded searching for GID %s',
entry_attrs['gidnumber'][0])
# We don't want to create a UPG so set the magic value in description
# to let the DS plugin know.
entry_attrs.setdefault('description', [])
entry_attrs['description'].append(NO_UPG_MAGIC)
# fill in required attributes by IPA
entry_attrs['ipauniqueid'] = 'autogenerate'
if 'homedirectory' not in entry_attrs:
homes_root = config.get('ipahomesrootdir', (paths.HOME_DIR, ))[0]
home_dir = '%s/%s' % (homes_root, pkey)
home_dir = home_dir.replace('//', '/').rstrip('/')
entry_attrs['homedirectory'] = home_dir
if 'loginshell' not in entry_attrs:
default_shell = config.get('ipadefaultloginshell',
[platformconstants.DEFAULT_SHELL])[0]
entry_attrs.setdefault('loginshell', default_shell)
# do not migrate all attributes
for attr in attr_blocklist:
entry_attrs.pop(attr, None)
# do not migrate all object classes
if 'objectclass' in entry_attrs:
for object_class in kwargs.get('oc_blocklist', []):
try:
entry_attrs['objectclass'].remove(object_class)
except ValueError: # object class not present
pass
_create_kerberos_principals(ldap, pkey, entry_attrs, failed)
# Fix any attributes with DN syntax that point to entries in the old
# tree
for attr in entry_attrs.keys():
if ldap.has_dn_syntax(attr):
for ind, value in enumerate(entry_attrs[attr]):
if not isinstance(value, DN):
# value is not DN instance, the automatic encoding may have
# failed due to missing schema or the remote attribute type OID was
# not detected as DN type. Try to work this around
logger.debug('%s: value %s of type %s in attribute %s is '
'not a DN, convert it',
pkey, value, type(value), attr)
try:
value = DN(value)
except ValueError as e:
logger.warning('%s: skipping normalization of value '
'%s of type %s in attribute %s which '
'could not be converted to DN: %s',
pkey, value, type(value), attr, e)
continue
try:
remote_entry = ds_ldap.get_entry(value, [api.Object.user.primary_key.name, api.Object.group.primary_key.name])
except errors.NotFound:
logger.warning('%s: attribute %s refers to non-existent '
'entry %s', pkey, attr, value)
continue
if value.endswith(search_bases['user']):
primary_key = api.Object.user.primary_key.name
container = api.env.container_user
elif value.endswith(search_bases['group']):
primary_key = api.Object.group.primary_key.name
container = api.env.container_group
else:
logger.warning('%s: value %s in attribute %s does not '
'belong into any known container',
pkey, value, attr)
continue
if not remote_entry.get(primary_key):
logger.warning('%s: there is no primary key %s to migrate '
'for %s', pkey, primary_key, attr)
continue
logger.debug('converting DN value %s for %s in %s',
value, attr, dn)
rdnval = remote_entry[primary_key][0].lower()
entry_attrs[attr][ind] = DN((primary_key, rdnval), container, api.env.basedn)
return dn
def _post_migrate_user(ldap, pkey, dn, entry_attrs, failed, config, ctx):
assert isinstance(dn, DN)
if 'def_group_dn' in ctx:
_update_default_group(ldap, ctx, False)
if 'description' in entry_attrs and NO_UPG_MAGIC in entry_attrs['description']:
entry_attrs['description'].remove(NO_UPG_MAGIC)
try:
update_attrs = ldap.get_entry(dn, ['description'])
update_attrs['description'] = entry_attrs['description']
ldap.update_entry(update_attrs)
except (errors.EmptyModlist, errors.NotFound):
pass
def _update_default_group(ldap, ctx, force):
migrate_cnt = ctx['migrate_cnt']
group_dn = ctx['def_group_dn']
# Purposely let this fire when migrate_cnt == 0 so on re-running migration
# it can catch any users migrated but not added to the default group.
if force or migrate_cnt % 100 == 0:
s = datetime.datetime.now()
searchfilter = "(&(objectclass=posixAccount)(!(memberof=%s)))" % group_dn
try:
result, _truncated = ldap.find_entries(
searchfilter, [''], DN(api.env.container_user, api.env.basedn),
scope=ldap.SCOPE_SUBTREE, time_limit=-1, size_limit=-1)
except errors.NotFound:
logger.debug('All users have default group set')
return
member_dns = [m.dn for m in result]
modlist = [(MOD_ADD, 'member', ldap.encode(member_dns))]
try:
with ldap.error_handler():
ldap.conn.modify_s(str(group_dn), modlist)
except errors.DatabaseError as e:
logger.error('Adding new members to default group failed: %s \n'
'members: %s', e, ','.join(member_dns))
e = datetime.datetime.now()
d = e - s
mode = " (forced)" if force else ""
logger.info('Adding %d users to group%s duration %s',
len(member_dns), mode, d)
# GROUP MIGRATION CALLBACKS AND VARS
def _pre_migrate_group(ldap, pkey, dn, entry_attrs, failed, config, ctx, **kwargs):
def convert_members_rfc2307bis(member_attr, search_bases, overwrite=False):
"""
Convert DNs in member attributes to work in IPA.
"""
new_members = []
entry_attrs.setdefault(member_attr, [])
for m in entry_attrs[member_attr]:
try:
m = DN(m)
except ValueError as e:
# This should be impossible unless the remote server
# doesn't enforce syntax checking.
logger.error('Malformed DN %s: %s', m, e)
continue
try:
rdnval = m[0].value
except IndexError:
logger.error('Malformed DN %s has no RDN?', m)
continue
if m.endswith(search_bases['user']):
logger.debug('migrating %s user %s', member_attr, m)
m = DN((api.Object.user.primary_key.name, rdnval),
api.env.container_user, api.env.basedn)
elif m.endswith(search_bases['group']):
logger.debug('migrating %s group %s', member_attr, m)
m = DN((api.Object.group.primary_key.name, rdnval),
api.env.container_group, api.env.basedn)
else:
logger.error('entry %s does not belong into any known '
'container', m)
continue
new_members.append(m)
del entry_attrs[member_attr]
if overwrite:
entry_attrs['member'] = []
entry_attrs['member'] += new_members
def convert_members_rfc2307(member_attr):
"""
Convert usernames in member attributes to work in IPA.
"""
new_members = []
entry_attrs.setdefault(member_attr, [])
for m in entry_attrs[member_attr]:
memberdn = DN((api.Object.user.primary_key.name, m),
api.env.container_user, api.env.basedn)
new_members.append(memberdn)
entry_attrs['member'] = new_members
assert isinstance(dn, DN)
attr_blocklist = ['memberofindirect','memberindirect']
attr_blocklist.extend(kwargs.get('attr_blocklist', []))
schema = kwargs.get('schema', None)
entry_attrs['ipauniqueid'] = 'autogenerate'
if schema == 'RFC2307bis':
search_bases = kwargs.get('search_bases', None)
if not search_bases:
raise ValueError('Search bases not specified')
convert_members_rfc2307bis('member', search_bases, overwrite=True)
convert_members_rfc2307bis('uniquemember', search_bases)
elif schema == 'RFC2307':
convert_members_rfc2307('memberuid')
else:
raise ValueError('Schema %s not supported' % schema)
# do not migrate all attributes
for attr in attr_blocklist:
entry_attrs.pop(attr, None)
# do not migrate all object classes
if 'objectclass' in entry_attrs:
for object_class in kwargs.get('oc_blocklist', []):
try:
entry_attrs['objectclass'].remove(object_class)
except ValueError: # object class not present
pass
return dn
def _group_exc_callback(ldap, dn, entry_attrs, exc, options):
assert isinstance(dn, DN)
if isinstance(exc, errors.DuplicateEntry):
if options.get('groupoverwritegid', False) and \
entry_attrs.get('gidnumber') is not None:
try:
new_entry_attrs = ldap.get_entry(dn, ['gidnumber'])
new_entry_attrs['gidnumber'] = entry_attrs['gidnumber']
ldap.update_entry(new_entry_attrs)
except errors.EmptyModlist:
# no change to the GID
pass
# mark as success
return
elif not options.get('groupoverwritegid', False) and \
entry_attrs.get('gidnumber') is not None:
msg = unicode(exc)
# add information about possibility to overwrite GID
msg = msg + unicode(_('. Check GID of the existing group. ' \
'Use --group-overwrite-gid option to overwrite the GID'))
raise errors.DuplicateEntry(message=msg)
raise exc
# DS MIGRATION PLUGIN
def construct_filter(template, oc_list):
oc_subfilter = ''.join([ '(objectclass=%s)' % oc for oc in oc_list])
return template % oc_subfilter
def validate_ldapuri(ugettext, ldapuri):
m = re.match(r'^ldaps?://[-\w\.]+(:\d+)?$', ldapuri)
if not m:
err_msg = _('Invalid LDAP URI.')
raise errors.ValidationError(name='ldap_uri', error=err_msg)
@register()
class migrate_ds(Command):
__doc__ = _('Migrate users and groups from DS to IPA.')
migrate_objects = {
# OBJECT_NAME: (search_filter, pre_callback, post_callback)
#
# OBJECT_NAME - is the name of an LDAPObject subclass
# search_filter - is the filter to retrieve objects from DS
# pre_callback - is called for each object just after it was
# retrieved from DS and before being added to IPA
# post_callback - is called for each object after it was added to IPA
# exc_callback - is called when adding entry to IPA raises an exception
#
# {pre, post}_callback parameters:
# ldap - ldap2 instance connected to IPA
# pkey - primary key value of the object (uid for users, etc.)
# dn - dn of the object as it (will be/is) stored in IPA
# entry_attrs - attributes of the object
# failed - a list of so-far failed objects
# config - IPA config entry attributes
# ctx - object context, used to pass data between callbacks
#
# If pre_callback return value evaluates to False, migration
# of the current object is aborted.
'user': {
'filter_template' : '(&(|%s)(uid=*))',
'oc_option' : 'userobjectclass',
'oc_blocklist_option' : 'userignoreobjectclass',
'attr_blocklist_option' : 'userignoreattribute',
'pre_callback' : _pre_migrate_user,
'post_callback' : _post_migrate_user,
'exc_callback' : None
},
'group': {
'filter_template' : '(&(|%s)(cn=*))',
'oc_option' : 'groupobjectclass',
'oc_blocklist_option' : 'groupignoreobjectclass',
'attr_blocklist_option' : 'groupignoreattribute',
'pre_callback' : _pre_migrate_group,
'post_callback' : None,
'exc_callback' : _group_exc_callback,
},
}
migrate_order = ('user', 'group')
takes_args = (
Str('ldapuri', validate_ldapuri,
cli_name='ldap_uri',
label=_('LDAP URI'),
doc=_('LDAP URI of DS server to migrate from'),
),
Password('bindpw',
cli_name='password',
label=_('Password'),
confirm=False,
doc=_('bind password'),
),
)
takes_options = (
DNParam('binddn?',
cli_name='bind_dn',
label=_('Bind DN'),
default=DN(('cn', 'directory manager')),
autofill=True,
),
DNParam('usercontainer',
cli_name='user_container',
label=_('User container'),
doc=_('DN of container for users in DS relative to base DN'),
default=DN(('ou', 'people')),
autofill=True,
),
DNParam('groupcontainer',
cli_name='group_container',
label=_('Group container'),
doc=_('DN of container for groups in DS relative to base DN'),
default=DN(('ou', 'groups')),
autofill=True,
),
Str('userobjectclass+',
cli_name='user_objectclass',
label=_('User object class'),
doc=_('Objectclasses used to search for user entries in DS'),
default=(u'person',),
autofill=True,
),
Str('groupobjectclass+',
cli_name='group_objectclass',
label=_('Group object class'),
doc=_('Objectclasses used to search for group entries in DS'),
default=(u'groupOfUniqueNames', u'groupOfNames'),
autofill=True,
),
Str('userignoreobjectclass*',
cli_name='user_ignore_objectclass',
label=_('Ignore user object class'),
doc=_('Objectclasses to be ignored for user entries in DS'),
default=tuple(),
autofill=True,
),
Str('userignoreattribute*',
cli_name='user_ignore_attribute',
label=_('Ignore user attribute'),
doc=_('Attributes to be ignored for user entries in DS'),
default=tuple(),
autofill=True,
),
Str('groupignoreobjectclass*',
cli_name='group_ignore_objectclass',
label=_('Ignore group object class'),
doc=_('Objectclasses to be ignored for group entries in DS'),
default=tuple(),
autofill=True,
),
Str('groupignoreattribute*',
cli_name='group_ignore_attribute',
label=_('Ignore group attribute'),
doc=_('Attributes to be ignored for group entries in DS'),
default=tuple(),
autofill=True,
),
Flag('groupoverwritegid',
cli_name='group_overwrite_gid',
label=_('Overwrite GID'),
doc=_('When migrating a group already existing in IPA domain overwrite the '\
'group GID and report as success'),
),
StrEnum('schema?',
cli_name='schema',
label=_('LDAP schema'),
doc=_('The schema used on the LDAP server. Supported values are RFC2307 and RFC2307bis. The default is RFC2307bis'),
values=_supported_schemas,
default=_supported_schemas[0],
autofill=True,
),
Flag('continue?',
label=_('Continue'),
doc=_('Continuous operation mode. Errors are reported but the process continues'),
default=False,
),
DNParam('basedn?',
cli_name='base_dn',
label=_('Base DN'),
doc=_('Base DN on remote LDAP server'),
),
Flag('compat?',
cli_name='with_compat',
label=_('Ignore compat plugin'),
doc=_('Allows migration despite the usage of compat plugin'),
default=False,
),
Str('cacertfile?',
cli_name='ca_cert_file',
label=_('CA certificate'),
doc=_('Load CA certificate of LDAP server from FILE'),
default=None,
noextrawhitespace=False,
),
Bool('use_def_group?',
cli_name='use_default_group',
label=_('Add to default group'),
doc=_('Add migrated users without a group to a default group '
'(default: true)'),
default=True,
autofill=True,
),
StrEnum('scope',
cli_name='scope',
label=_('Search scope'),
doc=_('LDAP search scope for users and groups: base, '
'onelevel, or subtree. Defaults to onelevel'),
values=sorted(_supported_scopes),
default=_default_scope,
autofill=True,
),
)
has_output = (
output.Output('result',
type=dict,
doc=_('Lists of objects migrated; categorized by type.'),
),
output.Output('failed',
type=dict,
doc=_('Lists of objects that could not be migrated; categorized by type.'),
),
output.Output('enabled',
type=bool,
doc=_('False if migration mode was disabled.'),
),
output.Output('compat',
type=bool,
doc=_('False if migration fails because the compatibility plug-in is enabled.'),
),
)
exclude_doc = _('%s to exclude from migration')
truncated_err_msg = _('''\
search results for objects to be migrated
have been truncated by the server;
migration process might be incomplete\n''')
def get_options(self):
"""
Call get_options of the baseclass and add "exclude" options
for each type of object being migrated.
"""
for option in super(migrate_ds, self).get_options():
yield option
for ldap_obj_name in self.migrate_objects:
ldap_obj = self.api.Object[ldap_obj_name]
name = 'exclude_%ss' % to_cli(ldap_obj_name)
doc = self.exclude_doc % ldap_obj.object_name_plural
yield Str(
'%s*' % name, cli_name=name, doc=doc, default=tuple(),
autofill=True
)
def normalize_options(self, options):
"""
Convert all "exclude" option values to lower-case.
Also, empty List parameters are converted to None, but the migration
plugin doesn't like that - convert back to empty lists.
"""
names = ['userobjectclass', 'groupobjectclass',
'userignoreobjectclass', 'userignoreattribute',
'groupignoreobjectclass', 'groupignoreattribute']
names.extend('exclude_%ss' % to_cli(n) for n in self.migrate_objects)
for name in names:
if options[name]:
options[name] = tuple(
v.lower() for v in options[name]
)
else:
options[name] = tuple()
def _get_search_bases(self, options, ds_base_dn, migrate_order):
search_bases = dict()
for ldap_obj_name in migrate_order:
container = options.get('%scontainer' % to_cli(ldap_obj_name))
if container:
# Don't append base dn if user already appended it in the container dn
if container.endswith(ds_base_dn):
search_base = container
else:
search_base = DN(container, ds_base_dn)
else:
search_base = ds_base_dn
search_bases[ldap_obj_name] = search_base
return search_bases
def migrate(self, ldap, config, ds_ldap, ds_base_dn, options):
"""
Migrate objects from DS to LDAP.
"""
assert isinstance(ds_base_dn, DN)
migrated = {} # {'OBJ': ['PKEY1', 'PKEY2', ...], ...}
failed = {} # {'OBJ': {'PKEY1': 'Failed 'cos blabla', ...}, ...}
search_bases = self._get_search_bases(options, ds_base_dn, self.migrate_order)
migration_start = datetime.datetime.now()
scope = _supported_scopes[options.get('scope')]
for ldap_obj_name in self.migrate_order:
ldap_obj = self.api.Object[ldap_obj_name]
template = self.migrate_objects[ldap_obj_name]['filter_template']
oc_list = options[to_cli(self.migrate_objects[ldap_obj_name]['oc_option'])]
search_filter = construct_filter(template, oc_list)
exclude = options['exclude_%ss' % to_cli(ldap_obj_name)]
context = dict(ds_ldap = ds_ldap)
migrated[ldap_obj_name] = []
failed[ldap_obj_name] = {}
try:
entries, truncated = ds_ldap.find_entries(
search_filter, ['*'], search_bases[ldap_obj_name],
scope,
time_limit=0, size_limit=-1
)
except errors.NotFound:
if not options.get('continue',False):
raise errors.NotFound(
reason=_('%(container)s LDAP search did not return any result '
'(search base: %(search_base)s, '
'objectclass: %(objectclass)s)')
% {'container': ldap_obj_name,
'search_base': search_bases[ldap_obj_name],
'objectclass': ', '.join(oc_list)}
)
else:
truncated = False
entries = []
if truncated:
logger.error(
'%s: %s',
ldap_obj.name, self.truncated_err_msg
)
blocklists = {}
for blocklist in ('oc_blocklist', 'attr_blocklist'):
blocklist_option = (
self.migrate_objects[ldap_obj_name][blocklist + '_option']
)
if blocklist_option is not None:
blocklists[blocklist] = options.get(
blocklist_option, tuple()
)
else:
blocklists[blocklist] = tuple()
# get default primary group for new users
if 'def_group_dn' not in context and options.get('use_def_group'):
def_group = config.get('ipadefaultprimarygroup')
context['def_group_dn'] = api.Object.group.get_dn(def_group)
try:
ldap.get_entry(context['def_group_dn'], ['gidnumber', 'cn'])
except errors.NotFound:
error_msg = _('Default group for new users not found')
raise errors.NotFound(reason=error_msg)
context['has_upg'] = ldap.has_upg()
valid_gids = set()
invalid_gids = set()
migrate_cnt = 0
context['migrate_cnt'] = 0
for entry_attrs in entries:
context['migrate_cnt'] = migrate_cnt
s = datetime.datetime.now()
ava = entry_attrs.dn[0][0]
if ava.attr == ldap_obj.primary_key.name:
# In case if pkey attribute is in the migrated object DN
# and the original LDAP is multivalued, make sure that
# we pick the correct value (the unique one stored in DN)
pkey = ava.value.lower()
else:
pkey = entry_attrs[ldap_obj.primary_key.name][0].lower()
if pkey in exclude:
continue
entry_attrs.dn = ldap_obj.get_dn(pkey)
entry_attrs['objectclass'] = list(
set(
config.get(
ldap_obj.object_class_config, ldap_obj.object_class
) + [o.lower() for o in entry_attrs['objectclass']]
)
)
entry_attrs[ldap_obj.primary_key.name][0] = entry_attrs[ldap_obj.primary_key.name][0].lower()
callback = self.migrate_objects[ldap_obj_name]['pre_callback']
if callable(callback):
try:
entry_attrs.dn = callback(
ldap, pkey, entry_attrs.dn, entry_attrs,
failed[ldap_obj_name], config, context,
schema=options['schema'],
search_bases=search_bases,
valid_gids=valid_gids,
invalid_gids=invalid_gids,
**blocklists
)
if not entry_attrs.dn:
continue
except errors.NotFound as e:
failed[ldap_obj_name][pkey] = unicode(e.reason)
continue
try:
ldap.add_entry(entry_attrs)
except errors.ExecutionError as e:
callback = self.migrate_objects[ldap_obj_name]['exc_callback']
if callable(callback):
try:
callback(
ldap, entry_attrs.dn, entry_attrs, e, options)
except errors.ExecutionError as e2:
failed[ldap_obj_name][pkey] = unicode(e2)
continue
else:
failed[ldap_obj_name][pkey] = unicode(e)
continue
migrated[ldap_obj_name].append(pkey)
callback = self.migrate_objects[ldap_obj_name]['post_callback']
if callable(callback):
callback(
ldap, pkey, entry_attrs.dn, entry_attrs,
failed[ldap_obj_name], config, context)
e = datetime.datetime.now()
d = e - s
total_dur = e - migration_start
migrate_cnt += 1
if migrate_cnt > 0 and migrate_cnt % 100 == 0:
logger.info("%d %ss migrated. %s elapsed.",
migrate_cnt, ldap_obj_name, total_dur)
logger.debug("%d %ss migrated, duration: %s (total %s)",
migrate_cnt, ldap_obj_name, d, total_dur)
if 'def_group_dn' in context:
_update_default_group(ldap, context, True)
return (migrated, failed)
def execute(self, ldapuri, bindpw, **options):
ldap = self.api.Backend.ldap2
self.normalize_options(options)
config = ldap.get_ipa_config()
ds_base_dn = options.get('basedn')
if ds_base_dn is not None:
assert isinstance(ds_base_dn, DN)
# check if migration mode is enabled
if not config.get('ipamigrationenabled', (False,))[0]:
return dict(result={}, failed={}, enabled=False, compat=True)
# connect to DS
if options.get('cacertfile') is not None:
# store CA cert into file
tmp_ca_cert_f = write_tmp_file(options['cacertfile'])
cacert = tmp_ca_cert_f.name
# start TLS connection or STARTTLS
ds_ldap = LDAPClient(ldapuri, cacert=cacert, start_tls=True)
ds_ldap.simple_bind(options['binddn'], bindpw)
tmp_ca_cert_f.close()
else:
ds_ldap = LDAPClient(ldapuri)
ds_ldap.simple_bind(options['binddn'], bindpw, insecure_bind=True)
# check whether the compat plugin is enabled
if not options.get('compat'):
try:
ldap.get_entry(DN(('cn', 'users'), ('cn', 'compat'),
(api.env.basedn)))
return dict(result={}, failed={}, enabled=True, compat=False)
except errors.NotFound:
pass
if not ds_base_dn:
# retrieve base DN from remote LDAP server
entries, _truncated = ds_ldap.find_entries(
'', ['namingcontexts', 'defaultnamingcontext'], DN(''),
ds_ldap.SCOPE_BASE, size_limit=-1, time_limit=0,
)
if 'defaultnamingcontext' in entries[0]:
ds_base_dn = DN(entries[0]['defaultnamingcontext'][0])
assert isinstance(ds_base_dn, DN)
else:
try:
ds_base_dn = DN(entries[0]['namingcontexts'][0])
assert isinstance(ds_base_dn, DN)
except (IndexError, KeyError) as e:
raise Exception(str(e))
# migrate!
(migrated, failed) = self.migrate(
ldap, config, ds_ldap, ds_base_dn, options
)
return dict(result=migrated, failed=failed, enabled=True, compat=True)
| 38,946
|
Python
|
.py
| 833
| 34.777911
| 130
| 0.579776
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,823
|
hbac.py
|
freeipa_freeipa/ipaserver/plugins/hbac.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from ipalib.text import _
__doc__ = _('Host-based access control commands')
| 149
|
Python
|
.py
| 5
| 28.4
| 66
| 0.746479
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,824
|
sudo.py
|
freeipa_freeipa/ipaserver/plugins/sudo.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from ipalib.text import _
__doc__ = _('commands for controlling sudo configuration')
| 158
|
Python
|
.py
| 5
| 30.2
| 66
| 0.761589
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,825
|
user.py
|
freeipa_freeipa/ipaserver/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 __future__ import absolute_import
import logging
import time
from time import gmtime, strftime
import posixpath
import six
from ipalib import api
from ipalib import errors
from ipalib import Bool, Flag, Str
from .baseuser import (
baseuser,
baseuser_add,
baseuser_del,
baseuser_mod,
baseuser_find,
baseuser_show,
NO_UPG_MAGIC,
UPG_DEFINITION_DN,
baseuser_output_params,
validate_nsaccountlock,
convert_nsaccountlock,
fix_addressbook_permission_bindrule,
baseuser_add_manager,
baseuser_remove_manager,
baseuser_add_cert,
baseuser_remove_cert,
baseuser_add_principal,
baseuser_remove_principal,
baseuser_add_certmapdata,
baseuser_remove_certmapdata,
baseuser_add_passkey,
baseuser_remove_passkey,
)
from .idviews import remove_ipaobject_overrides
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
pkey_to_unicode,
pkey_to_value,
LDAPCreate,
LDAPSearch,
LDAPQuery,
LDAPMultiQuery)
from . import baseldap
from ipalib.request import context
from ipalib import _, ngettext
from ipalib import output
from ipaplatform.paths import paths
from ipaplatform.constants import constants as platformconstants
from ipapython.dn import DN
from ipapython.ipaldap import LDAPClient
from ipapython.ipautil import ipa_generate_password, TMP_PWD_ENTROPY_BITS
from ipalib.capabilities import client_has_capability
from ipaserver.masters import get_masters
if six.PY3:
unicode = str
__doc__ = _("""
Users
Manage user entries. All users are POSIX users.
IPA supports a wide range of username formats, but you need to be aware of any
restrictions that may apply to your particular environment. For example,
usernames that start with a digit or usernames that exceed a certain length
may cause problems for some UNIX systems.
Use 'ipa config-mod' to change the username format allowed by IPA tools.
The user name must follow these rules:
- cannot contain only numbers
- must start with a letter, a number, _ or .
- may contain letters, numbers, _, ., or -
- may end with a letter, a number, _, ., - or $
Disabling a user account prevents that user from obtaining new Kerberos
credentials. It does not invalidate any credentials that have already
been issued.
Password management is not a part of this module. For more information
about this topic please see: ipa help passwd
Account lockout on password failure happens per IPA master. The user-status
command can be used to identify which master the user is locked out on.
It is on that master the administrator must unlock the user.
EXAMPLES:
Add a new user:
ipa user-add --first=Tim --last=User --password tuser1
Find all users whose entries include the string "Tim":
ipa user-find Tim
Find all users with "Tim" as the first name:
ipa user-find --first=Tim
Disable a user account:
ipa user-disable tuser1
Enable a user account:
ipa user-enable tuser1
Delete a user:
ipa user-del tuser1
""")
logger = logging.getLogger(__name__)
register = Registry()
user_output_params = baseuser_output_params
MEMBEROF_ADMINS = "(memberOf={})".format(
DN('cn=admins', api.env.container_group, api.env.basedn)
)
NOT_MEMBEROF_ADMINS = '(!{})'.format(MEMBEROF_ADMINS)
PROTECTED_USERS = ('admin',)
def check_protected_member(user, protected_group_name=u'admins'):
'''
Ensure admin and the last enabled member of a protected group cannot
be deleted.
'''
if user in PROTECTED_USERS:
raise errors.ProtectedEntryError(
label=_("user"),
key=user,
reason=_("privileged user"),
)
def check_last_member(user, protected_group_name=u'admins'):
'''
Ensure the last enabled member of a protected group cannot
be disabled.
'''
# Get all users in the protected group
result = api.Command.user_find(in_group=protected_group_name)
# Build list of users in the protected group who are enabled
result = result['result']
enabled_users = [entry['uid'][0] for entry in result if not entry['nsaccountlock']]
# If the user is the last enabled user raise LastMemberError exception
if enabled_users == [user]:
raise errors.LastMemberError(key=user, label=_(u'group'),
container=protected_group_name)
@register()
class user(baseuser):
"""
User object.
"""
container_dn = baseuser.active_container_dn
label = _('Users')
label_singular = _('User')
object_name = _('user')
object_name_plural = _('users')
permission_filter_objectclasses_string = '(objectclass=posixaccount)'
managed_permissions = {
'System: Read User Standard Attributes': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'sn', 'description', 'title', 'uid',
'displayname', 'givenname', 'initials', 'manager', 'gecos',
'gidnumber', 'homedirectory', 'loginshell', 'uidnumber',
'ipantsecurityidentifier'
},
},
'System: Read User Addressbook Attributes': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'seealso', 'telephonenumber',
'facsimiletelephonenumber', 'l', 'ou', 'st', 'postalcode', 'street',
'destinationindicator', 'internationalisdnnumber',
'physicaldeliveryofficename', 'postaladdress', 'postofficebox',
'preferreddeliverymethod', 'registeredaddress',
'teletexterminalidentifier', 'telexnumber', 'x121address',
'carlicense', 'departmentnumber', 'employeenumber',
'employeetype', 'preferredlanguage', 'mail', 'mobile', 'pager',
'audio', 'businesscategory', 'homephone', 'homepostaladdress',
'jpegphoto', 'labeleduri', 'o', 'photo', 'roomnumber',
'secretary', 'usercertificate',
'usersmimecertificate', 'x500uniqueidentifier',
'inetuserhttpurl', 'inetuserstatus',
'ipacertmapdata',
},
'fixup_function': fix_addressbook_permission_bindrule,
},
'System: Read User IPA Attributes': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipauniqueid', 'ipasshpubkey', 'ipauserauthtype', 'userclass',
'ipapasskey',
},
'fixup_function': fix_addressbook_permission_bindrule,
},
'System: Read User Kerberos Attributes': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'krbprincipalname', 'krbcanonicalname', 'krbprincipalaliases',
'krbprincipalexpiration', 'krbpasswordexpiration',
'krblastpwdchange', 'nsaccountlock', 'krbprincipaltype',
},
},
'System: Read User Kerberos Login Attributes': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'krblastsuccessfulauth', 'krblastfailedauth',
'krblastpwdchange', 'krblastadminunlock',
'krbloginfailedcount', 'krbpwdpolicyreference',
'krbticketpolicyreference', 'krbupenabled',
},
'default_privileges': {'User Administrators'},
},
'System: Read User Membership': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'memberof',
},
},
'System: Read UPG Definition': {
# Required for adding users
'replaces_global_anonymous_aci': True,
'non_object': True,
'ipapermlocation': UPG_DEFINITION_DN,
'ipapermtarget': UPG_DEFINITION_DN,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'User Administrators'},
},
'System: Add Users': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Users";allow (add) groupdn = "ldap:///cn=Add Users,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'User Administrators'},
},
'System: Add User to default group': {
'non_object': True,
'ipapermright': {'write'},
'ipapermlocation': DN(api.env.container_group, api.env.basedn),
'ipapermtarget': DN('cn=ipausers', api.env.container_group,
api.env.basedn),
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=ipausers,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add user to default group";allow (write) groupdn = "ldap:///cn=Add user to default group,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'User Administrators'},
},
'System: Change User password': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {
'krbprincipalkey', 'passwordhistory', 'sambalmpassword',
'sambantpassword', 'userpassword', 'krbpasswordexpiration'
},
'replaces': [
'(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(targetattr = "userpassword || krbprincipalkey || sambalmpassword || sambantpassword || passwordhistory")(version 3.0;acl "permission:Change a user password";allow (write) groupdn = "ldap:///cn=Change a user password,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(!(memberOf=cn=admins,cn=groups,cn=accounts,$SUFFIX))")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(targetattr = "userpassword || krbprincipalkey || sambalmpassword || sambantpassword || passwordhistory")(version 3.0;acl "permission:Change a user password";allow (write) groupdn = "ldap:///cn=Change a user password,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetattr = "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(version 3.0; acl "Windows PassSync service can write passwords"; allow (write) userdn="ldap:///uid=passsync,cn=sysaccounts,cn=etc,$SUFFIX";)',
],
'default_privileges': {
'User Administrators',
'Modify Users and Reset passwords',
'PassSync Service',
},
},
'System: Change Admin User password': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {
'krbprincipalkey', 'passwordhistory', 'sambalmpassword',
'sambantpassword', 'userpassword', 'krbpasswordexpiration'
},
'default_privileges': {
'PassSync Service',
},
},
'System: Manage User SSH Public Keys': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {'ipasshpubkey'},
'replaces': [
'(targetattr = "ipasshpubkey")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Manage User SSH Public Keys";allow (write) groupdn = "ldap:///cn=Manage User SSH Public Keys,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'User Administrators'},
},
'System: Manage User Certificates': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {'usercertificate'},
'default_privileges': {
'User Administrators',
'Modify Users and Reset passwords',
},
},
'System: Manage User Principals': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {'krbprincipalname', 'krbcanonicalname'},
'default_privileges': {
'User Administrators',
'Modify Users and Reset passwords',
},
},
'System: Modify Users': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {
'businesscategory', 'carlicense', 'cn', 'departmentnumber',
'description', 'displayname', 'employeetype',
'employeenumber', 'facsimiletelephonenumber',
'gecos', 'givenname', 'homedirectory', 'homephone',
'inetuserhttpurl', 'initials', 'l', 'labeleduri', 'loginshell',
'manager', 'mail', 'mepmanagedentry', 'mobile', 'objectclass',
'ou', 'pager', 'postalcode', 'roomnumber', 'secretary',
'seealso', 'sn', 'st', 'street', 'telephonenumber', 'title',
'userclass', 'preferredlanguage'
},
'replaces': [
'(targetattr = "givenname || sn || cn || displayname || title || initials || loginshell || gecos || homephone || mobile || pager || facsimiletelephonenumber || telephonenumber || street || roomnumber || l || st || postalcode || manager || secretary || description || carlicense || labeleduri || inetuserhttpurl || seealso || employeetype || businesscategory || ou || mepmanagedentry || objectclass")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Users";allow (write) groupdn = "ldap:///cn=Modify Users,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {
'User Administrators',
'Modify Users and Reset passwords',
},
},
'System: Remove Users': {
'ipapermright': {'delete'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'replaces': [
'(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Users";allow (delete) groupdn = "ldap:///cn=Remove Users,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'User Administrators'},
},
'System: Unlock User': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
NOT_MEMBEROF_ADMINS,
],
'ipapermdefaultattr': {
'krblastadminunlock', 'krbloginfailedcount', 'nsaccountlock',
},
'replaces': [
'(targetattr = "krbLastAdminUnlock || krbLoginFailedCount")(target = "ldap:///uid=*,cn=users,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Unlock user accounts";allow (write) groupdn = "ldap:///cn=Unlock user accounts,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'User Administrators'},
},
'System: Read User Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=users', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'uid', 'cn', 'gecos', 'gidnumber', 'uidnumber',
'homedirectory', 'loginshell',
},
},
'System: Read User Views Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=users', 'cn=*', 'cn=views', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'uid', 'cn', 'gecos', 'gidnumber', 'uidnumber',
'homedirectory', 'loginshell',
},
},
'System: Read User NT Attributes': {
'ipapermbindruletype': 'permission',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ntuserdomainid', 'ntuniqueid', 'ntuseracctexpires',
'ntusercodepage', 'ntuserdeleteaccount', 'ntuserlastlogoff',
'ntuserlastlogon',
},
'default_privileges': {'PassSync Service'},
},
'System: Manage User Certificate Mappings': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'ipacertmapdata', 'objectclass'},
'default_privileges': {
'Certificate Identity Mapping Administrators'
},
},
'System: Manage Passkey Mappings': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'ipapasskey', 'objectclass'},
'default_privileges': {
'Passkey Administrators'
},
},
}
takes_params = baseuser.takes_params + (
Bool('nsaccountlock?',
cli_name=('disabled'),
default=False,
label=_('Account disabled'),
),
Bool('preserved?',
label=_('Preserved user'),
default=False,
flags=['virtual_attribute', 'no_create', 'no_update'],
),
)
def get_delete_dn(self, *keys, **options):
active_dn = self.get_dn(*keys, **options)
return DN(active_dn[0], self.delete_container_dn, api.env.basedn)
def get_either_dn(self, *keys, **options):
'''
Returns the DN of a user and their objectclasses
The user can be active (active container) or delete (delete container)
If the user does not exist, returns the Active user DN
'''
ldap = self.backend
oc = []
# Check that this value is a Active user
try:
active_dn = self.get_dn(*keys, **options)
oc = ldap.get_entry(active_dn, ['dn', 'objectclass'])['objectclass']
# The Active user exists
dn = active_dn
except errors.NotFound:
# Check that this value is a Delete user
delete_dn = self.get_delete_dn(*keys, **options)
try:
oc = ldap.get_entry(
delete_dn, ['dn', 'objectclass']
)['objectclass']
# The Delete user exists
dn = delete_dn
except errors.NotFound:
# The user is neither Active/Delete -> returns that Active DN
dn = active_dn
return dn, oc
def _normalize_manager(self, manager):
"""
Given a userid verify the user's existence and return the dn.
"""
return super(user, self).normalize_manager(manager, self.active_container_dn)
def get_preserved_attribute(self, entry, options):
if options.get('raw', False):
return
delete_container_dn = DN(self.delete_container_dn, api.env.basedn)
if entry.dn.endswith(delete_container_dn):
entry['preserved'] = True
elif options.get('all', False):
entry['preserved'] = False
@register()
class user_add(baseuser_add):
__doc__ = _('Add a new user.')
msg_summary = _('Added user "%(value)s"')
has_output_params = baseuser_add.has_output_params + user_output_params
takes_options = LDAPCreate.takes_options + (
Flag('noprivate',
cli_name='noprivate',
doc=_('Don\'t create user private group'),
),
)
def get_options(self):
for option in super(user_add, self).get_options():
if option.name == "nsaccountlock":
flags = set(option.flags)
flags.add("no_option")
option = option.clone(flags=flags)
yield option
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
delete_dn = self.obj.get_delete_dn(*keys, **options)
try:
ldap.get_entry(delete_dn, [''])
except errors.NotFound:
pass
else:
raise self.obj.handle_duplicate_entry(*keys)
if not options.get('noprivate', False) and ldap.has_upg():
try:
# The Managed Entries plugin will allow a user to be created
# even if a group has a duplicate name. This would leave a user
# without a private group. Check for both the group and the user.
self.api.Object['group'].get_dn_if_exists(keys[-1])
try:
self.api.Command['user_show'](keys[-1])
self.obj.handle_duplicate_entry(*keys)
except errors.NotFound:
raise errors.ManagedGroupExistsError(group=keys[-1])
except errors.NotFound:
pass
else:
# we don't want an user private group to be created for this user
# add NO_UPG_MAGIC description attribute to let the DS plugin know
entry_attrs.setdefault('description', [])
entry_attrs['description'].append(NO_UPG_MAGIC)
entry_attrs.setdefault('uidnumber', baseldap.DNA_MAGIC)
if not client_has_capability(
options['version'], 'optional_uid_params'):
# https://fedorahosted.org/freeipa/ticket/2886
# Old clients say 999 (OLD_DNA_MAGIC) when they really mean
# "assign a value dynamically".
OLD_DNA_MAGIC = 999
if entry_attrs.get('uidnumber') == OLD_DNA_MAGIC:
entry_attrs['uidnumber'] = baseldap.DNA_MAGIC
if entry_attrs.get('gidnumber') == OLD_DNA_MAGIC:
entry_attrs['gidnumber'] = baseldap.DNA_MAGIC
validate_nsaccountlock(entry_attrs)
config = ldap.get_ipa_config()
if 'ipamaxusernamelength' in config:
if len(keys[-1]) > int(config.get('ipamaxusernamelength')[0]):
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('can be at most %(len)d characters') % dict(
len = int(config.get('ipamaxusernamelength')[0])
)
)
default_shell = config.get('ipadefaultloginshell',
[platformconstants.DEFAULT_SHELL])[0]
entry_attrs.setdefault('loginshell', default_shell)
# hack so we can request separate first and last name in CLI
full_name = '%s %s' % (entry_attrs['givenname'], entry_attrs['sn'])
entry_attrs.setdefault('cn', full_name)
if 'homedirectory' not in entry_attrs:
# get home's root directory from config
homes_root = config.get('ipahomesrootdir', [paths.HOME_DIR])[0]
# build user's home directory based on his uid
entry_attrs['homedirectory'] = posixpath.join(homes_root, keys[-1])
entry_attrs.setdefault('krbprincipalname', '%s@%s' % (entry_attrs['uid'], api.env.realm))
if entry_attrs.get('gidnumber') is None:
# gidNumber wasn't specified explicity, find out what it should be
if not options.get('noprivate', False) and ldap.has_upg():
# User Private Groups - uidNumber == gidNumber
entry_attrs['gidnumber'] = entry_attrs['uidnumber']
else:
# we're adding new users to a default group, get its gidNumber
# get default group name from config
def_primary_group = config.get('ipadefaultprimarygroup')
group_dn = self.api.Object['group'].get_dn(def_primary_group)
try:
group_attrs = ldap.get_entry(group_dn, ['gidnumber'])
except errors.NotFound:
error_msg = _('Default group for new users not found')
raise errors.NotFound(reason=error_msg)
if 'gidnumber' not in group_attrs:
error_msg = _('Default group for new users is not POSIX')
raise errors.NotFound(reason=error_msg)
entry_attrs['gidnumber'] = group_attrs['gidnumber']
if 'userpassword' not in entry_attrs and options.get('random'):
entry_attrs['userpassword'] = ipa_generate_password(
entropy_bits=TMP_PWD_ENTROPY_BITS)
# save the password so it can be displayed in post_callback
setattr(context, 'randompassword', entry_attrs['userpassword'])
if 'mail' in entry_attrs:
entry_attrs['mail'] = self.obj.normalize_and_validate_email(entry_attrs['mail'], config)
else:
# No e-mail passed in. If we have a default e-mail domain set
# then we'll add it automatically.
defaultdomain = config.get('ipadefaultemaildomain', [None])[0]
if defaultdomain:
entry_attrs['mail'] = self.obj.normalize_and_validate_email(keys[-1], config)
if 'manager' in entry_attrs:
entry_attrs['manager'] = self.obj.normalize_manager(entry_attrs['manager'], self.obj.active_container_dn)
if 'userclass' in entry_attrs and \
'ipauser' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('ipauser')
rcl = entry_attrs.get('ipatokenradiusconfiglink', None)
if rcl:
if 'ipatokenradiusproxyuser' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('ipatokenradiusproxyuser')
answer = self.api.Object['radiusproxy'].get_dn_if_exists(rcl)
entry_attrs['ipatokenradiusconfiglink'] = answer
rcl = entry_attrs.get('ipaidpconfiglink', None)
if rcl:
if 'ipaidpuser' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('ipaidpuser')
try:
answer = self.api.Object['idp'].get_dn_if_exists(rcl)
except errors.NotFound:
reason = "External IdP configuration {} not found"
raise errors.NotFound(reason=_(reason).format(rcl))
entry_attrs['ipaidpconfiglink'] = answer
self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys,
**options)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
config = ldap.get_ipa_config()
# add the user we just created into the default primary group
def_primary_group = config.get('ipadefaultprimarygroup')
group_dn = self.api.Object['group'].get_dn(def_primary_group)
# if the user is already a member of default primary group,
# do not raise error
# this can happen if automember rule or default group is set
try:
ldap.add_entry_to_group(dn, group_dn)
except errors.AlreadyGroupMember:
pass
# Fetch the entry again to update memberof, mep data, etc updated
# at the end of the transaction.
newentry = ldap.get_entry(dn, ['*'])
# delete description attribute NO_UPG_MAGIC if present
if (options.get('noprivate', False) or not ldap.has_upg()) and \
'description' in newentry and \
NO_UPG_MAGIC in newentry['description']:
newentry['description'].remove(NO_UPG_MAGIC)
ldap.update_entry(newentry)
entry_attrs.update(newentry)
# delete ipantsecurityidentifier if present
if ('ipantsecurityidentifier' in entry_attrs):
del entry_attrs['ipantsecurityidentifier']
if options.get('random', False):
try:
entry_attrs['randompassword'] = unicode(getattr(context, 'randompassword'))
except AttributeError:
# if both randompassword and userpassword options were used
pass
# generate subid
default_subid = config.single_value.get(
'ipaUserDefaultSubordinateId', False
)
if default_subid:
result = self.api.Command.subid_generate(
ipaowner=entry_attrs.single_value['uid'],
version=options['version']
)
entry_attrs["memberOf"].append(result['result']['dn'])
self.obj.get_preserved_attribute(entry_attrs, options)
self.post_common_callback(ldap, dn, entry_attrs, *keys, **options)
return dn
@register()
class user_del(baseuser_del):
__doc__ = _('Delete a user.')
msg_summary = _('Deleted user "%(value)s"')
msg_summary_preserved = _('Preserved user "%(value)s"')
takes_options = baseuser_del.takes_options + (
Bool('preserve?',
exclude='cli',
),
)
def _preserve_user(self, pkey, delete_container, **options):
assert isinstance(delete_container, DN)
dn, _oc = self.obj.get_either_dn(pkey, **options)
delete_dn = DN(dn[0], delete_container)
ldap = self.obj.backend
logger.debug("preserve move %s -> %s", dn, delete_dn)
if dn.endswith(delete_container):
raise errors.ExecutionError(
_('%s: user is already preserved' % pkey)
)
# Check that this value is a Active user
try:
original_entry_attrs = self._exc_wrapper(
pkey, options, ldap.get_entry)(dn, ['dn'])
except errors.NotFound:
raise self.obj.handle_not_found(pkey)
for callback in self.get_callbacks('pre'):
dn = callback(self, ldap, dn, pkey, **options)
assert isinstance(dn, DN)
# start to move the entry to Delete container
self._exc_wrapper(pkey, options, ldap.move_entry)(dn, delete_dn,
del_old=True)
# Then clear the credential attributes
attrs_to_clear = ['krbPrincipalKey', 'krbLastPwdChange',
'krbPasswordExpiration', 'userPassword']
entry_attrs = self._exc_wrapper(pkey, options, ldap.get_entry)(
delete_dn, attrs_to_clear)
clearedCredential = False
for attr in attrs_to_clear:
if attr.lower() in entry_attrs:
del entry_attrs[attr]
clearedCredential = True
if clearedCredential:
self._exc_wrapper(pkey, options, ldap.update_entry)(entry_attrs)
# Then restore some original entry attributes
attrs_to_restore = ['secretary', 'managedby', 'manager', 'ipauniqueid',
'uidnumber', 'gidnumber', 'passwordHistory']
entry_attrs = self._exc_wrapper(
pkey, options, ldap.get_entry)(delete_dn, attrs_to_restore)
restoreAttr = False
for attr in attrs_to_restore:
if ((attr.lower() in original_entry_attrs) and
not (attr.lower() in entry_attrs)):
restoreAttr = True
entry_attrs[attr.lower()] = original_entry_attrs[attr.lower()]
if restoreAttr:
self._exc_wrapper(pkey, options, ldap.update_entry)(entry_attrs)
def pre_callback(self, ldap, dn, *keys, **options):
dn, _oc = self.obj.get_either_dn(*keys, **options)
# For User life Cycle: user-del is a common plugin
# command to delete active user (active container) and
# delete user (delete container).
# If the target entry is a Delete entry, skip the orphaning/removal
# of OTP tokens.
check_protected_member(keys[-1])
check_last_member(keys[-1])
preserve = options.get('preserve', False)
if not preserve:
# Remove any ID overrides tied with this user
try:
remove_ipaobject_overrides(self.obj.backend, self.obj.api, dn)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if dn.endswith(DN(self.obj.delete_container_dn, api.env.basedn)):
return dn
# Delete all tokens owned and managed by this user.
# Orphan all tokens owned but not managed by this user.
owner = self.api.Object.user.get_primary_key_from_dn(dn)
results = self.api.Command.otptoken_find(
ipatokenowner=owner, no_members=False)['result']
for token in results:
orphan = not [x for x in token.get('managedby_user', []) if x == owner]
token = self.api.Object.otptoken.get_primary_key_from_dn(token['dn'])
if orphan:
self.api.Command.otptoken_mod(token, ipatokenowner=None)
else:
self.api.Command.otptoken_del(token)
# XXX: preserving doesn't work yet, see subordinate-ids.md
# Delete all subid entries owned by this user.
results = self.api.Command.subid_find(ipaowner=owner)["result"]
for subid_entry in results:
subid_pkey = self.api.Object.subid.get_primary_key_from_dn(
subid_entry["dn"]
)
self.api.Command.subid_del(subid_pkey)
return dn
def execute(self, *keys, **options):
# We are going to permanent delete or the user is already in the delete container.
delete_container = DN(self.obj.delete_container_dn, self.api.env.basedn)
# The user to delete is active and there is no 'no_preserve' option
if options.get('preserve', False):
failed = []
preserved = []
for pkey in keys[-1]:
try:
self._preserve_user(pkey, delete_container, **options)
preserved.append(pkey_to_value(pkey, options))
except Exception:
if not options.get('continue', False):
raise
failed.append(pkey_to_value(pkey, options))
val = dict(result=dict(failed=failed), value=preserved)
val['summary'] = self.msg_summary_preserved % dict(
value=pkey_to_unicode(preserved))
return val
else:
return super(user_del, self).execute(*keys, **options)
@register()
class user_mod(baseuser_mod):
__doc__ = _('Modify a user.')
msg_summary = _('Modified user "%(value)s"')
has_output_params = baseuser_mod.has_output_params + user_output_params
def get_options(self):
for option in super(user_mod, self).get_options():
if option.name == "nsaccountlock":
flags = set(option.flags)
flags.add("no_option")
option = option.clone(flags=flags)
yield option
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
dn, oc = self.obj.get_either_dn(*keys, **options)
if options.get('rename') and keys[-1] in PROTECTED_USERS:
raise errors.ProtectedEntryError(
label=_("user"),
key=keys[-1],
reason=_("privileged user"),
)
if 'objectclass' not in entry_attrs and 'rename' not in options:
entry_attrs.update({'objectclass': oc})
self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys,
**options)
validate_nsaccountlock(entry_attrs)
# TODO: forward uidNumber changes and rename to subids
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.post_common_callback(ldap, dn, entry_attrs, *keys, **options)
self.obj.get_preserved_attribute(entry_attrs, options)
return dn
@register()
class user_find(baseuser_find):
__doc__ = _('Search for users.')
member_attributes = ['memberof']
has_output_params = baseuser_find.has_output_params + user_output_params
msg_summary = ngettext(
'%(count)d user matched', '%(count)d users matched', 0
)
takes_options = LDAPSearch.takes_options + (
Flag('whoami',
label=_('Self'),
doc=_('Display user record for current Kerberos principal'),
),
)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *keys, **options):
assert isinstance(base_dn, DN)
self.pre_common_callback(ldap, filter, attrs_list, base_dn, scope,
*keys, **options)
if options.get('whoami'):
op_account = getattr(context, 'principal', None)
if op_account is None:
new_base_dn = DN(ldap.conn.whoami_s()[4:])
return ("(objectclass=posixaccount)", new_base_dn, scope)
return ("(&(objectclass=posixaccount)(krbprincipalname=%s))"%\
op_account, base_dn, scope)
preserved = options.get('preserved', False)
if preserved is None:
base_dn = self.api.env.basedn
scope = ldap.SCOPE_SUBTREE
elif preserved:
base_dn = DN(self.obj.delete_container_dn, self.api.env.basedn)
else:
base_dn = DN(self.obj.active_container_dn, self.api.env.basedn)
return (filter, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
if options.get('preserved', False) is None:
base_dns = (
DN(self.obj.active_container_dn, self.api.env.basedn),
DN(self.obj.delete_container_dn, self.api.env.basedn),
)
entries[:] = list(
e for e in entries if any(e.dn.endswith(bd) for bd in base_dns)
)
self.post_common_callback(ldap, entries, lockout=False, **options)
for entry in entries:
self.obj.get_preserved_attribute(entry, options)
return truncated
@register()
class user_show(baseuser_show):
__doc__ = _('Display information about a user.')
has_output_params = baseuser_show.has_output_params + user_output_params
takes_options = baseuser_show.takes_options + (
Str('out?',
doc=_('file to store certificate in'),
),
)
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
dn, _oc = self.obj.get_either_dn(*keys, **options)
self.pre_common_callback(ldap, dn, attrs_list, *keys, **options)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
convert_nsaccountlock(entry_attrs)
self.post_common_callback(ldap, dn, entry_attrs, *keys, **options)
self.obj.get_preserved_attribute(entry_attrs, options)
return dn
@register()
class user_undel(LDAPQuery):
__doc__ = _('Undelete a delete user account.')
has_output = output.standard_value
msg_summary = _('Undeleted user account "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
# First check that the user exists and is a delete one
delete_dn, _oc = self.obj.get_either_dn(*keys, **options)
try:
self._exc_wrapper(keys, options, ldap.get_entry)(delete_dn)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if delete_dn.endswith(DN(self.obj.active_container_dn,
api.env.basedn)):
raise errors.InvocationError(
message=_('user "%s" is already active') % keys[-1])
active_dn = DN(delete_dn[0], self.obj.active_container_dn, api.env.basedn)
# start to move the entry to the Active container
self._exc_wrapper(keys, options, ldap.move_entry)(delete_dn, active_dn, del_old=True)
# add the user we just undelete into the default primary group
config = ldap.get_ipa_config()
def_primary_group = config.get('ipadefaultprimarygroup')
group_dn = self.api.Object['group'].get_dn(def_primary_group)
# if the user is already a member of default primary group,
# do not raise error
# this can happen if automember rule or default group is set
try:
ldap.add_entry_to_group(active_dn, group_dn)
except errors.AlreadyGroupMember:
pass
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class user_stage(LDAPMultiQuery):
__doc__ = _('Move deleted user into staged area')
has_output = output.standard_multi_delete
msg_summary = _('Staged user account "%(value)s"')
# when moving from preserved to stage, some attributes may be
# present in the preserved entry but cannot be provided to
# stageuser_add
# For instance: dn and uid are derived from LOGIN argument
# has_keytab, has_password, preserved are virtual attributes
# ipauniqueid, krbcanonicalname, sshpubkeyfp, krbextradata
# are automatically generated
# ipacertmapdata can only be provided with user_add_certmapdata
# ipapasskey can only be provided with user_add_passkey
ignore_attrs = [u'dn', u'uid',
u'has_keytab', u'has_password', u'preserved',
u'ipauniqueid', u'krbcanonicalname',
u'sshpubkeyfp', u'krbextradata',
u'ipacertmapdata',
'ipantsecurityidentifier',
u'nsaccountlock',
u'ipapasskey']
def execute(self, *keys, **options):
def _build_setattr_arg(key, val):
if isinstance(val, bytes):
return u"{}={}".format(key, val.decode('UTF-8'))
else:
return u"{}={}".format(key, val)
staged = []
failed = []
for key in keys[-1]:
single_keys = keys[:-1] + (key,)
multi_keys = keys[:-1] + ((key,),)
user = self.api.Command.user_show(*single_keys, all=True)['result']
new_options = {}
for param in self.api.Command.stageuser_add.options():
try:
value = user[param.name]
except KeyError:
continue
if param.multivalue and not isinstance(value, (list, tuple)):
value = [value]
elif not param.multivalue and isinstance(value, (list, tuple)):
value = value[0]
new_options[param.name] = value
# Some attributes may not be accessible through the Command
# options and need to be added with --setattr
set_attr = []
for userkey in user.keys():
if userkey in new_options or userkey in self.ignore_attrs:
continue
value = user[userkey]
if isinstance(value, (list, tuple)):
for val in value:
set_attr.append(_build_setattr_arg(userkey, val))
else:
set_attr.append(_build_setattr_arg(userkey, val))
if set_attr:
new_options[u'setattr'] = set_attr
try:
self.api.Command.stageuser_add(*single_keys, **new_options)
# special handling for certmapdata
certmapdata = user.get(u'ipacertmapdata')
if certmapdata:
self.api.Command.stageuser_add_certmapdata(
*single_keys,
ipacertmapdata=certmapdata)
# special handling for passkey
passkey = user.get(u'ipapasskey')
if passkey:
self.api.Command.stageuser_add_passkey(
*single_keys,
ipapasskey=passkey)
try:
self.api.Command.user_del(*multi_keys, preserve=False)
except errors.ExecutionError:
self.api.Command.stageuser_del(*multi_keys)
raise
except errors.ExecutionError:
if not options['continue']:
raise
failed.append(key)
else:
staged.append(key)
return dict(
result=dict(
failed=pkey_to_value(failed, options),
),
value=pkey_to_value(staged, options),
)
@register()
class user_disable(LDAPQuery):
__doc__ = _('Disable a user account.')
has_output = output.standard_value
msg_summary = _('Disabled user account "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
check_last_member(keys[-1])
dn, _oc = self.obj.get_either_dn(*keys, **options)
ldap.deactivate_entry(dn)
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class user_enable(LDAPQuery):
__doc__ = _('Enable a user account.')
has_output = output.standard_value
has_output_params = LDAPQuery.has_output_params + user_output_params
msg_summary = _('Enabled user account "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
dn, _oc = self.obj.get_either_dn(*keys, **options)
ldap.activate_entry(dn)
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class user_unlock(LDAPQuery):
__doc__ = _("""
Unlock a user account
An account may become locked if the password is entered incorrectly too
many times within a specific time period as controlled by password
policy. A locked account is a temporary condition and may be unlocked by
an administrator.""")
has_output = output.standard_value
msg_summary = _('Unlocked account "%(value)s"')
def execute(self, *keys, **options):
dn, _oc = self.obj.get_either_dn(*keys, **options)
entry = self.obj.backend.get_entry(
dn, ['krbLastAdminUnlock', 'krbLoginFailedCount'])
entry['krbLastAdminUnlock'] = [strftime("%Y%m%d%H%M%SZ", gmtime())]
entry['krbLoginFailedCount'] = ['0']
self.obj.backend.update_entry(entry)
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class userstatus(LDAPObject):
parent_object = 'user'
takes_params = (
Bool('preserved?',
label=_('Preserved user'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('server',
label=_('Server'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('krbloginfailedcount',
label=_('Failed logins'),
flags={'no_create', 'no_update', 'no_search'},
),
Str('krblastsuccessfulauth',
label=_('Last successful authentication'),
flags={'no_create', 'no_update', 'no_search'},
),
Str('krblastfailedauth',
label=_('Last failed authentication'),
flags={'no_create', 'no_update', 'no_search'},
),
Str('now',
label=_('Time now'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('passwordgraceusertime',
label=_('Password grace count'),
flags={'no_create', 'no_update', 'no_search'},),
)
@register()
class user_status(LDAPQuery):
__doc__ = _("""
Lockout status of a user account
An account may become locked if the password is entered incorrectly too
many times within a specific time period as controlled by password
policy. A locked account is a temporary condition and may be unlocked by
an administrator.
This connects to each IPA master and displays the lockout status on
each one.
To determine whether an account is locked on a given server you need
to compare the number of failed logins and the time of the last failure.
For an account to be locked it must exceed the maxfail failures within
the failinterval duration as specified in the password policy associated
with the user.
The failed login counter is modified only when a user attempts a log in
so it is possible that an account may appear locked but the last failed
login attempt is older than the lockouttime of the password policy. This
means that the user may attempt a login again. """)
obj_name = 'userstatus'
attr_name = 'find'
has_output = output.standard_list_of_entries
def get_args(self):
for arg in super(user_status, self).get_args():
if arg.name == 'useruid':
arg = arg.clone(cli_name='login')
yield arg
def execute(self, *keys, **options):
ldap = self.obj.backend
dn, _oc = self.api.Object.user.get_either_dn(*keys, **options)
attr_list = ['krbloginfailedcount', 'krblastsuccessfulauth',
'krblastfailedauth', 'nsaccountlock',
'passwordgraceusertime']
disabled = False
masters = get_masters(ldap)
entries = []
count = 0
for host in masters:
if host == api.env.host:
other_ldap = self.obj.backend
else:
try:
other_ldap = LDAPClient(ldap_uri='ldap://%s' % host)
other_ldap.gssapi_bind()
except Exception as e:
logger.error("user_status: Connecting to %s failed with "
"%s", host, str(e))
newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed: %(error)s") % dict(host=host, error=str(e))
entries.append(newresult)
count += 1
continue
try:
entry = other_ldap.get_entry(dn, attr_list)
newresult = {'dn': dn}
for attr in ['krblastsuccessfulauth', 'krblastfailedauth']:
newresult[attr] = entry.get(attr, [u'N/A'])
newresult['krbloginfailedcount'] = entry.get('krbloginfailedcount', u'0')
newresult['passwordgraceusertime'] = \
entry.get('passwordgraceusertime', u'0')
if not options.get('raw', False):
for attr in ['krblastsuccessfulauth', 'krblastfailedauth']:
try:
if newresult[attr][0] == u'N/A':
continue
newtime = time.strptime(newresult[attr][0], '%Y%m%d%H%M%SZ')
newresult[attr][0] = unicode(time.strftime('%Y-%m-%dT%H:%M:%SZ', newtime))
except Exception as e:
logger.debug("time conversion failed with %s",
str(e))
newresult['server'] = host
if options.get('raw', False):
time_format = '%Y%m%d%H%M%SZ'
else:
time_format = '%Y-%m-%dT%H:%M:%SZ'
newresult['now'] = unicode(strftime(time_format, gmtime()))
convert_nsaccountlock(entry)
if 'nsaccountlock' in entry:
disabled = entry['nsaccountlock']
self.api.Object.user.get_preserved_attribute(entry, options)
entries.append(newresult)
count += 1
except errors.NotFound:
raise self.api.Object.user.handle_not_found(*keys)
except Exception as e:
logger.error("user_status: Retrieving status for %s failed "
"with %s", dn, str(e))
newresult = {'dn': dn}
newresult['server'] = _("%(host)s failed") % dict(host=host)
entries.append(newresult)
count += 1
if host != api.env.host:
other_ldap.close()
return dict(result=entries,
count=count,
truncated=False,
summary=unicode(_('Account disabled: %(disabled)s' %
dict(disabled=disabled))),
)
@register()
class user_add_cert(baseuser_add_cert):
__doc__ = _('Add one or more certificates to the user entry')
msg_summary = _('Added certificates to user "%(value)s"')
@register()
class user_remove_cert(baseuser_remove_cert):
__doc__ = _('Remove one or more certificates to the user entry')
msg_summary = _('Removed certificates from user "%(value)s"')
@register()
class user_add_certmapdata(baseuser_add_certmapdata):
__doc__ = _("Add one or more certificate mappings to the user entry.")
@register()
class user_remove_certmapdata(baseuser_remove_certmapdata):
__doc__ = _("Remove one or more certificate mappings from the user entry.")
@register()
class user_add_manager(baseuser_add_manager):
__doc__ = _("Add a manager to the user entry")
@register()
class user_remove_manager(baseuser_remove_manager):
__doc__ = _("Remove a manager to the user entry")
@register()
class user_add_principal(baseuser_add_principal):
__doc__ = _('Add new principal alias to the user entry')
msg_summary = _('Added new aliases to user "%(value)s"')
@register()
class user_remove_principal(baseuser_remove_principal):
__doc__ = _('Remove principal alias from the user entry')
msg_summary = _('Removed aliases from user "%(value)s"')
@register()
class user_add_passkey(baseuser_add_passkey):
__doc__ = _("Add one or more passkey mappings to the user entry.")
@register()
class user_remove_passkey(baseuser_remove_passkey):
__doc__ = _("Remove one or more passkey mappings from the user entry.")
| 56,253
|
Python
|
.py
| 1,210
| 35.293388
| 597
| 0.588835
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,826
|
config.py
|
freeipa_freeipa/ipaserver/plugins/config.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 dbus
import dbus.mainloop.glib
import logging
from ipalib import api
from ipalib import Bool, Int, Str, IA5Str, StrEnum, DNParam, Flag
from ipalib import errors
from ipalib.constants import MAXHOSTNAMELEN, IPA_CA_CN
from ipalib.plugable import Registry
from ipalib.request import context
from ipalib.util import validate_domain_name
from .baseldap import (
LDAPObject,
LDAPUpdate,
LDAPRetrieve)
from .selinuxusermap import validate_selinuxuser
from ipalib import _
from ipapython.admintool import ScriptError
from ipapython.dn import DN
from ipaserver.plugins.privilege import principal_has_privilege
from ipaserver.install.adtrust import set_and_check_netbios_name
logger = logging.getLogger(__name__)
# 389-ds attributes that should be skipped in attribute checks
OPERATIONAL_ATTRIBUTES = ('nsaccountlock', 'member', 'memberof',
'memberindirect', 'memberofindirect',)
DOMAIN_RESOLUTION_ORDER_SEPARATOR = u':'
__doc__ = _("""
Server configuration
Manage the default values that IPA uses and some of its tuning parameters.
NOTES:
The password notification value (--pwdexpnotify) is stored here so it will
be replicated. It is not currently used to notify users in advance of an
expiring password.
Some attributes are read-only, provided only for information purposes. These
include:
Certificate Subject base: the configured certificate subject base,
e.g. O=EXAMPLE.COM. This is configurable only at install time.
Password plug-in features: currently defines additional hashes that the
password will generate (there may be other conditions).
When setting the order list for mapping SELinux users you may need to
quote the value so it isn't interpreted by the shell.
The maximum length of a hostname in Linux is controlled by
MAXHOSTNAMELEN in the kernel and defaults to 64. Some other operating
systems, Solaris for example, allows hostnames up to 255 characters.
This option will allow flexibility in length but by default limiting
to the Linux maximum length.
EXAMPLES:
Show basic server configuration:
ipa config-show
Show all configuration options:
ipa config-show --all
Change maximum username length to 99 characters:
ipa config-mod --maxusername=99
Change maximum host name length to 255 characters:
ipa config-mod --maxhostname=255
Increase default time and size limits for maximum IPA server search:
ipa config-mod --searchtimelimit=10 --searchrecordslimit=2000
Set default user e-mail domain:
ipa config-mod --emaildomain=example.com
Enable migration mode to make "ipa migrate-ds" command operational:
ipa config-mod --enable-migration=TRUE
Define SELinux user map order:
ipa config-mod --ipaselinuxusermaporder='guest_u:s0$xguest_u:s0$user_u:s0-s0:c0.c1023$staff_u:s0-s0:c0.c1023$unconfined_u:s0-s0:c0.c1023'
""")
register = Registry()
def validate_search_records_limit(ugettext, value):
"""Check if value is greater than a realistic minimum.
Values 0 and -1 are valid, as they represent unlimited.
"""
if value in {-1, 0}:
return None
if value < 10:
return _('must be at least 10')
return None
@register()
class config(LDAPObject):
"""
IPA configuration object
"""
object_name = _('configuration options')
default_attributes = [
'ipamaxusernamelength', 'ipahomesrootdir', 'ipadefaultloginshell',
'ipadefaultprimarygroup', 'ipadefaultemaildomain', 'ipasearchtimelimit',
'ipasearchrecordslimit', 'ipausersearchfields', 'ipagroupsearchfields',
'ipamigrationenabled', 'ipacertificatesubjectbase',
'ipapwdexpadvnotify', 'ipaselinuxusermaporder',
'ipaselinuxusermapdefault', 'ipaconfigstring', 'ipakrbauthzdata',
'ipauserauthtype', 'ipadomainresolutionorder', 'ipamaxhostnamelength',
'ipauserdefaultsubordinateid',
]
container_dn = DN(('cn', 'ipaconfig'), ('cn', 'etc'))
permission_filter_objectclasses = ['ipaguiconfig']
managed_permissions = {
'System: Read Global Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass',
'ipacertificatesubjectbase', 'ipaconfigstring',
'ipadefaultemaildomain', 'ipadefaultloginshell',
'ipadefaultprimarygroup', 'ipadomainresolutionorder',
'ipagroupobjectclasses',
'ipagroupsearchfields', 'ipahomesrootdir',
'ipakrbauthzdata', 'ipamaxusernamelength',
'ipamigrationenabled', 'ipapwdexpadvnotify',
'ipaselinuxusermapdefault', 'ipaselinuxusermaporder',
'ipasearchrecordslimit', 'ipasearchtimelimit',
'ipauserauthtype', 'ipauserobjectclasses',
'ipausersearchfields', 'ipacustomfields',
'ipamaxhostnamelength', 'ipauserdefaultsubordinateid',
},
},
}
label = _('Configuration')
label_singular = _('Configuration')
takes_params = (
Int('ipamaxusernamelength',
cli_name='maxusername',
label=_('Maximum username length'),
minvalue=1,
maxvalue=255,
),
Int('ipamaxhostnamelength',
cli_name='maxhostname',
label=_('Maximum hostname length'),
minvalue=MAXHOSTNAMELEN,
maxvalue=255,),
IA5Str('ipahomesrootdir',
cli_name='homedirectory',
label=_('Home directory base'),
doc=_('Default location of home directories'),
),
Str('ipadefaultloginshell',
cli_name='defaultshell',
label=_('Default shell'),
doc=_('Default shell for new users'),
),
Str('ipadefaultprimarygroup',
cli_name='defaultgroup',
label=_('Default users group'),
doc=_('Default group for new users'),
),
Str('ipadefaultemaildomain?',
cli_name='emaildomain',
label=_('Default e-mail domain'),
doc=_('Default e-mail domain'),
),
Int('ipasearchtimelimit',
cli_name='searchtimelimit',
label=_('Search time limit'),
doc=_('Maximum amount of time (seconds) for a search (-1 or 0 is unlimited)'),
minvalue=-1,
),
Int('ipasearchrecordslimit',
validate_search_records_limit,
cli_name='searchrecordslimit',
label=_('Search size limit'),
doc=_('Maximum number of records to search (-1 or 0 is unlimited)'),
),
IA5Str('ipausersearchfields',
cli_name='usersearch',
label=_('User search fields'),
doc=_('A comma-separated list of fields to search in when searching for users'),
),
IA5Str('ipagroupsearchfields',
cli_name='groupsearch',
label=_('Group search fields'),
doc=_('A comma-separated list of fields to search in when searching for groups'),
),
Bool('ipamigrationenabled',
cli_name='enable_migration',
label=_('Enable migration mode'),
doc=_('Enable migration mode'),
),
DNParam('ipacertificatesubjectbase',
cli_name='subject',
label=_('Certificate Subject base'),
doc=_('Base for certificate subjects (OU=Test,O=Example)'),
flags=['no_update'],
),
Str('ipagroupobjectclasses+',
cli_name='groupobjectclasses',
label=_('Default group objectclasses'),
doc=_('Default group objectclasses (comma-separated list)'),
),
Str('ipauserobjectclasses+',
cli_name='userobjectclasses',
label=_('Default user objectclasses'),
doc=_('Default user objectclasses (comma-separated list)'),
),
Int('ipapwdexpadvnotify',
cli_name='pwdexpnotify',
label=_('Password Expiration Notification (days)'),
doc=_('Number of days\'s notice of impending password expiration'),
minvalue=0,
),
StrEnum('ipaconfigstring*',
cli_name='ipaconfigstring',
label=_('Password plugin features'),
doc=_('Extra hashes to generate in password plug-in'),
values=(u'AllowNThash',
u'KDC:Disable Last Success', u'KDC:Disable Lockout',
u'KDC:Disable Default Preauth for SPNs',
u'EnforceLDAPOTP'),
),
Str('ipaselinuxusermaporder',
label=_('SELinux user map order'),
doc=_('Order in increasing priority of SELinux users, delimited by $'),
),
Str('ipaselinuxusermapdefault?',
label=_('Default SELinux user'),
doc=_('Default SELinux user when no match is found in SELinux map rule'),
),
StrEnum('ipakrbauthzdata*',
cli_name='pac_type',
label=_('Default PAC types'),
doc=_('Default types of PAC supported for services'),
values=(u'MS-PAC', u'PAD', u'nfs:NONE'),
),
StrEnum(
'ipauserauthtype*',
cli_name='user_auth_type',
label=_('Default user authentication types'),
doc=_('Default types of supported user authentication'),
values=(u'password', u'radius', u'otp',
u'pkinit', u'hardened', u'idp', u'passkey', u'disabled'),
),
Bool('ipauserdefaultsubordinateid?',
cli_name='user_default_subid',
label=_('Enable adding subids to new users'),
doc=_('Enable adding subids to new users'),
),
Str(
'ipa_master_server*',
label=_('IPA masters'),
doc=_('List of all IPA masters'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ipa_master_hidden_server*',
label=_('Hidden IPA masters'),
doc=_('List of all hidden IPA masters'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'pkinit_server_server*',
label=_('IPA master capable of PKINIT'),
doc=_('IPA master which can process PKINIT requests'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ca_server_server*',
label=_('IPA CA servers'),
doc=_('IPA servers configured as certificate authority'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ca_server_hidden_server*',
label=_('Hidden IPA CA servers'),
doc=_('Hidden IPA servers configured as certificate authority'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ca_renewal_master_server?',
label=_('IPA CA renewal master'),
doc=_('Renewal master for IPA certificate authority'),
flags={'virtual_attribute', 'no_create'}
),
Str(
'kra_server_server*',
label=_('IPA KRA servers'),
doc=_('IPA servers configured as key recovery agent'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'kra_server_hidden_server*',
label=_('Hidden IPA KRA servers'),
doc=_('Hidden IPA servers configured as key recovery agent'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ipadomainresolutionorder?',
cli_name='domain_resolution_order',
label=_('Domain resolution order'),
doc=_('colon-separated list of domains used for short name'
' qualification')
),
Str(
'dns_server_server*',
label=_('IPA DNS servers'),
doc=_('IPA servers configured as domain name server'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'dns_server_hidden_server*',
label=_('Hidden IPA DNS servers'),
doc=_('Hidden IPA servers configured as domain name server'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'dnssec_key_master_server?',
label=_('IPA DNSSec key master'),
doc=_('DNSec key master'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Flag(
'enable_sid?',
label=_('Setup SID configuration'),
doc=_('New users and groups automatically get a SID assigned'),
flags={'virtual_attribute', 'no_create'}
),
Flag(
'add_sids?',
label=_('Add SIDs'),
doc=_('Add SIDs for existing users and groups'),
flags={'virtual_attribute', 'no_create'}
),
Str(
'netbios_name?',
label=_('NetBIOS name of the IPA domain'),
doc=_('NetBIOS name of the IPA domain'),
flags={'virtual_attribute', 'no_create'}
),
Str(
'hsm_token_name?',
label=_('HSM token name'),
doc=_('The HSM token name storing the CA private keys'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
)
def get_dn(self, *keys, **kwargs):
return DN(('cn', 'ipaconfig'), ('cn', 'etc'), api.env.basedn)
def update_entry_with_role_config(self, role_name, entry_attrs):
backend = self.api.Backend.serverroles
try:
role_config = backend.config_retrieve(role_name)
except errors.EmptyResult:
# No role config means current user identity
# has no rights to see it, return with no action
return
for key, value in role_config.items():
try:
entry_attrs.update({key: value})
except errors.EmptyResult:
# An update that doesn't change an entry is fine here
# Just ignore and move to the next key pair
pass
def show_servroles_attributes(self, entry_attrs, *roles, **options):
if options.get('raw', False):
return
for role in roles:
self.update_entry_with_role_config(role, entry_attrs)
def gather_trusted_domains(self):
"""
Aggregate all trusted domains into a dict keyed by domain names with
values corresponding to domain status (enabled/disabled)
"""
command = self.api.Command
try:
ad_forests = command.trust_find(sizelimit=0)['result']
except errors.NotFound:
return {}
trusted_domains = {}
for forest_name in [a['cn'][0] for a in ad_forests]:
forest_domains = command.trustdomain_find(
forest_name, sizelimit=0)['result']
trusted_domains.update(
{
dom['cn'][0]: dom['domain_enabled'][0]
for dom in forest_domains if 'domain_enabled' in dom
}
)
return trusted_domains
def _validate_single_domain(self, attr_name, domain, known_domains):
"""
Validate a single domain from domain resolution order
:param attr_name: name of attribute that holds domain resolution order
:param domain: domain name
:param known_domains: dict of domains known to IPA keyed by domain name
and valued by boolean value corresponding to domain status
(enabled/disabled)
:raises: ValidationError if the domain name is empty, syntactically
invalid or corresponds to a disable domain
NotFound if a syntactically correct domain name unknown to IPA
is supplied (not IPA domain and not any of trusted domains)
"""
if not domain:
raise errors.ValidationError(
name=attr_name,
error=_("Empty domain is not allowed")
)
try:
validate_domain_name(domain)
except ValueError as e:
raise errors.ValidationError(
name=attr_name,
error=_("Invalid domain name '%(domain)s': %(e)s")
% dict(domain=domain, e=e))
if domain not in known_domains:
raise errors.NotFound(
reason=_("Server has no information about domain '%(domain)s'")
% dict(domain=domain)
)
if not known_domains[domain]:
raise errors.ValidationError(
name=attr_name,
error=_("Disabled domain '%(domain)s' is not allowed")
% dict(domain=domain)
)
def validate_domain_resolution_order(self, entry_attrs):
"""
Validate domain resolution order, e.g. split by the delimiter (colon)
and check each domain name for non-emptiness, syntactic correctness,
and status (enabled/disabled).
supplying empty order (':') bypasses validations and allows to specify
empty attribute value.
"""
attr_name = 'ipadomainresolutionorder'
if attr_name not in entry_attrs:
return
domain_resolution_order = entry_attrs[attr_name]
# setting up an empty string means that the previous configuration has
# to be cleaned up/removed. So, do nothing and let it pass
if not domain_resolution_order:
return
# empty resolution order is signalized by single separator, do nothing
# and let it pass
if domain_resolution_order == DOMAIN_RESOLUTION_ORDER_SEPARATOR:
return
submitted_domains = domain_resolution_order.split(
DOMAIN_RESOLUTION_ORDER_SEPARATOR)
known_domains = self.gather_trusted_domains()
# add IPA domain to the list of domains. This one is always enabled
known_domains.update({self.api.env.domain: True})
for domain in submitted_domains:
self._validate_single_domain(attr_name, domain, known_domains)
@register()
class config_mod(LDAPUpdate):
__doc__ = _('Modify configuration options.')
def _enable_sid(self, ldap, options):
# the user must have the Replication Administrators privilege
privilege = 'Replication Administrators'
op_account = getattr(context, 'principal', None)
if not principal_has_privilege(self.api, op_account, privilege):
raise errors.ACIError(
info=_("not allowed to enable SID generation"))
# NetBIOS name is either taken from options or generated
try:
netbios_name, reset_netbios_name = set_and_check_netbios_name(
options.get('netbios_name', None), True, self.api)
except ScriptError:
raise errors.ValidationError(name="NetBIOS name",
error=_('Up to 15 characters and only uppercase ASCII letters'
', digits and dashes are allowed. Empty string is '
'not allowed.'))
_ret = 0
_stdout = ''
_stderr = ''
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
method_options = []
if options.get('add_sids', False):
method_options.extend(["--add-sids"])
method_options.extend(["--netbios-name", netbios_name])
if reset_netbios_name:
method_options.append("--reset-netbios-name")
# Dbus definition expects up to 10 arguments
method_options.extend([''] * (10 - len(method_options)))
try:
bus = dbus.SystemBus()
obj = bus.get_object('org.freeipa.server', '/',
follow_name_owner_changes=True)
server = dbus.Interface(obj, 'org.freeipa.server')
_ret, _stdout, _stderr = server.config_enable_sid(*method_options)
except dbus.DBusException as e:
logger.error('Failed to call org.freeipa.server.config_enable_sid.'
'DBus exception is %s', str(e))
raise errors.ExecutionError(message=_('Failed to call DBus'))
# The oddjob restarts dirsrv, we need to re-establish the conn
if self.api.Backend.ldap2.isconnected():
self.api.Backend.ldap2.disconnect()
self.api.Backend.ldap2.connect(ccache=context.ccache_name)
if _ret != 0:
logger.error("Helper config_enable_sid return code is %d", _ret)
raise errors.ExecutionError(
message=_('Configuration of SID failed. '
'See details in the error log'))
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if 'ipadefaultprimarygroup' in entry_attrs:
group=entry_attrs['ipadefaultprimarygroup']
try:
api.Object['group'].get_dn_if_exists(group)
except errors.NotFound:
raise errors.NotFound(message=_("The group doesn't exist"))
kw = {}
if 'ipausersearchfields' in entry_attrs:
kw['ipausersearchfields'] = 'ipauserobjectclasses'
if 'ipagroupsearchfields' in entry_attrs:
kw['ipagroupsearchfields'] = 'ipagroupobjectclasses'
if kw:
config = ldap.get_ipa_config(list(kw.values()))
for (k, v) in kw.items():
allowed_attrs = ldap.get_allowed_attributes(config[v])
# normalize attribute names
attributes = [field.strip().lower()
for field in entry_attrs[k].split(',')]
# test if all base types (without sub-types) are allowed
for a in attributes:
a, _unused1, _unused2 = a.partition(';')
if a not in allowed_attrs:
raise errors.ValidationError(
name=k, error=_('attribute "%s" not allowed') % a
)
# write normalized form to LDAP
entry_attrs[k] = ','.join(attributes)
# Set ipasearchrecordslimit to -1 if 0 is used
if 'ipasearchrecordslimit' in entry_attrs:
if entry_attrs['ipasearchrecordslimit'] == 0:
entry_attrs['ipasearchrecordslimit'] = -1
# Set ipasearchtimelimit to -1 if 0 is used
if 'ipasearchtimelimit' in entry_attrs:
if entry_attrs['ipasearchtimelimit'] == 0:
entry_attrs['ipasearchtimelimit'] = -1
for (attr, obj) in (('ipauserobjectclasses', 'user'),
('ipagroupobjectclasses', 'group')):
if attr in entry_attrs:
if not entry_attrs[attr]:
raise errors.ValidationError(name=attr,
error=_('May not be empty'))
objectclasses = list(set(entry_attrs[attr]).union(
self.api.Object[obj].possible_objectclasses))
new_allowed_attrs = ldap.get_allowed_attributes(objectclasses,
raise_on_unknown=True)
checked_attrs = self.api.Object[obj].default_attributes
if self.api.Object[obj].uuid_attribute:
checked_attrs = checked_attrs + [self.api.Object[obj].uuid_attribute]
for obj_attr in checked_attrs:
obj_attr, _unused1, _unused2 = obj_attr.partition(';')
if obj_attr.lower() in OPERATIONAL_ATTRIBUTES:
continue
if obj_attr.lower() in self.api.Object[obj].params and \
'virtual_attribute' in \
self.api.Object[obj].params[obj_attr.lower()].flags:
# skip virtual attributes
continue
if obj_attr.lower() not in new_allowed_attrs:
raise errors.ValidationError(name=attr,
error=_('%(obj)s default attribute %(attr)s would not be allowed!') \
% dict(obj=obj, attr=obj_attr))
if ('ipaselinuxusermapdefault' in entry_attrs or
'ipaselinuxusermaporder' in entry_attrs):
config = None
failedattr = 'ipaselinuxusermaporder'
if 'ipaselinuxusermapdefault' in entry_attrs:
defaultuser = entry_attrs['ipaselinuxusermapdefault']
failedattr = 'ipaselinuxusermapdefault'
# validate the new default user first
if defaultuser is not None:
error_message = validate_selinuxuser(_, defaultuser)
if error_message:
raise errors.ValidationError(name='ipaselinuxusermapdefault',
error=error_message)
else:
config = ldap.get_ipa_config()
defaultuser = config.get('ipaselinuxusermapdefault', [None])[0]
if 'ipaselinuxusermaporder' in entry_attrs:
order = entry_attrs['ipaselinuxusermaporder']
userlist = order.split('$')
# validate the new user order first
for user in userlist:
if not user:
raise errors.ValidationError(name='ipaselinuxusermaporder',
error=_('A list of SELinux users delimited by $ expected'))
error_message = validate_selinuxuser(_, user)
if error_message:
error_message = _("SELinux user '%(user)s' is not "
"valid: %(error)s") % dict(user=user,
error=error_message)
raise errors.ValidationError(name='ipaselinuxusermaporder',
error=error_message)
else:
if not config:
config = ldap.get_ipa_config()
order = config['ipaselinuxusermaporder']
userlist = order[0].split('$')
if defaultuser and defaultuser not in userlist:
raise errors.ValidationError(name=failedattr,
error=_('SELinux user map default user not in order list'))
if 'ca_renewal_master_server' in options:
new_master = options['ca_renewal_master_server']
try:
self.api.Object.server.get_dn_if_exists(new_master)
except errors.NotFound:
raise self.api.Object.server.handle_not_found(new_master)
backend = self.api.Backend.serverroles
backend.config_update(ca_renewal_master_server=new_master)
self.obj.validate_domain_resolution_order(entry_attrs)
# The options add_sids or netbios_name need the enable_sid option
for sid_option in ['add_sids', 'netbios_name']:
if options.get(sid_option, None) and not options['enable_sid']:
opt = "--" + sid_option.replace("_", "-")
error_message = _("You cannot specify %s without "
"the --enable-sid option" % opt)
raise errors.ValidationError(
name=opt,
error=error_message)
if options['enable_sid']:
self._enable_sid(ldap, options)
return dn
def exc_callback(self, keys, options, exc, call_func,
*call_args, **call_kwargs):
if (isinstance(exc, errors.EmptyModlist) and
call_func.__name__ == 'update_entry' and
('ca_renewal_master_server' in options or
options['enable_sid'])):
return
super(config_mod, self).exc_callback(
keys, options, exc, call_func, *call_args, **call_kwargs)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.show_servroles_attributes(
entry_attrs, "CA server", "KRA server", "IPA master",
"DNS server", **options)
return dn
@register()
class config_show(LDAPRetrieve):
__doc__ = _('Show the current configuration.')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
ca_dn = DN(('cn', IPA_CA_CN), api.env.container_ca, api.env.basedn)
try:
ca_entry = ldap.get_entry(ca_dn, ['ipacahsmconfiguration'])
except errors.NotFound:
pass
else:
if 'ipacahsmconfiguration' in ca_entry:
val = ca_entry['ipacahsmconfiguration'][0]
(token_name, _token_library_path) = val.split(';')
entry_attrs.update({'hsm_token_name': token_name})
self.obj.show_servroles_attributes(
entry_attrs, "CA server", "KRA server", "IPA master",
"DNS server", **options)
return dn
| 30,097
|
Python
|
.py
| 660
| 34.006061
| 140
| 0.591522
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,827
|
rabase.py
|
freeipa_freeipa/ipaserver/plugins/rabase.py
|
# Authors:
# Rob Crittenden <rcritten@@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/>.
"""
Backend plugin for RA activities.
The `ra` plugin provides access to the CA to issue, retrieve, and revoke
certificates via the following methods:
* `ra.check_request_status()` - check certificate request status.
* `ra.get_certificate()` - retrieve an existing certificate.
* `ra.request_certificate()` - request a new certificate.
* `ra.revoke_certificate()` - revoke a certificate.
* `ra.take_certificate_off_hold()` - take a certificate off hold.
"""
from __future__ import absolute_import
from ipalib import Backend
from ipalib import errors
import os
from ipaplatform.paths import paths
class rabase(Backend):
"""
Request Authority backend plugin.
"""
def __init__(self, api):
self.ca_cert = api.env.tls_ca_cert
if api.env.in_tree:
self.client_certfile = os.path.join(
api.env.dot_ipa, 'ra-agent.pem')
self.client_keyfile = os.path.join(api.env.dot_ipa, 'ra-agent.key')
else:
self.client_certfile = paths.RA_AGENT_PEM
self.client_keyfile = paths.RA_AGENT_KEY
super(rabase, self).__init__(api)
def check_request_status(self, request_id):
"""
Check status of a certificate signing request.
:param request_id: request ID
"""
raise errors.NotImplementedError(name='%s.check_request_status' % self.name)
def get_certificate(self, serial_number):
"""
Retrieve an existing certificate.
:param serial_number: certificate serial number
"""
raise errors.NotImplementedError(name='%s.get_certificate' % self.name)
def request_certificate(
self, csr, profile_id, ca_id, request_type='pkcs10'):
"""
Submit certificate signing request.
:param csr: The certificate signing request.
:param profile_id: Profile to use for this request.
:param ca_id: The Authority ID to send request to. ``None`` is allowed.
:param request_type: The request type (defaults to ``'pkcs10'``).
"""
raise errors.NotImplementedError(name='%s.request_certificate' % self.name)
def revoke_certificate(self, serial_number, revocation_reason=0):
"""
Revoke a certificate.
The integer ``revocation_reason`` code must have one of these values:
* ``0`` - unspecified
* ``1`` - keyCompromise
* ``2`` - cACompromise
* ``3`` - affiliationChanged
* ``4`` - superseded
* ``5`` - cessationOfOperation
* ``6`` - certificateHold
* ``8`` - removeFromCRL
* ``9`` - privilegeWithdrawn
* ``10`` - aACompromise
Note that reason code ``7`` is not used. See RFC 5280 for more details:
http://www.ietf.org/rfc/rfc5280.txt
:param serial_number: Certificate serial number.
:param revocation_reason: Integer code of revocation reason.
"""
raise errors.NotImplementedError(name='%s.revoke_certificate' % self.name)
def take_certificate_off_hold(self, serial_number):
"""
Take revoked certificate off hold.
:param serial_number: Certificate serial number.
"""
raise errors.NotImplementedError(name='%s.take_certificate_off_hold' % self.name)
def find(self, options):
"""
Search for certificates
:param options: dictionary of search options
"""
raise errors.NotImplementedError(name='%s.find' % self.name)
def updateCRL(self, wait='false'):
"""
Force update of the CRL
:param wait: if true, the call will be synchronous and return only
when the CRL has been generated
"""
raise errors.NotImplementedError(name='%s.updateCRL' % self.name)
| 4,634
|
Python
|
.py
| 108
| 35.62037
| 89
| 0.654444
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,828
|
otptoken.py
|
freeipa_freeipa/ipaserver/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 .baseldap import LDAPObject, LDAPAddMember, LDAPRemoveMember
from .baseldap import LDAPCreate, LDAPDelete, LDAPUpdate, LDAPSearch, LDAPRetrieve
from ipalib import api, Int, Str, Bool, DateTime, Flag, Bytes, IntEnum, StrEnum, _, ngettext
from ipalib.plugable import Registry
from ipalib.errors import (
PasswordMismatch,
ConversionError,
NotFound,
ValidationError)
from ipalib.request import context
from ipapython.dn import DN
import base64
import urllib
import uuid
import os
import six
if six.PY3:
unicode = str
__doc__ = _("""
OTP Tokens
""") + _("""
Manage OTP tokens.
""") + _("""
IPA supports the use of OTP tokens for multi-factor authentication. This
code enables the management of OTP tokens.
""") + _("""
EXAMPLES:
""") + _("""
Add a new token:
ipa otptoken-add --type=totp --owner=jdoe --desc="My soft token"
""") + _("""
Examine the token:
ipa otptoken-show a93db710-a31a-4639-8647-f15b2c70b78a
""") + _("""
Change the vendor:
ipa otptoken-mod a93db710-a31a-4639-8647-f15b2c70b78a --vendor="Red Hat"
""") + _("""
Delete a token:
ipa otptoken-del a93db710-a31a-4639-8647-f15b2c70b78a
""")
register = Registry()
topic = 'otp'
TOKEN_TYPES = {
u'totp': ['ipatokentotpclockoffset', 'ipatokentotptimestep'],
u'hotp': ['ipatokenhotpcounter']
}
# NOTE: For maximum compatibility, KEY_LENGTH % 5 == 0
KEY_LENGTH = 35
class OTPTokenKey(Bytes):
"""A binary password type specified in base32."""
password = True
def _convert_scalar(self, value, index=None):
if isinstance(value, (tuple, list)) and len(value) == 2:
(p1, p2) = value
if p1 != p2:
raise PasswordMismatch(name=self.name)
value = p1
if isinstance(value, unicode):
try:
value = base64.b32decode(value, True)
except TypeError as e:
raise ConversionError(name=self.name, error=str(e))
return super(OTPTokenKey, self)._convert_scalar(value)
def _convert_owner(userobj, entry_attrs, options):
if 'ipatokenowner' in entry_attrs and not options.get('raw', False):
entry_attrs['ipatokenowner'] = [userobj.get_primary_key_from_dn(o)
for o in entry_attrs['ipatokenowner']]
def _normalize_owner(userobj, entry_attrs):
owner = entry_attrs.get('ipatokenowner', None)
if owner:
try:
entry_attrs['ipatokenowner'] = userobj._normalize_manager(
owner
)[0]
except NotFound:
raise userobj.handle_not_found(owner)
def _check_interval(not_before, not_after):
if not_before and not_after:
return not_before <= not_after
return True
def _set_token_type(entry_attrs, **options):
klasses = [x.lower() for x in entry_attrs.get('objectclass', [])]
for ttype in TOKEN_TYPES:
cls = 'ipatoken' + ttype
if cls.lower() in klasses:
entry_attrs['type'] = ttype.upper()
if not options.get('all', False) or options.get('pkey_only', False):
entry_attrs.pop('objectclass', None)
@register()
class otptoken(LDAPObject):
"""
OTP Token object.
"""
container_dn = api.env.container_otp
object_name = _('OTP token')
object_name_plural = _('OTP tokens')
object_class = ['ipatoken']
possible_objectclasses = ['ipatokentotp', 'ipatokenhotp']
default_attributes = [
'ipatokenuniqueid', 'description', 'ipatokenowner',
'ipatokendisabled', 'ipatokennotbefore', 'ipatokennotafter',
'ipatokenvendor', 'ipatokenmodel', 'ipatokenserial', 'managedby'
]
attribute_members = {
'managedby': ['user'],
}
relationships = {
'managedby': ('Managed by', 'man_by_', 'not_man_by_'),
}
allow_rename = True
label = _('OTP Tokens')
label_singular = _('OTP Token')
takes_params = (
Str('ipatokenuniqueid',
cli_name='id',
label=_('Unique ID'),
primary_key=True,
flags=('optional_create'),
),
StrEnum('type?',
label=_('Type'),
doc=_('Type of the token'),
default=u'totp',
autofill=True,
values=tuple(list(TOKEN_TYPES) + [x.upper() for x in TOKEN_TYPES]),
flags=('virtual_attribute', 'no_update'),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Token description (informational only)'),
),
Str('ipatokenowner?',
cli_name='owner',
label=_('Owner'),
doc=_('Assigned user of the token (default: self)'),
),
Str('managedby_user?',
label=_('Manager'),
doc=_('Assigned manager of the token (default: self)'),
flags=['no_create', 'no_update', 'no_search'],
),
Bool('ipatokendisabled?',
cli_name='disabled',
label=_('Disabled'),
doc=_('Mark the token as disabled (default: false)')
),
DateTime('ipatokennotbefore?',
cli_name='not_before',
label=_('Validity start'),
doc=_('First date/time the token can be used'),
),
DateTime('ipatokennotafter?',
cli_name='not_after',
label=_('Validity end'),
doc=_('Last date/time the token can be used'),
),
Str('ipatokenvendor?',
cli_name='vendor',
label=_('Vendor'),
doc=_('Token vendor name (informational only)'),
),
Str('ipatokenmodel?',
cli_name='model',
label=_('Model'),
doc=_('Token model (informational only)'),
),
Str('ipatokenserial?',
cli_name='serial',
label=_('Serial'),
doc=_('Token serial (informational only)'),
),
OTPTokenKey('ipatokenotpkey?',
cli_name='key',
label=_('Key'),
doc=_('Token secret (Base32; default: random)'),
default_from=lambda: os.urandom(KEY_LENGTH),
autofill=True,
# force server-side conversion
normalizer=lambda x: x,
flags=('no_display', 'no_update', 'no_search'),
),
StrEnum('ipatokenotpalgorithm?',
cli_name='algo',
label=_('Algorithm'),
doc=_('Token hash algorithm'),
default=u'sha1',
autofill=True,
flags=('no_update'),
values=(u'sha1', u'sha256', u'sha384', u'sha512'),
),
IntEnum('ipatokenotpdigits?',
cli_name='digits',
label=_('Digits'),
doc=_('Number of digits each token code will have'),
values=(6, 8),
default=6,
autofill=True,
flags=('no_update'),
),
Int('ipatokentotpclockoffset?',
cli_name='offset',
label=_('Clock offset'),
doc=_('TOTP token / IPA server time difference'),
default=0,
autofill=True,
flags=('no_update'),
),
Int('ipatokentotptimestep?',
cli_name='interval',
label=_('Clock interval'),
doc=_('Length of TOTP token code validity'),
default=30,
autofill=True,
minvalue=5,
flags=('no_update'),
),
Int('ipatokenhotpcounter?',
cli_name='counter',
label=_('Counter'),
doc=_('Initial counter for the HOTP token'),
default=0,
autofill=True,
minvalue=0,
flags=('no_update'),
),
Str('uri?',
label=_('URI'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
)
@register()
class otptoken_add(LDAPCreate):
__doc__ = _('Add a new OTP token.')
msg_summary = _('Added OTP token "%(value)s"')
takes_options = LDAPCreate.takes_options + (
Flag('qrcode?', label=_('(deprecated)'), flags=('no_option')),
Flag('no_qrcode', label=_('Do not display QR code'), default=False),
)
def execute(self, ipatokenuniqueid=None, **options):
return super(otptoken_add, self).execute(ipatokenuniqueid, **options)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
# Fill in a default UUID when not specified.
if entry_attrs.get('ipatokenuniqueid', None) is None:
entry_attrs['ipatokenuniqueid'] = str(uuid.uuid4())
dn = DN("ipatokenuniqueid=%s" % entry_attrs['ipatokenuniqueid'], dn)
if not _check_interval(options.get('ipatokennotbefore', None),
options.get('ipatokennotafter', None)):
raise ValidationError(name='not_after',
error='is before the validity start')
# Set the object class and defaults for specific token types
options['type'] = options['type'].lower()
entry_attrs['objectclass'] = otptoken.object_class + ['ipatoken' + options['type']]
for ttype, tattrs in TOKEN_TYPES.items():
if ttype != options['type']:
for tattr in tattrs:
if tattr in entry_attrs:
del entry_attrs[tattr]
# If owner was not specified, default to the person adding this token.
# If managedby was not specified, attempt a sensible default.
if 'ipatokenowner' not in entry_attrs or 'managedby' not in entry_attrs:
cur_dn = DN(self.api.Backend.ldap2.conn.whoami_s()[4:])
if cur_dn:
cur_uid = cur_dn[0].value
prev_uid = entry_attrs.setdefault('ipatokenowner', cur_uid)
if cur_uid == prev_uid:
entry_attrs.setdefault('managedby', cur_dn.ldap_text())
# Resolve the owner's dn
_normalize_owner(self.api.Object.user, entry_attrs)
# Get the issuer for the URI
owner = entry_attrs.get('ipatokenowner', None)
issuer = api.env.realm
if owner is not None:
try:
issuer = ldap.get_entry(owner, ['krbprincipalname'])['krbprincipalname'][0]
except (NotFound, IndexError):
pass
# Check if key is not empty
if entry_attrs['ipatokenotpkey'] is None:
raise ValidationError(name='key', error=_(u'cannot be empty'))
# Build the URI parameters
args = {}
args['issuer'] = issuer
args['secret'] = base64.b32encode(entry_attrs['ipatokenotpkey'])
args['digits'] = entry_attrs['ipatokenotpdigits']
args['algorithm'] = entry_attrs['ipatokenotpalgorithm'].upper()
if options['type'] == 'totp':
args['period'] = entry_attrs['ipatokentotptimestep']
elif options['type'] == 'hotp':
args['counter'] = entry_attrs['ipatokenhotpcounter']
# Build the URI
label = urllib.parse.quote(entry_attrs['ipatokenuniqueid'])
parameters = urllib.parse.urlencode(args)
uri = u'otpauth://%s/%s:%s?%s' % (options['type'], issuer, label, parameters)
setattr(context, 'uri', uri)
attrs_list.append("objectclass")
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
entry_attrs['uri'] = getattr(context, 'uri')
_set_token_type(entry_attrs, **options)
_convert_owner(self.api.Object.user, entry_attrs, options)
return super(otptoken_add, self).post_callback(ldap, dn, entry_attrs, *keys, **options)
@register()
class otptoken_del(LDAPDelete):
__doc__ = _('Delete an OTP token.')
msg_summary = _('Deleted OTP token "%(value)s"')
@register()
class otptoken_mod(LDAPUpdate):
__doc__ = _('Modify a OTP token.')
msg_summary = _('Modified OTP token "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
notafter_set = True
notbefore = options.get('ipatokennotbefore', None)
notafter = options.get('ipatokennotafter', None)
# notbefore xor notafter, exactly one of them is not None
if bool(notbefore) ^ bool(notafter):
result = self.api.Command.otptoken_show(keys[-1])['result']
if notbefore is None:
notbefore = result.get('ipatokennotbefore', [None])[0]
if notafter is None:
notafter_set = False
notafter = result.get('ipatokennotafter', [None])[0]
if not _check_interval(notbefore, notafter):
if notafter_set:
raise ValidationError(name='not_after',
error='is before the validity start')
else:
raise ValidationError(name='not_before',
error='is after the validity end')
_normalize_owner(self.api.Object.user, entry_attrs)
# ticket #4681: if the owner of the token is changed and the
# user also manages this token, then we should automatically
# set the 'managedby' attribute to the new owner
if 'ipatokenowner' in entry_attrs and 'managedby' not in entry_attrs:
new_owner = entry_attrs.get('ipatokenowner', None)
prev_entry = ldap.get_entry(dn, attrs_list=['ipatokenowner',
'managedby'])
prev_owner = prev_entry.get('ipatokenowner', None)
prev_managedby = prev_entry.get('managedby', None)
if (new_owner != prev_owner) and (prev_owner == prev_managedby):
entry_attrs.setdefault('managedby', new_owner)
attrs_list.append("objectclass")
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
_set_token_type(entry_attrs, **options)
_convert_owner(self.api.Object.user, entry_attrs, options)
return super(otptoken_mod, self).post_callback(ldap, dn, entry_attrs, *keys, **options)
@register()
class otptoken_find(LDAPSearch):
__doc__ = _('Search for OTP token.')
msg_summary = ngettext('%(count)d OTP token matched', '%(count)d OTP tokens matched', 0)
def pre_callback(self, ldap, filters, attrs_list, *args, **kwargs):
# This is a hack, but there is no other way to
# replace the objectClass when searching
type = kwargs.get('type', '')
if type not in TOKEN_TYPES:
type = ''
filters = filters.replace("(objectclass=ipatoken)",
"(objectclass=ipatoken%s)" % type)
attrs_list.append("objectclass")
return super(otptoken_find, self).pre_callback(ldap, filters, attrs_list, *args, **kwargs)
def args_options_2_entry(self, *args, **options):
entry = super(otptoken_find, self).args_options_2_entry(*args, **options)
_normalize_owner(self.api.Object.user, entry)
return entry
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry in entries:
_set_token_type(entry, **options)
_convert_owner(self.api.Object.user, entry, options)
return super(otptoken_find, self).post_callback(ldap, entries, truncated, *args, **options)
@register()
class otptoken_show(LDAPRetrieve):
__doc__ = _('Display information about an OTP token.')
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
attrs_list.append("objectclass")
return super(otptoken_show, self).pre_callback(ldap, dn, attrs_list, *keys, **options)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
_set_token_type(entry_attrs, **options)
_convert_owner(self.api.Object.user, entry_attrs, options)
return super(otptoken_show, self).post_callback(ldap, dn, entry_attrs, *keys, **options)
@register()
class otptoken_add_managedby(LDAPAddMember):
__doc__ = _('Add users that can manage this token.')
member_attributes = ['managedby']
@register()
class otptoken_remove_managedby(LDAPRemoveMember):
__doc__ = _('Remove users that can manage this token.')
member_attributes = ['managedby']
| 17,076
|
Python
|
.py
| 406
| 32.980296
| 99
| 0.598133
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,829
|
dogtag.py
|
freeipa_freeipa/ipaserver/plugins/dogtag.py
|
# Authors:
# Ade Lee <alee@redhat.com>
# Andrew Wnuk <awnuk@redhat.com>
# Jason Gerard DeRose <jderose@redhat.com>
# Rob Crittenden <rcritten@@redhat.com>
# John Dennis <jdennis@redhat.com>
# Fraser Tweedale <ftweedal@redhat.com>
# Abhijeet Kasurde <akasurde@redhat.com>
#
# Copyright (C) 2014-2016 Red Hat, Inc.
# 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/>.
r'''
==============================================
Backend plugin for RA using Dogtag (e.g. CMS)
==============================================
Overview of interacting with CMS:
---------------------------------
CMS stands for "Certificate Management System". It has been released under a
variety of names, the open source version is called "dogtag".
IPA now uses the REST API provided by dogtag, as documented at
https://github.com/dogtagpki/pki/wiki/REST-API
The below is still relevant in places, particularly with data handling.
This history of Javascript parsing and using the optional XML is left
for historical purposes and for the last-used xml-based call that
IPA makes (updateCRL).
CMS consists of a number of servlets which in rough terms can be thought of as
RPC commands. A servlet is invoked by making an HTTP request to a specific URL
and passing URL arguments. Normally CMS responds with an HTTP response consisting
of HTML to be rendered by a web browser. This HTTP HTML response has both
Javascript SCRIPT components and HTML rendering code. One of the Javascript
SCRIPT blocks holds the data for the result. The rest of the response is derived
from templates associated with the servlet which may be customized. The
templates pull the result data from Javascript variables.
One way to get the result data is to parse the HTML looking for the Javascript
variable initializations. Simple string searches are not a robust method. First of
all one must be sure the string is only found in a Javascript SCRIPT block and
not somewhere else in the HTML document. Some of the Javascript variable
initializations are rather complex (e.g. lists of structures). It would be hard
to correctly parse such complex and diverse Javascript. Existing Javascript
parsers are not generally available. Finally, it's important to know the
character encoding for strings. There is a somewhat complex set of precedent
rules for determining the current character encoding from the HTTP header,
meta-equiv tags, mime Content-Type and charset attributes on HTML elements. All
of this means trying to read the result data from a CMS HTML response is
difficult to do robustly.
However, CMS also supports returning the result data as a XML document
(distinct from an XHTML document which would be essentially the same as
described above). There are a wide variety of tools to robustly parse
XML. Because XML is so well defined things like escapes, character encodings,
etc. are automatically handled by the tools.
Thus we never try to parse Javascript, instead we always ask CMS to return us an
XML document by passing the URL argument xml="true". The body of the HTTP
response is an XML document rather than HTML with embedded Javascript.
To parse the XML documents we use the Python lxml package which is a Python
binding around the libxml2 implementation. libxml2 is a very fast, standard
compliant, feature full XML implementation. libxml2 is the XML library of choice
for many projects. One of the features in lxml and libxml2 that is particularly
valuable to us is the XPath implementation. We make heavy use of XPath to find
data in the XML documents we're parsing.
Parse Results vs. IPA command results:
--------------------------------------
CMS results can be parsed from either HTML or XML. CMS unfortunately is not
consistent with how it names items or how it utilizes data types. IPA has strict
rules about data types. Also IPA would like to see a more consistent view CMS
data. Therefore we split the task of parsing CMS results out from the IPA
command code. The parse functions normalize the result data by using a
consistent set of names and data types. The IPA command only deals with the
normalized parse results. This also allow us to use different parsers if need be
(i.e. if we had to parse Javascript for some reason). The parse functions
attempt to parse as must information from the CMS result as is possible. It puts
the parse result into a dict whose normalized key/value pairs are easy to
access. IPA commands do not need to return all the parsed results, it can pick
and choose what it wants to return in the IPA command result from the parse
result. It also rest assured the values in the parse result will be the correct
data type. Thus the general sequence of steps for an IPA command talking to CMS
are:
#. Receive IPA arguments from IPA command
#. Formulate URL with arguments for CMS
#. Make request to CMS server
#. Extract XML document from HTML body returned by CMS
#. Parse XML document using matching parse routine which returns response dict
#. Extract relevant items from parse result and insert into command result
#. Return command result
Serial Numbers:
---------------
Serial numbers are integral values of any magnitude because they are based on
ASN.1 integers. CMS uses the Java BigInteger to represent these. Fortunately
Python also has support for big integers via the Python long() object. Any
BigIntegers we receive from CMS as a string can be parsed into a Python long
without loss of information.
However Python has a neat trick. It normally represents integers via the int
object which internally uses the native C long type. If you create an int
object by passing the int constructor a string it will check the magnitude of
the value. If it would fit in a C long then it returns you an int
object. However if the value is too big for a C long type then it returns you
a Python long object instead. This is a very nice property because it's much
more efficient to use C long types when possible (e.g. Python int), but when
necessary you'll get a Python long() object to handle large magnitude
values. Python also nicely handles type promotion transparently between int
and long objects. For example if you multiply two int objects you may get back
a long object if necessary. In general Python int and long objects may be
freely mixed without the programmer needing to be aware of which type of
integral object is being operated on.
The leads to the following rule, always parse a string representing an
integral value using the int() constructor even if it might have large
magnitude because Python will return either an int or a long automatically. By
the same token don't test for type of an object being int exclusively because
it could either be an int or a long object.
Internally we should always being using int or long object to hold integral
values. This is because we should be able to compare them correctly, be free
from concerns about having the know the radix of the string, perform
arithmetic operations, and convert to string representation (with correct
radix) when necessary. In other words internally we should never handle
integral values as strings.
However, the XMLRPC transport cannot properly handle a Python long object. The
XMLRPC encoder upon seeing a Python long will test to see if the value fits
within the range of an 32-bit integer, if so it passes the integer parameter
otherwise it raises an Overflow exception. The XMLRPC specification does
permit 64-bit integers (e.g. i8) and the Python XMLRPC module could allow long
values within the 64-bit range to be passed if it were patched, however this
only moves the problem, it does not solve passing big integers through
XMLRPC. Thus we must always pass big integers as a strings through the XMLRPC
interface. But upon receiving that value from XMLRPC we should convert it back
into an int or long object. Recall also that Python will automatically perform
a conversion to string if you output the int or long object in a string context.
Radix Issues:
-------------
CMS uses the following conventions: Serial numbers are always returned as
hexadecimal strings without a radix prefix. When CMS takes a serial number as
input it accepts the value in either decimal or hexadecimal utilizing the radix
prefix (e.g. 0x) to determine how to parse the value.
IPA has adopted the convention that all integral values in the user interface
will use base 10 decimal radix.
Basic rules on handling these values
1. Reading a serial number from CMS requires conversion from hexadecimal
by converting it into a Python int or long object, use the int constructor:
serial_number = int(serial_number, 16)
2. Big integers passed to XMLRPC must be decimal unicode strings
unicode(serial_number)
3. Big integers received from XMLRPC must be converted back to int or long
objects from the decimal string representation.
serial_number = int(serial_number)
Xpath pattern matching on node names:
-------------------------------------
There are many excellent tutorial on how to use xpath to find items in an XML
document, as such there is no need to repeat this information here. However,
most xpath tutorials make the assumption the node names you're searching for are
fixed. For example:
doc.xpath('//book/chapter[*]/section[2]')
Selects the second section of every chapter of the book. In this example the
node names 'book', 'chapter', 'section' are fixed. But what if the XML document
embedded the chapter number in the node name, for example 'chapter1',
'chapter2', etc.? (If you're thinking this would be incredibly lame, you're
right, but sadly people do things like this). Thus in this case you can't use
the node name 'chapter' in the xpath location step because it's not fixed and
hence won't match 'chapter1', 'chapter2', etc. The solution to this seems
obvious, use some type of pattern matching on the node name. Unfortunately this
advanced use of xpath is seldom discussed in tutorials and it's not obvious how
to do it. Here are some hints.
Use the built-in xpath string functions. Most of the examples illustrate the
string function being passed the text *contents* of the node via '.' or
string(.). However we don't want to pass the contents of the node, instead we
want to pass the node name. To do this use the name() function. One way we could
solve the chapter problem above is by using a predicate which says if the node
name begins with 'chapter' it's a match. Here is how you can do that.
doc.xpath("//book/*[starts-with(name(), 'chapter')]/section[2]")
The built-in starts-with() returns true if its first argument starts with its
second argument. Thus the example above says if the node name of the second
location step begins with 'chapter' consider it a match and the search
proceeds to the next location step, which in this example is any node named
'section'.
But what if we would like to utilize the power of regular expressions to perform
the test against the node name? In this case we can use the EXSLT regular
expression extension. EXSLT extensions are accessed by using XML
namespaces. The regular expression name space identifier is 're:' In lxml we
need to pass a set of namespaces to XPath object constructor in order to allow
it to bind to those namespaces during its evaluation. Then we just use the
EXSLT regular expression match() function on the node name. Here is how this is
done:
regexpNS = "http://exslt.org/regular-expressions"
find = etree.XPath("//book/*[re:match(name(), '^chapter(_\d+)$')]/section[2]",
namespaces={'re':regexpNS}
find(doc)
What is happening here is that etree.XPath() has returned us an evaluator
function which we bind to the name 'find'. We've passed it a set of namespaces
as a dict via the 'namespaces' keyword parameter of etree.XPath(). The predicate
for the second location step uses the 're:' namespace to find the function name
'match'. The re:match() takes a string to search as its first argument and a
regular expression pattern as its second argument. In this example the string
to search is the node name of the location step because we called the built-in
node() function of XPath. The regular expression pattern we've passed says it's
a match if the string begins with 'chapter' is followed by any number of
digits and nothing else follows.
'''
from __future__ import absolute_import
import json
import logging
from lxml import etree
import time
import contextlib
import six
from ipalib import Backend, api, x509
from ipapython.dn import DN
import ipapython.cookie
from ipapython import dogtag, ipautil
from ipaserver.masters import find_providing_server
import pki
from pki.client import PKIConnection
import pki.crypto as cryptoutil
from pki.kra import KRAClient
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
# These are general status return values used when
# CMSServlet.outputError() is invoked.
CMS_SUCCESS = 0
CMS_FAILURE = 1
CMS_AUTH_FAILURE = 2
# CMS (Certificate Management System) status return values
# These are requestStatus return values used with templates
CMS_STATUS_UNAUTHORIZED = 1
CMS_STATUS_SUCCESS = 2
CMS_STATUS_PENDING = 3
CMS_STATUS_SVC_PENDING = 4
CMS_STATUS_REJECTED = 5
CMS_STATUS_ERROR = 6
CMS_STATUS_EXCEPTION = 7
def cms_request_status_to_string(request_status):
'''
:param request_status: The integral request status value
:return: String name of request status
'''
return {
1 : 'UNAUTHORIZED',
2 : 'SUCCESS',
3 : 'PENDING',
4 : 'SVC_PENDING',
5 : 'REJECTED',
6 : 'ERROR',
7 : 'EXCEPTION',
}.get(request_status, "unknown(%d)" % request_status)
def get_request_status_xml(doc):
'''
:param doc: The root node of the xml document to parse
:returns: request status as an integer
Returns the request status from a CMS operation. May be one of:
- CMS_STATUS_UNAUTHORIZED = 1
- CMS_STATUS_SUCCESS = 2
- CMS_STATUS_PENDING = 3
- CMS_STATUS_SVC_PENDING = 4
- CMS_STATUS_REJECTED = 5
- CMS_STATUS_ERROR = 6
- CMS_STATUS_EXCEPTION = 7
CMS will often fail to return requestStatus when the status is
SUCCESS. Therefore if we fail to find a requestStatus field we default the
result to CMS_STATUS_SUCCESS.
'''
request_status = doc.xpath('//xml/fixed/requestStatus[1]')
if len(request_status) == 1:
request_status = int(request_status[0].text)
else:
# When a request is successful CMS often omits the requestStatus
request_status = CMS_STATUS_SUCCESS
# However, if an error string was returned it's an error no
# matter what CMS returned as requestStatus.
# Just to make life interesting CMS sometimes returns an empty error string
# when nothing wrong occurred.
error_detail = doc.xpath('//xml/fixed/errorDetails[1]')
if len(error_detail) == 1 and len(error_detail[0].text.strip()) > 0:
# There was a non-empty error string, if the status was something
# other than error or exception then force it to be an error.
if not (request_status in (CMS_STATUS_ERROR, CMS_STATUS_EXCEPTION)):
request_status = CMS_STATUS_ERROR
return request_status
def parse_error_template_xml(doc):
'''
:param doc: The root node of the xml document to parse
:returns: result dict
CMS currently returns errors via XML as either a "template" document
(generated by CMSServlet.outputXML() or a "response" document (generated by
CMSServlet.outputError()).
This routine is used to parse a "template" style error or exception
document.
This routine should be use when the CMS requestStatus is ERROR or
EXCEPTION. It is capable of parsing both. A CMS ERROR occurs when a known
anticipated error condition occurs (e.g. asking for an item which does not
exist). A CMS EXCEPTION occurs when an exception is thrown in the CMS server
and it's not caught and converted into an ERROR. Think of EXCEPTIONS as the
"catch all" error situation.
ERROR's and EXCEPTIONS's both have error message strings associated with
them. For an ERROR it's errorDetails, for an EXCEPTION it's
unexpectedError. In addition an EXCEPTION may include an array of additional
error strings in it's errorDescription field.
After parsing the results are returned in a result dict. The following
table illustrates the mapping from the CMS data item to what may be found in
the result dict. If a CMS data item is absent it will also be absent in the
result dict.
+----------------+---------------+------------------+---------------+
|cms name |cms type |result name |result type |
+================+===============+==================+===============+
|requestStatus |int |request_status |int |
+----------------+---------------+------------------+---------------+
|errorDetails |string |error_string [1]_ |unicode |
+----------------+---------------+------------------+---------------+
|unexpectedError |string |error_string [1]_ |unicode |
+----------------+---------------+------------------+---------------+
|errorDescription|[string] |error_descriptions|[unicode] |
+----------------+---------------+------------------+---------------+
|authority |string |authority |unicode |
+----------------+---------------+------------------+---------------+
.. [1] errorDetails is the error message string when the requestStatus
is ERROR. unexpectedError is the error message string when
the requestStatus is EXCEPTION. This routine recognizes both
ERROR's and EXCEPTION's and depending on which is found folds
the error message into the error_string result value.
'''
response = {}
response['request_status'] = CMS_STATUS_ERROR # assume error
request_status = doc.xpath('//xml/fixed/requestStatus[1]')
if len(request_status) == 1:
request_status = int(request_status[0].text)
response['request_status'] = request_status
error_descriptions = []
for description in doc.xpath('//xml/records[*]/record/errorDescription'):
error_descriptions.append(etree.tostring(description, method='text',
encoding=unicode).strip())
if len(error_descriptions) > 0:
response['error_descriptions'] = error_descriptions
authority = doc.xpath('//xml/fixed/authorityName[1]')
if len(authority) == 1:
authority = etree.tostring(authority[0], method='text',
encoding=unicode).strip()
response['authority'] = authority
# Should never get both errorDetail and unexpectedError
error_detail = doc.xpath('//xml/fixed/errorDetails[1]')
if len(error_detail) == 1:
error_detail = etree.tostring(error_detail[0], method='text',
encoding=unicode).strip()
response['error_string'] = error_detail
unexpected_error = doc.xpath('//xml/fixed/unexpectedError[1]')
if len(unexpected_error) == 1:
unexpected_error = etree.tostring(unexpected_error[0], method='text',
encoding=unicode).strip()
response['error_string'] = unexpected_error
return response
def parse_updateCRL_xml(doc):
'''
:param doc: The root node of the xml document to parse
:returns: result dict
:except ValueError:
After parsing the results are returned in a result dict. The following
table illustrates the mapping from the CMS data item to what may be found
in the result dict. If a CMS data item is absent it will also be absent in
the result dict.
If the requestStatus is not SUCCESS then the response dict will have the
contents described in `parse_error_template_xml`.
+-----------------+-------------+-----------------------+---------------+
|cms name |cms type |result name |result type |
+=================+=============+=======================+===============+
|crlIssuingPoint |string |crl_issuing_point |unicode |
+-----------------+-------------+-----------------------+---------------+
|crlUpdate |string |crl_update [1] |unicode |
+-----------------+-------------+-----------------------+---------------+
.. [1] crlUpdate may be one of:
- "Success"
- "Failure"
- "missingParameters"
- "testingNotEnabled"
- "testingInProgress"
- "Scheduled"
- "inProgress"
- "disabled"
- "notInitialized"
'''
request_status = get_request_status_xml(doc)
if request_status != CMS_STATUS_SUCCESS:
response = parse_error_template_xml(doc)
return response
response = {}
response['request_status'] = request_status
crl_issuing_point = doc.xpath('//xml/header/crlIssuingPoint[1]')
if len(crl_issuing_point) == 1:
crl_issuing_point = etree.tostring(
crl_issuing_point[0], method='text',
encoding=unicode).strip()
response['crl_issuing_point'] = crl_issuing_point
crl_update = doc.xpath('//xml/header/crlUpdate[1]')
if len(crl_update) == 1:
crl_update = etree.tostring(crl_update[0], method='text',
encoding=unicode).strip()
response['crl_update'] = crl_update
return response
#-------------------------------------------------------------------------------
from ipalib import Registry, errors, SkipPluginModule
# We only load the dogtag RA plugin if it is necessary to do so.
# This is legacy code from when multiple RA backends were supported.
#
# If the plugins are loaded by the server then load the RA backend.
#
if api.isdone("finalize") and not (
api.env.ra_plugin == 'dogtag' or api.env.context == 'installer'
):
# In this case, abort loading this plugin module...
raise SkipPluginModule(reason='Not loading dogtag RA plugin')
import os
from ipaserver.plugins import rabase
from ipalib.constants import TYPE_ERROR
from ipalib import _
from ipaplatform.paths import paths
register = Registry()
class RestClient(Backend):
"""Simple Dogtag REST client to be subclassed by other backends.
This class is a context manager. Authenticated calls must be
executed in a ``with`` suite::
@register()
class ra_certprofile(RestClient):
path = 'profile'
...
with api.Backend.ra_certprofile as profile_api:
# REST client is now logged in
profile_api.create_profile(...)
"""
DEFAULT_PROFILE = dogtag.DEFAULT_PROFILE
KDC_PROFILE = dogtag.KDC_PROFILE
path = None
@staticmethod
def _parse_dogtag_error(body):
try:
return pki.PKIException.from_json(
json.loads(ipautil.decode_json(body)))
except Exception:
return None
def __init__(self, api):
self.ca_cert = api.env.tls_ca_cert
if api.env.in_tree:
self.client_certfile = os.path.join(
api.env.dot_ipa, 'ra-agent.pem')
self.client_keyfile = os.path.join(
api.env.dot_ipa, 'ra-agent.key')
else:
self.client_certfile = paths.RA_AGENT_PEM
self.client_keyfile = paths.RA_AGENT_KEY
super(RestClient, self).__init__(api)
self._ca_host = None
# session cookie
self.override_port = None
self.cookie = None
@property
def ca_host(self):
"""
:returns: FQDN of a host hopefully providing a CA service
Select our CA host, cache it for the first time.
"""
if self._ca_host is not None:
return self._ca_host
preferred = [api.env.ca_host]
if api.env.host != api.env.ca_host:
preferred.append(api.env.host)
ca_host = find_providing_server(
'CA', conn=self.api.Backend.ldap2, preferred_hosts=preferred,
api=self.api
)
if ca_host is None:
# TODO: need during installation, CA is not yet set as enabled
ca_host = api.env.ca_host
# object is locked, need to use __setattr__()
object.__setattr__(self, '_ca_host', ca_host)
return ca_host
def __enter__(self):
"""Log into the REST API"""
if self.cookie is not None:
return None
# Refresh the ca_host property
object.__setattr__(self, '_ca_host', None)
status, resp_headers, _resp_body = dogtag.https_request(
self.ca_host, self.override_port or self.env.ca_agent_port,
url='/ca/rest/account/login',
cafile=self.ca_cert,
client_certfile=self.client_certfile,
client_keyfile=self.client_keyfile,
method='GET'
)
cookies = ipapython.cookie.Cookie.parse(resp_headers.get('set-cookie', ''))
if status != 200 or len(cookies) == 0:
raise errors.RemoteRetrieveError(reason=_('Failed to authenticate to CA REST API'))
object.__setattr__(self, 'cookie', str(cookies[0]))
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Log out of the REST API"""
dogtag.https_request(
self.ca_host, self.override_port or self.env.ca_agent_port,
url='/ca/rest/account/logout',
cafile=self.ca_cert,
client_certfile=self.client_certfile,
client_keyfile=self.client_keyfile,
method='GET'
)
object.__setattr__(self, 'cookie', None)
def _ssldo(self, method, path, headers=None, body=None, use_session=True):
"""
Perform an HTTPS request.
:param method: HTTP method to use
:param path: Path component. This will *extend* the path defined for
the class (if any).
:param headers: Additional headers to include in the request.
:param body: Request body.
:param use_session: If ``True``, session cookie is added to request
(client must be logged in).
:return: (http_status, http_headers, http_body)
as (integer, dict, str)
:raises: ``RemoteRetrieveError`` if ``use_session`` is not ``False``
and client is not logged in.
"""
headers = headers or {}
if use_session:
if self.cookie is None:
raise errors.RemoteRetrieveError(
reason=_("REST API is not logged in."))
headers['Cookie'] = self.cookie
resource = '/ca/rest'
if self.path is not None:
resource = os.path.join(resource, self.path)
if path is not None:
resource = os.path.join(resource, path)
# perform main request
status, resp_headers, resp_body = dogtag.https_request(
self.ca_host, self.override_port or self.env.ca_agent_port,
url=resource,
cafile=self.ca_cert,
client_certfile=self.client_certfile,
client_keyfile=self.client_keyfile,
method=method, headers=headers, body=body
)
if status < 200 or status >= 300:
explanation = self._parse_dogtag_error(resp_body) or ''
raise errors.HTTPRequestError(
status=status,
reason=_('Non-2xx response from CA REST API: %(status)d. %(explanation)s')
% {'status': status, 'explanation': explanation}
)
return (status, resp_headers, resp_body)
@register()
class ra(rabase.rabase, RestClient):
"""
Request Authority backend plugin.
"""
DEFAULT_PROFILE = dogtag.DEFAULT_PROFILE
def raise_certificate_operation_error(self, func_name, err_msg=None, detail=None):
"""
:param func_name: function name where error occurred
:param err_msg: diagnostic error message, if not supplied it will be
'Unable to communicate with CMS'
:param detail: extra information that will be appended to err_msg
inside a parenthesis. This may be an HTTP status msg
Raise a CertificateOperationError and log the error message.
"""
if err_msg is None:
err_msg = _('Unable to communicate with CMS')
if detail is not None:
err_msg = u'%s (%s)' % (err_msg, detail)
logger.error('%s.%s(): %s', type(self).__name__, func_name, err_msg)
if detail == 404:
raise errors.NotFound(reason=err_msg)
raise errors.CertificateOperationError(error=err_msg)
def _request(self, url, port, **kw):
"""
:param url: The URL to post to.
:param kw: Keyword arguments to encode into POST body.
:return: (http_status, http_headers, http_body)
as (integer, dict, str)
Perform an HTTP request.
"""
return dogtag.http_request(self.ca_host, port, url, **kw)
def _sslget(self, url, port, **kw):
"""
:param url: The URL to post to.
:param kw: Keyword arguments to encode into POST body.
:return: (http_status, http_headers, http_body)
as (integer, dict, str)
Perform an HTTPS request
"""
return dogtag.https_request(
self.ca_host, port, url,
cafile=self.ca_cert,
client_certfile=self.client_certfile,
client_keyfile=self.client_keyfile,
**kw)
def get_parse_result_xml(self, xml_text, parse_func):
'''
:param xml_text: The XML text to parse
:param parse_func: The XML parsing function to apply to the parsed DOM tree.
:return: parsed result dict
Utility routine which parses the input text into an XML DOM tree
and then invokes the parsing function on the DOM tree in order
to get the parsing result as a dict of key/value pairs.
'''
parser = etree.XMLParser()
try:
doc = etree.fromstring(xml_text, parser)
except etree.XMLSyntaxError as e:
self.raise_certificate_operation_error('get_parse_result_xml',
detail=str(e))
result = parse_func(doc)
logger.debug(
"%s() xml_text:\n%r\nparse_result:\n%r",
parse_func.__name__, xml_text, result)
return result
def check_request_status(self, request_id):
"""
:param request_id: request ID
Check status of a certificate signing request.
The command returns a dict with these possible key/value pairs.
Some key/value pairs may be absent.
+-------------------+---------------+---------------+
|result name |result type |comments |
+===================+===============+===============+
|serial_number |unicode [1]_ | |
+-------------------+---------------+---------------+
|request_id |unicode [1]_ | |
+-------------------+---------------+---------------+
|cert_request_status|unicode [2]_ | |
+-------------------+---------------+---------------+
.. [1] The certID and requestId values are returned in
JSON as hex regardless of what the request contains.
They are converted to decimal in the return value.
.. [2] cert_request_status, requestStatus, may be one of:
- "begin"
- "pending"
- "approved"
- "svc_pending"
- "canceled"
- "rejected"
- "complete"
The REST API responds with JSON in the form of:
{
"requestID": "0x3",
"requestType": "enrollment",
"requestStatus": "complete",
"requestURL": "https://ipa.example.test:8443/ca/rest/certrequests/3",
"certId": "0x3",
"certURL": "https://ipa.example.test:8443/ca/rest/certs/3",
"certRequestType": "pkcs10",
"operationResult": "success",
"requestId": "0x3"
}
"""
logger.debug('%s.check_request_status()', type(self).__name__)
# Call CMS
path = 'certrequests/{}'.format(request_id)
try:
http_status, _http_headers, http_body = self._ssldo(
'GET', path, use_session=False,
headers={
'Accept': 'application/json',
},
)
except errors.HTTPRequestError as e:
self.raise_certificate_operation_error(
'check_request_status',
err_msg=e.msg,
detail=e.status # pylint: disable=no-member
)
# Parse and handle errors
if http_status != 200:
# Note: this is a bit of an API change in that the error
# returned contains the hex value of the certificate
# but it's embedded in the 404. I doubt anything relies
# on it.
self.raise_certificate_operation_error('check_request_status',
detail=http_status)
try:
parse_result = json.loads(ipautil.decode_json(http_body))
except ValueError:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
operation_result = parse_result['operationResult']
if operation_result != "success":
self.raise_certificate_operation_error(
'check_request_status',
cms_request_status_to_string(operation_result),
parse_result.get('errorMessage'))
# Return command result
cmd_result = {}
if 'certId' in parse_result:
cmd_result['serial_number'] = int(parse_result['certId'], 16)
if 'requestID' in parse_result:
cmd_result['request_id'] = int(parse_result['requestID'], 16)
if 'requestStatus' in parse_result:
cmd_result['cert_request_status'] = parse_result['requestStatus']
return cmd_result
def get_certificate(self, serial_number):
"""
Retrieve an existing certificate.
:param serial_number: Certificate serial number. May be int,
decimal string, or hex string with "0x"
prefix.
The command returns a dict with these possible key/value pairs.
Some key/value pairs may be absent.
+-----------------+---------------+---------------+
|result name |result type |comments |
+=================+===============+===============+
|certificate |unicode [1]_ | |
+-----------------+---------------+---------------+
|serial_number |unicode [2]_ | |
+-----------------+---------------+---------------+
|revocation_reason|int [3]_ | |
+-----------------+---------------+---------------+
.. [1] Base64 encoded
.. [2] Passed through RPC as decimal string. Can convert to
optimal integer type (int or long) via int(serial_number)
.. [3] revocation reason may be one of:
- 0 = UNSPECIFIED
- 1 = KEY_COMPROMISE
- 2 = CA_COMPROMISE
- 3 = AFFILIATION_CHANGED
- 4 = SUPERSEDED
- 5 = CESSATION_OF_OPERATION
- 6 = CERTIFICATE_HOLD
- 8 = REMOVE_FROM_CRL
- 9 = PRIVILEGE_WITHDRAWN
- 10 = AA_COMPROMISE
"""
logger.debug('%s.get_certificate()', type(self).__name__)
# Call CMS
path = 'certs/{}'.format(serial_number)
try:
_http_status, _http_headers, http_body = self._ssldo(
'GET', path, use_session=False,
headers={
'Accept': 'application/json',
},
)
except errors.HTTPRequestError as e:
self.raise_certificate_operation_error(
'get_certificate',
err_msg=e.msg,
detail=e.status # pylint: disable=no-member
)
try:
resp = json.loads(ipautil.decode_json(http_body))
except ValueError:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
# Return command result
cmd_result = {}
if 'Encoded' in resp:
s = resp['Encoded']
# The 'cert' plugin expects the result to be base64-encoded
# X.509 DER. We expect the result to be PEM. We have to
# strip the PEM headers and we use PEM_CERT_REGEX to do it.
match = x509.PEM_CERT_REGEX.search(s.encode('utf-8'))
if match:
s = match.group(2).decode('utf-8')
cmd_result['certificate'] = s.strip()
if 'id' in resp:
serial = int(resp['id'], 0)
cmd_result['serial_number'] = unicode(serial)
cmd_result['serial_number_hex'] = u'0x%X' % serial
if 'RevocationReason' in resp and resp['RevocationReason'] is not None:
cmd_result['revocation_reason'] = resp['RevocationReason']
return cmd_result
def request_certificate(
self, csr, profile_id, ca_id, request_type='pkcs10'):
"""
:param csr: The certificate signing request.
:param profile_id: The profile to use for the request.
:param ca_id: The Authority ID to send request to. ``None`` is allowed.
:param request_type: The request type (defaults to ``'pkcs10'``).
Submit certificate signing request.
The command returns a dict with these key/value pairs:
``serial_number``
``unicode``, decimal representation
``serial_number_hex``
``unicode``, hex representation with ``'0x'`` leader
``certificate``
``unicode``, base64-encoded DER
``request_id``
``unicode``, decimal representation
"""
logger.debug('%s.request_certificate()', type(self).__name__)
# Call CMS
template = '''
{{
"ProfileID" : "{profile}",
"Renewal" : false,
"RemoteHost" : "",
"RemoteAddress" : "",
"Input" : [ {{
"id" : "i1",
"ClassID" : "certReqInputImpl",
"Name" : "Certificate Request Input",
"ConfigAttribute" : [ ],
"Attribute" : [ {{
"name" : "cert_request_type",
"Value" : "{req_type}",
"Descriptor" : {{
"Syntax" : "cert_request_type",
"Description" : "Certificate Request Type"
}}
}}, {{
"name" : "cert_request",
"Value" : "{req}",
"Descriptor" : {{
"Syntax" : "cert_request",
"Description" : "Certificate Request"
}}
}} ]
}} ],
"Output" : [ ],
"Attributes" : {{
"Attribute" : [ ]
}}
}}
'''
data = template.format(
profile=profile_id,
req_type=request_type,
req=csr,
)
data = data.replace('\n', '')
path = 'certrequests'
if ca_id:
path += '?issuer-id={}'.format(ca_id)
_http_status, _http_headers, http_body = self._ssldo(
'POST', path,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body=data,
use_session=False,
)
try:
resp_obj = json.loads(ipautil.decode_json(http_body))
except ValueError as e:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
# Return command result
cmd_result = {}
entries = resp_obj.get('entries', [])
# ipa cert-request only handles a single PKCS #10 request so
# there's only one certinfo in the result.
if len(entries) < 1:
return cmd_result
certinfo = entries[0]
if certinfo['requestStatus'] != 'complete':
raise errors.CertificateOperationError(
error=certinfo.get('errorMessage'))
if 'certId' in certinfo:
cmd_result = self.get_certificate(certinfo['certId'])
cert = ''.join(cmd_result['certificate'].splitlines())
cmd_result['certificate'] = cert
if 'requestURL' in certinfo:
cmd_result['request_id'] = certinfo['requestURL'].split('/')[-1]
return cmd_result
def get_pki_version(self):
"""
Retrieve the version of a remote PKI server.
The REST API request is a GET to the info URI:
GET /pki/rest/info HTTP/1.1
The response is: {"Version":"11.5.0","Attributes":{"Attribute":[]}}
"""
path = "/pki/rest/info"
logger.debug('%s.get_pki_version()', type(self).__name__)
http_status, _http_headers, http_body = self._ssldo(
'GET', path,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
use_session=False,
)
if http_status != 200:
self.raise_certificate_operation_error('get_pki_version',
detail=http_status)
try:
response = json.loads(ipautil.decode_json(http_body))
except ValueError as e:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
return response.get('Version')
def revoke_certificate(self, serial_number, revocation_reason=0):
"""
:param serial_number: Certificate serial number. Must be a string value
because serial numbers may be of any magnitude and
XMLRPC cannot handle integers larger than 64-bit.
The string value should be decimal, but may
optionally be prefixed with a hex radix prefix
if the integral value is represented as
hexadecimal. If no radix prefix is supplied
the string will be interpreted as decimal.
:param revocation_reason: Integer code of revocation reason.
Revoke a certificate.
The command returns a dict with these possible key/value pairs.
Some key/value pairs may be absent.
+---------------+---------------+---------------+
|result name |result type |comments |
+===============+===============+===============+
|revoked |bool | |
+---------------+---------------+---------------+
The REST API responds with JSON in the form of:
{
"requestID": "0x17",
"requestType": "revocation",
"requestStatus": "complete",
"requestURL": "https://ipa.example.test:8443/ca/rest/certrequests/23",
"certId": "0x12",
"certURL": "https://ipa.example.test:8443/ca/rest/certs/18",
"operationResult": "success",
"requestId": "0x17"
}
requestID appears to be deprecated in favor of requestId.
The Ids are in hex. IPA has traditionally returned these as
decimal. The REST API raises exceptions using hex which
will be a departure from previous behavior but unless we
scrape it out of the message there isn't much we can do.
"""
reasons = ["Unspecified",
"Key_Compromise",
"CA_Compromise",
"Affiliation_Changed",
"Superseded",
"Cessation_of_Operation",
"Certificate_Hold",
"NOTUSED", # value 7 is not used
"Remove_from_CRL",
"Privilege_Withdrawn",
"AA_Compromise"]
logger.debug('%s.revoke_certificate()', type(self).__name__)
if type(revocation_reason) is not int:
raise TypeError(TYPE_ERROR % ('revocation_reason', int, revocation_reason, type(revocation_reason)))
if revocation_reason == 7:
self.raise_certificate_operation_error(
'revoke_certificate',
detail='7 is not a valid revocation reason'
)
# dogtag changed the argument case for revocation from
# "reason" to "Reason" in PKI 11.4.0. Detect that change
# based on the remote version and pass the expected value
# in.
pki_version = pki.util.Version(self.get_pki_version())
if pki_version is None:
self.raise_certificate_operation_error('revoke_certificate',
detail="Remove version not "
"detected")
if pki_version < pki.util.Version("11.4.0"):
reason = "reason"
else:
reason = "Reason"
# Convert serial number to integral type from string to properly handle
# radix issues. Note: the int object constructor will properly handle
# large magnitude integral values by returning a Python long type
# when necessary.
serial_number = int(serial_number, 0)
path = 'agent/certs/{}/revoke'.format(serial_number)
data = '{{"{}":"{}"}}'.format(reason, reasons[revocation_reason])
http_status, _http_headers, http_body = self._ssldo(
'POST', path,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body=data,
use_session=False,
)
if http_status != 200:
self.raise_certificate_operation_error('revoke_certificate',
detail=http_status)
try:
response = json.loads(ipautil.decode_json(http_body))
except ValueError as e:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
request_status = response['operationResult']
if request_status != 'success':
self.raise_certificate_operation_error(
'revoke_certificate',
request_status,
response.get('errorMessage')
)
# Return command result
cmd_result = {}
# We can assume the revocation was successful because if it failed
# then REST will return a non-200 or operationalResult will not
# be 'success'.
cmd_result['revoked'] = True
return cmd_result
def take_certificate_off_hold(self, serial_number):
"""
:param serial_number: Certificate serial number. Must be a string value
because serial numbers may be of any magnitude
and XMLRPC cannot handle integers larger than
64-bit. The string value should be decimal, but
may optionally be prefixed with a hex radix
prefix if the integral value is represented as
hexadecimal. If no radix prefix is supplied
the string will be interpreted as decimal.
Take revoked certificate off hold.
The command returns a dict with these possible key/value pairs.
Some key/value pairs may be absent.
+---------------+---------------+---------------+
|result name |result type |comments |
+===============+===============+===============+
|requestStatus |unicode | |
|errorMessage |unicode | |
+---------------+---------------+---------------+
The REST API responds with JSON in the form of:
{
"requestID":"0x19",
"requestType":"unrevocation",
"requestStatus":"complete",
"requestURL":"https://ipa.example.test:8443/ca/rest/certrequests/25",
"operationResult":"success",
"requestId":"0x19"
}
Being REST, some errors are returned as HTTP codes. Like
not being authenticated (401) or un-revoking a non-revoked
certificate (404).
For removing hold, unrevoking a non-revoked certificate will
return errorMessage.
requestID appears to be deprecated in favor of requestId.
The Ids are in hex. IPA has traditionally returned these as
decimal. The REST API raises exceptions using hex which
will be a departure from previous behavior but unless we
scrape it out of the message there isn't much we can do.
"""
logger.debug('%s.take_certificate_off_hold()', type(self).__name__)
# Convert serial number to integral type from string to properly handle
# radix issues. Note: the int object constructor will properly handle
# large magnitude integral values by returning a Python long type when
# necessary.
serial_number = int(serial_number, 0)
path = 'agent/certs/{}/unrevoke'.format(serial_number)
http_status, _http_headers, http_body = self._ssldo(
'POST', path,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
},
use_session=False,
)
if http_status != 200:
self.raise_certificate_operation_error(
'take_certificate_off_hold',
detail=http_status)
try:
response = json.loads(ipautil.decode_json(http_body))
except ValueError as e:
logger.debug("Response from CA was not valid JSON: %s", e)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
request_status = response['operationResult']
if request_status != 'success':
self.raise_certificate_operation_error(
'take_certificate_off_hold',
request_status,
response.get('errorMessage'))
# Return command result
cmd_result = {}
if 'errorMessage' in response:
cmd_result['error_string'] = response['errorMessage']
# We can assume the un-revocation was successful because if it failed
# then REST will return a non-200 or operationalResult will not
# be 'success'.
cmd_result['unrevoked'] = True
return cmd_result
def find(self, options):
"""
Search for certificates
:param options: dictionary of search options
"""
def convert_time(value):
"""
Convert time to milliseconds to pass to dogtag
"""
ts = time.strptime(value, '%Y-%m-%d')
return int(time.mktime(ts) * 1000)
logger.debug('%s.find()', type(self).__name__)
cert_search_request = dict()
# This matches the default configuration of the pki tool.
booloptions = {'serialNumberRangeInUse': True,
'subjectInUse': False,
'matchExactly': False,
'revokedByInUse': False,
'revokedOnInUse': False,
'revocationReasonInUse': False,
'issuedByInUse': False,
'issuedOnInUse': False,
'validNotBeforeInUse': False,
'validNotAfterInUse': False,
'validityLengthInUse': False,
'certTypeInUse': False}
if options.get('exactly', False):
booloptions['matchExactly'] = True
if 'subject' in options:
cert_search_request['commonName'] = options['subject']
booloptions['subjectInUse'] = True
if 'issuer' in options:
cert_search_request['issuerDN'] = options['issuer']
if 'revocation_reason' in options:
cert_search_request['revocationReason'] = unicode(
options['revocation_reason'])
booloptions['revocationReasonInUse'] = True
if 'min_serial_number' in options:
cert_search_request['serialFrom'] = unicode(
options['min_serial_number'])
if 'max_serial_number' in options:
cert_search_request['serialTo'] = unicode(
options['max_serial_number'])
if 'status' in options:
cert_search_request['status'] = options['status']
# date_types is a tuple that consists of:
# 1. attribute name passed from IPA API
# 2. attribute name used by REST API
# 3. boolean to set in the REST API
date_types = (
('validnotbefore_from', 'validNotBeforeFrom', 'validNotBeforeInUse'),
('validnotbefore_to', 'validNotBeforeTo', 'validNotBeforeInUse'),
('validnotafter_from', 'validNotAfterFrom', 'validNotAfterInUse'),
('validnotafter_to', 'validNotAfterTo', 'validNotAfterInUse'),
('issuedon_from', 'issuedOnFrom','issuedOnInUse'),
('issuedon_to', 'issuedOnTo','issuedOnInUse'),
('revokedon_from', 'revokedOnFrom','revokedOnInUse'),
('revokedon_to', 'revokedOnTo','revokedOnInUse'),
)
for (attr, dattr, battr) in date_types:
if attr in options:
epoch = convert_time(options[attr])
cert_search_request[dattr] = unicode(epoch)
booloptions[battr] = True
# Add the boolean options to our XML document
for opt, value in booloptions.items():
cert_search_request[opt] = str(value).lower()
payload = json.dumps(cert_search_request, sort_keys=True)
logger.debug('%s.find(): request: %s', type(self).__name__, payload)
url = '/ca/rest/certs/search?size=%d' % (
options.get('sizelimit', 0x7fffffff))
# pylint: disable=unused-variable
status, _, data = dogtag.https_request(
self.ca_host, 443,
url=url,
client_certfile=None,
client_keyfile=None,
cafile=self.ca_cert,
method='POST',
headers={'Accept-Encoding': 'gzip, deflate',
'User-Agent': 'IPA',
'Content-Type': 'application/json',
'Accept': 'application/json'},
body=payload
)
if status != 200:
try:
response = json.loads(ipautil.decode_json(data))
except ValueError as e:
logger.debug("Response from CA was not valid JSON: %s", e)
self.raise_certificate_operation_error(
'find',
detail='Failed to parse error response')
# Try to parse out the returned error. If this fails then
# raise the generic certificate operations error.
try:
msg = response.get('Message')
msg = msg.split(':', 1)[0]
except etree.XMLSyntaxError as e:
self.raise_certificate_operation_error('find',
detail=status)
# Message, at least in the case of search failing, consists
# of "<message>: <java stack trace>". Use just the first
# bit.
self.raise_certificate_operation_error('find',
err_msg=msg,
detail=status)
logger.debug('%s.find(): response: %s', type(self).__name__, data)
try:
data = json.loads(data)
except TypeError as e:
self.raise_certificate_operation_error('find',
detail=str(e))
# Grab all the certificates
certs = data['entries']
results = []
for cert in certs:
response_request = {}
response_request['serial_number'] = int(
cert.get('id'), 16) # parse as hex
response_request["serial_number_hex"] = (
"0x%X" % response_request["serial_number"]
)
dn = cert.get('SubjectDN')
if dn:
response_request['subject'] = dn
issuer_dn = cert.get('IssuerDN')
if issuer_dn:
response_request['issuer'] = issuer_dn
not_valid_before_utc = cert.get('NotValidBefore')
if not_valid_before_utc:
response_request['valid_not_before'] = (
not_valid_before_utc)
not_valid_after_utc = cert.get('NotValidAfter')
if not_valid_after_utc:
response_request['valid_not_after'] = (not_valid_after_utc)
status = cert.get('Status')
if status:
response_request['status'] = status
results.append(response_request)
return results
def updateCRL(self, wait='false'):
"""
Force update of the CRL
:param wait: if true, the call will be synchronous and return only
when the CRL has been generated
"""
logger.debug('%s.updateCRL()', type(self).__name__)
# Call CMS
http_status, _http_headers, http_body = (
self._sslget('/ca/agent/ca/updateCRL',
self.override_port or self.env.ca_agent_port,
crlIssuingPoint='MasterCRL',
waitForUpdate=wait,
xml='true')
)
# Parse and handle errors
if http_status != 200:
self.raise_certificate_operation_error('updateCRL',
detail=http_status)
parse_result = self.get_parse_result_xml(http_body,
parse_updateCRL_xml)
request_status = parse_result['request_status']
if request_status != CMS_STATUS_SUCCESS:
self.raise_certificate_operation_error(
'updateCRL',
cms_request_status_to_string(request_status),
parse_result.get('error_string'))
# Return command result
cmd_result = {}
if 'crl_issuing_point' in parse_result:
cmd_result['crlIssuingPoint'] = parse_result['crl_issuing_point']
if 'crl_update' in parse_result:
cmd_result['crlUpdate'] = parse_result['crl_update']
return cmd_result
# ----------------------------------------------------------------------------
@register()
class kra(Backend):
"""
KRA backend plugin (for Vault)
"""
def __init__(self, api, kra_port=443):
self.kra_port = kra_port
super(kra, self).__init__(api)
@property
def kra_host(self):
"""
:return: host
as str
Select our KRA host.
"""
preferred = [api.env.ca_host]
if api.env.host != api.env.ca_host:
preferred.append(api.env.host)
kra_host = find_providing_server(
'KRA', self.api.Backend.ldap2, preferred_hosts=preferred,
api=self.api
)
if kra_host is None:
# TODO: need during installation, KRA is not yet set as enabled
kra_host = api.env.ca_host
return kra_host
@contextlib.contextmanager
def get_client(self):
"""
Returns an authenticated KRA client to access KRA services.
Raises a generic exception if KRA is not enabled.
"""
if not self.api.Command.kra_is_enabled()['result']:
# TODO: replace this with a more specific exception
raise RuntimeError('KRA service is not enabled')
crypto = cryptoutil.CryptographyCryptoProvider(
transport_cert_nick="ra_agent",
transport_cert=x509.load_certificate_from_file(paths.RA_AGENT_PEM)
)
# TODO: obtain KRA host & port from IPA service list or point to KRA load balancer
# https://fedorahosted.org/freeipa/ticket/4557
connection = PKIConnection(
'https',
self.kra_host,
str(self.kra_port),
'kra',
cert_paths=paths.IPA_CA_CRT
)
connection.set_authentication_cert(paths.RA_AGENT_PEM,
paths.RA_AGENT_KEY)
yield KRAClient(connection, crypto)
@register()
class ra_certprofile(RestClient):
"""
Profile management backend plugin.
"""
path = 'profiles'
def create_profile(self, profile_data):
"""
Import the profile into Dogtag
"""
self._ssldo('POST', 'raw',
headers={
'Content-type': 'application/xml',
'Accept': 'application/json',
},
body=profile_data
)
def read_profile(self, profile_id):
"""
Read the profile configuration from Dogtag
"""
_status, _resp_headers, resp_body = self._ssldo(
'GET', profile_id + '/raw')
return resp_body
def update_profile(self, profile_id, profile_data):
"""
Update the profile configuration in Dogtag
"""
self._ssldo('PUT', profile_id + '/raw',
headers={
'Content-type': 'application/xml',
'Accept': 'application/json',
},
body=profile_data
)
def enable_profile(self, profile_id):
"""
Enable the profile in Dogtag
"""
self._ssldo('POST', profile_id + '?action=enable')
def disable_profile(self, profile_id):
"""
Enable the profile in Dogtag
"""
self._ssldo('POST', profile_id + '?action=disable')
def delete_profile(self, profile_id):
"""
Delete the profile from Dogtag
"""
self._ssldo('DELETE', profile_id, headers={'Accept': 'application/json'})
@register()
class ra_lightweight_ca(RestClient):
"""
Lightweight CA management backend plugin.
"""
path = 'authorities'
def create_ca(self, dn):
"""Create CA with the given DN.
New CA is issued by IPA CA. Nested sub-CAs and unrelated
root CAs are not yet supported.
Return the (parsed) JSON response from server.
"""
assert isinstance(dn, DN)
_status, _resp_headers, resp_body = self._ssldo(
'POST', None,
headers={
'Content-type': 'application/json',
'Accept': 'application/json',
},
body=json.dumps({"parentID": "host-authority", "dn": unicode(dn)}),
)
try:
return json.loads(ipautil.decode_json(resp_body))
except Exception as e:
logger.debug('%s', e, exc_info=True)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON")
)
def read_ca(self, ca_id):
_status, _resp_headers, resp_body = self._ssldo(
'GET', ca_id, headers={'Accept': 'application/json'})
try:
return json.loads(ipautil.decode_json(resp_body))
except Exception as e:
logger.debug('%s', e, exc_info=True)
raise errors.RemoteRetrieveError(
reason=_("Response from CA was not valid JSON"))
def read_ca_cert(self, ca_id):
_status, _resp_headers, resp_body = self._ssldo(
'GET', '{}/cert'.format(ca_id),
headers={'Accept': 'application/pkix-cert'})
return resp_body
def read_ca_chain(self, ca_id):
_status, _resp_headers, resp_body = self._ssldo(
'GET', '{}/chain'.format(ca_id),
headers={'Accept': 'application/pkcs7-mime'})
return resp_body
def disable_ca(self, ca_id):
self._ssldo(
'POST', ca_id + '/disable',
headers={'Accept': 'application/json'},
)
def enable_ca(self, ca_id):
self._ssldo(
'POST', ca_id + '/enable',
headers={'Accept': 'application/json'},
)
def delete_ca(self, ca_id):
self._ssldo('DELETE', ca_id)
@register()
class ra_securitydomain(RestClient):
"""
Security domain management backend plugin.
Dogtag handles the creation of securitydomain entries
we need to clean them up when an IPA server is removed.
"""
path = 'securityDomain/hosts'
def delete_domain(self, hostname, type):
"""
Delete a security domain
"""
self._ssldo(
'DELETE', f'{type}%20{hostname}%20443',
headers={'Accept': 'application/json'}
)
| 67,224
|
Python
|
.py
| 1,442
| 36.741331
| 112
| 0.595397
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,830
|
baseuser.py
|
freeipa_freeipa/ipaserver/plugins/baseuser.py
|
# Authors:
# Thierry Bordaz <tbordaz@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 base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
import re
import six
from ipalib import api, errors, constants
from ipalib import (
Flag, Int, Password, Str, Bool, StrEnum, DateTime, DNParam)
from ipalib.parameters import Principal, Certificate
from ipalib.plugable import Registry
from .baseldap import (
DN, LDAPObject, LDAPCreate, LDAPUpdate, LDAPSearch, LDAPDelete,
LDAPRetrieve, LDAPAddAttribute, LDAPModAttribute, LDAPRemoveAttribute,
LDAPAddMember, LDAPRemoveMember,
LDAPAddAttributeViaOption, LDAPRemoveAttributeViaOption,
add_missing_object_class
)
from ipaserver.plugins.service import (validate_realm, normalize_principal)
from ipalib.request import context
from ipalib import _
from ipapython import kerberos
from ipapython.ipautil import ipa_generate_password, TMP_PWD_ENTROPY_BITS
from ipapython.ipavalidate import Email
from ipalib.util import (
normalize_sshpubkey,
validate_sshpubkey,
convert_sshpubkey_post,
remove_sshpubkey_from_output_post,
remove_sshpubkey_from_output_list_post,
add_sshpubkey_to_attrs_pre,
set_krbcanonicalname,
check_principal_realm_in_trust_namespace,
ensure_last_krbprincipalname,
ensure_krbcanonicalname_set
)
if six.PY3:
unicode = str
__doc__ = _("""
Baseuser
This contains common definitions for user/stageuser
""")
register = Registry()
NO_UPG_MAGIC = '__no_upg__'
baseuser_output_params = (
Flag('has_keytab',
label=_('Kerberos keys available'),
),
)
UPG_DEFINITION_DN = DN(('cn', 'UPG Definition'),
('cn', 'Definitions'),
('cn', 'Managed Entries'),
('cn', 'etc'),
api.env.basedn)
def validate_nsaccountlock(entry_attrs):
if 'nsaccountlock' in entry_attrs:
nsaccountlock = entry_attrs['nsaccountlock']
if not isinstance(nsaccountlock, (bool, Bool)):
if not isinstance(nsaccountlock, str):
raise errors.OnlyOneValueAllowed(attr='nsaccountlock')
if nsaccountlock.lower() not in ('true', 'false'):
raise errors.ValidationError(name='nsaccountlock',
error=_('must be TRUE or FALSE'))
def radius_dn2pk(api, entry_attrs):
cl = entry_attrs.get('ipatokenradiusconfiglink', None)
if cl:
pk = api.Object['radiusproxy'].get_primary_key_from_dn(cl[0])
entry_attrs['ipatokenradiusconfiglink'] = [pk]
def idp_dn2pk(api, entry_attrs):
cl = entry_attrs.get('ipaidpconfiglink', None)
if cl:
pk = api.Object['idp'].get_primary_key_from_dn(cl[0])
entry_attrs['ipaidpconfiglink'] = [pk]
def convert_nsaccountlock(entry_attrs):
if 'nsaccountlock' not in entry_attrs:
entry_attrs['nsaccountlock'] = False
else:
nsaccountlock = Bool('temp')
entry_attrs['nsaccountlock'] = nsaccountlock.convert(entry_attrs['nsaccountlock'][0])
def normalize_user_principal(value):
principal = kerberos.Principal(normalize_principal(value))
lowercase_components = ((principal.username.lower(),) +
principal.components[1:])
return unicode(
kerberos.Principal(lowercase_components, realm=principal.realm))
def fix_addressbook_permission_bindrule(name, template, is_new,
anonymous_read_aci,
**other_options):
"""Fix bind rule type for Read User Addressbook/IPA Attributes permission
When upgrading from an old IPA that had the global read ACI,
or when installing the first replica with granular read permissions,
we need to keep allowing anonymous access to many user attributes.
This fixup_function changes the bind rule type accordingly.
"""
if is_new and anonymous_read_aci:
template['ipapermbindruletype'] = 'anonymous'
def update_samba_attrs(ldap, dn, entry_attrs, **options):
smb_attrs = {'ipantlogonscript', 'ipantprofilepath',
'ipanthomedirectory', 'ipanthomedirectorydrive'}
if 'objectclass' not in entry_attrs:
try:
oc = ldap.get_entry(dn, ['objectclass'])['objectclass']
except errors.NotFound:
# In case the entry really does not exist,
# compare against an empty list
oc = []
else:
oc = entry_attrs['objectclass']
if 'ipantuserattrs' not in (item.lower() for item in oc):
for attr in smb_attrs:
if options.get(attr, None):
raise errors.ValidationError(
name=attr,
error=_(
'Object class ipaNTUserAttrs is missing, '
'user entry cannot have SMB attributes.'
)
)
def validate_passkey(ugettext, key):
"""
Validate the format for passkey mappings.
The expected format is passkey:<key id>,<pubkey>
"""
pattern = re.compile(
r'^passkey:(?P<id>[^,]*),(?P<pkey>[^,]*),?(?P<userid>.*)$')
result = re.match(pattern, key)
if result is None:
return '"%s" is not a valid passkey mapping' % key
# Validate the id part
try:
base64.b64decode(result.group('id'), validate=True)
except Exception:
return '"%s" is not a valid passkey mapping, invalid id' % key
# Validate the pkey part
try:
pem = "-----BEGIN PUBLIC KEY-----\n" + \
result.group('pkey') + \
"\n-----END PUBLIC KEY-----"
load_pem_public_key(data=pem.encode('utf-8'),
backend=default_backend())
except ValueError:
return '"%s" is not a valid passkey mapping, invalid key' % key
# Validate the (optional) userid
try:
userid = result.group('userid')
if userid:
base64.b64decode(userid, validate=True)
except Exception:
return '"%s" is not a valid passkey mapping, invalid userid' % key
return None
class baseuser(LDAPObject):
"""
baseuser object.
"""
stage_container_dn = api.env.container_stageuser
active_container_dn = api.env.container_user
delete_container_dn = api.env.container_deleteuser
object_class = ['posixaccount']
object_class_config = 'ipauserobjectclasses'
possible_objectclasses = [
'meporiginentry', 'ipauserauthtypeclass', 'ipauser',
'ipatokenradiusproxyuser', 'ipacertmapobject',
'ipantuserattrs', 'ipaidpuser', 'ipapasskeyuser',
]
disallow_object_classes = ['krbticketpolicyaux']
permission_filter_objectclasses = ['posixaccount']
search_attributes_config = 'ipausersearchfields'
default_attributes = [
'uid', 'givenname', 'sn', 'homedirectory', 'loginshell',
'uidnumber', 'gidnumber', 'mail', 'ou',
'telephonenumber', 'title', 'memberof', 'nsaccountlock',
'memberofindirect', 'ipauserauthtype', 'userclass',
'ipatokenradiusconfiglink', 'ipatokenradiususername',
'ipaidpconfiglink', 'ipaidpsub',
'krbprincipalexpiration', 'usercertificate;binary',
'krbprincipalname', 'krbcanonicalname',
'ipacertmapdata', 'ipantlogonscript', 'ipantprofilepath',
'ipanthomedirectory', 'ipanthomedirectorydrive',
'ipapasskey',
]
search_display_attributes = [
'uid', 'givenname', 'sn', 'homedirectory', 'krbcanonicalname',
'krbprincipalname', 'loginshell',
'mail', 'telephonenumber', 'title', 'nsaccountlock',
'uidnumber', 'gidnumber', 'sshpubkeyfp',
]
uuid_attribute = 'ipauniqueid'
attribute_members = {
'manager': ['user'],
'memberof': [
'group', 'netgroup', 'role', 'hbacrule', 'sudorule', 'subid'
],
'memberofindirect': ['group', 'netgroup', 'role', 'hbacrule', 'sudorule'],
}
allow_rename = True
bindable = True
password_attributes = [('userpassword', 'has_password'),
('krbprincipalkey', 'has_keytab')]
label = _('Users')
label_singular = _('User')
takes_params = (
Str('uid',
pattern=constants.PATTERN_GROUPUSER_NAME,
pattern_errmsg=constants.ERRMSG_GROUPUSER_NAME.format('user'),
maxlength=255,
cli_name='login',
label=_('User login'),
primary_key=True,
default_from=lambda givenname, sn: givenname[0] + sn,
normalizer=lambda value: value.lower(),
),
Str('givenname',
cli_name='first',
label=_('First name'),
),
Str('sn',
cli_name='last',
label=_('Last name'),
),
Str('cn',
label=_('Full name'),
default_from=lambda givenname, sn: '%s %s' % (givenname, sn),
autofill=True,
),
Str('displayname?',
label=_('Display name'),
default_from=lambda givenname, sn: '%s %s' % (givenname, sn),
autofill=True,
),
Str('initials?',
label=_('Initials'),
default_from=lambda givenname, sn: '%c%c' % (givenname[0], sn[0]),
autofill=True,
),
Str('homedirectory?',
cli_name='homedir',
label=_('Home directory'),
),
Str('gecos?',
label=_('GECOS'),
default_from=lambda givenname, sn: '%s %s' % (givenname, sn),
autofill=True,
),
Str('loginshell?',
cli_name='shell',
label=_('Login shell'),
),
Principal(
'krbcanonicalname?',
validate_realm,
label=_('Principal name'),
flags={'no_option', 'no_create', 'no_update', 'no_search'},
normalizer=normalize_user_principal
),
Principal(
'krbprincipalname*',
validate_realm,
cli_name='principal',
label=_('Principal alias'),
default_from=lambda uid: kerberos.Principal(
uid.lower(), realm=api.env.realm),
autofill=True,
normalizer=normalize_user_principal,
),
DateTime('krbprincipalexpiration?',
cli_name='principal_expiration',
label=_('Kerberos principal expiration'),
),
DateTime('krbpasswordexpiration?',
cli_name='password_expiration',
label=_('User password expiration'),
),
Str('mail*',
cli_name='email',
label=_('Email address'),
),
Password('userpassword?',
cli_name='password',
label=_('Password'),
doc=_('Prompt to set the user password'),
# FIXME: This is temporary till bug is fixed causing updates to
# bomb out via the webUI.
exclude='webui',
),
Flag('random?',
doc=_('Generate a random user password'),
flags=('no_search', 'virtual_attribute'),
default=False,
),
Str('randompassword?',
label=_('Random password'),
flags=('no_create', 'no_update', 'no_search', 'virtual_attribute'),
),
Int('uidnumber?',
cli_name='uid',
label=_('UID'),
doc=_('User ID Number (system will assign one if not provided)'),
minvalue=1,
),
Int('gidnumber?',
label=_('GID'),
doc=_('Group ID Number'),
minvalue=1,
),
Str('street?',
cli_name='street',
label=_('Street address'),
),
Str('l?',
cli_name='city',
label=_('City'),
),
Str('st?',
cli_name='state',
label=_('State/Province'),
),
Str('postalcode?',
label=_('ZIP'),
),
Str('telephonenumber*',
cli_name='phone',
label=_('Telephone Number')
),
Str('mobile*',
label=_('Mobile Telephone Number')
),
Str('pager*',
label=_('Pager Number')
),
Str('facsimiletelephonenumber*',
cli_name='fax',
label=_('Fax Number'),
),
Str('ou?',
cli_name='orgunit',
label=_('Org. Unit'),
),
Str('title?',
label=_('Job Title'),
),
# keep backward compatibility using single value manager option
Str('manager?',
label=_('Manager'),
),
Str('carlicense*',
label=_('Car License'),
),
Str('ipasshpubkey*', validate_sshpubkey,
cli_name='sshpubkey',
label=_('SSH public key'),
normalizer=normalize_sshpubkey,
flags=['no_search'],
),
Str('sshpubkeyfp*',
label=_('SSH public key fingerprint'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
StrEnum(
'ipauserauthtype*',
cli_name='user_auth_type',
label=_('User authentication types'),
doc=_('Types of supported user authentication'),
values=(u'password', u'radius', u'otp', u'pkinit', u'hardened',
u'idp', u'passkey'),
),
Str('userclass*',
cli_name='class',
label=_('Class'),
doc=_('User category (semantics placed on this attribute are for '
'local interpretation)'),
),
Str('ipatokenradiusconfiglink?',
cli_name='radius',
label=_('RADIUS proxy configuration'),
),
Str('ipatokenradiususername?',
cli_name='radius_username',
label=_('RADIUS proxy username'),
),
Str('ipaidpconfiglink?',
cli_name='idp',
label=_('External IdP configuration'),
),
Str('ipaidpsub?',
cli_name='idp_user_id',
label=_('External IdP user identifier'),
doc=_('A string that identifies the user at external IdP'),
),
Str('departmentnumber*',
label=_('Department Number'),
),
Str('employeenumber?',
label=_('Employee Number'),
),
Str('employeetype?',
label=_('Employee Type'),
),
Str('preferredlanguage?',
label=_('Preferred Language'),
pattern=(
r'^(([a-zA-Z]{1,8}(-[a-zA-Z]{1,8})?'
r'(;q\=((0(\.[0-9]{0,3})?)|(1(\.0{0,3})?)))?'
r'(\s*,\s*[a-zA-Z]{1,8}(-[a-zA-Z]{1,8})?'
r'(;q\=((0(\.[0-9]{0,3})?)|(1(\.0{0,3})?)))?)*)|(\*))$'
),
pattern_errmsg='must match RFC 2068 - 14.4, e.g., "da, en-gb;q=0.8, en;q=0.7"',
),
Certificate('usercertificate*',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded user certificate'),
),
Str(
'ipacertmapdata*',
cli_name='certmapdata',
label=_('Certificate mapping data'),
doc=_('Certificate mapping data'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipantlogonscript?',
cli_name='smb_logon_script',
label=_('SMB logon script path'),
flags=['no_create'],
),
Str('ipantprofilepath?',
cli_name='smb_profile_path',
label=_('SMB profile path'),
flags=['no_create'],
),
Str('ipanthomedirectory?',
cli_name='smb_home_dir',
label=_('SMB Home Directory'),
flags=['no_create'],
),
StrEnum('ipanthomedirectorydrive?',
cli_name='smb_home_drive',
label=_('SMB Home Directory Drive'),
flags=['no_create'],
values=(
'A:', 'B:', 'C:', 'D:', 'E:', 'F:', 'G:', 'H:', 'I:',
'J:', 'K:', 'L:', 'M:', 'N:', 'O:', 'P:', 'Q:', 'R:',
'S:', 'T:', 'U:', 'V:', 'W:', 'X:', 'Y:', 'Z:'),
),
Str('ipapasskey*', validate_passkey,
cli_name='passkey',
label=_('Passkey mapping'),
doc=_('Passkey mapping'),
flags=['no_create', 'no_update', 'no_search'],
),
)
def normalize_and_validate_email(self, email, config=None):
if not config:
config = self.backend.get_ipa_config()
# check if default email domain should be added
defaultdomain = config.get('ipadefaultemaildomain', [None])[0]
if email:
norm_email = []
if not isinstance(email, (list, tuple)):
email = [email]
for m in email:
if isinstance(m, str):
if '@' not in m and defaultdomain:
m = m + u'@' + defaultdomain
if not Email(m):
raise errors.ValidationError(name='email', error=_('invalid e-mail format: %(email)s') % dict(email=m))
norm_email.append(m)
else:
if not Email(m):
raise errors.ValidationError(name='email', error=_('invalid e-mail format: %(email)s') % dict(email=m))
norm_email.append(m)
return norm_email
return email
def normalize_manager(self, manager, container):
"""
Given a userid verify the user's existence (in the appropriate containter) and return the dn.
"""
if not manager:
return None
if not isinstance(manager, list):
manager = [manager]
try:
container_dn = DN(container, api.env.basedn)
for i, mgr in enumerate(manager):
if isinstance(mgr, DN) and mgr.endswith(container_dn):
continue
entry_attrs = self.backend.find_entry_by_attr(
self.primary_key.name, mgr, self.object_class, [''],
container_dn
)
manager[i] = entry_attrs.dn
except errors.NotFound:
raise errors.NotFound(reason=_('manager %(manager)s not found') % dict(manager=mgr))
return manager
def _user_status(self, user, container):
assert isinstance(user, DN)
return user.endswith(container)
def active_user(self, user):
assert isinstance(user, DN)
return self._user_status(user, DN(self.active_container_dn, api.env.basedn))
def stage_user(self, user):
assert isinstance(user, DN)
return self._user_status(user, DN(self.stage_container_dn, api.env.basedn))
def delete_user(self, user):
assert isinstance(user, DN)
return self._user_status(user, DN(self.delete_container_dn, api.env.basedn))
def convert_usercertificate_pre(self, entry_attrs):
if 'usercertificate' in entry_attrs:
entry_attrs['usercertificate;binary'] = entry_attrs.pop(
'usercertificate')
def convert_usercertificate_post(self, entry_attrs, **options):
if 'usercertificate;binary' in entry_attrs:
entry_attrs['usercertificate'] = entry_attrs.pop(
'usercertificate;binary')
def convert_attribute_members(self, entry_attrs, *keys, **options):
super(baseuser, self).convert_attribute_members(
entry_attrs, *keys, **options)
if options.get("raw", False):
return
# due the backward compatibility, managers have to be returned in
# 'manager' attribute instead of 'manager_user'
try:
entry_attrs['failed_manager'] = entry_attrs.pop('manager')
except KeyError:
pass
try:
entry_attrs['manager'] = entry_attrs.pop('manager_user')
except KeyError:
pass
class baseuser_add(LDAPCreate):
"""
Prototype command plugin to be implemented by real plugin
"""
def pre_common_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
assert isinstance(dn, DN)
set_krbcanonicalname(entry_attrs)
self.obj.convert_usercertificate_pre(entry_attrs)
if entry_attrs.get('ipatokenradiususername', None):
add_missing_object_class(ldap, u'ipatokenradiusproxyuser', dn,
entry_attrs, update=False)
if entry_attrs.get('ipauserauthtype', None):
add_missing_object_class(ldap, u'ipauserauthtypeclass', dn,
entry_attrs, update=False)
if (
entry_attrs.get('ipaidpconfiglink', None)
or entry_attrs.get('ipaidpsub', None)
):
add_missing_object_class(ldap, 'ipaidpuser', dn,
entry_attrs, update=False)
def post_common_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_usercertificate_post(entry_attrs, **options)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
convert_sshpubkey_post(entry_attrs)
if 'nsaccountlock' in entry_attrs:
convert_nsaccountlock(entry_attrs)
radius_dn2pk(self.api, entry_attrs)
idp_dn2pk(self.api, entry_attrs)
class baseuser_del(LDAPDelete):
"""
Prototype command plugin to be implemented by real plugin
"""
class baseuser_mod(LDAPUpdate):
"""
Prototype command plugin to be implemented by real plugin
"""
NAME_PATTERN = re.compile(constants.PATTERN_GROUPUSER_NAME)
def check_namelength(self, ldap, **options):
if options.get('rename') is not None:
config = ldap.get_ipa_config()
if 'ipamaxusernamelength' in config:
if len(options['rename']) > int(config.get('ipamaxusernamelength')[0]):
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('can be at most %(len)d characters') % dict(
len = int(config.get('ipamaxusernamelength')[0])
)
)
def check_name(self, entry_attrs):
if 'uid' in entry_attrs:
# Check the pattern if the user is renamed
if self.NAME_PATTERN.match(entry_attrs.single_value['uid']) is None:
raise errors.ValidationError(
name='uid',
error=constants.ERRMSG_GROUPUSER_NAME.format('user'))
def preserve_krbprincipalname_pre(self, ldap, entry_attrs, *keys, **options):
"""
preserve user principal aliases during rename operation. This is the
pre-callback part of this. Another method called during post-callback
shall insert the principals back
"""
if options.get('rename', None) is None:
return
try:
old_entry = ldap.get_entry(
entry_attrs.dn, attrs_list=(
'krbprincipalname', 'krbcanonicalname'))
if 'krbcanonicalname' not in old_entry:
return
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.context.krbprincipalname = old_entry.get(
'krbprincipalname', [])
def preserve_krbprincipalname_post(self, ldap, entry_attrs, **options):
"""
Insert the preserved aliases back to the user entry during rename
operation
"""
if options.get('rename', None) is None or not hasattr(
self.context, 'krbprincipalname'):
return
obj_pkey = self.obj.get_primary_key_from_dn(entry_attrs.dn)
canonical_name = entry_attrs['krbcanonicalname'][0]
principals_to_add = tuple(p for p in self.context.krbprincipalname if
p != canonical_name)
if principals_to_add:
result = self.api.Command.user_add_principal(
obj_pkey, principals_to_add)['result']
entry_attrs['krbprincipalname'] = result.get('krbprincipalname', [])
def check_mail(self, entry_attrs):
if 'mail' in entry_attrs:
entry_attrs['mail'] = self.obj.normalize_and_validate_email(entry_attrs['mail'])
def check_manager(self, entry_attrs, container):
if 'manager' in entry_attrs:
entry_attrs['manager'] = self.obj.normalize_manager(entry_attrs['manager'], container)
def check_userpassword(self, entry_attrs, **options):
if 'userpassword' not in entry_attrs and options.get('random'):
entry_attrs['userpassword'] = ipa_generate_password(
entropy_bits=TMP_PWD_ENTROPY_BITS)
# save the password so it can be displayed in post_callback
setattr(context, 'randompassword', entry_attrs['userpassword'])
def check_objectclass(self, ldap, dn, entry_attrs):
# Some attributes may require additional object classes
special_attrs = {'ipasshpubkey', 'ipauserauthtype', 'userclass',
'ipatokenradiusconfiglink', 'ipatokenradiususername',
'ipaidpconfiglink', 'ipaidpsub'}
if special_attrs.intersection(entry_attrs):
if 'objectclass' in entry_attrs:
obj_classes = entry_attrs['objectclass']
else:
_entry_attrs = ldap.get_entry(dn, ['objectclass'])
obj_classes = entry_attrs['objectclass'] = _entry_attrs['objectclass']
# IMPORTANT: compare objectclasses as case insensitive
obj_classes = [o.lower() for o in obj_classes]
if 'ipasshpubkey' in entry_attrs and 'ipasshuser' not in obj_classes:
entry_attrs['objectclass'].append('ipasshuser')
if 'ipauserauthtype' in entry_attrs and 'ipauserauthtypeclass' not in obj_classes:
entry_attrs['objectclass'].append('ipauserauthtypeclass')
if 'userclass' in entry_attrs and 'ipauser' not in obj_classes:
entry_attrs['objectclass'].append('ipauser')
if 'ipatokenradiusconfiglink' in entry_attrs:
cl = entry_attrs['ipatokenradiusconfiglink']
if cl:
if 'ipatokenradiusproxyuser' not in obj_classes:
entry_attrs['objectclass'].append('ipatokenradiusproxyuser')
answer = self.api.Object['radiusproxy'].get_dn_if_exists(cl)
entry_attrs['ipatokenradiusconfiglink'] = answer
if 'ipaidpsub' in entry_attrs:
if 'ipaidpuser' not in obj_classes:
entry_attrs['objectclass'].append('ipaidpuser')
if 'ipaidpconfiglink' in entry_attrs:
cl = entry_attrs['ipaidpconfiglink']
if cl:
if 'ipaidpuser' not in obj_classes:
entry_attrs['objectclass'].append('ipaidpuser')
try:
answer = self.api.Object['idp'].get_dn_if_exists(cl)
except errors.NotFound:
reason = "External IdP configuration {} not found"
raise errors.NotFound(reason=_(reason).format(cl))
entry_attrs['ipaidpconfiglink'] = answer
# Note: we could have used the method add_missing_object_class
# but since the data is already fetched and lowercased in
# obj_classes, it is more efficient to use the same approach
# as the code right above these lines
if 'ipatokenradiususername' in entry_attrs:
if 'ipatokenradiusproxyuser' not in obj_classes:
entry_attrs['objectclass'].append(
'ipatokenradiusproxyuser')
def pre_common_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
assert isinstance(dn, DN)
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
self.check_namelength(ldap, **options)
self.check_name(entry_attrs)
self.check_mail(entry_attrs)
self.check_manager(entry_attrs, self.obj.active_container_dn)
self.check_userpassword(entry_attrs, **options)
self.check_objectclass(ldap, dn, entry_attrs)
self.obj.convert_usercertificate_pre(entry_attrs)
self.preserve_krbprincipalname_pre(ldap, entry_attrs, *keys, **options)
update_samba_attrs(ldap, dn, entry_attrs, **options)
def post_common_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.preserve_krbprincipalname_post(ldap, entry_attrs, **options)
if options.get('random', False):
try:
entry_attrs['randompassword'] = unicode(getattr(context, 'randompassword'))
except AttributeError:
# if both randompassword and userpassword options were used
pass
convert_nsaccountlock(entry_attrs)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
self.obj.convert_usercertificate_post(entry_attrs, **options)
convert_sshpubkey_post(entry_attrs)
remove_sshpubkey_from_output_post(self.context, entry_attrs)
radius_dn2pk(self.api, entry_attrs)
idp_dn2pk(self.api, entry_attrs)
class baseuser_find(LDAPSearch):
"""
Prototype command plugin to be implemented by real plugin
"""
def args_options_2_entry(self, *args, **options):
newoptions = {}
self.common_enhance_options(newoptions, **options)
options.update(newoptions)
return super(baseuser_find, self).args_options_2_entry(
*args, **options)
def common_enhance_options(self, newoptions, **options):
# assure the manager attr is a dn, not just a bare uid
manager = options.get('manager')
if manager is not None:
newoptions['manager'] = self.obj.normalize_manager(manager, self.obj.active_container_dn)
# Ensure that the RADIUS config link is a dn, not just the name
cl = 'ipatokenradiusconfiglink'
if cl in options:
newoptions[cl] = self.api.Object['radiusproxy'].get_dn(options[cl])
# Ensure that the IdP config link is a dn, not just the name
cl = 'ipaidpconfiglink'
if cl in options:
newoptions[cl] = self.api.Object['idp'].get_dn(options[cl])
def pre_common_callback(self, ldap, filters, attrs_list, base_dn, scope,
*args, **options):
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
def post_common_callback(self, ldap, entries, lockout=False, **options):
for attrs in entries:
self.obj.convert_usercertificate_post(attrs, **options)
if (lockout):
attrs['nsaccountlock'] = True
else:
convert_nsaccountlock(attrs)
convert_sshpubkey_post(attrs)
remove_sshpubkey_from_output_list_post(self.context, entries)
class baseuser_show(LDAPRetrieve):
"""
Prototype command plugin to be implemented by real plugin
"""
def pre_common_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
def post_common_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
self.obj.convert_usercertificate_post(entry_attrs, **options)
convert_sshpubkey_post(entry_attrs)
remove_sshpubkey_from_output_post(self.context, entry_attrs)
radius_dn2pk(self.api, entry_attrs)
idp_dn2pk(self.api, entry_attrs)
class baseuser_add_manager(LDAPAddMember):
member_attributes = ['manager']
class baseuser_remove_manager(LDAPRemoveMember):
member_attributes = ['manager']
class baseuser_add_principal(LDAPAddAttribute):
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
check_principal_realm_in_trust_namespace(self.api, *keys)
ensure_krbcanonicalname_set(ldap, entry_attrs)
return dn
class baseuser_remove_principal(LDAPRemoveAttribute):
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
ensure_last_krbprincipalname(ldap, entry_attrs, *keys)
return dn
class baseuser_add_cert(LDAPAddAttributeViaOption):
attribute = 'usercertificate'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
self.obj.convert_usercertificate_pre(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_usercertificate_post(entry_attrs, **options)
return dn
class baseuser_remove_cert(LDAPRemoveAttributeViaOption):
attribute = 'usercertificate'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
self.obj.convert_usercertificate_pre(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_usercertificate_post(entry_attrs, **options)
return dn
class ModCertMapData(LDAPModAttribute):
attribute = 'ipacertmapdata'
takes_options = (
DNParam(
'issuer?',
cli_name='issuer',
label=_('Issuer'),
doc=_('Issuer of the certificate'),
flags=['virtual_attribute']
),
DNParam(
'subject?',
cli_name='subject',
label=_('Subject'),
doc=_('Subject of the certificate'),
flags=['virtual_attribute']
),
Certificate(
'certificate*',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded user certificate'),
flags=['virtual_attribute']
),
)
@staticmethod
def _build_mapdata(subject, issuer):
return u'X509:<I>{issuer}<S>{subject}'.format(
issuer=issuer.x500_text(), subject=subject.x500_text())
@classmethod
def _convert_options_to_certmap(cls, entry_attrs, issuer=None,
subject=None, certificates=()):
"""
Converts options to ipacertmapdata
When --subject --issuer or --certificate options are used,
the value for ipacertmapdata is built from extracting subject and
issuer,
converting their values to X500 ordering and using the format
X509:<I>issuer<S>subject
For instance:
X509:<I>O=DOMAIN,CN=Certificate Authority<S>O=DOMAIN,CN=user
A list of values can be returned if --certificate is used multiple
times, or in conjunction with --subject --issuer.
"""
data = []
data.extend(entry_attrs.get(cls.attribute, list()))
if issuer or subject:
data.append(cls._build_mapdata(subject, issuer))
for cert in certificates:
issuer = DN(cert.issuer)
subject = DN(cert.subject)
if not subject:
raise errors.ValidationError(
name='certificate',
error=_('cannot have an empty subject'))
data.append(cls._build_mapdata(subject, issuer))
entry_attrs[cls.attribute] = data
def get_args(self):
# ipacertmapdata is not mandatory as it can be built
# from the values subject+issuer or from reading certificate
for arg in super(ModCertMapData, self).get_args():
if arg.name == 'ipacertmapdata':
yield arg.clone(required=False, alwaysask=False)
else:
yield arg.clone()
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
# The 3 valid calls are
# ipa user-add-certmapdata LOGIN --subject xx --issuer yy
# ipa user-add-certmapdata LOGIN [DATA] --certificate xx
# ipa user-add-certmapdata LOGIN DATA
# Check that at least one of the 3 formats is used
try:
certmapdatas = keys[1] or []
except IndexError:
certmapdatas = []
issuer = options.get('issuer')
subject = options.get('subject')
certificates = options.get('certificate', [])
# If only LOGIN is supplied, then we need either subject or issuer or
# certificate
if (not certmapdatas and not issuer and not subject and
not certificates):
raise errors.RequirementError(name='ipacertmapdata')
# If subject or issuer is provided, other options are not allowed
if subject or issuer:
if certificates:
raise errors.MutuallyExclusiveError(
reason=_('cannot specify both subject/issuer '
'and certificate'))
if certmapdatas:
raise errors.MutuallyExclusiveError(
reason=_('cannot specify both subject/issuer '
'and ipacertmapdata'))
# If subject or issuer is provided, then the other one is required
if not subject:
raise errors.RequirementError(name='subject')
if not issuer:
raise errors.RequirementError(name='issuer')
# if the command is called with --subject --issuer or --certificate
# we need to add ipacertmapdata to the attrs_list in order to
# display the resulting value in the command output
if 'ipacertmapdata' not in attrs_list:
attrs_list.append('ipacertmapdata')
self._convert_options_to_certmap(
entry_attrs,
issuer=issuer,
subject=subject,
certificates=certificates)
return dn
class baseuser_add_certmapdata(ModCertMapData, LDAPAddAttribute):
__doc__ = _("Add one or more certificate mappings to the user entry.")
msg_summary = _('Added certificate mappings to user "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
dn = super(baseuser_add_certmapdata, self).pre_callback(
ldap, dn, entry_attrs, attrs_list, *keys, **options)
# The objectclass ipacertmapobject may not be present on
# existing user entries. We need to add it if we define a new
# value for ipacertmapdata
add_missing_object_class(ldap, u'ipacertmapobject', dn)
return dn
class baseuser_remove_certmapdata(ModCertMapData,
LDAPRemoveAttribute):
__doc__ = _("Remove one or more certificate mappings from the user entry.")
msg_summary = _('Removed certificate mappings from user "%(value)s"')
class ModPassKey(LDAPModAttribute):
attribute = 'ipapasskey'
class baseuser_add_passkey(ModPassKey, LDAPAddAttribute):
__doc__ = _("Add one or more passkey mappings to the user entry.")
msg_summary = _('Added passkey mappings to user "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
dn = super(baseuser_add_passkey, self).pre_callback(
ldap, dn, entry_attrs, attrs_list, *keys, **options)
# The objectclass ipafpasskeyuser may not be present on
# existing user entries. We need to add it if we define a new
# value for ipapasskey
add_missing_object_class(ldap, u'ipapasskeyuser', dn)
return dn
class baseuser_remove_passkey(ModPassKey, LDAPRemoveAttribute):
__doc__ = _("Remove one or more passkey mappings from the user entry.")
msg_summary = _('Removed passkey mappings from user "%(value)s"')
| 41,239
|
Python
|
.py
| 953
| 32.558237
| 127
| 0.591243
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,831
|
vault.py
|
freeipa_freeipa/ipaserver/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/>.
import six
from ipalib.frontend import Command, Object
from ipalib import api, errors
from ipalib import Bytes, Flag, Str, StrEnum
from ipalib import output
from ipalib.constants import (
VAULT_WRAPPING_SUPPORTED_ALGOS, VAULT_WRAPPING_DEFAULT_ALGO,
VAULT_WRAPPING_3DES, VAULT_WRAPPING_AES128_CBC,
)
from ipalib.crud import PKQuery, Retrieve
from ipalib.parameters import Principal
from ipalib.plugable import Registry
from .baseldap import LDAPObject, LDAPCreate, LDAPDelete,\
LDAPSearch, LDAPUpdate, LDAPRetrieve, LDAPAddMember, LDAPRemoveMember,\
LDAPModMember, pkey_to_value
from ipalib.request import context
from .service import normalize_principal, validate_realm
from ipalib import _, ngettext
from ipapython import kerberos
from ipapython.dn import DN
from ipaserver.masters import is_service_enabled
if api.env.in_server:
import pki.account
import pki.key
from pki.crypto import DES_EDE3_CBC_OID
from pki.crypto import AES_128_CBC_OID
from pki import PKIException
if six.PY3:
unicode = str
__doc__ = _("""
Vaults
""") + _("""
Manage vaults.
""") + _("""
Vault is a secure place to store a secret. One vault can only
store one secret. When archiving a secret in a vault, the
existing secret (if any) is overwritten.
""") + _("""
Based on the ownership there are three vault categories:
* user/private vault
* service vault
* shared vault
""") + _("""
User vaults are vaults owned used by a particular user. Private
vaults are vaults owned the current user. Service vaults are
vaults owned by a service. Shared vaults are owned by the admin
but they can be used by other users or services.
""") + _("""
Based on the security mechanism there are three types of
vaults:
* standard vault
* symmetric vault
* asymmetric vault
""") + _("""
Standard vault uses a secure mechanism to transport and
store the secret. The secret can only be retrieved by users
that have access to the vault.
""") + _("""
Symmetric vault is similar to the standard vault, but it
pre-encrypts the secret using a password before transport.
The secret can only be retrieved using the same password.
""") + _("""
Asymmetric vault is similar to the standard vault, but it
pre-encrypts the secret using a public key before transport.
The secret can only be retrieved using the private key.
""") + _("""
EXAMPLES:
""") + _("""
List vaults:
ipa vault-find
[--user <user>|--service <service>|--shared]
""") + _("""
Add a standard vault:
ipa vault-add <name>
[--user <user>|--service <service>|--shared]
--type standard
""") + _("""
Add a symmetric vault:
ipa vault-add <name>
[--user <user>|--service <service>|--shared]
--type symmetric --password-file password.txt
""") + _("""
Add an asymmetric vault:
ipa vault-add <name>
[--user <user>|--service <service>|--shared]
--type asymmetric --public-key-file public.pem
""") + _("""
Show a vault:
ipa vault-show <name>
[--user <user>|--service <service>|--shared]
""") + _("""
Modify vault description:
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--desc <description>
""") + _("""
Modify vault type:
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--type <type>
[old password/private key]
[new password/public key]
""") + _("""
Modify symmetric vault password:
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--change-password
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--old-password <old password>
--new-password <new password>
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--old-password-file <old password file>
--new-password-file <new password file>
""") + _("""
Modify asymmetric vault keys:
ipa vault-mod <name>
[--user <user>|--service <service>|--shared]
--private-key-file <old private key file>
--public-key-file <new public key file>
""") + _("""
Delete a vault:
ipa vault-del <name>
[--user <user>|--service <service>|--shared]
""") + _("""
Display vault configuration:
ipa vaultconfig-show
""") + _("""
Archive data into standard vault:
ipa vault-archive <name>
[--user <user>|--service <service>|--shared]
--in <input file>
""") + _("""
Archive data into symmetric vault:
ipa vault-archive <name>
[--user <user>|--service <service>|--shared]
--in <input file>
--password-file password.txt
""") + _("""
Archive data into asymmetric vault:
ipa vault-archive <name>
[--user <user>|--service <service>|--shared]
--in <input file>
""") + _("""
Retrieve data from standard vault:
ipa vault-retrieve <name>
[--user <user>|--service <service>|--shared]
--out <output file>
""") + _("""
Retrieve data from symmetric vault:
ipa vault-retrieve <name>
[--user <user>|--service <service>|--shared]
--out <output file>
--password-file password.txt
""") + _("""
Retrieve data from asymmetric vault:
ipa vault-retrieve <name>
[--user <user>|--service <service>|--shared]
--out <output file> --private-key-file private.pem
""") + _("""
Add vault owners:
ipa vault-add-owner <name>
[--user <user>|--service <service>|--shared]
[--users <users>] [--groups <groups>] [--services <services>]
""") + _("""
Delete vault owners:
ipa vault-remove-owner <name>
[--user <user>|--service <service>|--shared]
[--users <users>] [--groups <groups>] [--services <services>]
""") + _("""
Add vault members:
ipa vault-add-member <name>
[--user <user>|--service <service>|--shared]
[--users <users>] [--groups <groups>] [--services <services>]
""") + _("""
Delete vault members:
ipa vault-remove-member <name>
[--user <user>|--service <service>|--shared]
[--users <users>] [--groups <groups>] [--services <services>]
""")
register = Registry()
vault_options = (
Principal(
'service?',
validate_realm,
doc=_('Service name of the service vault'),
normalizer=normalize_principal,
),
Flag(
'shared?',
doc=_('Shared vault'),
),
Str(
'username?',
cli_name='user',
doc=_('Username of the user vault'),
),
)
class VaultModMember(LDAPModMember):
def get_options(self):
for param in super(VaultModMember, self).get_options():
if param.name == 'service' and param not in vault_options:
param = param.clone_rename('services')
yield param
def get_member_dns(self, **options):
if 'services' in options:
options['service'] = options.pop('services')
else:
options.pop('service', None)
return super(VaultModMember, self).get_member_dns(**options)
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
for fail in failed.values():
fail['services'] = fail.pop('service', [])
self.obj.get_container_attribute(entry_attrs, options)
return completed, dn
@register()
class vaultcontainer(LDAPObject):
__doc__ = _("""
Vault Container object.
""")
container_dn = api.env.container_vault
object_name = _('vaultcontainer')
object_name_plural = _('vaultcontainers')
object_class = ['ipaVaultContainer']
permission_filter_objectclasses = ['ipaVaultContainer']
attribute_members = {
'owner': ['user', 'group', 'service'],
}
label = _('Vault Containers')
label_singular = _('Vault Container')
managed_permissions = {
'System: Read Vault Containers': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description', 'owner',
},
'default_privileges': {'Vault Administrators'},
},
'System: Add Vault Containers': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'add'},
'default_privileges': {'Vault Administrators'},
},
'System: Delete Vault Containers': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'delete'},
'default_privileges': {'Vault Administrators'},
},
'System: Modify Vault Containers': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'write'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description',
},
'default_privileges': {'Vault Administrators'},
},
'System: Manage Vault Container Ownership': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'write'},
'ipapermdefaultattr': {
'owner',
},
'default_privileges': {'Vault Administrators'},
},
}
takes_params = (
Str(
'owner_user?',
label=_('Owner users'),
),
Str(
'owner_group?',
label=_('Owner groups'),
),
Str(
'owner_service?',
label=_('Owner services'),
),
Str(
'owner?',
label=_('Failed owners'),
),
Str(
'service?',
label=_('Vault service'),
flags={'virtual_attribute'},
),
Flag(
'shared?',
label=_('Shared vault'),
flags={'virtual_attribute'},
),
Str(
'username?',
label=_('Vault user'),
flags={'virtual_attribute'},
),
)
def get_dn(self, *keys, **options):
"""
Generates vault DN from parameters.
"""
service = options.get('service')
shared = options.get('shared')
user = options.get('username')
count = (bool(service) + bool(shared) + bool(user))
if count > 1:
raise errors.MutuallyExclusiveError(
reason=_('Service, shared and user options ' +
'cannot be specified simultaneously'))
parent_dn = super(vaultcontainer, self).get_dn(*keys, **options)
if not count:
principal = kerberos.Principal(getattr(context, 'principal'))
if principal.is_host:
raise errors.NotImplementedError(
reason=_('Host is not supported'))
elif principal.is_service:
service = unicode(principal)
else:
user = principal.username
if service:
dn = DN(('cn', service), ('cn', 'services'), parent_dn)
elif shared:
dn = DN(('cn', 'shared'), parent_dn)
elif user:
dn = DN(('cn', user), ('cn', 'users'), parent_dn)
else:
raise RuntimeError
return dn
def get_container_attribute(self, entry, options):
if options.get('raw', False):
return
container_dn = DN(self.container_dn, self.api.env.basedn)
if entry.dn.endswith(DN(('cn', 'services'), container_dn)):
entry['service'] = entry.dn[0]['cn']
elif entry.dn.endswith(DN(('cn', 'shared'), container_dn)):
entry['shared'] = True
elif entry.dn.endswith(DN(('cn', 'users'), container_dn)):
entry['username'] = entry.dn[0]['cn']
@register()
class vaultcontainer_show(LDAPRetrieve):
__doc__ = _('Display information about a vault container.')
takes_options = LDAPRetrieve.takes_options + vault_options
has_output_params = LDAPRetrieve.has_output_params
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.get_container_attribute(entry_attrs, options)
return dn
@register()
class vaultcontainer_del(LDAPDelete):
__doc__ = _('Delete a vault container.')
takes_options = LDAPDelete.takes_options + vault_options
msg_summary = _('Deleted vault container')
subtree_delete = False
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
return dn
def execute(self, *keys, **options):
keys = keys + (u'',)
return super(vaultcontainer_del, self).execute(*keys, **options)
@register()
class vaultcontainer_add_owner(VaultModMember, LDAPAddMember):
__doc__ = _('Add owners to a vault container.')
takes_options = LDAPAddMember.takes_options + vault_options
member_attributes = ['owner']
member_param_label = _('owner %s')
member_count_out = ('%i owner added.', '%i owners added.')
has_output = (
output.Entry('result'),
output.Output(
'failed',
type=dict,
doc=_('Owners that could not be added'),
),
output.Output(
'completed',
type=int,
doc=_('Number of owners added'),
),
)
@register()
class vaultcontainer_remove_owner(VaultModMember, LDAPRemoveMember):
__doc__ = _('Remove owners from a vault container.')
takes_options = LDAPRemoveMember.takes_options + vault_options
member_attributes = ['owner']
member_param_label = _('owner %s')
member_count_out = ('%i owner removed.', '%i owners removed.')
has_output = (
output.Entry('result'),
output.Output(
'failed',
type=dict,
doc=_('Owners that could not be removed'),
),
output.Output(
'completed',
type=int,
doc=_('Number of owners removed'),
),
)
@register()
class vault(LDAPObject):
__doc__ = _("""
Vault object.
""")
container_dn = api.env.container_vault
object_name = _('vault')
object_name_plural = _('vaults')
object_class = ['ipaVault']
permission_filter_objectclasses = ['ipaVault']
default_attributes = [
'cn',
'description',
'ipavaulttype',
'ipavaultsalt',
'ipavaultpublickey',
'owner',
'member',
]
search_display_attributes = [
'cn',
'description',
'ipavaulttype',
]
attribute_members = {
'owner': ['user', 'group', 'service'],
'member': ['user', 'group', 'service'],
}
label = _('Vaults')
label_singular = _('Vault')
managed_permissions = {
'System: Read Vaults': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description', 'ipavaulttype',
'ipavaultsalt', 'ipavaultpublickey', 'owner', 'member',
'memberuser', 'memberhost',
},
'default_privileges': {'Vault Administrators'},
},
'System: Add Vaults': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'add'},
'default_privileges': {'Vault Administrators'},
},
'System: Delete Vaults': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'delete'},
'default_privileges': {'Vault Administrators'},
},
'System: Modify Vaults': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'write'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description', 'ipavaulttype',
'ipavaultsalt', 'ipavaultpublickey',
},
'default_privileges': {'Vault Administrators'},
},
'System: Manage Vault Ownership': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'write'},
'ipapermdefaultattr': {
'owner',
},
'default_privileges': {'Vault Administrators'},
},
'System: Manage Vault Membership': {
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN(api.env.container_vault, api.env.basedn),
'ipapermright': {'write'},
'ipapermdefaultattr': {
'member',
},
'default_privileges': {'Vault Administrators'},
},
}
takes_params = (
Str(
'cn',
cli_name='name',
label=_('Vault name'),
primary_key=True,
pattern='^[a-zA-Z0-9_.-]+$',
pattern_errmsg='may only include letters, numbers, _, ., and -',
maxlength=255,
),
Str(
'description?',
cli_name='desc',
label=_('Description'),
doc=_('Vault description'),
),
StrEnum(
'ipavaulttype?',
cli_name='type',
label=_('Type'),
doc=_('Vault type'),
values=(u'standard', u'symmetric', u'asymmetric', ),
default=u'symmetric',
autofill=True,
),
Bytes(
'ipavaultsalt?',
cli_name='salt',
label=_('Salt'),
doc=_('Vault salt'),
flags=['no_search'],
),
Bytes(
'ipavaultpublickey?',
cli_name='public_key',
label=_('Public key'),
doc=_('Vault public key'),
flags=['no_search'],
),
Str(
'owner_user?',
label=_('Owner users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str(
'owner_group?',
label=_('Owner groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str(
'owner_service?',
label=_('Owner services'),
flags=['no_create', 'no_update', 'no_search'],
),
Str(
'owner?',
label=_('Failed owners'),
flags=['no_create', 'no_update', 'no_search'],
),
Str(
'service?',
label=_('Vault service'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Flag(
'shared?',
label=_('Shared vault'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str(
'username?',
label=_('Vault user'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
)
def _translate_algorithm(self, name):
if name is None:
name = VAULT_WRAPPING_DEFAULT_ALGO
if name not in VAULT_WRAPPING_SUPPORTED_ALGOS:
msg = _("{algo} is not a supported vault wrapping algorithm")
raise errors.ValidationError(msg.format(algo=name))
if name == VAULT_WRAPPING_3DES:
return DES_EDE3_CBC_OID
elif name == VAULT_WRAPPING_AES128_CBC:
return AES_128_CBC_OID
else:
# unreachable
raise ValueError(name)
def get_dn(self, *keys, **options):
"""
Generates vault DN from parameters.
"""
service = options.get('service')
shared = options.get('shared')
user = options.get('username')
count = (bool(service) + bool(shared) + bool(user))
if count > 1:
raise errors.MutuallyExclusiveError(
reason=_('Service, shared, and user options ' +
'cannot be specified simultaneously'))
# TODO: create container_dn after object initialization then reuse it
container_dn = DN(self.container_dn, self.api.env.basedn)
dn = super(vault, self).get_dn(*keys, **options)
assert dn.endswith(container_dn)
rdns = DN(*dn[:-len(container_dn)])
if not count:
principal = kerberos.Principal(getattr(context, 'principal'))
if principal.is_host:
raise errors.NotImplementedError(
reason=_('Host is not supported'))
elif principal.is_service:
service = unicode(principal)
else:
user = principal.username
if service:
parent_dn = DN(('cn', service), ('cn', 'services'), container_dn)
elif shared:
parent_dn = DN(('cn', 'shared'), container_dn)
elif user:
parent_dn = DN(('cn', user), ('cn', 'users'), container_dn)
else:
raise RuntimeError
return DN(rdns, parent_dn)
def create_container(self, dn, owner_dn):
"""
Creates vault container and its parents.
"""
# TODO: create container_dn after object initialization then reuse it
container_dn = DN(self.container_dn, self.api.env.basedn)
entries = []
while dn:
assert dn.endswith(container_dn)
rdn = dn[0]
entry = self.backend.make_entry(
dn,
{
'objectclass': ['ipaVaultContainer'],
'cn': rdn['cn'],
'owner': [owner_dn],
})
# if entry can be added, return
try:
self.backend.add_entry(entry)
break
except errors.NotFound:
pass
# otherwise, create parent entry first
dn = DN(*dn[1:])
entries.insert(0, entry)
# then create the entries again
for entry in entries:
self.backend.add_entry(entry)
def get_key_id(self, dn):
"""
Generates a client key ID to archive/retrieve data in KRA.
"""
# TODO: create container_dn after object initialization then reuse it
container_dn = DN(self.container_dn, self.api.env.basedn)
# make sure the DN is a vault DN
if not dn.endswith(container_dn, 1):
raise ValueError('Invalid vault DN: %s' % dn)
# construct the vault ID from the bottom up
id = u''
for rdn in dn[:-len(container_dn)]:
name = rdn['cn']
id = u'/' + name + id
return 'ipa:' + id
def get_container_attribute(self, entry, options):
if options.get('raw', False):
return
container_dn = DN(self.container_dn, self.api.env.basedn)
if entry.dn.endswith(DN(('cn', 'services'), container_dn)):
entry['service'] = entry.dn[1]['cn']
elif entry.dn.endswith(DN(('cn', 'shared'), container_dn)):
entry['shared'] = True
elif entry.dn.endswith(DN(('cn', 'users'), container_dn)):
entry['username'] = entry.dn[1]['cn']
@register()
class vault_add_internal(LDAPCreate):
__doc__ = _('Add a vault.')
NO_CLI = True
takes_options = LDAPCreate.takes_options + vault_options
msg_summary = _('Added vault "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
principal = kerberos.Principal(getattr(context, 'principal'))
if principal.is_service:
owner_dn = self.api.Object.service.get_dn(unicode(principal))
else:
owner_dn = self.api.Object.user.get_dn(principal.username)
parent_dn = DN(*dn[1:])
try:
self.obj.create_container(parent_dn, owner_dn)
except (errors.DuplicateEntry, errors.ACIError):
pass
# vault should be owned by the creator
entry_attrs['owner'] = owner_dn
return dn
def post_callback(self, ldap, dn, entry, *keys, **options):
self.obj.get_container_attribute(entry, options)
return dn
@register()
class vault_del(LDAPDelete):
__doc__ = _('Delete a vault.')
takes_options = LDAPDelete.takes_options + vault_options
msg_summary = _('Deleted vault "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
return dn
def post_callback(self, ldap, dn, *args, **options):
assert isinstance(dn, DN)
with self.api.Backend.kra.get_client() as kra_client:
# pylint: disable=used-before-assignment
kra_account = pki.account.AccountClient(kra_client.connection)
# pylint: enable=used-before-assignment
kra_account.login()
client_key_id = self.obj.get_key_id(dn)
# deactivate vault record in KRA
response = kra_client.keys.list_keys(
client_key_id, pki.key.KeyClient.KEY_STATUS_ACTIVE)
for key_info in response.key_infos:
kra_client.keys.modify_key_status(
key_info.get_key_id(),
pki.key.KeyClient.KEY_STATUS_INACTIVE)
kra_account.logout()
return True
@register()
class vault_find(LDAPSearch):
__doc__ = _('Search for vaults.')
takes_options = LDAPSearch.takes_options + vault_options + (
Flag(
'services?',
doc=_('List all service vaults'),
),
Flag(
'users?',
doc=_('List all user vaults'),
),
)
has_output_params = LDAPSearch.has_output_params
msg_summary = ngettext(
'%(count)d vault matched',
'%(count)d vaults matched',
0,
)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args,
**options):
assert isinstance(base_dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
if options.get('users') or options.get('services'):
mutex = ['service', 'services', 'shared', 'username', 'users']
count = sum(bool(options.get(option)) for option in mutex)
if count > 1:
raise errors.MutuallyExclusiveError(
reason=_('Service(s), shared, and user(s) options ' +
'cannot be specified simultaneously'))
scope = ldap.SCOPE_SUBTREE
container_dn = DN(self.obj.container_dn,
self.api.env.basedn)
if options.get('services'):
base_dn = DN(('cn', 'services'), container_dn)
else:
base_dn = DN(('cn', 'users'), container_dn)
else:
base_dn = self.obj.get_dn(None, **options)
return filter, base_dn, scope
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry in entries:
self.obj.get_container_attribute(entry, options)
return truncated
def exc_callback(self, args, options, exc, call_func, *call_args,
**call_kwargs):
if call_func.__name__ == 'find_entries':
if isinstance(exc, errors.NotFound):
# ignore missing containers since they will be created
# automatically on vault creation.
raise errors.EmptyResult(reason=str(exc))
raise exc
@register()
class vault_mod_internal(LDAPUpdate):
__doc__ = _('Modify a vault.')
NO_CLI = True
takes_options = LDAPUpdate.takes_options + vault_options
msg_summary = _('Modified vault "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list,
*keys, **options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.get_container_attribute(entry_attrs, options)
return dn
@register()
class vault_show(LDAPRetrieve):
__doc__ = _('Display information about a vault.')
takes_options = LDAPRetrieve.takes_options + vault_options
has_output_params = LDAPRetrieve.has_output_params
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.get_container_attribute(entry_attrs, options)
return dn
@register()
class vaultconfig(Object):
__doc__ = _('Vault configuration')
takes_params = (
Bytes(
'transport_cert',
label=_('Transport Certificate'),
),
Str(
'kra_server_server*',
label=_('IPA KRA servers'),
doc=_('IPA servers configured as key recovery agents'),
flags={'virtual_attribute', 'no_create', 'no_update'}
)
)
@register()
class vaultconfig_show(Retrieve):
__doc__ = _('Show vault configuration.')
takes_options = (
Str(
'transport_out?',
doc=_('Output file to store the transport certificate'),
),
)
def execute(self, *args, **options):
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
config = dict(
wrapping_supported_algorithms=VAULT_WRAPPING_SUPPORTED_ALGOS,
wrapping_default_algorithm=VAULT_WRAPPING_DEFAULT_ALGO,
)
with self.api.Backend.kra.get_client() as kra_client:
transport_cert = kra_client.system_certs.get_transport_cert()
config['transport_cert'] = transport_cert.binary
self.api.Object.config.show_servroles_attributes(
config, "KRA server", **options)
return {
'result': config,
'value': None,
}
@register()
class vault_archive_internal(PKQuery):
__doc__ = _('Archive data into a vault.')
NO_CLI = True
takes_options = vault_options + (
Bytes(
'session_key',
doc=_('Session key wrapped with transport certificate'),
),
Bytes(
'vault_data',
doc=_('Vault data encrypted with session key'),
),
Bytes(
'nonce',
doc=_('Nonce'),
),
StrEnum(
'wrapping_algo?',
doc=_('Key wrapping algorithm'),
values=VAULT_WRAPPING_SUPPORTED_ALGOS,
default=VAULT_WRAPPING_3DES,
autofill=True,
),
)
has_output = output.standard_entry
msg_summary = _('Archived data into vault "%(value)s"')
def execute(self, *args, **options):
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
wrapped_vault_data = options.pop('vault_data')
nonce = options.pop('nonce')
wrapped_session_key = options.pop('session_key')
wrapping_algo = options.pop('wrapping_algo', None)
algorithm_oid = self.obj._translate_algorithm(wrapping_algo)
# retrieve vault info
vault = self.api.Command.vault_show(*args, **options)['result']
# connect to KRA
with self.api.Backend.kra.get_client() as kra_client:
kra_account = pki.account.AccountClient(kra_client.connection)
kra_account.login()
client_key_id = self.obj.get_key_id(vault['dn'])
# deactivate existing vault record in KRA
response = kra_client.keys.list_keys(
client_key_id,
pki.key.KeyClient.KEY_STATUS_ACTIVE)
for key_info in response.key_infos:
kra_client.keys.modify_key_status(
key_info.get_key_id(),
pki.key.KeyClient.KEY_STATUS_INACTIVE)
# forward wrapped data to KRA
try:
kra_client.keys.archive_encrypted_data(
client_key_id,
pki.key.KeyClient.PASS_PHRASE_TYPE,
wrapped_vault_data,
wrapped_session_key,
algorithm_oid=algorithm_oid,
nonce_iv=nonce,
)
except PKIException as e:
kra_account.logout()
raise errors.EncodingError(
message=_("Unable to archive key: %s") % e)
finally:
kra_account.logout()
response = {
'value': args[-1],
'result': {},
}
response['summary'] = self.msg_summary % response
return response
@register()
class vault_retrieve_internal(PKQuery):
__doc__ = _('Retrieve data from a vault.')
NO_CLI = True
takes_options = vault_options + (
Bytes(
'session_key',
doc=_('Session key wrapped with transport certificate'),
),
StrEnum(
'wrapping_algo?',
doc=_('Key wrapping algorithm'),
values=VAULT_WRAPPING_SUPPORTED_ALGOS,
default=VAULT_WRAPPING_3DES,
autofill=True,
),
)
has_output = output.standard_entry
msg_summary = _('Retrieved data from vault "%(value)s"')
def execute(self, *args, **options):
if not self.api.Command.kra_is_enabled()['result']:
raise errors.InvocationError(
format=_('KRA service is not enabled'))
wrapped_session_key = options.pop('session_key')
wrapping_algo = options.pop('wrapping_algo', None)
algorithm_oid = self.obj._translate_algorithm(wrapping_algo)
# retrieve vault info
vault = self.api.Command.vault_show(*args, **options)['result']
# connect to KRA
with self.api.Backend.kra.get_client() as kra_client:
kra_account = pki.account.AccountClient(kra_client.connection)
kra_account.login()
client_key_id = self.obj.get_key_id(vault['dn'])
# find vault record in KRA
response = kra_client.keys.list_keys(
client_key_id,
pki.key.KeyClient.KEY_STATUS_ACTIVE)
if not len(response.key_infos):
raise errors.NotFound(reason=_('No archived data.'))
key_info = response.key_infos[0]
# XXX hack
kra_client.keys.encrypt_alg_oid = algorithm_oid
# retrieve encrypted data from KRA
try:
key = kra_client.keys.retrieve_key(
key_info.get_key_id(),
wrapped_session_key)
except PKIException as e:
kra_account.logout()
raise errors.EncodingError(
message=_("Unable to retrieve key: %s") % e)
finally:
kra_account.logout()
response = {
'value': args[-1],
'result': {
'vault_data': key.encrypted_data,
'nonce': key.nonce_data,
},
}
response['summary'] = self.msg_summary % response
return response
@register()
class vault_add_owner(VaultModMember, LDAPAddMember):
__doc__ = _('Add owners to a vault.')
takes_options = LDAPAddMember.takes_options + vault_options
member_attributes = ['owner']
member_param_label = _('owner %s')
member_count_out = ('%i owner added.', '%i owners added.')
has_output = (
output.Entry('result'),
output.Output(
'failed',
type=dict,
doc=_('Owners that could not be added'),
),
output.Output(
'completed',
type=int,
doc=_('Number of owners added'),
),
)
@register()
class vault_remove_owner(VaultModMember, LDAPRemoveMember):
__doc__ = _('Remove owners from a vault.')
takes_options = LDAPRemoveMember.takes_options + vault_options
member_attributes = ['owner']
member_param_label = _('owner %s')
member_count_out = ('%i owner removed.', '%i owners removed.')
has_output = (
output.Entry('result'),
output.Output(
'failed',
type=dict,
doc=_('Owners that could not be removed'),
),
output.Output(
'completed',
type=int,
doc=_('Number of owners removed'),
),
)
@register()
class vault_add_member(VaultModMember, LDAPAddMember):
__doc__ = _('Add members to a vault.')
takes_options = LDAPAddMember.takes_options + vault_options
@register()
class vault_remove_member(VaultModMember, LDAPRemoveMember):
__doc__ = _('Remove members from a vault.')
takes_options = LDAPRemoveMember.takes_options + vault_options
@register()
class kra_is_enabled(Command):
__doc__ = _('Checks if any of the servers has the KRA service enabled')
NO_CLI = True
has_output = output.standard_value
def execute(self, *args, **options):
result = is_service_enabled('KRA', conn=self.api.Backend.ldap2)
return dict(result=result, value=pkey_to_value(None, options))
| 39,630
|
Python
|
.py
| 1,065
| 28.048826
| 88
| 0.574308
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,832
|
dnsserver.py
|
freeipa_freeipa/ipaserver/plugins/dnsserver.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
from ipalib import (
_,
ngettext,
api,
DNSNameParam,
Str,
StrEnum,
errors,
)
from ipalib.frontend import Local
from ipalib.plugable import Registry
from ipalib.util import (
normalize_hostname,
hostname_validator,
validate_bind_forwarder,
)
from ipaserver.plugins.baseldap import (
LDAPObject,
LDAPRetrieve,
LDAPUpdate,
LDAPSearch,
LDAPCreate,
LDAPDelete,
)
from .dns import dns_container_exists
from ipapython.dn import DN
__doc__ = _("""
DNS server configuration
""") + _("""
Manipulate DNS server configuration
""") + _("""
EXAMPLES:
""") + _("""
Show configuration of a specific DNS server:
ipa dnsserver-show
""") + _("""
Update configuration of a specific DNS server:
ipa dnsserver-mod
""")
register = Registry()
topic = None
dnsserver_object_class = ['top', 'idnsServerConfigObject']
@register()
class dnsserver(LDAPObject):
"""
DNS Servers
"""
container_dn = api.env.container_dnsservers
object_name = _('DNS server')
object_name_plural = _('DNS servers')
object_class = dnsserver_object_class
default_attributes = [
'idnsServerId',
'idnsSOAmName',
'idnsForwarders',
'idnsForwardPolicy',
]
label = _('DNS Servers')
label_singular = _('DNS Server')
permission_filter_objectclasses = ['idnsServerConfigObject']
managed_permissions = {
'System: Read DNS Servers Configuration': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass',
'idnsServerId',
'idnsSOAmName',
'idnsForwarders',
'idnsForwardPolicy',
'idnsSubstitutionVariable',
},
'ipapermlocation': api.env.basedn,
'default_privileges': {
'DNS Servers',
'DNS Administrators'
},
},
'System: Modify DNS Servers Configuration': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'idnsSOAmName',
'idnsForwarders',
'idnsForwardPolicy',
'idnsSubstitutionVariable',
},
'ipapermlocation': api.env.basedn,
'default_privileges': {'DNS Administrators'},
},
}
takes_params = (
Str(
'idnsserverid',
hostname_validator,
cli_name='hostname',
primary_key=True,
label=_('Server name'),
doc=_('DNS Server name'),
normalizer=normalize_hostname,
),
DNSNameParam(
'idnssoamname?',
cli_name='soa_mname_override',
label=_('SOA mname override'),
doc=_('SOA mname (authoritative server) override'),
),
Str(
'idnsforwarders*',
validate_bind_forwarder,
cli_name='forwarder',
label=_('Forwarders'),
doc=_(
'Per-server forwarders. A custom port can be specified '
'for each forwarder using a standard format '
'"IP_ADDRESS port PORT"'
),
),
StrEnum(
'idnsforwardpolicy?',
cli_name='forward_policy',
label=_('Forward policy'),
doc=_(
'Per-server conditional forwarding policy. Set to "none" to '
'disable forwarding to global forwarder for this zone. In '
'that case, conditional zone forwarders are disregarded.'
),
values=(u'only', u'first', u'none'),
),
)
def get_dn(self, *keys, **options):
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('DNS is not configured'))
return super(dnsserver, self).get_dn(*keys, **options)
@register()
class dnsserver_mod(LDAPUpdate):
__doc__ = _('Modify DNS server configuration')
topic = 'dns'
msg_summary = _('Modified DNS server "%(value)s"')
@register()
class dnsserver_find(LDAPSearch):
__doc__ = _('Search for DNS servers.')
topic = 'dns'
msg_summary = ngettext(
'%(count)d DNS server matched',
'%(count)d DNS servers matched', 0
)
def pre_callback(self, ldap, filters, attrs_list,
base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.InvocationError(
format=_('IPA DNS Server is not installed'))
return (filters, base_dn, scope)
@register()
class dnsserver_show(LDAPRetrieve):
__doc__=_('Display configuration of a DNS server.')
topic = 'dns'
@register()
class dnsserver_add(LDAPCreate, Local):
"""
Only for internal use, this is not part of public API on purpose.
Be careful in future this will be transformed to public API call
"""
__doc__ = _('Add a new DNS server.')
topic = 'dns'
msg_summary = _('Added new DNS server "%(value)s"')
@register()
class dnsserver_del(LDAPDelete, Local):
"""
Only for internal use, this is not part of public API on purpose.
Be careful in future this will be transformed to public API call
"""
__doc__ = _('Delete a DNS server')
topic = 'dns'
msg_summary = _('Deleted DNS server "%(value)s"')
| 5,570
|
Python
|
.py
| 178
| 23.488764
| 77
| 0.587654
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,833
|
automember.py
|
freeipa_freeipa/ipaserver/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/>.
import uuid
import time
import ldap as _ldap
import six
from ipalib import api, errors, Str, StrEnum, DNParam, Flag, _, ngettext
from ipalib import output, Method, Object
from ipalib.plugable import Registry
from .baseldap import (
pkey_to_value,
entry_to_dict,
LDAPObject,
LDAPCreate,
LDAPUpdate,
LDAPDelete,
LDAPSearch,
LDAPRetrieve)
from ipalib.request import context
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Auto Membership Rule.
""") + _("""
Bring clarity to the membership of hosts and users by configuring inclusive
or exclusive regex patterns, you can automatically assign a new entries into
a group or hostgroup based upon attribute information.
""") + _("""
A rule is directly associated with a group by name, so you cannot create
a rule without an accompanying group or hostgroup.
""") + _("""
A condition is a regular expression used by 389-ds to match a new incoming
entry with an automember rule. If it matches an inclusive rule then the
entry is added to the appropriate group or hostgroup.
""") + _("""
A default group or hostgroup could be specified for entries that do not
match any rule. In case of user entries this group will be a fallback group
because all users are by default members of group specified in IPA config.
""") + _("""
The automember-rebuild command can be used to retroactively run automember rules
against existing entries, thus rebuilding their membership.
""") + _("""
EXAMPLES:
""") + _("""
Add the initial group or hostgroup:
ipa hostgroup-add --desc="Web Servers" webservers
ipa group-add --desc="Developers" devel
""") + _("""
Add the initial rule:
ipa automember-add --type=hostgroup webservers
ipa automember-add --type=group devel
""") + _(r"""
Add a condition to the rule:
ipa automember-add-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers
ipa automember-add-condition --key=manager --type=group --inclusive-regex=^uid=mscott devel
""") + _(r"""
Add an exclusive condition to the rule to prevent auto assignment:
ipa automember-add-condition --key=fqdn --type=hostgroup --exclusive-regex=^web5\.example\.com webservers
""") + _("""
Add a host:
ipa host-add web1.example.com
""") + _("""
Add a user:
ipa user-add --first=Tim --last=User --password tuser1 --manager=mscott
""") + _("""
Verify automembership:
ipa hostgroup-show webservers
Host-group: webservers
Description: Web Servers
Member hosts: web1.example.com
ipa group-show devel
Group name: devel
Description: Developers
GID: 1004200000
Member users: tuser
""") + _(r"""
Remove a condition from the rule:
ipa automember-remove-condition --key=fqdn --type=hostgroup --inclusive-regex=^web[1-9]+\.example\.com webservers
""") + _("""
Modify the automember rule:
ipa automember-mod
""") + _("""
Set the default (fallback) target group:
ipa automember-default-group-set --default-group=webservers --type=hostgroup
ipa automember-default-group-set --default-group=ipausers --type=group
""") + _("""
Remove the default (fallback) target group:
ipa automember-default-group-remove --type=hostgroup
ipa automember-default-group-remove --type=group
""") + _("""
Show the default (fallback) target group:
ipa automember-default-group-show --type=hostgroup
ipa automember-default-group-show --type=group
""") + _("""
Find all of the automember rules:
ipa automember-find
""") + _("""
Find all of the orphan automember rules:
ipa automember-find-orphans --type=hostgroup
Find all of the orphan automember rules and remove them:
ipa automember-find-orphans --type=hostgroup --remove
""") + _("""
Display a automember rule:
ipa automember-show --type=hostgroup webservers
ipa automember-show --type=group devel
""") + _("""
Delete an automember rule:
ipa automember-del --type=hostgroup webservers
ipa automember-del --type=group devel
""") + _("""
Rebuild membership for all users:
ipa automember-rebuild --type=group
""") + _("""
Rebuild membership for all hosts:
ipa automember-rebuild --type=hostgroup
""") + _("""
Rebuild membership for specified users:
ipa automember-rebuild --users=tuser1 --users=tuser2
""") + _("""
Rebuild membership for specified hosts:
ipa automember-rebuild --hosts=web1.example.com --hosts=web2.example.com
""")
register = Registry()
# Options used by Condition Add and Remove.
INCLUDE_RE = 'automemberinclusiveregex'
EXCLUDE_RE = 'automemberexclusiveregex'
REBUILD_TASK_CONTAINER = DN(('cn', 'automember rebuild membership'),
('cn', 'tasks'),
('cn', 'config'))
regex_attrs = (
Str('automemberinclusiveregex*',
cli_name='inclusive_regex',
label=_('Inclusive Regex'),
doc=_('Inclusive Regex'),
alwaysask=True,
flags={'no_create', 'no_update', 'no_search'},
),
Str('automemberexclusiveregex*',
cli_name='exclusive_regex',
label=_('Exclusive Regex'),
doc=_('Exclusive Regex'),
alwaysask=True,
flags={'no_create', 'no_update', 'no_search'},
),
)
regex_key = (
Str('key',
label=_('Attribute Key'),
doc=_('Attribute to filter via regex. For example fqdn for a host, or manager for a user'),
flags=['no_create', 'no_update', 'no_search']
),
)
group_type = (
StrEnum('type',
label=_('Grouping Type'),
doc=_('Grouping to which the rule applies'),
values=(u'group', u'hostgroup', ),
),
)
@register()
class automember(LDAPObject):
"""
Bring automember to a hostgroup with an Auto Membership Rule.
"""
container_dn = api.env.container_automember
object_name = 'Automember rule'
object_name_plural = 'Automember rules'
object_class = ['top', 'automemberregexrule']
permission_filter_objectclasses = ['automemberregexrule']
default_attributes = [
'automemberinclusiveregex', 'automemberexclusiveregex',
'cn', 'automembertargetgroup', 'description', 'automemberdefaultgroup'
]
managed_permissions = {
'System: Read Automember Definitions': {
'non_object': True,
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermtargetfilter': {'(objectclass=automemberdefinition)'},
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'automemberscope', 'automemberfilter',
'automembergroupingattr', 'automemberdefaultgroup',
'automemberdisabled',
},
'default_privileges': {'Automember Readers',
'Automember Task Administrator'},
},
'System: Read Automember Rules': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'automembertargetgroup', 'description',
'automemberexclusiveregex', 'automemberinclusiveregex',
},
'default_privileges': {'Automember Readers',
'Automember Task Administrator'},
},
'System: Read Automember Tasks': {
'non_object': True,
'ipapermlocation': DN('cn=tasks', 'cn=config'),
'ipapermtarget': DN('cn=*', REBUILD_TASK_CONTAINER),
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'*'},
'default_privileges': {'Automember Task Administrator'},
},
}
label = _('Auto Membership Rule')
takes_params = (
Str('cn',
cli_name='automember_rule',
label=_('Automember Rule'),
doc=_('Automember Rule'),
primary_key=True,
normalizer=lambda value: value.lower(),
flags={'no_search'},
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this auto member rule'),
),
Str('automemberdefaultgroup?',
cli_name='default_group',
label=_('Default (fallback) Group'),
doc=_('Default group for entries to land'),
flags=['no_create', 'no_update', 'no_search']
),
) + regex_attrs
def dn_exists(self, otype, oname):
ldap = self.api.Backend.ldap2
dn = self.api.Object[otype].get_dn(oname)
try:
entry = ldap.get_entry(dn, [])
except errors.NotFound:
raise errors.NotFound(
reason=_(u'%(otype)s "%(oname)s" not found') %
dict(otype=otype, oname=oname)
)
return entry.dn
def get_dn(self, *keys, **options):
if self.parent_object:
parent_dn = self.api.Object[self.parent_object].get_dn(*keys[:-1])
else:
parent_dn = DN(self.container_dn, api.env.basedn)
grouptype = options['type']
try:
ndn = DN(('cn', keys[-1]), ('cn', grouptype), parent_dn)
except IndexError:
ndn = DN(('cn', grouptype), parent_dn)
return ndn
def check_attr(self, attr):
"""
Verify that the user supplied key is a valid attribute in the schema
"""
ldap = self.api.Backend.ldap2
obj = ldap.schema.get_obj(_ldap.schema.AttributeType, attr)
if obj is not None:
return obj
else:
raise errors.NotFound(reason=_('%s is not a valid attribute.') % attr)
def automember_container_exists(ldap):
try:
ldap.get_entry(DN(api.env.container_automember, api.env.basedn), [])
except errors.NotFound:
return False
return True
@register()
class automember_add(LDAPCreate):
__doc__ = _("""
Add an automember rule.
""")
takes_options = LDAPCreate.takes_options + group_type
msg_summary = _('Added automember rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
entry_attrs['cn'] = keys[-1]
if not automember_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('Auto Membership is not configured'))
entry_attrs['automembertargetgroup'] = self.obj.dn_exists(options['type'], keys[-1])
return dn
def execute(self, *keys, **options):
result = super(automember_add, self).execute(*keys, **options)
result['value'] = pkey_to_value(keys[-1], options)
return result
@register()
class automember_add_condition(LDAPUpdate):
__doc__ = _("""
Add conditions to an automember rule.
""")
has_output_params = (
Str('failed',
label=_('Failed to add'),
flags=['suppress_empty'],
),
)
takes_options = regex_attrs + regex_key + group_type
msg_summary = _('Added condition(s) to "%(value)s"')
# Prepare the output to expect failed results
has_output = (
output.summary,
output.Entry('result'),
output.value,
output.Output('failed',
type=dict,
doc=_('Conditions that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of conditions added'),
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# Check to see if the automember rule exists
try:
dn = ldap.get_entry(dn, []).dn
except errors.NotFound:
raise errors.NotFound(reason=_(u'Auto member rule: %s not found!') % keys[0])
# Define container key
key = options['key']
# Check to see if the attribute is valid
self.obj.check_attr(key)
key = '%s=' % key
completed = 0
failed = {'failed': {}}
for attr in (INCLUDE_RE, EXCLUDE_RE):
failed['failed'][attr] = []
if attr in options and options[attr]:
entry_attrs[attr] = [key + condition for condition in options[attr]]
completed += len(entry_attrs[attr])
try:
old_entry = ldap.get_entry(dn, [attr])
for regex in old_entry.keys():
if not isinstance(entry_attrs[regex], (list, tuple)):
entry_attrs[regex] = [entry_attrs[regex]]
duplicate = set(old_entry[regex]) & set(entry_attrs[regex])
if len(duplicate) > 0:
completed -= 1
else:
entry_attrs[regex] = list(entry_attrs[regex]) + old_entry[regex]
except errors.NotFound:
failed['failed'][attr].append(regex)
entry_attrs = entry_to_dict(entry_attrs, **options)
# Set failed and completed to they can be harvested in the execute super
setattr(context, 'failed', failed)
setattr(context, 'completed', completed)
setattr(context, 'entry_attrs', entry_attrs)
# Make sure to returned the failed results if there is nothing to remove
if completed == 0:
ldap.get_entry(dn, attrs_list)
raise errors.EmptyModlist
return dn
def execute(self, *keys, **options):
__doc__ = _("""
Override this so we can add completed and failed to the return result.
""")
try:
result = super(automember_add_condition, self).execute(*keys, **options)
except errors.EmptyModlist:
result = {'result': getattr(context, 'entry_attrs'), 'value': keys[-1]}
result['failed'] = getattr(context, 'failed')
result['completed'] = getattr(context, 'completed')
result['value'] = pkey_to_value(keys[-1], options)
return result
@register()
class automember_remove_condition(LDAPUpdate):
__doc__ = _("""
Remove conditions from an automember rule.
""")
takes_options = regex_attrs + regex_key + group_type
msg_summary = _('Removed condition(s) from "%(value)s"')
# Prepare the output to expect failed results
has_output = (
output.summary,
output.Entry('result'),
output.value,
output.Output('failed',
type=dict,
doc=_('Conditions that could not be removed'),
),
output.Output('completed',
type=int,
doc=_('Number of conditions removed'),
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# Check to see if the automember rule exists
try:
ldap.get_entry(dn, [])
except errors.NotFound:
raise errors.NotFound(reason=_(u'Auto member rule: %s not found!') % keys[0])
# Define container key
type_attr_default = {'group': 'manager', 'hostgroup': 'fqdn'}
key = options.get('key', type_attr_default[options['type']])
key = '%s=' % key
completed = 0
failed = {'failed': {}}
# Check to see if there are existing exclusive conditions present.
dn = ldap.get_entry(dn, [EXCLUDE_RE]).dn
for attr in (INCLUDE_RE, EXCLUDE_RE):
failed['failed'][attr] = []
if attr in options and options[attr]:
entry_attrs[attr] = [key + condition for condition in options[attr]]
entry_attrs_ = ldap.get_entry(dn, [attr])
old_entry = entry_attrs_.get(attr, [])
for regex in entry_attrs[attr]:
if regex in old_entry:
old_entry.remove(regex)
completed += 1
else:
failed['failed'][attr].append(regex)
entry_attrs[attr] = old_entry
entry_attrs = entry_to_dict(entry_attrs, **options)
# Set failed and completed to they can be harvested in the execute super
setattr(context, 'failed', failed)
setattr(context, 'completed', completed)
setattr(context, 'entry_attrs', entry_attrs)
# Make sure to returned the failed results if there is nothing to remove
if completed == 0:
ldap.get_entry(dn, attrs_list)
raise errors.EmptyModlist
return dn
def execute(self, *keys, **options):
__doc__ = _("""
Override this so we can set completed and failed.
""")
try:
result = super(automember_remove_condition, self).execute(*keys, **options)
except errors.EmptyModlist:
result = {'result': getattr(context, 'entry_attrs'), 'value': keys[-1]}
result['failed'] = getattr(context, 'failed')
result['completed'] = getattr(context, 'completed')
result['value'] = pkey_to_value(keys[-1], options)
return result
@register()
class automember_mod(LDAPUpdate):
__doc__ = _("""
Modify an automember rule.
""")
takes_options = LDAPUpdate.takes_options + group_type
msg_summary = _('Modified automember rule "%(value)s"')
def execute(self, *keys, **options):
result = super(automember_mod, self).execute(*keys, **options)
result['value'] = pkey_to_value(keys[-1], options)
return result
@register()
class automember_del(LDAPDelete):
__doc__ = _("""
Delete an automember rule.
""")
takes_options = group_type
msg_summary = _('Deleted automember rule "%(value)s"')
@register()
class automember_find(LDAPSearch):
__doc__ = _("""
Search for automember rules.
""")
takes_options = group_type
msg_summary = ngettext(
'%(count)d rules matched', '%(count)d rules matched', 0
)
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
scope = ldap.SCOPE_SUBTREE
ndn = DN(('cn', options['type']), base_dn)
return (filters, ndn, scope)
@register()
class automember_show(LDAPRetrieve):
__doc__ = _("""
Display information about an automember rule.
""")
takes_options = group_type
def execute(self, *keys, **options):
result = super(automember_show, self).execute(*keys, **options)
result['value'] = pkey_to_value(keys[-1], options)
return result
@register()
class automember_default_group(automember):
managed_permissions = {}
def get_params(self):
for param in super(automember_default_group, self).get_params():
if param.name in ('cn', 'description'):
continue
yield param
@register()
class automember_default_group_set(LDAPUpdate):
__doc__ = _("""
Set default (fallback) group for all unmatched entries.
""")
obj_name = 'automember_default_group'
takes_options = (
Str('automemberdefaultgroup',
cli_name='default_group',
label=_('Default (fallback) Group'),
doc=_('Default (fallback) group for entries to land'),
flags=['no_create', 'no_update']
),
) + group_type
msg_summary = _('Set default (fallback) group for automember "%(value)s"')
has_output = output.simple_entry
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
dn = DN(('cn', options['type']), api.env.container_automember,
api.env.basedn)
entry_attrs['automemberdefaultgroup'] = self.obj.dn_exists(options['type'], options['automemberdefaultgroup'])
return dn
def execute(self, *keys, **options):
result = super(automember_default_group_set, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['type'], options)
return result
@register()
class automember_default_group_remove(LDAPUpdate):
__doc__ = _("""
Remove default (fallback) group for all unmatched entries.
""")
obj_name = 'automember_default_group'
takes_options = group_type
msg_summary = _('Removed default (fallback) group for automember "%(value)s"')
has_output = output.simple_entry
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
dn = DN(('cn', options['type']), api.env.container_automember,
api.env.basedn)
attr = 'automemberdefaultgroup'
entry_attrs_ = ldap.get_entry(dn, [attr])
if attr not in entry_attrs_:
raise errors.NotFound(reason=_(u'No default (fallback) group set'))
else:
entry_attrs[attr] = []
return entry_attrs_.dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if 'automemberdefaultgroup' not in entry_attrs:
entry_attrs['automemberdefaultgroup'] = unicode(_('No default (fallback) group set'))
return dn
def execute(self, *keys, **options):
result = super(automember_default_group_remove, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['type'], options)
return result
@register()
class automember_default_group_show(LDAPRetrieve):
__doc__ = _("""
Display information about the default (fallback) automember groups.
""")
obj_name = 'automember_default_group'
takes_options = group_type
has_output = output.simple_entry
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
dn = DN(('cn', options['type']), api.env.container_automember,
api.env.basedn)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if 'automemberdefaultgroup' not in entry_attrs:
entry_attrs['automemberdefaultgroup'] = unicode(_('No default (fallback) group set'))
return dn
def execute(self, *keys, **options):
result = super(automember_default_group_show, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['type'], options)
return result
@register()
class automember_task(Object):
takes_params = (
DNParam(
'dn',
label=_('Task DN'),
doc=_('DN of the started task'),
),
)
@register()
class automember_rebuild(Method):
__doc__ = _('Rebuild auto membership.')
obj_name = 'automember_task'
attr_name = 'rebuild'
# TODO: Add a --dry-run option:
# https://fedorahosted.org/freeipa/ticket/3936
takes_options = (
group_type[0].clone(
required=False,
label=_('Rebuild membership for all members of a grouping')
),
Str(
'users*',
label=_('Users'),
doc=_('Rebuild membership for specified users'),
),
Str(
'hosts*',
label=_('Hosts'),
doc=_('Rebuild membership for specified hosts'),
),
Flag(
'no_wait?',
default=False,
label=_('No wait'),
doc=_("Don't wait for rebuilding membership"),
),
)
has_output = output.standard_entry
def validate(self, **kw):
"""
Validation rules:
- at least one of 'type', 'users', 'hosts' is required
- 'users' and 'hosts' cannot be combined together
- if 'users' and 'type' are specified, 'type' must be 'group'
- if 'hosts' and 'type' are specified, 'type' must be 'hostgroup'
"""
super(automember_rebuild, self).validate(**kw)
users, hosts, gtype = kw.get('users'), kw.get('hosts'), kw.get('type')
if not (gtype or users or hosts):
raise errors.MutuallyExclusiveError(
reason=_('at least one of options: type, users, hosts must be '
'specified')
)
if users and hosts:
raise errors.MutuallyExclusiveError(
reason=_("users and hosts cannot both be set")
)
if gtype == 'group' and hosts:
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be set when type is 'group'")
)
if gtype == 'hostgroup' and users:
raise errors.MutuallyExclusiveError(
reason=_("users cannot be set when type is 'hostgroup'")
)
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
cn = str(uuid.uuid4())
gtype = options.get('type')
if not gtype:
gtype = 'group' if options.get('users') else 'hostgroup'
types = {
'group': (
'user',
'users',
DN(api.env.container_user, api.env.basedn)
),
'hostgroup': (
'host',
'hosts',
DN(api.env.container_host, api.env.basedn)
),
}
obj_name, opt_name, basedn = types[gtype]
obj = self.api.Object[obj_name]
names = options.get(opt_name)
if names:
for name in names:
try:
obj.get_dn_if_exists(name)
except errors.NotFound:
raise obj.handle_not_found(name)
search_filter = ldap.make_filter_from_attr(
obj.primary_key.name,
names,
rules=ldap.MATCH_ANY
)
else:
search_filter = '(%s=*)' % obj.primary_key.name
task_dn = DN(('cn', cn), REBUILD_TASK_CONTAINER)
entry = ldap.make_entry(
task_dn,
objectclass=['top', 'extensibleObject'],
cn=[cn],
basedn=[basedn],
filter=[search_filter],
scope=['sub'],
ttl=[3600])
ldap.add_entry(entry)
summary = _('Automember rebuild membership task started')
result = {'dn': task_dn}
if not options.get('no_wait'):
summary = _('Automember rebuild membership task completed')
result = {}
start_time = time.time()
while True:
try:
task = ldap.get_entry(task_dn)
except errors.NotFound:
break
if 'nstaskexitcode' in task:
if str(task.single_value['nstaskexitcode']) == '0':
summary=task.single_value['nstaskstatus']
break
raise errors.DatabaseError(
desc=task.single_value['nstaskstatus'],
info=_("Task DN = '%s'" % task_dn))
time.sleep(1)
if time.time() > (start_time + 60):
raise errors.TaskTimeout(task=_('Automember'), task_dn=task_dn)
return dict(
result=result,
summary=unicode(summary),
value=pkey_to_value(None, options))
@register()
class automember_find_orphans(LDAPSearch):
__doc__ = _("""
Search for orphan automember rules. The command might need to be run as
a privileged user user to get all orphan rules.
""")
takes_options = group_type + (
Flag(
'remove?',
doc=_("Remove orphan automember rules"),
),
)
msg_summary = ngettext(
'%(count)d rules matched', '%(count)d rules matched', 0
)
def execute(self, *keys, **options):
results = super().execute(*keys, **options)
remove_option = options.get('remove')
pkey_only = options.get('pkey_only', False)
ldap = self.obj.backend
orphans = []
for entry in results["result"]:
am_dn_entry = entry['automembertargetgroup'][0]
# Make DN for --raw option
if not isinstance(am_dn_entry, DN):
am_dn_entry = DN(am_dn_entry)
try:
ldap.get_entry(am_dn_entry)
except errors.NotFound:
if pkey_only:
# For pkey_only remove automembertargetgroup
del(entry['automembertargetgroup'])
orphans.append(entry)
if remove_option:
ldap.delete_entry(entry['dn'])
results["result"][:] = orphans
results["count"] = len(orphans)
return results
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope, *args,
**options):
assert isinstance(base_dn, DN)
scope = ldap.SCOPE_SUBTREE
ndn = DN(('cn', options['type']), base_dn)
if options.get('pkey_only', False):
# For pkey_only add automembertargetgroup
attrs_list.append('automembertargetgroup')
return filters, ndn, scope
| 29,884
|
Python
|
.py
| 760
| 30.643421
| 118
| 0.596408
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,834
|
passwd.py
|
freeipa_freeipa/ipaserver/plugins/passwd.py
|
# Authors:
# Rob Crittenden <rcritten@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 logging
import six
from ipalib import api, errors, krb_utils
from ipalib import Command
from ipalib import Password
from ipalib import _
from ipalib import output
from ipalib.parameters import Principal
from ipalib.plugable import Registry
from ipalib.request import context
from ipapython import kerberos
from ipapython.dn import DN
from ipaserver.plugins.baseuser import normalize_user_principal
from ipaserver.plugins.service import validate_realm
if six.PY3:
unicode = str
__doc__ = _("""
Set a user's password
If someone other than a user changes that user's password (e.g., Helpdesk
resets it) then the password will need to be changed the first time it
is used. This is so the end-user is the only one who knows the password.
The IPA password policy controls how often a password may be changed,
what strength requirements exist, and the length of the password history.
If the user authentication method is set to password+OTP, the user should
pass the --otp option when resetting the password.
EXAMPLES:
To reset your own password:
ipa passwd
To reset your own password when password+OTP is set as authentication method:
ipa passwd --otp
To change another user's password:
ipa passwd tuser1
""")
logger = logging.getLogger(__name__)
register = Registry()
# We only need to prompt for the current password when changing a password
# for yourself, but the parameter is still required
MAGIC_VALUE = u'CHANGING_PASSWORD_FOR_ANOTHER_USER'
def get_current_password(principal):
"""
If the user is changing their own password then return None so the
current password is prompted for, otherwise return a fixed value to
be ignored later.
"""
current_principal = krb_utils.get_principal()
if current_principal == unicode(normalize_user_principal(principal)):
return None
else:
return MAGIC_VALUE
@register()
class passwd(Command):
__doc__ = _("Set a user's password.")
takes_args = (
Principal(
'principal',
validate_realm,
cli_name='user',
label=_('User name'),
primary_key=True,
autofill=True,
default_from=lambda: kerberos.Principal(krb_utils.get_principal()),
normalizer=lambda value: normalize_user_principal(value),
),
Password('password',
label=_('New Password'),
),
Password('current_password',
label=_('Current Password'),
confirm=False,
default_from=lambda principal: get_current_password(principal),
autofill=True,
),
)
takes_options = (
Password('otp?',
label=_('OTP'),
doc=_('The OTP if the user has a token configured'),
confirm=False,
),
)
has_output = output.simple_value
msg_summary = _('Changed password for "%(value)s"')
def execute(self, principal, password, current_password, **options):
"""
Execute the passwd operation.
The dn should not be passed as a keyword argument as it is constructed
by this method.
Returns the entry
:param principal: The login name or principal of the user
:param password: the new password
:param current_password: the existing password, if applicable
"""
ldap = self.api.Backend.ldap2
principal = unicode(principal)
entry_attrs = ldap.find_entry_by_attr(
'krbprincipalname', principal, 'posixaccount', [''],
DN(api.env.container_user, api.env.basedn)
)
if principal == getattr(context, 'principal', None) and \
current_password == MAGIC_VALUE:
# No cheating
logger.warning('User attempted to change password using magic '
'value')
raise errors.ACIError(info=_('Invalid credentials'))
if current_password == MAGIC_VALUE:
ldap.modify_password(entry_attrs.dn, password)
else:
otp = options.get('otp')
ldap.modify_password(entry_attrs.dn, password, current_password, otp)
return dict(
result=True,
value=principal,
)
| 5,067
|
Python
|
.py
| 131
| 32.152672
| 81
| 0.678215
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,835
|
domainlevel.py
|
freeipa_freeipa/ipaserver/plugins/domainlevel.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from collections import namedtuple
from ipalib import _
from ipalib import Command
from ipalib import errors
from ipalib import output
from ipalib.parameters import Int
from ipalib.plugable import Registry
from ipalib.constants import DOMAIN_LEVEL_0, MIN_DOMAIN_LEVEL
from ipapython.dn import DN
__doc__ = _("""
Raise the IPA Domain Level.
""")
register = Registry()
DomainLevelRange = namedtuple('DomainLevelRange', ['min', 'max'])
domainlevel_output = (
output.Output('result', int, _('Current domain level:')),
)
def get_domainlevel_dn(api):
domainlevel_dn = DN(
('cn', 'Domain Level'),
('cn', 'ipa'),
('cn', 'etc'),
api.env.basedn
)
return domainlevel_dn
def get_domainlevel_range(master_entry):
try:
return DomainLevelRange(
int(master_entry['ipaMinDomainLevel'][0]),
int(master_entry['ipaMaxDomainLevel'][0])
)
except KeyError:
return DomainLevelRange(DOMAIN_LEVEL_0, DOMAIN_LEVEL_0)
def check_conflict_entries(ldap, api, desired_value):
"""
Check if conflict entries exist in topology subtree
"""
container_dn = DN(
('cn', 'ipa'),
('cn', 'etc'),
api.env.basedn
)
conflict = "(nsds5replconflict=*)"
subentry = "(|(objectclass=ldapsubentry)(objectclass=*))"
try:
ldap.get_entries(
filter="(& %s %s)" % (conflict, subentry),
base_dn=container_dn,
scope=ldap.SCOPE_SUBTREE)
message = _("Domain Level cannot be raised to {0}, "
"existing replication conflicts have to be resolved."
).format(desired_value)
raise errors.InvalidDomainLevelError(reason=message)
except errors.NotFound:
pass
def get_master_entries(ldap, api):
"""
Returns list of LDAPEntries representing IPA masters.
"""
dn = DN(api.env.container_masters, api.env.basedn)
masters, _dummy = ldap.find_entries(
filter="(cn=*)",
base_dn=dn,
scope=ldap.SCOPE_ONELEVEL,
paged_search=True, # we need to make sure to get all of them
)
return masters
@register()
class domainlevel_get(Command):
__doc__ = _('Query current Domain Level.')
has_output = domainlevel_output
def execute(self, *args, **options):
ldap = self.api.Backend.ldap2
entry = ldap.get_entries(
get_domainlevel_dn(self.api),
scope=ldap.SCOPE_BASE,
filter='(objectclass=ipadomainlevelconfig)',
attrs_list=['ipaDomainLevel']
)[0]
try:
value = int(entry.single_value['ipaDomainLevel'])
return {'result': value}
except KeyError:
raise errors.NotFound(
reason=_(
'Server does not support domain level functionality'))
@register()
class domainlevel_set(Command):
__doc__ = _('Change current Domain Level.')
has_output = domainlevel_output
takes_args = (
Int('ipadomainlevel',
cli_name='level',
label=_('Domain Level'),
minvalue=MIN_DOMAIN_LEVEL,
),
)
def execute(self, *args, **options):
"""
Checks all the IPA masters for supported domain level ranges.
If the desired domain level is within the supported range of all
masters, it will be raised.
Domain level cannot be lowered.
"""
ldap = self.api.Backend.ldap2
current_entry = ldap.get_entry(get_domainlevel_dn(self.api))
current_value = int(current_entry.single_value['ipadomainlevel'])
desired_value = int(args[0])
# Domain level cannot be lowered
if int(desired_value) < int(current_value):
message = _("Domain Level cannot be lowered.")
raise errors.InvalidDomainLevelError(reason=message)
# Check if every master supports the desired level
for master in get_master_entries(ldap, self.api):
supported = get_domainlevel_range(master)
if supported.min > desired_value or supported.max < desired_value:
message = _("Domain Level cannot be raised to {0}, server {1} "
"does not support it."
).format(desired_value, master['cn'][0])
raise errors.InvalidDomainLevelError(reason=message)
# Check if conflict entries exist in topology subtree
# should be resolved first
check_conflict_entries(ldap, self.api, desired_value)
current_entry.single_value['ipaDomainLevel'] = desired_value
ldap.update_entry(current_entry)
return {'result': int(current_entry.single_value['ipaDomainLevel'])}
| 4,837
|
Python
|
.py
| 129
| 29.44186
| 79
| 0.628694
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,836
|
krbtpolicy.py
|
freeipa_freeipa/ipaserver/plugins/krbtpolicy.py
|
# Authors:
# 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 ipalib import api, errors, output, _
from ipalib import Int, Str
from . import baseldap
from .baseldap import entry_to_dict, pkey_to_value
from ipalib.plugable import Registry
from ipapython.dn import DN
__doc__ = _("""
Kerberos ticket policy
There is a single Kerberos ticket policy. This policy defines the
maximum ticket lifetime and the maximum renewal age, the period during
which the ticket is renewable.
You can also create a per-user ticket policy by specifying the user login.
For changes to the global policy to take effect, restarting the KDC service
is required, which can be achieved using:
service krb5kdc restart
Changes to per-user policies take effect immediately for newly requested
tickets (e.g. when the user next runs kinit).
EXAMPLES:
Display the current Kerberos ticket policy:
ipa krbtpolicy-show
Reset the policy to the default:
ipa krbtpolicy-reset
Modify the policy to 8 hours max life, 1-day max renewal:
ipa krbtpolicy-mod --maxlife=28800 --maxrenew=86400
Display effective Kerberos ticket policy for user 'admin':
ipa krbtpolicy-show admin
Reset per-user policy for user 'admin':
ipa krbtpolicy-reset admin
Modify per-user policy for user 'admin':
ipa krbtpolicy-mod admin --maxlife=3600
""")
register = Registry()
# FIXME: load this from a config file?
_default_values = {
'krbmaxticketlife': 86400,
'krbmaxrenewableage': 604800,
'krbauthindmaxticketlife': 86400,
'krbauthindmaxrenewableage': 604800,
}
# These attributes never have non-optional values, so they should be
# ignored in post callbacks
_option_based_attrs = ('krbauthindmaxticketlife', 'krbauthindmaxrenewableage')
_supported_options = ('otp', 'radius', 'pkinit', 'hardened', 'idp', 'passkey')
@register()
class krbtpolicy(baseldap.LDAPObject):
"""
Kerberos Ticket Policy object
"""
container_dn = DN(('cn', api.env.realm), ('cn', 'kerberos'))
object_name = _('kerberos ticket policy settings')
default_attributes = ['krbmaxticketlife', 'krbmaxrenewableage',
'krbauthindmaxticketlife',
'krbauthindmaxrenewableage']
limit_object_classes = ['krbticketpolicyaux']
# permission_filter_objectclasses is deliberately missing,
# so it is not possible to create a permission of `--type krbtpolicy`.
# This is because we need two permissions to cover both global and per-user
# policies.
managed_permissions = {
'System: Read Default Kerberos Ticket Policy': {
'non_object': True,
'replaces_global_anonymous_aci': True,
'ipapermtargetfilter': ['(objectclass=krbticketpolicyaux)'],
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'krbdefaultencsalttypes', 'krbmaxrenewableage',
'krbmaxticketlife', 'krbsupportedencsalttypes',
'objectclass', 'krbauthindmaxticketlife',
'krbauthindmaxrenewableage',
},
'default_privileges': {
'Kerberos Ticket Policy Readers',
},
},
'System: Read User Kerberos Ticket Policy': {
'non_object': True,
'replaces_global_anonymous_aci': True,
'ipapermlocation': DN(api.env.container_user, api.env.basedn),
'ipapermtargetfilter': ['(objectclass=krbticketpolicyaux)'],
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'krbmaxrenewableage', 'krbmaxticketlife',
'krbauthindmaxticketlife', 'krbauthindmaxrenewableage',
},
'default_privileges': {
'Kerberos Ticket Policy Readers',
},
},
}
label = _('Kerberos Ticket Policy')
label_singular = _('Kerberos Ticket Policy')
takes_params = (
Str('uid?',
cli_name='user',
label=_('User name'),
doc=_('Manage ticket policy for specific user'),
primary_key=True,
),
Int('krbmaxticketlife?',
cli_name='maxlife',
label=_('Max life'),
doc=_('Maximum ticket life (seconds)'),
minvalue=1,
),
Int('krbmaxrenewableage?',
cli_name='maxrenew',
label=_('Max renew'),
doc=_('Maximum renewable age (seconds)'),
minvalue=1,
),
Int('krbauthindmaxticketlife_otp?',
cli_name='otp_maxlife',
label=_('OTP max life'),
doc=_('OTP token maximum ticket life (seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_otp?',
cli_name='otp_maxrenew',
label=_('OTP max renew'),
doc=_('OTP token ticket maximum renewable age (seconds)'),
minvalue=1),
Int('krbauthindmaxticketlife_radius?',
cli_name='radius_maxlife',
label=_('RADIUS max life'),
doc=_('RADIUS maximum ticket life (seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_radius?',
cli_name='radius_maxrenew',
label=_('RADIUS max renew'),
doc=_('RADIUS ticket maximum renewable age (seconds)'),
minvalue=1),
Int('krbauthindmaxticketlife_pkinit?',
cli_name='pkinit_maxlife',
label=_('PKINIT max life'),
doc=_('PKINIT maximum ticket life (seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_pkinit?',
cli_name='pkinit_maxrenew',
label=_('PKINIT max renew'),
doc=_('PKINIT ticket maximum renewable age (seconds)'),
minvalue=1),
Int('krbauthindmaxticketlife_hardened?',
cli_name='hardened_maxlife',
label=_('Hardened max life'),
doc=_('Hardened ticket maximum ticket life (seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_hardened?',
cli_name='hardened_maxrenew',
label=_('Hardened max renew'),
doc=_('Hardened ticket maximum renewable age (seconds)'),
minvalue=1),
Int('krbauthindmaxticketlife_idp?',
cli_name='idp_maxlife',
label=_('IdP max life'),
doc=_('External Identity Provider ticket maximum ticket life '
'(seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_idp?',
cli_name='idp_maxrenew',
label=_('IdP max renew'),
doc=_('External Identity Provider ticket maximum renewable '
'age (seconds)'),
minvalue=1),
Int('krbauthindmaxticketlife_passkey?',
cli_name='passkey_maxlife',
label=_('Passkey max life'),
doc=_('Passkey ticket maximum ticket life (seconds)'),
minvalue=1),
Int('krbauthindmaxrenewableage_passkey?',
cli_name='passkey_maxrenew',
label=_('Passkey max renew'),
doc=_('Passkey ticket maximum renewable age (seconds)'),
minvalue=1),
)
def get_dn(self, *keys, **kwargs):
if keys[-1] is not None:
return self.api.Object.user.get_dn(*keys, **kwargs)
return DN(self.container_dn, api.env.basedn)
def rename_authind_options_from_ldap(entry_attrs, options):
if options.get('raw', False):
return
for subtype in _supported_options:
for attr in _option_based_attrs:
name = '{};{}'.format(attr, subtype)
if name in entry_attrs:
new_name = '{}_{}'.format(attr, subtype)
entry_attrs[new_name] = entry_attrs.pop(name)
def rename_authind_options_to_ldap(entry_attrs):
for subtype in _supported_options:
for attr in _option_based_attrs:
name = '{}_{}'.format(attr, subtype)
if name in entry_attrs:
new_name = '{};{}'.format(attr, subtype)
entry_attrs[new_name] = entry_attrs.pop(name)
@register()
class krbtpolicy_mod(baseldap.LDAPUpdate):
__doc__ = _('Modify Kerberos ticket policy.')
def execute(self, uid=None, **options):
return super(krbtpolicy_mod, self).execute(uid, **options)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# disable all flag
# ticket policies are attached to objects with unrelated attributes
if options.get('all'):
options['all'] = False
# Rename authentication indicator-specific policy elements to LDAP
rename_authind_options_to_ldap(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
# Rename authentication indicator-specific policy elements from LDAP
rename_authind_options_from_ldap(entry_attrs, options)
return dn
@register()
class krbtpolicy_show(baseldap.LDAPRetrieve):
__doc__ = _('Display the current Kerberos ticket policy.')
def execute(self, uid=None, **options):
return super(krbtpolicy_show, self).execute(uid, **options)
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# disable all flag
# ticket policies are attached to objects with unrelated attributes
if options.get('all'):
options['all'] = False
return dn
def post_callback(self, ldap, dn, entry, *keys, **options):
default_entry = None
rights = None
for attrname in self.obj.default_attributes:
if attrname not in entry:
if keys[-1] is not None:
# User entry doesn't override the attribute.
# Check if this is caused by insufficient read rights
if rights is None:
rights = baseldap.get_effective_rights(
ldap, dn, self.obj.default_attributes)
if 'r' not in rights.get(attrname.lower(), ''):
raise errors.ACIError(
info=_('Ticket policy for %s could not be read') %
keys[-1])
# Fallback to the default
if default_entry is None:
try:
default_dn = self.obj.get_dn(None)
default_entry = ldap.get_entry(default_dn)
except errors.NotFound:
default_entry = {}
if attrname in default_entry:
entry[attrname] = default_entry[attrname]
elif attrname in _option_based_attrs:
# If default entry contains option-based default attrs,
# copy the options explicitly
attrs = [(a, a.split(';')[0]) for a in default_entry]
for a in attrs:
if a[1] == attrname and a[0] not in entry:
entry[a[0]] = default_entry[a[0]]
if attrname not in entry and attrname not in _option_based_attrs:
raise errors.ACIError(
info=_('Default ticket policy could not be read'))
# Rename authentication indicator-specific policy elements from LDAP
rename_authind_options_from_ldap(entry, options)
return dn
@register()
class krbtpolicy_reset(baseldap.LDAPQuery):
__doc__ = _('Reset Kerberos ticket policy to the default values.')
has_output = output.standard_entry
def execute(self, uid=None, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(uid, **options)
def_values = {}
# if reseting policy for a user - just his values
if uid is not None:
for a in self.obj.default_attributes:
def_values[a] = None
# if reseting global policy - set values to default
else:
def_values = _default_values.copy()
entry = ldap.get_entry(dn, list(def_values))
# For per-indicator policies, drop them to defaults
for subtype in _supported_options:
for attr in _option_based_attrs:
name = '{};{}'.format(attr, subtype)
if name in entry:
if uid is not None:
def_values[name] = None
else:
def_values[name] = _default_values[attr]
# Remove non-subtyped attrs variants,
# they should never be used directly.
for attr in _option_based_attrs:
if attr in def_values:
del def_values[attr]
entry.update(def_values)
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
if uid is not None:
# policy for user was deleted, retrieve global policy
dn = self.obj.get_dn(None)
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
entry_attrs = entry_to_dict(entry_attrs, **options)
rename_authind_options_from_ldap(entry_attrs, options)
return dict(result=entry_attrs, value=pkey_to_value(uid, options))
| 14,206
|
Python
|
.py
| 322
| 33.73913
| 80
| 0.604236
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,837
|
hbacsvc.py
|
freeipa_freeipa/ipaserver/plugins/hbacsvc.py
|
# Authors:
# Rob Crittenden <rcritten@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 ipalib import api
from ipalib import Str
from ipalib.plugable import Registry
from .baseldap import LDAPObject, LDAPCreate, LDAPDelete
from .baseldap import LDAPUpdate, LDAPSearch, LDAPRetrieve
from ipalib import _, ngettext
__doc__ = _("""
HBAC Services
The PAM services that HBAC can control access to. The name used here
must match the service name that PAM is evaluating.
EXAMPLES:
Add a new HBAC service:
ipa hbacsvc-add tftp
Modify an existing HBAC service:
ipa hbacsvc-mod --desc="TFTP service" tftp
Search for HBAC services. This example will return two results, the FTP
service and the newly-added tftp service:
ipa hbacsvc-find ftp
Delete an HBAC service:
ipa hbacsvc-del tftp
""")
register = Registry()
topic = 'hbac'
@register()
class hbacsvc(LDAPObject):
"""
HBAC Service object.
"""
container_dn = api.env.container_hbacservice
object_name = _('HBAC service')
object_name_plural = _('HBAC services')
object_class = [ 'ipaobject', 'ipahbacservice' ]
permission_filter_objectclasses = ['ipahbacservice']
default_attributes = ['cn', 'description', 'memberof']
uuid_attribute = 'ipauniqueid'
attribute_members = {
'memberof': ['hbacsvcgroup'],
}
managed_permissions = {
'System: Read HBAC Services': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'description', 'ipauniqueid', 'memberof', 'objectclass',
},
},
'System: Add HBAC Services': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=hbacservices,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Add HBAC services";allow (add) groupdn = "ldap:///cn=Add HBAC services,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Delete HBAC Services': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=hbacservices,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Delete HBAC services";allow (delete) groupdn = "ldap:///cn=Delete HBAC services,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
}
label = _('HBAC Services')
label_singular = _('HBAC Service')
takes_params = (
Str('cn',
cli_name='service',
label=_('Service name'),
doc=_('HBAC service'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('HBAC service description'),
),
)
@register()
class hbacsvc_add(LDAPCreate):
__doc__ = _('Add a new HBAC service.')
msg_summary = _('Added HBAC service "%(value)s"')
@register()
class hbacsvc_del(LDAPDelete):
__doc__ = _('Delete an existing HBAC service.')
msg_summary = _('Deleted HBAC service "%(value)s"')
@register()
class hbacsvc_mod(LDAPUpdate):
__doc__ = _('Modify an HBAC service.')
msg_summary = _('Modified HBAC service "%(value)s"')
@register()
class hbacsvc_find(LDAPSearch):
__doc__ = _('Search for HBAC services.')
msg_summary = ngettext(
'%(count)d HBAC service matched', '%(count)d HBAC services matched', 0
)
@register()
class hbacsvc_show(LDAPRetrieve):
__doc__ = _('Display information about an HBAC service.')
| 4,423
|
Python
|
.py
| 117
| 32.025641
| 218
| 0.650749
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,838
|
location.py
|
freeipa_freeipa/ipaserver/plugins/location.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import (
absolute_import,
division,
)
from ipalib import (
_,
ngettext,
api,
Str,
DNSNameParam,
output,
messages
)
from ipalib.errors import DependentEntry
from ipalib.plugable import Registry
from ipaserver.dns_data_management import IPASystemRecords
from ipaserver.plugins.baseldap import (
LDAPCreate,
LDAPSearch,
LDAPRetrieve,
LDAPDelete,
LDAPObject,
LDAPUpdate,
)
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
__doc__ = _("""
IPA locations
""") + _("""
Manipulate DNS locations
""") + _("""
EXAMPLES:
""") + _("""
Find all locations:
ipa location-find
""") + _("""
Show specific location:
ipa location-show location
""") + _("""
Add location:
ipa location-add location --description 'My location'
""") + _("""
Delete location:
ipa location-del location
""")
register = Registry()
@register()
class location(LDAPObject):
"""
IPA locations
"""
container_dn = api.env.container_locations
object_name = _('location')
object_name_plural = _('locations')
object_class = ['top', 'ipaLocationObject']
search_attributes = ['idnsName']
default_attributes = [
'idnsname', 'description'
]
label = _('IPA Locations')
label_singular = _('IPA Location')
permission_filter_objectclasses = ['ipaLocationObject']
managed_permissions = {
'System: Read IPA Locations': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'idnsname', 'description',
},
'default_privileges': {'DNS Administrators'},
},
'System: Add IPA Locations': {
'ipapermright': {'add'},
'default_privileges': {'DNS Administrators'},
},
'System: Remove IPA Locations': {
'ipapermright': {'delete'},
'default_privileges': {'DNS Administrators'},
},
'System: Modify IPA Locations': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'description',
},
'default_privileges': {'DNS Administrators'},
},
}
takes_params = (
DNSNameParam(
'idnsname',
cli_name='name',
primary_key=True,
label=_('Location name'),
doc=_('IPA location name'),
# dns name must be relative, we will put it into middle of
# location domain name for location records
only_relative=True,
),
Str(
'description?',
label=_('Description'),
doc=_('IPA Location description'),
),
Str(
'servers_server*',
label=_('Servers'),
doc=_('Servers that belongs to the IPA location'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str(
'dns_server*',
label=_('Advertised by servers'),
doc=_('List of servers which advertise the given location'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
)
def get_dn(self, *keys, **options):
loc = keys[0]
assert isinstance(loc, DNSName)
loc_a = loc.ToASCII()
return super(location, self).get_dn(loc_a, **options)
@register()
class location_add(LDAPCreate):
__doc__ = _('Add a new IPA location.')
msg_summary = _('Added IPA location "%(value)s"')
@register()
class location_del(LDAPDelete):
__doc__ = _('Delete an IPA location.')
msg_summary = _('Deleted IPA location "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if not options.get('force'):
servers = self.api.Command.server_find(
in_location=keys[-1])['result']
location_member = servers[0]['cn'][0] if servers else None
if location_member:
raise DependentEntry(
label=_('IPA Server'),
key=keys[-1],
dependent=location_member
)
system_records =IPASystemRecords(self.api)
_success, failed = system_records.remove_location_records(keys[-1])
if failed:
self.add_message(messages.AutomaticDNSRecordsUpdateFailed())
return dn
@register()
class location_mod(LDAPUpdate):
__doc__ = _('Modify information about an IPA location.')
msg_summary = _('Modified IPA location "%(value)s"')
@register()
class location_find(LDAPSearch):
__doc__ = _('Search for IPA locations.')
msg_summary = ngettext(
'%(count)d IPA location matched',
'%(count)d IPA locations matched', 0
)
@register()
class location_show(LDAPRetrieve):
__doc__ = _('Display information about an IPA location.')
has_output = LDAPRetrieve.has_output + (
output.Output(
'servers',
type=dict,
doc=_('Servers in location'),
flags={'no_display'}, # we use customized print to CLI
),
)
def execute(self, *keys, **options):
result = super(location_show, self).execute(*keys, **options)
servers_additional_info = {}
if not options.get('raw'):
servers_name = []
dns_servers = []
weight_sum = 0
servers = self.api.Command.server_find(
in_location=keys[0], no_members=False)['result']
for server in servers:
s_name = server['cn'][0]
servers_name.append(s_name)
weight = int(server.get('ipaserviceweight', [100])[0])
weight_sum += weight
servers_additional_info[s_name] = {
'cn': server['cn'],
'ipaserviceweight': server.get(
'ipaserviceweight', [u'100']),
}
s_roles = server.get('enabled_role_servrole', ())
if s_roles:
servers_additional_info[s_name][
'enabled_role_servrole'] = s_roles
if 'DNS server' in s_roles:
dns_servers.append(s_name)
# 1. If all masters have weight == 0 then all are equally
# weighted.
# 2. If any masters have weight == 0 then they have an
# extremely small chance of being chosen, percentage is
# 0.1.
# 3. Otherwise it's percentage change is based on the sum of
# the weights of non-zero masters.
dividend = 100.0
if weight_sum != 0:
for server in servers_additional_info.values():
if int(server['ipaserviceweight'][0]) == 0:
dividend = dividend - 0.1
for server in servers_additional_info.values():
if weight_sum == 0:
val = 100 / len(servers)
elif int(server['ipaserviceweight'][0]) == 0:
val = 0.1
else:
val = (
int(server['ipaserviceweight'][0]) *
dividend / weight_sum
)
server['service_relative_weight'] = [
u'{:.1f}%'.format(val)
]
if servers_name:
result['result']['servers_server'] = servers_name
if dns_servers:
result['result']['dns_server'] = dns_servers
if not dns_servers and servers_additional_info:
self.add_message(messages.LocationWithoutDNSServer(
location=keys[0]
))
result['servers'] = servers_additional_info
return result
| 7,983
|
Python
|
.py
| 230
| 24.930435
| 79
| 0.545608
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,839
|
radiusproxy.py
|
freeipa_freeipa/ipaserver/plugins/radiusproxy.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 .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve)
from ipalib import api, Str, Int, Password, _, ngettext
from ipalib import errors
from ipalib.plugable import Registry
from ipalib.util import validate_hostname, validate_ipaddr
from ipalib.errors import ValidationError
from ipapython.dn import DN
import re
__doc__ = _("""
RADIUS Proxy Servers
""") + _("""
Manage RADIUS Proxy Servers.
""") + _("""
IPA supports the use of an external RADIUS proxy server for krb5 OTP
authentications. This permits a great deal of flexibility when
integrating with third-party authentication services.
""") + _("""
EXAMPLES:
""") + _("""
Add a new server:
ipa radiusproxy-add MyRADIUS --server=radius.example.com:1812
""") + _("""
Find all servers whose entries include the string "example.com":
ipa radiusproxy-find example.com
""") + _("""
Examine the configuration:
ipa radiusproxy-show MyRADIUS
""") + _("""
Change the secret:
ipa radiusproxy-mod MyRADIUS --secret
""") + _("""
Delete a configuration:
ipa radiusproxy-del MyRADIUS
""")
register = Registry()
LDAP_ATTRIBUTE = re.compile("^[a-zA-Z][a-zA-Z0-9-]*$")
def validate_attributename(ugettext, attr):
if not LDAP_ATTRIBUTE.match(attr):
raise ValidationError(name="ipatokenusermapattribute",
error=_('invalid attribute name'))
def validate_radiusserver(ugettext, server):
split = server.rsplit(':', 1)
server = split[0]
if len(split) == 2:
try:
port = int(split[1])
if (port < 0 or port > 65535):
raise ValueError()
except ValueError:
raise ValidationError(name="ipatokenradiusserver",
error=_('invalid port number'))
if validate_ipaddr(server):
return
try:
validate_hostname(server, check_fqdn=True, allow_underscore=True)
except ValueError as e:
raise errors.ValidationError(name="ipatokenradiusserver",
error=str(e))
@register()
class radiusproxy(LDAPObject):
"""
RADIUS Server object.
"""
container_dn = api.env.container_radiusproxy
object_name = _('RADIUS proxy server')
object_name_plural = _('RADIUS proxy servers')
object_class = ['ipatokenradiusconfiguration']
default_attributes = ['cn', 'description', 'ipatokenradiusserver',
'ipatokenradiustimeout', 'ipatokenradiusretries', 'ipatokenusermapattribute'
]
search_attributes = ['cn', 'description', 'ipatokenradiusserver']
allow_rename = True
label = _('RADIUS Servers')
label_singular = _('RADIUS Server')
takes_params = (
Str('cn',
cli_name='name',
label=_('RADIUS proxy server name'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this RADIUS proxy server'),
),
Str('ipatokenradiusserver', validate_radiusserver,
cli_name='server',
label=_('Server'),
doc=_('The hostname or IP (with or without port)'),
),
Password('ipatokenradiussecret',
cli_name='secret',
label=_('Secret'),
doc=_('The secret used to encrypt data'),
confirm=True,
),
Int('ipatokenradiustimeout?',
cli_name='timeout',
label=_('Timeout'),
doc=_('The total timeout across all retries (in seconds)'),
minvalue=1,
),
Int('ipatokenradiusretries?',
cli_name='retries',
label=_('Retries'),
doc=_('The number of times to retry authentication'),
minvalue=0,
maxvalue=10,
),
Str('ipatokenusermapattribute?', validate_attributename,
cli_name='userattr',
label=_('User attribute'),
doc=_('The username attribute on the user object'),
),
)
managed_permissions = {
'System: Read Radius Servers': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipatokenradiusserver', 'description',
'ipatokenradiustimeout', 'ipatokenradiusretries',
'ipatokenusermapattribute'
},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermtargetfilter': {
'(objectclass=ipatokenradiusconfiguration)'},
'default_privileges': {
'User Administrators',
'Stage User Administrators'},
}
}
@register()
class radiusproxy_add(LDAPCreate):
__doc__ = _('Add a new RADIUS proxy server.')
msg_summary = _('Added RADIUS proxy server "%(value)s"')
@register()
class radiusproxy_del(LDAPDelete):
__doc__ = _('Delete a RADIUS proxy server.')
msg_summary = _('Deleted RADIUS proxy server "%(value)s"')
@register()
class radiusproxy_mod(LDAPUpdate):
__doc__ = _('Modify a RADIUS proxy server.')
msg_summary = _('Modified RADIUS proxy server "%(value)s"')
@register()
class radiusproxy_find(LDAPSearch):
__doc__ = _('Search for RADIUS proxy servers.')
msg_summary = ngettext(
'%(count)d RADIUS proxy server matched', '%(count)d RADIUS proxy servers matched', 0
)
def get_options(self):
for option in super(radiusproxy_find, self).get_options():
if option.name == 'ipatokenradiussecret':
option = option.clone(flags={'no_option'})
yield option
@register()
class radiusproxy_show(LDAPRetrieve):
__doc__ = _('Display information about a RADIUS proxy server.')
| 6,631
|
Python
|
.py
| 182
| 29.521978
| 92
| 0.633748
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,840
|
permission.py
|
freeipa_freeipa/ipaserver/plugins/permission.py
|
# Authors:
# Petr Viktorin <pviktori@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/>.
import logging
import re
import traceback
import six
from . import baseldap
from .privilege import validate_permission_to_privilege
from ipalib import errors
from ipalib.parameters import Str, StrEnum, DNParam, Flag
from ipalib import api, _, ngettext
from ipalib import messages
from ipalib.plugable import Registry
from ipalib.capabilities import client_has_capability
from ipalib.aci import ACI
from ipapython.dn import DN
from ipalib.request import context
if six.PY3:
unicode = str
__doc__ = _("""
Permissions
""") + _("""
A permission enables fine-grained delegation of rights. A permission is
a human-readable wrapper around a 389-ds Access Control Rule,
or instruction (ACI).
A permission grants the right to perform a specific task such as adding a
user, modifying a group, etc.
""") + _("""
A permission may not contain other permissions.
""") + _("""
* A permission grants access to read, write, add, delete, read, search,
or compare.
* A privilege combines similar permissions (for example all the permissions
needed to add a user).
* A role grants a set of privileges to users, groups, hosts or hostgroups.
""") + _("""
A permission is made up of a number of different parts:
1. The name of the permission.
2. The target of the permission.
3. The rights granted by the permission.
""") + _("""
Rights define what operations are allowed, and may be one or more
of the following:
1. write - write one or more attributes
2. read - read one or more attributes
3. search - search on one or more attributes
4. compare - compare one or more attributes
5. add - add a new entry to the tree
6. delete - delete an existing entry
7. all - all permissions are granted
""") + _("""
Note the distinction between attributes and entries. The permissions are
independent, so being able to add a user does not mean that the user will
be editable.
""") + _("""
There are a number of allowed targets:
1. subtree: a DN; the permission applies to the subtree under this DN
2. target filter: an LDAP filter
3. target: DN with possible wildcards, specifies entries permission applies to
""") + _("""
Additionally, there are the following convenience options.
Setting one of these options will set the corresponding attribute(s).
1. type: a type of object (user, group, etc); sets subtree and target filter.
2. memberof: apply to members of a group; sets target filter
3. targetgroup: grant access to modify a specific group (such as granting
the rights to manage group membership); sets target.
""") + _("""
Managed permissions
""") + _("""
Permissions that come with IPA by default can be so-called "managed"
permissions. These have a default set of attributes they apply to,
but the administrator can add/remove individual attributes to/from the set.
""") + _("""
Deleting or renaming a managed permission, as well as changing its target,
is not allowed.
""") + _("""
EXAMPLES:
""") + _("""
Add a permission that grants the creation of users:
ipa permission-add --type=user --permissions=add "Add Users"
""") + _("""
Add a permission that grants the ability to manage group membership:
ipa permission-add --attrs=member --permissions=write --type=group "Manage Group Members"
""")
logger = logging.getLogger(__name__)
register = Registry()
_DEPRECATED_OPTION_ALIASES = {
'permissions': 'ipapermright',
'filter': 'extratargetfilter',
'subtree': 'ipapermlocation',
}
KNOWN_FLAGS = {'SYSTEM', 'V2', 'MANAGED'}
def strip_ldap_prefix(uri):
prefix = 'ldap:///'
if not uri.startswith(prefix):
raise ValueError('%r does not start with %r' % (uri, prefix))
return uri[len(prefix):]
def prevalidate_filter(ugettext, value):
if not value.startswith('(') or not value.endswith(')'):
return _('must be enclosed in parentheses')
return None
class DNOrURL(DNParam):
"""DN parameter that allows, and strips, a "ldap:///" prefix on input
Used for ``subtree`` to maintain backward compatibility.
"""
def _convert_scalar(self, value, index=None):
if isinstance(value, str) and value.startswith('ldap:///'):
value = strip_ldap_prefix(value)
return super(DNOrURL, self)._convert_scalar(value)
def validate_type(ugettext, typestr):
try:
obj = api.Object[typestr]
except KeyError:
return _('"%s" is not an object type') % typestr
if not getattr(obj, 'permission_filter_objectclasses', None):
return _('"%s" is not a valid permission type') % typestr
return None
def _disallow_colon(option):
"""Given a "cn" option, return a new "cn" option with ':' disallowed
Used in permission-add and for --rename in permission-mod to prevent user
from creating new permissions with ":" in the name.
"""
return option.clone(
pattern='^[-_ a-zA-Z0-9.]+$',
pattern_errmsg="May only contain letters, numbers, -, _, ., and space",
)
_ipapermissiontype_param = Str(
'ipapermissiontype+',
label=_('Permission flags'),
flags={'no_create', 'no_update', 'no_search'},
)
@register()
class permission(baseldap.LDAPObject):
"""
Permission object.
"""
container_dn = api.env.container_permission
object_name = _('permission')
object_name_plural = _('permissions')
# For use the complete object_class list, including 'top', so
# the updater doesn't try to delete 'top' every time.
object_class = ['top', 'groupofnames', 'ipapermission', 'ipapermissionv2']
permission_filter_objectclasses = ['ipapermission']
default_attributes = ['cn', 'member', 'memberof',
'memberindirect', 'ipapermissiontype', 'objectclass',
'ipapermdefaultattr', 'ipapermincludedattr', 'ipapermexcludedattr',
'ipapermbindruletype', 'ipapermlocation', 'ipapermright',
'ipapermtargetfilter', 'ipapermtarget'
]
attribute_members = {
'member': ['privilege'],
'memberindirect': ['role'],
}
allow_rename = True
managed_permissions = {
'System: Read Permissions': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'ipapermissiontype',
'o', 'objectclass', 'ou', 'owner', 'seealso',
'ipapermdefaultattr', 'ipapermincludedattr',
'ipapermexcludedattr', 'ipapermbindruletype', 'ipapermtarget',
'ipapermlocation', 'ipapermright', 'ipapermtargetfilter',
'member', 'memberof', 'memberuser', 'memberhost',
},
'default_privileges': {'RBAC Readers'},
},
'System: Read ACIs': {
# Readable ACIs are needed for reading legacy permissions.
'non_object': True,
'ipapermlocation': api.env.basedn,
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'aci'},
'default_privileges': {'RBAC Readers'},
},
'System: Modify Privilege Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=permissions,cn=pbac,$SUFFIX")(version 3.0;acl "permission:Modify privilege membership";allow (write) groupdn = "ldap:///cn=Modify privilege membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Delegation Administrator'},
},
}
label = _('Permissions')
label_singular = _('Permission')
takes_params = (
Str('cn',
cli_name='name',
label=_('Permission name'),
primary_key=True,
pattern='^[-_ a-zA-Z0-9.:/]+$',
pattern_errmsg="May only contain letters, numbers, "
"-, _, ., :, /, and space",
),
StrEnum(
'ipapermright*',
cli_name='right',
label=_('Granted rights'),
doc=_('Rights to grant '
'(read, search, compare, write, add, delete, all)'),
values=(u'read', u'search', u'compare',
u'write', u'add', u'delete', u'all'),
flags={'ask_create'},
),
Str('attrs*',
label=_('Effective attributes'),
doc=_('All attributes to which the permission applies'),
flags={'virtual_attribute', 'allow_mod_for_managed_permission'},
),
Str('ipapermincludedattr*',
cli_name='includedattrs',
label=_('Included attributes'),
doc=_('User-specified attributes to which the permission applies'),
flags={'no_create', 'allow_mod_for_managed_permission'},
),
Str('ipapermexcludedattr*',
cli_name='excludedattrs',
label=_('Excluded attributes'),
doc=_('User-specified attributes to which the permission '
'explicitly does not apply'),
flags={'no_create', 'allow_mod_for_managed_permission'},
),
Str('ipapermdefaultattr*',
cli_name='defaultattrs',
label=_('Default attributes'),
doc=_('Attributes to which the permission applies by default'),
flags={'no_create', 'no_update'},
),
StrEnum(
'ipapermbindruletype',
cli_name='bindtype',
label=_('Bind rule type'),
doc=_('Bind rule type'),
autofill=True,
values=('permission', 'all', 'anonymous', 'self'),
default='permission',
flags={'allow_mod_for_managed_permission'},
),
DNOrURL(
'ipapermlocation?',
cli_name='subtree',
label=_('Subtree'),
doc=_('Subtree to apply permissions to'),
# force server-side conversion
normalizer=lambda x: x,
flags={'ask_create'},
),
Str(
'extratargetfilter*', prevalidate_filter,
cli_name='filter',
label=_('Extra target filter'),
doc=_('Extra target filter'),
flags={'virtual_attribute'},
),
Str(
'ipapermtargetfilter*', prevalidate_filter,
cli_name='rawfilter',
label=_('Raw target filter'),
doc=_('All target filters, including those implied by '
'type and memberof'),
),
DNParam(
'ipapermtarget?',
cli_name='target',
label=_('Target DN'),
doc=_('Optional DN to apply the permission to '
'(must be in the subtree, but may not yet exist)'),
),
DNParam(
'ipapermtargetto?',
cli_name='targetto',
label=_('Target DN subtree'),
doc=_('Optional DN subtree where an entry can be moved to '
'(must be in the subtree, but may not yet exist)'),
),
DNParam(
'ipapermtargetfrom?',
cli_name='targetfrom',
label=_('Origin DN subtree'),
doc=_('Optional DN subtree from where an entry can be moved '
'(must be in the subtree, but may not yet exist)'),
),
Str('memberof*',
label=_('Member of group'), # FIXME: Does this label make sense?
doc=_('Target members of a group (sets memberOf targetfilter)'),
flags={'ask_create', 'virtual_attribute'},
),
Str('targetgroup?',
label=_('Target group'),
doc=_('User group to apply permissions to (sets target)'),
flags={'ask_create', 'virtual_attribute'},
),
Str(
'type?', validate_type,
label=_('Type'),
doc=_('Type of IPA object '
'(sets subtree and objectClass targetfilter)'),
flags={'ask_create', 'virtual_attribute'},
),
) + tuple(
Str(old_name + '*',
doc=_('Deprecated; use %s' % new_name),
flags={'no_option', 'virtual_attribute'})
for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items()
) + (
_ipapermissiontype_param,
Str('aci',
label=_('ACI'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
)
def reject_system(self, entry):
"""Raise if permission entry has unknown flags, or is a SYSTEM perm"""
flags = entry.get('ipapermissiontype', [])
for flag in flags:
if flag not in KNOWN_FLAGS:
raise errors.ACIError(
info=_('Permission with unknown flag %s may not be '
'modified or removed') % flag)
if list(flags) == [u'SYSTEM']:
raise errors.ACIError(
info=_('A SYSTEM permission may not be modified or removed'))
def _get_filter_attr_info(self, entry):
"""Get information on filter-related virtual attributes
Returns a dict with this information:
'implicit_targetfilters': targetfilters implied by memberof and type
'memberof': list of names of groups from memberof
'type': the type
"""
ipapermtargetfilter = entry.get('ipapermtargetfilter', [])
ipapermlocation = entry.single_value.get('ipapermlocation')
implicit_targetfilters = set()
result = {'implicit_targetfilters': implicit_targetfilters}
# memberof
memberof = []
for targetfilter in ipapermtargetfilter:
match = re.match(r'^\(memberof=(.*)\)$', targetfilter, re.I)
if match:
try:
dn = DN(match.group(1))
except ValueError:
# Malformed DN; e.g. (memberof=*)
continue
groups_dn = DN(self.api.Object.group.container_dn,
self.api.env.basedn)
if dn[1:] == groups_dn[:] and dn[0].attr == 'cn':
memberof.append(dn[0].value)
implicit_targetfilters.add(match.group(0))
if memberof:
result['memberof'] = memberof
# type
if ipapermtargetfilter and ipapermlocation:
for obj in self.api.Object():
filt = self.make_type_filter(obj)
if not filt:
continue
wantdn = DN(obj.container_dn, self.api.env.basedn)
if DN(ipapermlocation) != wantdn:
continue
if filt in ipapermtargetfilter:
result['type'] = [unicode(obj.name)]
implicit_targetfilters.add(filt)
break
return result
def postprocess_result(self, entry, options):
"""Update a permission entry for output (in place)
:param entry: The entry to update
:param options:
Command options. Contains keys such as ``raw``, ``all``,
``pkey_only``, ``version``.
"""
old_client = not client_has_capability(
options['version'], 'permissions2')
if not options.get('raw') and not options.get('pkey_only'):
ipapermtargetfilter = entry.get('ipapermtargetfilter', [])
ipapermtarget = entry.single_value.get('ipapermtarget')
# targetgroup
if ipapermtarget:
dn = DN(ipapermtarget)
if (dn[1:] == DN(self.api.Object.group.container_dn,
self.api.env.basedn)[:] and
dn[0].attr == 'cn' and dn[0].value != '*'):
entry.single_value['targetgroup'] = dn[0].value
filter_attr_info = self._get_filter_attr_info(entry)
if 'type' in filter_attr_info:
entry['type'] = filter_attr_info['type']
if 'memberof' in filter_attr_info:
entry['memberof'] = filter_attr_info['memberof']
if 'implicit_targetfilters' in filter_attr_info:
extratargetfilter = sorted(
set(ipapermtargetfilter) -
filter_attr_info['implicit_targetfilters'])
if extratargetfilter:
entry['extratargetfilter'] = extratargetfilter
# old output names
if old_client:
for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items():
if new_name in entry:
entry[old_name] = entry[new_name]
del entry[new_name]
rights = entry.get('attributelevelrights')
if rights:
if 'ipapermtarget' in rights:
rights['targetgroup'] = rights['ipapermtarget']
if 'ipapermtargetfilter' in rights:
rights['memberof'] = rights['ipapermtargetfilter']
type_rights = set(rights['ipapermtargetfilter'])
location_rights = set(rights.get('ipapermlocation', ''))
type_rights.intersection_update(location_rights)
rights['type'] = ''.join(sorted(
type_rights, key=rights['ipapermtargetfilter'].index))
if 'ipapermincludedattr' in rights:
rights['attrs'] = ''.join(sorted(
set(rights['ipapermincludedattr']) &
set(rights.get('ipapermexcludedattr', '')),
key=rights['ipapermincludedattr'].index))
if old_client:
for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items():
if new_name in rights:
rights[old_name] = rights[new_name]
del rights[new_name]
if options.get('raw'):
# Retreive the ACI from LDAP to ensure we get the real thing
try:
_acientry, acistring = self._get_aci_entry_and_string(entry)
except errors.NotFound:
if list(entry.get('ipapermissiontype')) == ['SYSTEM']:
# SYSTEM permissions don't have normal ACIs
pass
else:
raise
else:
entry.single_value['aci'] = acistring
else:
effective_attrs = self.get_effective_attrs(entry)
if effective_attrs:
entry['attrs'] = effective_attrs
if (not options.get('all') and
not entry.get('ipapermexcludedattr') and
not entry.get('ipapermdefaultattr')):
entry.pop('ipapermincludedattr', None)
if old_client:
# Legacy clients expect some attributes as a single value
for attr in 'type', 'targetgroup', 'aci':
if attr in entry:
entry[attr] = entry.single_value[attr]
# memberof was also single-valued, but not any more
if entry.get('memberof'):
joined_value = u', '.join(str(m) for m in entry['memberof'])
entry['memberof'] = joined_value
if 'subtree' in entry:
# Legacy clients expect subtree as a URL
dn = entry.single_value['subtree']
entry['subtree'] = u'ldap:///%s' % dn
if 'filter' in entry:
# Legacy clients expect filter without parentheses
new_filter = []
for flt in entry['filter']:
assert flt[0] == '(' and flt[-1] == ')'
new_filter.append(flt[1:-1])
entry['filter'] = new_filter
if not options['raw'] and not options['all']:
# Don't return the raw target filter by default
entry.pop('ipapermtargetfilter', None)
def get_effective_attrs(self, entry):
attrs = set(entry.get('ipapermdefaultattr', ()))
attrs.update(entry.get('ipapermincludedattr', ()))
if ('read' in entry.get('ipapermright', ()) and
'objectclass' in (x.lower() for x in attrs)):
# Add special-cased operational attributes
# We want to allow reading these whenever reading the objectclass
# is allowed.
# (But they can still be excluded explicitly, at least in managed
# permissions).
attrs.update((u'entryusn', u'createtimestamp', u'modifytimestamp'))
attrs.difference_update(entry.get('ipapermexcludedattr', ()))
return sorted(attrs)
def make_aci(self, entry):
"""Make an ACI string from the given permission entry"""
msg = None
aci_parts = []
name = entry.single_value['cn']
# targetattr
attrs = self.get_effective_attrs(entry)
if attrs:
aci_parts.append("(targetattr = \"%s\")" % ' || '.join(attrs))
else:
# If we are re-parsing an entry for validation then
# the effective attrs may be empty.
if entry.get('attrs') is None:
rights = set(['read', 'write', 'search', 'compare'])
permrights = set(entry['ipapermright'])
for right in ('add', 'delete'):
permrights.discard(right)
if permrights and permrights.issubset(rights):
msg = messages.MissingTargetAttributesinPermission(
right=', '.join(sorted(entry['ipapermright']))
)
# target
ipapermtarget = entry.single_value.get('ipapermtarget')
if ipapermtarget:
aci_parts.append("(target = \"%s\")" %
'ldap:///%s' % ipapermtarget)
# target_to
ipapermtargetto = entry.single_value.get('ipapermtargetto')
if ipapermtargetto:
aci_parts.append("(target_to = \"%s\")" %
'ldap:///%s' % ipapermtargetto)
# target_from
ipapermtargetfrom = entry.single_value.get('ipapermtargetfrom')
if ipapermtargetfrom:
aci_parts.append("(target_from = \"%s\")" %
'ldap:///%s' % ipapermtargetfrom)
# targetfilter
ipapermtargetfilter = entry.get('ipapermtargetfilter')
if ipapermtargetfilter:
assert all(f.startswith('(') and f.endswith(')')
for f in ipapermtargetfilter)
if len(ipapermtargetfilter) == 1:
filter = ipapermtargetfilter[0]
else:
filter = '(&%s)' % ''.join(sorted(ipapermtargetfilter))
aci_parts.append("(targetfilter = \"%s\")" % filter)
# version, name, rights, bind rule
ipapermbindruletype = entry.single_value.get('ipapermbindruletype',
'permission')
if ipapermbindruletype == 'permission':
dn = DN(('cn', name), self.container_dn, self.api.env.basedn)
bindrule = 'groupdn = "ldap:///%s"' % dn
elif ipapermbindruletype == 'all':
bindrule = 'userdn = "ldap:///all"'
elif ipapermbindruletype == 'anonymous':
bindrule = 'userdn = "ldap:///anyone"'
elif ipapermbindruletype == 'self':
bindrule = 'userdn = "ldap:///self"'
else:
raise ValueError(ipapermbindruletype)
aci_parts.append('(version 3.0;acl "permission:%s";allow (%s) %s;)' % (
name, ','.join(sorted(entry['ipapermright'])), bindrule))
return ''.join(aci_parts), msg
def add_aci(self, permission_entry):
"""Add the ACI coresponding to the given permission entry"""
ldap = self.api.Backend.ldap2
acistring, _msg = self.make_aci(permission_entry)
location = permission_entry.single_value.get('ipapermlocation',
self.api.env.basedn)
logger.debug('Adding ACI %r to %s', acistring, location)
try:
entry = ldap.get_entry(location, ['aci'])
except errors.NotFound:
raise errors.NotFound(reason=_('Entry %s not found') % location)
entry.setdefault('aci', []).append(acistring)
ldap.update_entry(entry)
def remove_aci(self, permission_entry):
"""Remove the ACI corresponding to the given permission entry
:return: tuple:
- entry
- removed ACI string, or None if none existed previously
"""
return self._replace_aci(permission_entry)
def update_aci(self, permission_entry, old_name=None):
"""Update the ACI corresponding to the given permission entry
:return: tuple:
- entry
- removed ACI string, or None if none existed previously
"""
new_acistring, _msg = self.make_aci(permission_entry)
return self._replace_aci(permission_entry, old_name, new_acistring)
def _replace_aci(self, permission_entry, old_name=None, new_acistring=None):
"""Replace ACI corresponding to permission_entry
:param old_name: the old name of the permission, if different from new
:param new_acistring: new ACI string; if None the ACI is just deleted
:return: tuple:
- entry
- removed ACI string, or None if none existed previously
"""
ldap = self.api.Backend.ldap2
acientry, acistring = self._get_aci_entry_and_string(
permission_entry, old_name, notfound_ok=True)
# (pylint thinks `acientry` is just a dict, but it's an LDAPEntry)
acidn = acientry.dn
if acistring is not None:
logger.debug('Removing ACI %r from %s', acistring, acidn)
acientry['aci'].remove(acistring)
if new_acistring:
logger.debug('Adding ACI %r to %s', new_acistring, acidn)
acientry.setdefault('aci', []).append(new_acistring)
try:
ldap.update_entry(acientry)
except errors.EmptyModlist:
logger.debug('No changes to ACI')
return acientry, acistring
def check_attrs(self, result, *keys, **options):
"""Re-build the ACI to determine if there are rights that
only work when there are attributes defined."""
ldap = self.backend
dn = self.get_dn(*keys, **options)
entry = ldap.make_entry(dn, result['result'])
for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items():
if old_name in entry:
entry[new_name] = entry[old_name]
del entry[old_name]
_acistring, msg = self.make_aci(entry)
if msg:
messages.add_message(
options['version'],
result,
msg,
)
def _get_aci_entry_and_string(self, permission_entry, name=None,
notfound_ok=False, cached_acientry=None):
"""Get the entry and ACI corresponding to the permission entry
:param name: The name of the permission, or None for the cn
:param notfound_ok:
If true, (acientry, None) will be returned on missing ACI, rather
than raising exception
:param cached_acientry: See upgrade_permission()
"""
ldap = self.api.Backend.ldap2
if name is None:
name = permission_entry.single_value['cn']
location = permission_entry.single_value.get('ipapermlocation',
self.api.env.basedn)
wanted_aciname = 'permission:%s' % name
if (cached_acientry and
cached_acientry.dn == location and
'aci' in cached_acientry):
acientry = cached_acientry
else:
try:
acientry = ldap.get_entry(location, ['aci'])
except errors.NotFound:
acientry = ldap.make_entry(location)
acis = acientry.get('aci', ())
for acistring in acis:
try:
aci = ACI(acistring)
except SyntaxError as e:
logger.warning('Unparseable ACI %s: %s (at %s)',
acistring, e, location)
continue
if aci.name == wanted_aciname:
return acientry, acistring
if notfound_ok:
return acientry, None
raise errors.NotFound(
reason=_('The ACI for permission %(name)s was not found '
'in %(dn)s ') % {'name': name, 'dn': location})
def upgrade_permission(self, entry, target_entry=None,
output_only=False, cached_acientry=None):
"""Upgrade the given permission entry to V2, in-place
The entry is only upgraded if it is a plain old-style permission,
that is, it has no flags set.
:param target_entry:
If given, ``target_entry`` is filled from information taken
from the ACI corresponding to ``entry``.
If None, ``entry`` itself is filled
:param output_only:
If true, the flags & objectclass are not updated to V2.
Used for the -find and -show commands.
:param cached_acientry:
Optional pre-retreived entry that contains the existing ACI.
If it is None or its DN does not match the location DN,
cached_acientry is ignored and the entry is retreived from LDAP.
"""
if entry.get('ipapermissiontype'):
# Only convert old-style, non-SYSTEM permissions -- i.e. no flags
return
base, acistring = self._get_aci_entry_and_string(
entry, cached_acientry=cached_acientry)
if not target_entry:
target_entry = entry
# The DN of old permissions is always basedn
# (pylint thinks `base` is just a dict, but it's an LDAPEntry)
assert base.dn == self.api.env.basedn, base
aci = ACI(acistring)
if 'target' in aci.target:
target_entry.single_value['ipapermtarget'] = DN(strip_ldap_prefix(
aci.target['target']['expression']))
if 'targetfilter' in aci.target:
target_entry.single_value['ipapermtargetfilter'] = unicode(
aci.target['targetfilter']['expression'])
if aci.bindrule['expression'] == 'ldap:///all':
target_entry.single_value['ipapermbindruletype'] = u'all'
elif aci.bindrule['expression'] == 'ldap:///anyone':
target_entry.single_value['ipapermbindruletype'] = u'anonymous'
else:
target_entry.single_value['ipapermbindruletype'] = u'permission'
target_entry['ipapermright'] = aci.permissions
if 'targetattr' in aci.target:
target_entry['ipapermincludedattr'] = [
unicode(a) for a in aci.target['targetattr']['expression']]
if not output_only:
target_entry['ipapermissiontype'] = ['SYSTEM', 'V2']
if 'ipapermissionv2' not in entry['objectclass']:
target_entry['objectclass'] = list(entry['objectclass']) + [
u'ipapermissionv2']
target_entry['ipapermlocation'] = [self.api.env.basedn]
# Make sure we're not losing *any info* by the upgrade
new_acistring, _msg = self.make_aci(target_entry)
if not ACI(new_acistring).isequal(aci):
raise ValueError('Cannot convert ACI, %r != %r' % (new_acistring,
acistring))
def make_type_filter(self, obj):
"""Make a filter for a --type based permission from an Object"""
objectclasses = getattr(obj, 'permission_filter_objectclasses', None)
if not objectclasses:
return None
filters = [u'(objectclass=%s)' % o for o in objectclasses]
if len(filters) == 1:
return filters[0]
else:
return '(|%s)' % ''.join(sorted(filters))
def preprocess_options(self, options,
return_filter_ops=False,
merge_targetfilter=False):
"""Preprocess options (in-place)
:param options: A dictionary of options
:param return_filter_ops:
If false, assumes there is no pre-existing entry;
additional values of ipapermtargetfilter are added to options.
If true, a dictionary of operations on ipapermtargetfilter is
returned.
These operations must be performed after the existing entry
is retrieved.
The dict has the following keys:
- remove: list of regular expression objects;
implicit values that match any of them should be removed
- add: list of values to be added, after any removals
:merge_targetfilter:
If true, the extratargetfilter is copied into ipapermtargetfilter.
"""
if 'extratargetfilter' in options:
if 'ipapermtargetfilter' in options:
raise errors.ValidationError(
name='ipapermtargetfilter',
error=_('cannot specify full target filter '
'and extra target filter simultaneously'))
if merge_targetfilter:
options['ipapermtargetfilter'] = options['extratargetfilter']
filter_ops = {'add': [], 'remove': []}
if options.get('subtree'):
if isinstance(options['subtree'], (list, tuple)):
[options['subtree']] = options['subtree']
try:
options['subtree'] = strip_ldap_prefix(options['subtree'])
except ValueError:
raise errors.ValidationError(
name='subtree',
error='does not start with "ldap:///"')
# Handle old options
for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items():
if old_name in options:
if client_has_capability(options['version'], 'permissions2'):
raise errors.ValidationError(
name=old_name,
error=_('option was renamed; use %s') % new_name)
if new_name in options:
raise errors.ValidationError(
name=old_name,
error=(_('Cannot use %(old_name)s with %(new_name)s') %
{'old_name': old_name, 'new_name': new_name}))
options[new_name] = options[old_name]
del options[old_name]
# memberof
if 'memberof' in options:
filter_ops['remove'].append(re.compile(r'\(memberOf=.*\)', re.I))
memberof = options.pop('memberof')
for group in (memberof or ()):
try:
groupdn = self.api.Object.group.get_dn_if_exists(group)
except errors.NotFound:
raise errors.NotFound(
reason=_('%s: group not found') % group)
filter_ops['add'].append(u'(memberOf=%s)' % groupdn)
# targetgroup
if 'targetgroup' in options:
targetgroup = options.pop('targetgroup')
if targetgroup:
if 'ipapermtarget' in options:
raise errors.ValidationError(
name='ipapermtarget',
error=_('target and targetgroup are mutually exclusive'))
try:
groupdn = self.api.Object.group.get_dn_if_exists(targetgroup)
except errors.NotFound:
raise errors.NotFound(
reason=_('%s: group not found') % targetgroup)
options['ipapermtarget'] = groupdn
else:
if 'ipapermtarget' not in options:
options['ipapermtarget'] = None
# type
if 'type' in options:
objtype = options.pop('type')
filter_ops['remove'].append(re.compile(r'\(objectclass=.*\)', re.I))
filter_ops['remove'].append(re.compile(
r'\(\|(\(objectclass=[^(]*\))+\)', re.I))
if objtype:
if 'ipapermlocation' in options:
raise errors.ValidationError(
name='ipapermlocation',
error=_('subtree and type are mutually exclusive'))
obj = self.api.Object[objtype.lower()]
filt = self.make_type_filter(obj)
if not filt:
raise errors.ValidationError(
_('"%s" is not a valid permission type') % objtype)
filter_ops['add'].append(filt)
container_dn = DN(obj.container_dn, self.api.env.basedn)
options['ipapermlocation'] = container_dn
else:
if 'ipapermlocation' not in options:
options['ipapermlocation'] = None
if return_filter_ops:
return filter_ops
elif filter_ops['add']:
options['ipapermtargetfilter'] = list(options.get(
'ipapermtargetfilter') or []) + filter_ops['add']
return None
def validate_permission(self, entry):
ldap = self.Backend.ldap2
# Rough filter validation by a search
if entry.get('ipapermtargetfilter'):
try:
ldap.find_entries(
filter=ldap.combine_filters(entry['ipapermtargetfilter'],
rules='&'),
base_dn=self.env.basedn,
scope=ldap.SCOPE_BASE,
size_limit=1)
except errors.NotFound:
pass
except errors.BadSearchFilter:
raise errors.ValidationError(
name='ipapermtargetfilter',
error=_('Bad search filter'))
# Ensure location exists
if entry.get('ipapermlocation'):
location = DN(entry.single_value['ipapermlocation'])
try:
ldap.get_entry(location, attrs_list=[])
except errors.NotFound:
raise errors.ValidationError(
name='ipapermlocation',
error=_('Entry %s does not exist') % location)
# Ensure there's something in the ACI's filter
needed_attrs = (
'ipapermtarget', 'ipapermtargetfilter',
'ipapermincludedattr', 'ipapermexcludedattr', 'ipapermdefaultattr')
if not any(v for a in needed_attrs for v in (entry.get(a) or ())):
raise errors.ValidationError(
name='target',
error=_('there must be at least one target entry specifier '
'(e.g. target, targetfilter, attrs)'))
# Ensure there's a right
if not entry.get('ipapermright'):
raise errors.RequirementError(name='ipapermright')
@register()
class permission_add_noaci(baseldap.LDAPCreate):
__doc__ = _('Add a system permission without an ACI (internal command)')
msg_summary = _('Added permission "%(value)s"')
NO_CLI = True
takes_options = (
_ipapermissiontype_param,
)
def get_options(self):
perm_options = set(o.name for o in self.obj.takes_params)
for option in super(permission_add_noaci, self).get_options():
# From new options, only cn & ipapermissiontype are supported
if option.name in ['ipapermissiontype']:
yield option.clone()
# Other options such as raw, version are supported
elif option.name not in perm_options:
yield option.clone()
def pre_callback(self, ldap, dn, entry, attrs_list, *keys, **options):
entry['ipapermissiontype'] = list(options['ipapermissiontype'])
entry['objectclass'] = [oc for oc in entry['objectclass']
if oc.lower() != 'ipapermissionv2']
return dn
@register()
class permission_add(baseldap.LDAPCreate):
__doc__ = _('Add a new permission.')
msg_summary = _('Added permission "%(value)s"')
# Need to override execute so that processed options apply to
# the whole command, not just the callbacks
def execute(self, *keys, **options):
self.obj.preprocess_options(options, merge_targetfilter=True)
result = super(permission_add, self).execute(*keys, **options)
self.obj.check_attrs(result, *keys, **options)
return result
def get_args(self):
for arg in super(permission_add, self).get_args():
if arg.name == 'cn':
yield _disallow_colon(arg)
else:
yield arg
def pre_callback(self, ldap, dn, entry, attrs_list, *keys, **options):
entry['ipapermissiontype'] = ['SYSTEM', 'V2']
entry['cn'] = list(keys)
if not entry.get('ipapermlocation'):
entry.setdefault('ipapermlocation', [api.env.basedn])
if 'attrs' in options:
if 'ipapermincludedattr' in options:
raise errors.ValidationError(
name='attrs',
error=_('attrs and included attributes are '
'mutually exclusive'))
entry['ipapermincludedattr'] = list(options.pop('attrs') or ())
self.obj.validate_permission(entry)
return dn
def post_callback(self, ldap, dn, entry, *keys, **options):
try:
self.obj.add_aci(entry)
except Exception as e:
# Adding the ACI failed.
# We want to be 100% sure the ACI is not there, so try to
# remove it. (This is a no-op if the ACI was not added.)
self.obj.remove_aci(entry)
# Remove the entry.
# The permission entry serves as a "lock" tho prevent
# permission-add commands started at the same time from
# interfering. As long as the entry is there, the other
# permission-add will fail with DuplicateEntry.
# So deleting entry ("releasing the lock") must be the last
# thing we do here.
try:
self.api.Backend['ldap2'].delete_entry(entry)
except errors.NotFound:
pass
if isinstance(e, errors.NotFound):
# add_aci may raise NotFound if the subtree is only virtual
# like cn=compat,SUFFIX and thus passes the LDAP get entry test
location = DN(entry.single_value['ipapermlocation'])
raise errors.ValidationError(
name='ipapermlocation',
error=_('Cannot store permission ACI to %s') % location)
# Re-raise original exception
raise
self.obj.postprocess_result(entry, options)
return dn
@register()
class permission_del(baseldap.LDAPDelete):
__doc__ = _('Delete a permission.')
msg_summary = _('Deleted permission "%(value)s"')
takes_options = baseldap.LDAPDelete.takes_options + (
Flag('force',
label=_('Force'),
flags={'no_option', 'no_output'},
doc=_('force delete of SYSTEM permissions'),
),
)
def pre_callback(self, ldap, dn, *keys, **options):
try:
entry = ldap.get_entry(dn, attrs_list=self.obj.default_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if not options.get('force'):
self.obj.reject_system(entry)
if entry.get('ipapermdefaultattr'):
raise errors.ACIError(
info=_('cannot delete managed permissions'))
try:
self.obj.remove_aci(entry)
except errors.NotFound:
raise errors.NotFound(
reason=_('ACI of permission %s was not found') % keys[0])
return dn
@register()
class permission_mod(baseldap.LDAPUpdate):
__doc__ = _('Modify a permission.')
msg_summary = _('Modified permission "%(value)s"')
def execute(self, *keys, **options):
context.filter_ops = self.obj.preprocess_options(
options, return_filter_ops=True)
result = super(permission_mod, self).execute(*keys, **options)
self.obj.check_attrs(result, *keys, **options)
return result
def get_options(self):
for opt in super(permission_mod, self).get_options():
if opt.name == 'rename':
yield _disallow_colon(opt)
else:
yield opt
def pre_callback(self, ldap, dn, entry, attrs_list, *keys, **options):
if 'rename' in options and not options['rename']:
raise errors.ValidationError(name='rename',
error='New name can not be empty')
try:
attrs_list = self.obj.default_attributes
old_entry = ldap.get_entry(dn, attrs_list=attrs_list)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
self.obj.reject_system(old_entry)
self.obj.upgrade_permission(old_entry)
if 'MANAGED' in old_entry.get('ipapermissiontype', ()):
for option_name in sorted(options):
if option_name == 'rename':
raise errors.ValidationError(
name=option_name,
error=_('cannot rename managed permissions'))
option = self.options[option_name]
allow_mod = 'allow_mod_for_managed_permission' in option.flags
if (option.attribute and not allow_mod or
option_name == 'extratargetfilter'):
raise errors.ValidationError(
name=option_name,
error=_('not modifiable on managed permissions'))
if context.filter_ops.get('add'):
raise errors.ValidationError(
name='ipapermtargetfilter',
error=_('not modifiable on managed permissions'))
else:
if options.get('ipapermexcludedattr'):
# prevent setting excluded attributes on normal permissions
# (but do allow deleting them all)
raise errors.ValidationError(
name='ipapermexcludedattr',
error=_('only available on managed permissions'))
if 'attrs' in options:
if any(a in options for a in ('ipapermincludedattr',
'ipapermexcludedattr')):
raise errors.ValidationError(
name='attrs',
error=_('attrs and included/excluded attributes are '
'mutually exclusive'))
attrs = set(options.pop('attrs') or ())
defaults = set(old_entry.get('ipapermdefaultattr', ()))
entry['ipapermincludedattr'] = list(attrs - defaults)
entry['ipapermexcludedattr'] = list(defaults - attrs)
# Check setting bindtype for an assigned permission
if options.get('ipapermbindruletype') and old_entry.get('member'):
raise errors.ValidationError(
name='ipapermbindruletype',
error=_('cannot set bindtype for a permission that is '
'assigned to a privilege'))
# Since `entry` only contains the attributes we are currently changing,
# it cannot be used directly to generate an ACI.
# First we need to copy the original data into it.
for key, value in old_entry.items():
if (key not in options and
key != 'cn' and
key not in self.obj.attribute_members):
entry.setdefault(key, value)
# For extratargetfilter, add it to the implicit filters
# to get the full target filter
if 'extratargetfilter' in options:
filter_attr_info = self.obj._get_filter_attr_info(entry)
entry['ipapermtargetfilter'] = (
list(options['extratargetfilter'] or []) +
list(filter_attr_info['implicit_targetfilters']))
filter_ops = context.filter_ops
old_filter_attr_info = self.obj._get_filter_attr_info(old_entry)
old_implicit_filters = old_filter_attr_info['implicit_targetfilters']
removes = filter_ops.get('remove', [])
new_filters = set(
filt for filt in (entry.get('ipapermtargetfilter') or [])
if filt not in old_implicit_filters or
not any(rem.match(filt) for rem in removes))
new_filters.update(filter_ops.get('add', []))
new_filters.update(options.get('ipapermtargetfilter') or [])
entry['ipapermtargetfilter'] = list(new_filters)
if not entry.get('ipapermlocation'):
entry['ipapermlocation'] = [self.api.env.basedn]
self.obj.validate_permission(entry)
old_location = old_entry.single_value.get('ipapermlocation',
self.api.env.basedn)
if old_location == options.get('ipapermlocation', old_location):
context.permision_moving_aci = False
else:
context.permision_moving_aci = True
try:
context.old_aci_info = self.obj.remove_aci(old_entry)
except errors.NotFound as e:
logger.error('permission ACI not found: %s', e)
# To pass data to postcallback, we currently need to use the context
context.old_entry = old_entry
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
if call_func.__name__ == 'update_entry':
self._revert_aci()
raise exc
def _revert_aci(self):
old_aci_info = getattr(context, 'old_aci_info', None)
if old_aci_info:
# Try to roll back the old ACI
entry, old_aci_string = old_aci_info
if old_aci_string:
logger.warning('Reverting ACI on %s to %s', entry.dn,
old_aci_string)
entry['aci'].append(old_aci_string)
self.Backend.ldap2.update_entry(entry)
def post_callback(self, ldap, dn, entry, *keys, **options):
old_entry = context.old_entry
try:
if context.permision_moving_aci:
self.obj.add_aci(entry)
else:
self.obj.update_aci(entry, old_entry.single_value['cn'])
except Exception:
# Don't revert attributes which don't exist in LDAP
entry.pop('attributelevelrights', None)
for attr in list(
filter(
lambda x: x not in ["member", "memberof"],
[*self.obj.relationships],
)
):
entry.pop(attr, None)
logger.error('Error updating ACI: %s', traceback.format_exc())
logger.warning('Reverting entry')
old_entry.reset_modlist(entry)
ldap.update_entry(old_entry)
self._revert_aci()
raise
self.obj.postprocess_result(entry, options)
entry['dn'] = entry.dn
return dn
@register()
class permission_find(baseldap.LDAPSearch):
__doc__ = _('Search for permissions.')
msg_summary = ngettext(
'%(count)d permission matched', '%(count)d permissions matched', 0)
def execute(self, *keys, **options):
self.obj.preprocess_options(options, merge_targetfilter=True)
return super(permission_find, self).execute(*keys, **options)
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope,
*args, **options):
if 'attrs' in options and 'ipapermincludedattr' in options:
raise errors.ValidationError(
name='attrs',
error=_('attrs and included/excluded attributes are '
'mutually exclusive'))
if options.get('attrs'):
# Effective attributes:
# each attr must be in either default or included,
# but not in excluded
filters = ldap.combine_filters(
[filters] + [
'(&'
'(|'
'(ipapermdefaultattr=%(attr)s)'
'(ipapermincludedattr=%(attr)s))'
'(!(ipapermexcludedattr=%(attr)s)))' % {'attr': attr}
for attr in options['attrs']
],
ldap.MATCH_ALL,
)
return filters, base_dn, scope
def post_callback(self, ldap, entries, truncated, *args, **options):
if 'attrs' in options:
options['ipapermincludedattr'] = options['attrs']
attribute_options = [o for o in options
if (o in self.options and
self.options[o].attribute)]
if not options.get('pkey_only'):
for entry in entries:
# Old-style permissions might have matched (e.g. by name)
self.obj.upgrade_permission(entry, output_only=True)
if not truncated:
max_entries = options.get(
'sizelimit', self.api.Backend.ldap2.size_limit
)
if max_entries > 0:
# should we get more entries than current sizelimit, fail
assert len(entries) <= max_entries
filters = ['(objectclass=ipaPermission)',
'(!(ipaPermissionType=V2))']
if 'name' in options:
filters.append(ldap.make_filter_from_attr('cn',
options['name'],
exact=False))
index = tuple(self.args).index('criteria')
try:
term = args[index]
filters.append(self.get_term_filter(ldap, term))
except IndexError:
term = None
attrs_list = list(self.obj.default_attributes)
attrs_list += list(self.obj.attribute_members)
if options.get('all'):
attrs_list.append('*')
try:
legacy_entries, truncated = ldap.find_entries(
base_dn=DN(self.obj.container_dn, self.api.env.basedn),
filter=ldap.combine_filters(filters, rules=ldap.MATCH_ALL),
attrs_list=attrs_list, size_limit=max_entries)
# Retrieve the root entry (with all legacy ACIs) at once
root_entry = ldap.get_entry(DN(api.env.basedn), ['aci'])
except errors.NotFound:
legacy_entries = ()
logger.debug('potential legacy entries: %s', len(legacy_entries))
nonlegacy_names = {e.single_value['cn'] for e in entries}
for entry in legacy_entries:
if entry.single_value['cn'] in nonlegacy_names:
continue
self.obj.upgrade_permission(entry, output_only=True,
cached_acientry=root_entry)
# If all given options match, include the entry
# Do a case-insensitive match, on any value if multi-valued
for opt in attribute_options:
optval = options[opt]
if not isinstance(optval, (tuple, list)):
optval = [optval]
value = entry.get(opt)
if not value:
break
if not all(any(str(ov).lower() in str(v).lower()
for v in value) for ov in optval):
break
else:
# Each search term must be present in some
# attribute value
for arg in args:
if arg:
arg = arg.lower()
if not any(arg in str(value).lower()
for values in entry.values()
for value in values):
break
else:
if max_entries > 0 and len(entries) == max_entries:
# We've reached the limit, set truncated flag
# (max_entries <= 0 means unlimited)
truncated = True
break
entries.append(entry)
for entry in entries:
if options.get('pkey_only'):
for opt_name in list(entry):
if opt_name != self.obj.primary_key.name:
del entry[opt_name]
else:
self.obj.postprocess_result(entry, options)
return truncated
@register()
class permission_show(baseldap.LDAPRetrieve):
__doc__ = _('Display information about a permission.')
def post_callback(self, ldap, dn, entry, *keys, **options):
self.obj.upgrade_permission(entry, output_only=True)
self.obj.postprocess_result(entry, options)
return dn
@register()
class permission_add_member(baseldap.LDAPAddMember):
__doc__ = _('Add members to a permission.')
NO_CLI = True
def pre_callback(self, ldap, dn, member_dns, failed, *keys, **options):
# We can only add permissions with bind rule type set to
# "permission" (or old-style permissions)
validate_permission_to_privilege(self.api, keys[-1])
return dn
@register()
class permission_remove_member(baseldap.LDAPRemoveMember):
__doc__ = _('Remove members from a permission.')
NO_CLI = True
| 59,018
|
Python
|
.py
| 1,274
| 33.791209
| 253
| 0.567239
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,841
|
ping.py
|
freeipa_freeipa/ipaserver/plugins/ping.py
|
# Authors:
# Rob Crittenden <rcritten@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 ipalib import Command
from ipalib import output
from ipalib import _
from ipalib.plugable import Registry
from ipapython.version import VERSION, API_VERSION
__doc__ = _("""
Ping the remote IPA server to ensure it is running.
The ping command sends an echo request to an IPA server. The server
returns its version information. This is used by an IPA client
to confirm that the server is available and accepting requests.
The server from xmlrpc_uri in /etc/ipa/default.conf is contacted first.
If it does not respond then the client will contact any servers defined
by ldap SRV records in DNS.
EXAMPLES:
Ping an IPA server:
ipa ping
------------------------------------------
IPA server version 2.1.9. API version 2.20
------------------------------------------
Ping an IPA server verbosely:
ipa -v ping
ipa: INFO: trying https://ipa.example.com/ipa/xml
ipa: INFO: Forwarding 'ping' to server 'https://ipa.example.com/ipa/xml'
-----------------------------------------------------
IPA server version 2.1.9. API version 2.20
-----------------------------------------------------
""")
register = Registry()
@register()
class ping(Command):
__doc__ = _('Ping a remote server.')
has_output = (
output.summary,
)
def execute(self, **options):
"""
A possible enhancement would be to take an argument and echo it
back but a fixed value works for now.
"""
return dict(summary=u'IPA server version %s. API version %s' % (VERSION, API_VERSION))
| 2,320
|
Python
|
.py
| 58
| 37.137931
| 94
| 0.676889
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,842
|
host.py
|
freeipa_freeipa/ipaserver/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 __future__ import absolute_import
import logging
import six
from ipalib import api, errors, util
from ipalib import messages
from ipalib import Str, StrEnum, Flag
from ipalib.parameters import Data, Principal, Certificate
from ipalib.plugable import Registry
from .baseldap import (LDAPQuery, LDAPObject, LDAPCreate,
LDAPDelete, LDAPUpdate, LDAPSearch,
LDAPRetrieve, LDAPAddMember,
LDAPRemoveMember, host_is_master,
pkey_to_value, add_missing_object_class,
LDAPAddAttribute, LDAPRemoveAttribute,
LDAPAddAttributeViaOption,
LDAPRemoveAttributeViaOption)
from .service import (
validate_realm, validate_auth_indicator, normalize_principal,
set_certificate_attrs, ticket_flags_params, update_krbticketflags,
set_kerberos_attrs, rename_ipaallowedtoperform_from_ldap,
rename_ipaallowedtoperform_to_ldap, revoke_certs)
from .dns import (dns_container_exists,
add_records_for_host_validation, add_records_for_host,
get_reverse_zone)
from ipalib import _, ngettext
from ipalib import output
from ipalib.request import context
from ipalib.util import (normalize_sshpubkey, validate_sshpubkey_no_options,
convert_sshpubkey_post,
add_sshpubkey_to_attrs_pre,
remove_sshpubkey_from_output_post,
remove_sshpubkey_from_output_list_post,
normalize_hostname,
hostname_validator,
set_krbcanonicalname
)
from ipapython.ipautil import (
ipa_generate_password,
CheckedIPAddress,
TMP_PWD_ENTROPY_BITS
)
from ipapython.dnsutil import DNSName, zone_for_name
from ipapython.ssh import SSHPublicKey
from ipapython.dn import DN
from ipapython import kerberos
from functools import reduce
if six.PY3:
unicode = str
__doc__ = _("""
Hosts/Machines
A host represents a machine. It can be used in a number of contexts:
- service entries are associated with a host
- a host stores the host/ service principal
- a host can be used in Host-based Access Control (HBAC) rules
- every enrolled client generates a host entry
""") + _("""
ENROLLMENT:
There are three enrollment scenarios when enrolling a new client:
1. You are enrolling as a full administrator. The host entry may exist
or not. A full administrator is a member of the hostadmin role
or the admins group.
2. You are enrolling as a limited administrator. The host must already
exist. A limited administrator is a member a role with the
Host Enrollment privilege.
3. The host has been created with a one-time password.
""") + _("""
RE-ENROLLMENT:
Host that has been enrolled at some point, and lost its configuration (e.g. VM
destroyed) can be re-enrolled.
For more information, consult the manual pages for ipa-client-install.
A host can optionally store information such as where it is located,
the OS that it runs, etc.
""") + _("""
EXAMPLES:
""") + _("""
Add a new host:
ipa host-add --location="3rd floor lab" --locality=Dallas test.example.com
""") + _("""
Delete a host:
ipa host-del test.example.com
""") + _("""
Add a new host with a one-time password:
ipa host-add --os='Fedora 12' --password=Secret123 test.example.com
""") + _("""
Add a new host with a random one-time password:
ipa host-add --os='Fedora 12' --random test.example.com
""") + _("""
Modify information about a host:
ipa host-mod --os='Fedora 12' test.example.com
""") + _("""
Remove SSH public keys of a host and update DNS to reflect this change:
ipa host-mod --sshpubkey= --updatedns test.example.com
""") + _("""
Disable the host Kerberos key, SSL certificate and all of its services:
ipa host-disable test.example.com
""") + _("""
Add a host that can manage this host's keytab and certificate:
ipa host-add-managedby --hosts=test2 test
""") + _("""
Allow user to create a keytab:
ipa host-allow-create-keytab test2 --users=tuser1
""")
logger = logging.getLogger(__name__)
register = Registry()
def remove_ptr_rec(ipaddr, fqdn):
"""
Remove PTR record of IP address (ipaddr)
:return: True if PTR record was removed, False if record was not found
"""
logger.debug('deleting PTR record of ipaddr %s', ipaddr)
try:
revzone, revname = get_reverse_zone(ipaddr)
# assume that target in PTR record is absolute name (otherwise it is
# non-standard configuration)
delkw = {'ptrrecord': u"%s" % fqdn.make_absolute()}
api.Command['dnsrecord_del'](revzone, revname, **delkw)
except (errors.NotFound, errors.AttrValueNotFound):
logger.debug('PTR record of ipaddr %s not found', ipaddr)
return False
return True
def update_sshfp_record(zone, record, entry_attrs):
if 'ipasshpubkey' not in entry_attrs:
return
pubkeys = entry_attrs['ipasshpubkey'] or ()
sshfps = []
for pubkey in pubkeys:
try:
sshfp = SSHPublicKey(pubkey).fingerprint_dns_sha1()
except (ValueError, UnicodeDecodeError):
continue
if sshfp is not None:
sshfps.append(sshfp)
try:
sshfp = SSHPublicKey(pubkey).fingerprint_dns_sha256()
except (ValueError, UnicodeDecodeError):
continue
if sshfp is not None:
sshfps.append(sshfp)
try:
api.Command['dnsrecord_mod'](zone, record, sshfprecord=sshfps)
except errors.EmptyModlist:
pass
def convert_ipaassignedidview_post(entry_attrs, options):
"""
Converts the ID View DN to its name for the better looking output.
"""
if 'ipaassignedidview' in entry_attrs and not options.get('raw'):
idview_name = entry_attrs.single_value['ipaassignedidview'][0].value
entry_attrs.single_value['ipaassignedidview'] = idview_name
host_output_params = (
Flag('has_keytab',
label=_('Keytab'),
),
Str('managedby_host',
label='Managed by',
),
Str('managing_host',
label='Managing',
),
Str('managedby',
label=_('Failed managedby'),
),
Str('ipaallowedtoperform_read_keys_user',
label=_('Users allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_group',
label=_('Groups allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_host',
label=_('Hosts allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_hostgroup',
label=_('Host Groups allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_write_keys_user',
label=_('Users allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_group',
label=_('Groups allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_host',
label=_('Hosts allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_hostgroup',
label=_('Host Groups allowed to create keytab'),
),
Str('ipaallowedtoperform_read_keys',
label=_('Failed allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_write_keys',
label=_('Failed allowed to create keytab'),
),
Str('ipaallowedtoperform_write_delegation_user',
label=_('Users allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_group',
label=_('Groups allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_host',
label=_('Hosts allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_hostgroup',
label=_('Host Groups allowed to add resource delegation')),
)
def validate_ipaddr(ugettext, ipaddr):
"""
Verify that we have either an IPv4 or IPv6 address.
"""
try:
CheckedIPAddress(ipaddr)
except Exception as e:
return unicode(e)
return None
def resolve_fqdn(name):
hostentry = api.Command['host_show'](name)['result']
return hostentry['fqdn'][0]
class HostPassword(Str):
"""
A data type for host passwords to not log password values
The Password type cannot be used because it disallows
setting a password on the command-line which would break
backwards compatibility.
"""
kwargs = Data.kwargs + (
('pattern', (str,), None),
('noextrawhitespace', bool, False),
)
def safe_value(self, value):
return u'********'
@register()
class host(LDAPObject):
"""
Host object.
"""
container_dn = api.env.container_host
object_name = _('host')
object_name_plural = _('hosts')
object_class = ['ipaobject', 'nshost', 'ipahost', 'pkiuser', 'ipaservice']
possible_objectclasses = ['ipaallowedoperations']
permission_filter_objectclasses = ['ipahost']
# object_class_config = 'ipahostobjectclasses'
search_attributes = [
'fqdn', 'description', 'l', 'nshostlocation', 'krbcanonicalname',
'krbprincipalname', 'nshardwareplatform', 'nsosversion', 'managedby',
]
default_attributes = [
'fqdn', 'description', 'l', 'nshostlocation', 'krbcanonicalname',
'krbprincipalname',
'nshardwareplatform', 'nsosversion', 'usercertificate', 'memberof',
'managedby', 'memberofindirect', 'macaddress',
'userclass', 'ipaallowedtoperform', 'ipaassignedidview',
'krbprincipalauthind', 'memberprincipal',
]
uuid_attribute = 'ipauniqueid'
attribute_members = {
'enrolledby': ['user'],
'memberof': ['hostgroup', 'netgroup', 'role', 'hbacrule', 'sudorule'],
'managedby': ['host'],
'managing': ['host'],
'memberofindirect': ['hostgroup', 'netgroup', 'role', 'hbacrule',
'sudorule'],
'ipaallowedtoperform_read_keys': ['user', 'group', 'host', 'hostgroup'],
'ipaallowedtoperform_write_keys': ['user', 'group', 'host', 'hostgroup'],
'ipaallowedtoperform_write_delegation':
['user', 'group', 'host', 'hostgroup'],
}
bindable = True
relationships = {
'memberof': ('Member Of', 'in_', 'not_in_'),
'enrolledby': ('Enrolled by', 'enroll_by_', 'not_enroll_by_'),
'managedby': ('Managed by', 'man_by_', 'not_man_by_'),
'managing': ('Managing', 'man_', 'not_man_'),
'ipaallowedtoperform_read_keys': ('Allow to retrieve keytab by', 'retrieve_keytab_by_', 'not_retrieve_keytab_by_'),
'ipaallowedtoperform_write_keys': ('Allow to create keytab by', 'write_keytab_by_', 'not_write_keytab_by'),
'ipaallowedtoperform_write_delegation':
('Allow to modify resource delegation ACL',
'write_delegation_by_', 'not_write_delegation_by'),
}
password_attributes = [('userpassword', 'has_password'),
('krbprincipalkey', 'has_keytab')]
managed_permissions = {
'System: Read Hosts': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'description', 'fqdn', 'ipaclientversion',
'ipakrbauthzdata', 'ipasshpubkey', 'ipauniqueid',
'krbprincipalname', 'l', 'macaddress', 'nshardwareplatform',
'nshostlocation', 'nsosversion', 'objectclass',
'serverhostname', 'usercertificate', 'userclass',
'enrolledby', 'managedby', 'ipaassignedidview',
'krbcanonicalname', 'krbprincipalaliases',
'krbprincipalexpiration', 'krbpasswordexpiration',
'krblastpwdchange', 'krbprincipalauthind', 'memberprincipal',
},
},
'System: Read Host Membership': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'memberof',
},
},
'System: Add Hosts': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Hosts";allow (add) groupdn = "ldap:///cn=Add Hosts,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators'},
},
'System: Add krbPrincipalName to a Host': {
# Allow an admin to enroll a host that has a one-time password.
# When a host is created with a password no krbPrincipalName is set.
# This will let it be added if the client ends up enrolling with
# an administrator instead.
'ipapermright': {'write'},
'ipapermtargetfilter': [
'(objectclass=ipahost)',
'(!(krbprincipalname=*))',
],
'ipapermdefaultattr': {'krbprincipalname'},
'replaces': [
'(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(targetfilter = "(!(krbprincipalname=*))")(targetattr = "krbprincipalname")(version 3.0;acl "permission:Add krbPrincipalName to a host"; allow (write) groupdn = "ldap:///cn=Add krbPrincipalName to a host,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Enroll a Host': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'objectclass', 'enrolledby', 'nshardwareplatform', 'nsosversion'
},
'replaces': [
'(targetattr = "objectclass")(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Enroll a host";allow (write) groupdn = "ldap:///cn=Enroll a host,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetattr = "enrolledby || objectclass")(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Enroll a host";allow (write) groupdn = "ldap:///cn=Enroll a host,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Manage Host SSH Public Keys': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'ipasshpubkey'},
'replaces': [
'(targetattr = "ipasshpubkey")(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Manage Host SSH Public Keys";allow (write) groupdn = "ldap:///cn=Manage Host SSH Public Keys,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators'},
},
'System: Manage Host Keytab': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
'(objectclass=ipahost)',
'(!(memberOf=%s))' % DN('cn=ipaservers',
api.env.container_hostgroup,
api.env.basedn),
],
'ipapermdefaultattr': {'krblastpwdchange', 'krbprincipalkey',
'ipaprotectedoperation;write_keys'},
'replaces': [
'(targetattr = "krbprincipalkey || krblastpwdchange")(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Manage host keytab";allow (write) groupdn = "ldap:///cn=Manage host keytab,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Manage Host Keytab Permissions': {
'ipapermright': {'read', 'search', 'compare', 'write'},
'ipapermdefaultattr': {
'ipaallowedtoperform;write_keys',
'ipaallowedtoperform;read_keys', 'objectclass'
},
'default_privileges': {'Host Administrators'},
},
'System: Modify Hosts': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'description', 'l', 'nshardwareplatform', 'nshostlocation',
'nsosversion', 'macaddress', 'userclass', 'ipaassignedidview',
'krbprincipalauthind',
},
'replaces': [
'(targetattr = "description || l || nshostlocation || nshardwareplatform || nsosversion")(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Hosts";allow (write) groupdn = "ldap:///cn=Modify Hosts,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators'},
},
'System: Remove Hosts': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///fqdn=*,cn=computers,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Hosts";allow (delete) groupdn = "ldap:///cn=Remove Hosts,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Administrators'},
},
'System: Manage Host Certificates': {
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {'usercertificate'},
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Manage Host Principals': {
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {'krbprincipalname', 'krbcanonicalname'},
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Manage Host Enrollment Password': {
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {'userpassword'},
'default_privileges': {'Host Administrators', 'Host Enrollment'},
},
'System: Read Host Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=computers', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'macaddress',
},
},
'System: Manage Host Resource Delegation': {
'ipapermright': {'write', 'delete'},
'ipapermdefaultattr': {'memberprincipal', 'objectclass'},
'default_privileges': {'Host Administrators'},
}
}
label = _('Hosts')
label_singular = _('Host')
takes_params = (
Str('fqdn', hostname_validator,
cli_name='hostname',
label=_('Host name'),
primary_key=True,
normalizer=normalize_hostname,
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this host'),
),
Str('l?',
cli_name='locality',
label=_('Locality'),
doc=_('Host locality (e.g. "Baltimore, MD")'),
),
Str('nshostlocation?',
cli_name='location',
label=_('Location'),
doc=_('Host physical location hint (e.g. "Lab 2")'),
),
Str('nshardwareplatform?',
cli_name='platform',
label=_('Platform'),
doc=_('Host hardware platform (e.g. "Lenovo T61")'),
),
Str('nsosversion?',
cli_name='os',
label=_('Operating system'),
doc=_('Host operating system and version (e.g. "Fedora 9")'),
),
HostPassword('userpassword?',
cli_name='password',
label=_('User password'),
doc=_('Password used in bulk enrollment'),
flags=('no_search',),
),
Flag('random?',
doc=_('Generate a random password to be used in bulk enrollment'),
flags=('no_search', 'virtual_attribute'),
default=False,
),
Str('randompassword?',
label=_('Random password'),
flags=('no_create', 'no_update', 'no_search', 'virtual_attribute'),
),
Certificate('usercertificate*',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded host certificate'),
),
Str('subject',
label=_('Subject'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('serial_number',
label=_('Serial Number'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('serial_number_hex',
label=_('Serial Number (hex)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('issuer',
label=_('Issuer'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('valid_not_before',
label=_('Not Before'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('valid_not_after',
label=_('Not After'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('sha1_fingerprint',
label=_('Fingerprint (SHA1)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('sha256_fingerprint',
label=_('Fingerprint (SHA256)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('revocation_reason?',
label=_('Revocation reason'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Principal(
'krbcanonicalname?',
validate_realm,
label=_('Principal name'),
normalizer=normalize_principal,
flags={'no_create', 'no_update', 'no_search'},
),
Principal(
'krbprincipalname*',
validate_realm,
label=_('Principal alias'),
normalizer=normalize_principal,
flags=['no_create', 'no_search'],
),
Str(
'memberprincipal*',
cli_name='principal',
label=_('Delegation principal'),
doc=_('Delegation principal'),
normalizer=normalize_principal,
flags={'no_create', 'no_update', 'no_search'}
),
Str('macaddress*',
normalizer=lambda value: value.upper(),
pattern=r'^([a-fA-F0-9]{2}[:|\-]?){5}[a-fA-F0-9]{2}$',
pattern_errmsg=('Must be of the form HH:HH:HH:HH:HH:HH, where '
'each H is a hexadecimal character.'),
label=_('MAC address'),
doc=_('Hardware MAC address(es) on this host'),
),
Str('ipasshpubkey*', validate_sshpubkey_no_options,
cli_name='sshpubkey',
label=_('SSH public key'),
normalizer=normalize_sshpubkey,
flags=['no_search'],
),
Str('sshpubkeyfp*',
label=_('SSH public key fingerprint'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('userclass*',
cli_name='class',
label=_('Class'),
doc=_('Host category (semantics placed on this attribute are for '
'local interpretation)'),
),
Str('ipaassignedidview?',
label=_('Assigned ID View'),
flags=['no_option'],
),
StrEnum(
'krbprincipalauthind*',
cli_name='auth_ind',
label=_('Authentication Indicators'),
doc=_("Defines an allow list for Authentication Indicators."
" Use 'otp' to allow OTP-based 2FA authentications."
" Use 'radius' to allow RADIUS-based 2FA authentications."
" Use 'pkinit' to allow PKINIT-based 2FA authentications."
" Use 'hardened' to allow brute-force hardened password"
" authentication by SPAKE or FAST."
" Use 'idp' to allow External Identity Provider"
" authentications."
" Use 'passkey' to allow passkey-based 2FA authentications."
" With no indicator specified,"
" all authentication mechanisms are allowed."),
values=(u'radius', u'otp', u'pkinit', u'hardened', u'idp',
u'passkey'),
),
) + ticket_flags_params
def get_dn(self, *keys, **options):
hostname = keys[-1]
dn = super(host, self).get_dn(hostname, **options)
try:
self.backend.get_entry(dn, [''])
except errors.NotFound:
try:
entry_attrs = self.backend.find_entry_by_attr(
'serverhostname', hostname, self.object_class, [''],
DN(self.container_dn, api.env.basedn))
dn = entry_attrs.dn
except errors.NotFound:
pass
return dn
def get_managed_hosts(self, dn):
host_filter = 'managedBy=%s' % dn
host_attrs = ['fqdn']
ldap = self.api.Backend.ldap2
managed_hosts = []
try:
(hosts, _truncated) = ldap.find_entries(
base_dn=DN(self.container_dn, api.env.basedn),
filter=host_filter, attrs_list=host_attrs)
for host in hosts:
managed_hosts.append(host.dn)
except errors.NotFound:
return []
return managed_hosts
def suppress_netgroup_memberof(self, ldap, entry_attrs):
"""
We don't want to show managed netgroups so remove them from the
memberofindirect list.
"""
ng_container = DN(api.env.container_netgroup, api.env.basedn)
for member in list(entry_attrs.get('memberofindirect', [])):
memberdn = DN(member)
if not memberdn.endswith(ng_container):
continue
filter = ldap.make_filter({'objectclass': 'mepmanagedentry'})
try:
ldap.get_entries(memberdn, ldap.SCOPE_BASE, filter, [''])
except errors.NotFound:
pass
else:
entry_attrs['memberofindirect'].remove(member)
@register()
class host_add(LDAPCreate):
__doc__ = _('Add a new host.')
has_output_params = LDAPCreate.has_output_params + host_output_params
msg_summary = _('Added host "%(value)s"')
member_attributes = ['managedby']
takes_options = LDAPCreate.takes_options + (
Flag('force',
label=_('Force'),
doc=_('force host name even if not in DNS'),
),
Flag('no_reverse',
doc=_('skip reverse DNS detection'),
),
Str('ip_address?', validate_ipaddr,
doc=_('Add the host to DNS with this IP address'),
label=_('IP Address'),
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
config = ldap.get_ipa_config()
if 'ipamaxhostnamelength' in config:
maxlen = int(config.get('ipamaxhostnamelength')[0])
if len(keys[-1]) > maxlen:
raise errors.ValidationError(
name=self.obj.primary_key.cli_name,
error=_('can be at most %(len)d characters' %
dict(len=maxlen))
)
if options.get('ip_address') and dns_container_exists(ldap):
parts = keys[-1].split('.')
host = parts[0]
domain = unicode('.'.join(parts[1:]))
check_reverse = not options.get('no_reverse', False)
add_records_for_host_validation('ip_address',
DNSName(host),
DNSName(domain).make_absolute(),
options['ip_address'],
check_forward=True,
check_reverse=check_reverse)
if not options.get('force', False) and 'ip_address' not in options:
util.verify_host_resolvable(keys[-1])
if 'locality' in entry_attrs:
entry_attrs['l'] = entry_attrs['locality']
entry_attrs['cn'] = keys[-1]
entry_attrs['serverhostname'] = keys[-1].split('.', 1)[0]
if not entry_attrs.get('userpassword', False) and not options.get('random', False):
entry_attrs['krbprincipalname'] = 'host/%s@%s' % (
keys[-1], self.api.env.realm
)
if 'krbprincipalaux' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('krbprincipalaux')
if 'krbprincipal' not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append('krbprincipal')
set_krbcanonicalname(entry_attrs)
else:
if 'krbprincipalaux' in entry_attrs['objectclass']:
entry_attrs['objectclass'].remove('krbprincipalaux')
if 'krbprincipal' in entry_attrs['objectclass']:
entry_attrs['objectclass'].remove('krbprincipal')
if options.get('random'):
entry_attrs['userpassword'] = ipa_generate_password(
entropy_bits=TMP_PWD_ENTROPY_BITS, special=None)
# save the password so it can be displayed in post_callback
setattr(context, 'randompassword', entry_attrs['userpassword'])
entry_attrs['managedby'] = dn
entry_attrs['objectclass'].append('ieee802device')
entry_attrs['objectclass'].append('ipasshhost')
update_krbticketflags(ldap, entry_attrs, attrs_list, options, False)
if 'krbticketflags' in entry_attrs:
entry_attrs['objectclass'].append('krbticketpolicyaux')
validate_auth_indicator(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if dns_container_exists(ldap):
try:
parts = keys[-1].split('.')
host = parts[0]
domain = unicode('.'.join(parts[1:]))
if options.get('ip_address'):
add_reverse = not options.get('no_reverse', False)
add_records_for_host(DNSName(host),
DNSName(domain).make_absolute(),
options['ip_address'],
add_forward=True,
add_reverse=add_reverse)
del options['ip_address']
update_sshfp_record(domain, unicode(parts[0]), entry_attrs)
except Exception as e:
self.add_message(messages.FailedToAddHostDNSRecords(reason=e))
if options.get('random', False):
try:
entry_attrs['randompassword'] = unicode(
getattr(context, 'randompassword'))
except AttributeError:
# On the off-chance some other extension deletes this from the
# context, don't crash.
pass
set_certificate_attrs(entry_attrs)
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
if options.get('all', False):
entry_attrs['managing'] = self.obj.get_managed_hosts(dn)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
if entry_attrs['has_password']:
# If an OTP is set there is no keytab, at least not one
# fetched anywhere.
entry_attrs['has_keytab'] = False
convert_sshpubkey_post(entry_attrs)
return dn
@register()
class host_del(LDAPDelete):
__doc__ = _('Delete a host.')
msg_summary = _('Deleted host "%(value)s"')
member_attributes = ['managedby']
takes_options = LDAPDelete.takes_options + (
Flag('updatedns?',
doc=_('Remove A, AAAA, SSHFP and PTR records of the host(s) '
'managed by IPA DNS'),
default=False,
),
)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
fqdn = resolve_fqdn(keys[-1])
host_is_master(ldap, fqdn)
# Remove all service records for this host
truncated = True
while truncated:
try:
ret = api.Command['service_find'](fqdn, pkey_only=True)
truncated = ret['truncated']
services = ret['result']
except errors.NotFound:
break
else:
for entry_attrs in services:
principal = kerberos.Principal(
entry_attrs['krbprincipalname'][0])
hostname = principal.hostname
if hostname.lower() == fqdn:
api.Command['service_del'](principal)
updatedns = options.get('updatedns', False)
if updatedns:
try:
updatedns = dns_container_exists(ldap)
except errors.NotFound:
updatedns = False
if updatedns:
# Remove A, AAAA, SSHFP and PTR records of the host
fqdn_dnsname = DNSName(fqdn).make_absolute()
zone = DNSName(zone_for_name(fqdn_dnsname))
relative_hostname = fqdn_dnsname.relativize(zone)
# Get all resources for this host
rec_removed = False
try:
record = api.Command['dnsrecord_show'](
zone, relative_hostname)['result']
except errors.NotFound:
pass
else:
# remove PTR records first
for attr in ('arecord', 'aaaarecord'):
for val in record.get(attr, []):
rec_removed = (
remove_ptr_rec(val, fqdn_dnsname) or
rec_removed
)
try:
# remove all A, AAAA, SSHFP records of the host
api.Command['dnsrecord_mod'](
zone,
record['idnsname'][0],
arecord=[],
aaaarecord=[],
sshfprecord=[]
)
except errors.EmptyModlist:
pass
else:
rec_removed = True
if not rec_removed:
self.add_message(
messages.FailedToRemoveHostDNSRecords(
host=fqdn,
reason=_("No A, AAAA, SSHFP or PTR records found.")
)
)
if self.api.Command.ca_is_enabled()['result']:
certs = self.api.Command.cert_find(host=keys)['result']
revoke_certs(certs)
return dn
@register()
class host_mod(LDAPUpdate):
__doc__ = _('Modify information about a host.')
has_output_params = LDAPUpdate.has_output_params + host_output_params
msg_summary = _('Modified host "%(value)s"')
member_attributes = ['managedby']
takes_options = LDAPUpdate.takes_options + (
Flag('updatedns?',
doc=_('Update DNS entries'),
default=False,
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
fqdn = resolve_fqdn(keys[-1])
# Allow an existing OTP to be reset but don't allow a OTP to be
# added to an enrolled host.
if options.get('userpassword') or options.get('random'):
entry = {}
self.obj.get_password_attributes(ldap, dn, entry)
if not entry['has_password'] and entry['has_keytab']:
raise errors.ValidationError(
name='password',
error=_('Password cannot be set on enrolled host.'))
# Once a principal name is set it cannot be changed
if 'cn' in entry_attrs:
raise errors.ACIError(info=_('cn is immutable'))
if 'locality' in entry_attrs:
entry_attrs['l'] = entry_attrs['locality']
if 'krbprincipalname' in entry_attrs:
entry_attrs_old = ldap.get_entry(
dn, ['objectclass', 'krbprincipalname']
)
if 'krbprincipalname' in entry_attrs_old:
msg = 'Principal name already set, it is unchangeable.'
raise errors.ACIError(info=msg)
obj_classes = entry_attrs_old['objectclass']
if 'krbprincipalaux' not in (item.lower() for item in
obj_classes):
obj_classes.append('krbprincipalaux')
entry_attrs['objectclass'] = obj_classes
# verify certificates
certs = entry_attrs.get('usercertificate') or []
# revoke removed certificates
ca_is_enabled = self.api.Command.ca_is_enabled()['result']
if 'usercertificate' in options and ca_is_enabled:
try:
entry_attrs_old = ldap.get_entry(dn, ['usercertificate'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
old_certs = entry_attrs_old.get('usercertificate', [])
removed_certs = set(old_certs) - set(certs)
for cert in removed_certs:
rm_certs = api.Command.cert_find(
certificate=cert,
host=keys)['result']
revoke_certs(rm_certs)
if certs:
entry_attrs['usercertificate'] = certs
if options.get('random'):
entry_attrs['userpassword'] = ipa_generate_password(
entropy_bits=TMP_PWD_ENTROPY_BITS)
setattr(context, 'randompassword', entry_attrs['userpassword'])
if 'macaddress' in entry_attrs:
if 'objectclass' in entry_attrs:
obj_classes = entry_attrs['objectclass']
else:
_entry_attrs = ldap.get_entry(dn, ['objectclass'])
obj_classes = _entry_attrs['objectclass']
if 'ieee802device' not in (item.lower() for item in obj_classes):
obj_classes.append('ieee802device')
entry_attrs['objectclass'] = obj_classes
if options.get('updatedns', False) and dns_container_exists(ldap):
parts = fqdn.split('.')
domain = unicode('.'.join(parts[1:]))
try:
result = api.Command['dnszone_show'](domain)['result']
domain = result['idnsname'][0]
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
update_sshfp_record(domain, unicode(parts[0]), entry_attrs)
if 'ipasshpubkey' in entry_attrs:
if 'objectclass' in entry_attrs:
obj_classes = entry_attrs['objectclass']
else:
_entry_attrs = ldap.get_entry(dn, ['objectclass'])
obj_classes = entry_attrs['objectclass'] = _entry_attrs['objectclass']
if 'ipasshhost' not in (item.lower() for item in obj_classes):
obj_classes.append('ipasshhost')
update_krbticketflags(ldap, entry_attrs, attrs_list, options, True)
if 'krbticketflags' in entry_attrs:
if 'objectclass' not in entry_attrs:
entry_attrs_old = ldap.get_entry(dn, ['objectclass'])
entry_attrs['objectclass'] = entry_attrs_old['objectclass']
if 'krbticketpolicyaux' not in (item.lower() for item in
entry_attrs['objectclass']):
entry_attrs['objectclass'].append('krbticketpolicyaux')
if 'krbprincipalauthind' in entry_attrs:
if 'objectclass' not in entry_attrs:
entry_attrs_old = ldap.get_entry(dn, ['objectclass'])
entry_attrs['objectclass'] = entry_attrs_old['objectclass']
if 'krbprincipalaux' not in (item.lower() for item in
entry_attrs['objectclass']):
entry_attrs['objectclass'].append('krbprincipalaux')
validate_auth_indicator(entry_attrs)
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if options.get('random', False):
entry_attrs['randompassword'] = unicode(getattr(context, 'randompassword'))
set_certificate_attrs(entry_attrs)
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
if entry_attrs['has_password']:
# If an OTP is set there is no keytab, at least not one
# fetched anywhere.
entry_attrs['has_keytab'] = False
if options.get('all', False):
entry_attrs['managing'] = self.obj.get_managed_hosts(dn)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
convert_sshpubkey_post(entry_attrs)
remove_sshpubkey_from_output_post(self.context, entry_attrs)
convert_ipaassignedidview_post(entry_attrs, options)
return dn
@register()
class host_find(LDAPSearch):
__doc__ = _('Search for hosts.')
has_output_params = LDAPSearch.has_output_params + host_output_params
msg_summary = ngettext(
'%(count)d host matched', '%(count)d hosts matched', 0
)
member_attributes = ['memberof', 'enrolledby', 'managedby']
def get_options(self):
for option in super(host_find, self).get_options():
yield option
# "managing" membership has to be added and processed separately
for option in self.get_member_options('managing'):
yield option
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
if 'locality' in attrs_list:
attrs_list.remove('locality')
attrs_list.append('l')
if 'man_host' in options or 'not_man_host' in options:
hosts = []
if options.get('man_host') is not None:
for pkey in options.get('man_host', []):
dn = self.obj.get_dn(pkey)
try:
entry_attrs = ldap.get_entry(dn, ['managedby'])
except errors.NotFound:
raise self.obj.handle_not_found(pkey)
hosts.append(set(entry_attrs.get('managedby', '')))
hosts = list(reduce(lambda s1, s2: s1 & s2, hosts))
if not hosts:
# There is no host managing _all_ hosts in --man-hosts
filter = ldap.combine_filters(
(filter, '(objectclass=disabled)'), ldap.MATCH_ALL
)
not_hosts = []
if options.get('not_man_host') is not None:
for pkey in options.get('not_man_host', []):
dn = self.obj.get_dn(pkey)
try:
entry_attrs = ldap.get_entry(dn, ['managedby'])
except errors.NotFound:
raise self.obj.handle_not_found(pkey)
not_hosts += entry_attrs.get('managedby', [])
not_hosts = list(set(not_hosts))
for target_hosts, filter_op in ((hosts, ldap.MATCH_ANY),
(not_hosts, ldap.MATCH_NONE)):
hosts_avas = [DN(host)[0][0] for host in target_hosts]
hosts_filters = [ldap.make_filter_from_attr(ava.attr, ava.value)
for ava in hosts_avas]
hosts_filter = ldap.combine_filters(hosts_filters, filter_op)
filter = ldap.combine_filters(
(filter, hosts_filter), ldap.MATCH_ALL
)
if not options.get('pkey_only', False):
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
return (filter.replace('locality', 'l'), base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
for entry_attrs in entries:
hostname = entry_attrs['fqdn']
if isinstance(hostname, (tuple, list)):
hostname = hostname[0]
try:
set_certificate_attrs(entry_attrs)
except errors.CertificateFormatError as e:
self.add_message(
messages.CertificateInvalid(
subject=hostname,
reason=e,
)
)
logger.error("Invalid certificate: %s", e)
del(entry_attrs['usercertificate'])
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
if options.get('all', False):
entry_attrs['managing'] = self.obj.get_managed_hosts(entry_attrs.dn)
convert_sshpubkey_post(entry_attrs)
convert_ipaassignedidview_post(entry_attrs, options)
remove_sshpubkey_from_output_list_post(self.context, entries)
return truncated
@register()
class host_show(LDAPRetrieve):
__doc__ = _('Display information about a host.')
has_output_params = LDAPRetrieve.has_output_params + host_output_params
takes_options = LDAPRetrieve.takes_options + (
Str('out?',
doc=_('file to store certificate in'),
),
)
member_attributes = ['managedby']
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
add_sshpubkey_to_attrs_pre(self.context, attrs_list)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
if entry_attrs['has_password']:
# If an OTP is set there is no keytab, at least not one
# fetched anywhere.
entry_attrs['has_keytab'] = False
hostname = entry_attrs['fqdn']
if isinstance(hostname, (tuple, list)):
hostname = hostname[0]
try:
set_certificate_attrs(entry_attrs)
except errors.CertificateFormatError as e:
self.add_message(
messages.CertificateInvalid(
subject=hostname,
reason=e,
)
)
del(entry_attrs['usercertificate'])
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
if options.get('all', False):
entry_attrs['managing'] = self.obj.get_managed_hosts(dn)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
convert_sshpubkey_post(entry_attrs)
remove_sshpubkey_from_output_post(self.context, entry_attrs)
convert_ipaassignedidview_post(entry_attrs, options)
return dn
@register()
class host_disable(LDAPQuery):
__doc__ = _('Disable the Kerberos key, SSL certificate and all services of a host.')
has_output = output.standard_value
msg_summary = _('Disabled host "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
fqdn = resolve_fqdn(keys[-1])
host_is_master(ldap, fqdn)
# See if we actually do anthing here, and if not raise an exception
done_work = False
truncated = True
while truncated:
try:
ret = api.Command['service_find'](fqdn, pkey_only=True)
truncated = ret['truncated']
services = ret['result']
except errors.NotFound:
break
else:
for entry_attrs in services:
principal = kerberos.Principal(
entry_attrs['krbprincipalname'][0])
hostname = principal.hostname
if hostname.lower() == fqdn:
try:
api.Command['service_disable'](principal)
done_work = True
except errors.AlreadyInactive:
pass
dn = self.obj.get_dn(*keys, **options)
try:
entry_attrs = ldap.get_entry(dn, ['usercertificate'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if self.api.Command.ca_is_enabled()['result']:
certs = self.api.Command.cert_find(host=keys)['result']
if certs:
revoke_certs(certs)
# Remove the usercertificate altogether
entry_attrs['usercertificate'] = None
ldap.update_entry(entry_attrs)
done_work = True
self.obj.get_password_attributes(ldap, dn, entry_attrs)
if entry_attrs['has_keytab']:
ldap.remove_principal_key(dn)
done_work = True
if not done_work:
raise errors.AlreadyInactive()
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
return dn
@register()
class host_add_managedby(LDAPAddMember):
__doc__ = _('Add hosts that can manage this host.')
member_attributes = ['managedby']
has_output_params = LDAPAddMember.has_output_params + host_output_params
allow_same = True
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
return (completed, dn)
@register()
class host_remove_managedby(LDAPRemoveMember):
__doc__ = _('Remove hosts that can manage this host.')
member_attributes = ['managedby']
has_output_params = LDAPRemoveMember.has_output_params + host_output_params
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, entry_attrs)
return (completed, dn)
@register()
class host_allow_retrieve_keytab(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to retrieve a keytab'
' of this host.')
member_attributes = ['ipaallowedtoperform_read_keys']
has_output_params = LDAPAddMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class host_disallow_retrieve_keytab(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to retrieve a '
'keytab of this host.')
member_attributes = ['ipaallowedtoperform_read_keys']
has_output_params = LDAPRemoveMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class host_allow_create_keytab(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to create a keytab '
'of this host.')
member_attributes = ['ipaallowedtoperform_write_keys']
has_output_params = LDAPAddMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class host_disallow_create_keytab(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to create a '
'keytab of this host.')
member_attributes = ['ipaallowedtoperform_write_keys']
has_output_params = LDAPRemoveMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class host_add_cert(LDAPAddAttributeViaOption):
__doc__ = _('Add certificates to host entry')
msg_summary = _('Added certificates to host "%(value)s"')
attribute = 'usercertificate'
@register()
class host_remove_cert(LDAPRemoveAttributeViaOption):
__doc__ = _('Remove certificates from host entry')
msg_summary = _('Removed certificates from host "%(value)s"')
attribute = 'usercertificate'
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
for cert in options.get('usercertificate', []):
revoke_certs(api.Command.cert_find(
certificate=cert,
host=keys)['result'])
return dn
@register()
class host_add_principal(LDAPAddAttribute):
__doc__ = _('Add new principal alias to host entry')
msg_summary = _('Added new aliases to host "%(value)s"')
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.check_principal_realm_in_trust_namespace(self.api, *keys)
util.ensure_krbcanonicalname_set(ldap, entry_attrs)
return dn
@register()
class host_remove_principal(LDAPRemoveAttribute):
__doc__ = _('Remove principal alias from a host entry')
msg_summary = _('Removed aliases from host "%(value)s"')
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.ensure_last_krbprincipalname(ldap, entry_attrs, *keys)
return dn
@register()
class host_add_delegation(LDAPAddAttribute):
__doc__ = _('Add new resource delegation to a host')
msg_summary = _('Added new resource delegation to the host "%(value)s"')
attribute = 'memberprincipal'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.check_principal_realm_supported(
self.api, *keys, attr_name=self.attribute)
if self.attribute in entry_attrs:
add_missing_object_class(ldap, 'resourcedelegation', dn)
return dn
@register()
class host_remove_delegation(LDAPRemoveAttribute):
__doc__ = _('Remove resource delegation from a host')
msg_summary = _('Removed resource delegation from the host "%(value)s"')
attribute = 'memberprincipal'
@register()
class host_allow_add_delegation(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to handle a '
'resource delegation of this host.')
member_attributes = ['ipaallowedtoperform_write_delegation']
has_output_params = LDAPAddMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class host_disallow_add_delegation(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to handle a '
'resource delegation of this host.')
member_attributes = ['ipaallowedtoperform_write_delegation']
has_output_params = LDAPRemoveMember.has_output_params + host_output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
| 59,195
|
Python
|
.py
| 1,305
| 34.472031
| 316
| 0.590836
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,843
|
netgroup.py
|
freeipa_freeipa/ipaserver/plugins/netgroup.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# 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 ipalib import api, errors
from ipalib import Str, StrEnum, Flag
from ipalib.plugable import Registry
from .baseldap import (
external_host_param,
add_external_pre_callback,
add_external_post_callback,
remove_external_post_callback,
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember)
from ipalib import _, ngettext
from .hbacrule import is_all
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Netgroups
A netgroup is a group used for permission checking. It can contain both
user and host values.
EXAMPLES:
Add a new netgroup:
ipa netgroup-add --desc="NFS admins" admins
Add members to the netgroup:
ipa netgroup-add-member --users=tuser1 --users=tuser2 admins
Remove a member from the netgroup:
ipa netgroup-remove-member --users=tuser2 admins
Display information about a netgroup:
ipa netgroup-show admins
Delete a netgroup:
ipa netgroup-del admins
""")
register = Registry()
NETGROUP_PATTERN='^[a-zA-Z0-9_.][a-zA-Z0-9_.-]*$'
NETGROUP_PATTERN_ERRMSG='may only include letters, numbers, _, -, and .'
# according to most common use cases the netgroup pattern should fit
# also the nisdomain pattern
NISDOMAIN_PATTERN=NETGROUP_PATTERN
NISDOMAIN_PATTERN_ERRMSG=NETGROUP_PATTERN_ERRMSG
output_params = (
Str('memberuser_user?',
label='Member User',
),
Str('memberuser_group?',
label='Member Group',
),
Str('memberhost_host?',
label=_('Member Host'),
),
Str('memberhost_hostgroup?',
label='Member Hostgroup',
),
)
@register()
class netgroup(LDAPObject):
"""
Netgroup object.
"""
container_dn = api.env.container_netgroup
object_name = _('netgroup')
object_name_plural = _('netgroups')
object_class = ['ipaobject', 'ipaassociation', 'ipanisnetgroup']
permission_filter_objectclasses = ['ipanisnetgroup']
search_attributes = [
'cn', 'description', 'memberof', 'externalhost', 'nisdomainname',
'memberuser', 'memberhost', 'member', 'usercategory', 'hostcategory',
]
default_attributes = [
'cn', 'description', 'memberof', 'externalhost', 'nisdomainname',
'memberuser', 'memberhost', 'member', 'memberindirect',
'usercategory', 'hostcategory',
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
attribute_members = {
'member': ['netgroup'],
'memberof': ['netgroup'],
'memberindirect': ['netgroup'],
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
}
relationships = {
'member': ('Member', '', 'no_'),
'memberof': ('Member Of', 'in_', 'not_in_'),
'memberindirect': (
'Indirect Member', None, 'no_indirect_'
),
'memberuser': ('Member', '', 'no_'),
'memberhost': ('Member', '', 'no_'),
}
managed_permissions = {
'System: Read Netgroups': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'description', 'hostcategory', 'ipaenabledflag',
'ipauniqueid', 'nisdomainname', 'usercategory', 'objectclass',
},
},
'System: Read Netgroup Membership': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'externalhost', 'member', 'memberof', 'memberuser',
'memberhost', 'objectclass',
},
},
'System: Add Netgroups': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=ng,cn=alt,$SUFFIX")(version 3.0;acl "permission:Add netgroups";allow (add) groupdn = "ldap:///cn=Add netgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Netgroups Administrators'},
},
'System: Modify Netgroup Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'externalhost', 'member', 'memberhost', 'memberuser'
},
'replaces': [
'(targetattr = "memberhost || externalhost || memberuser || member")(target = "ldap:///ipauniqueid=*,cn=ng,cn=alt,$SUFFIX")(version 3.0;acl "permission:Modify netgroup membership";allow (write) groupdn = "ldap:///cn=Modify netgroup membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Netgroups Administrators'},
},
'System: Modify Netgroups': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'description'},
'replaces': [
'(targetattr = "description")(target = "ldap:///ipauniqueid=*,cn=ng,cn=alt,$SUFFIX")(version 3.0; acl "permission:Modify netgroups";allow (write) groupdn = "ldap:///cn=Modify netgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Netgroups Administrators'},
},
'System: Remove Netgroups': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=ng,cn=alt,$SUFFIX")(version 3.0;acl "permission:Remove netgroups";allow (delete) groupdn = "ldap:///cn=Remove netgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Netgroups Administrators'},
},
'System: Read Netgroup Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=ng', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'membernisnetgroup', 'nisnetgrouptriple',
},
},
}
label = _('Netgroups')
label_singular = _('Netgroup')
takes_params = (
Str('cn',
pattern=NETGROUP_PATTERN,
pattern_errmsg=NETGROUP_PATTERN_ERRMSG,
cli_name='name',
label=_('Netgroup name'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Netgroup description'),
),
Str('nisdomainname?',
pattern=NISDOMAIN_PATTERN,
pattern_errmsg=NISDOMAIN_PATTERN_ERRMSG,
cli_name='nisdomain',
label=_('NIS domain name'),
),
Str('ipauniqueid?',
cli_name='uuid',
label='IPA unique ID',
doc=_('IPA unique ID'),
flags=['no_create', 'no_update'],
),
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the rule applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the rule applies to'),
values=(u'all', ),
),
external_host_param,
)
def get_primary_key_from_dn(self, dn):
assert isinstance(dn, DN)
if not dn.rdns:
return u''
first_ava = dn.rdns[0][0]
if first_ava[0] == self.primary_key.name:
return unicode(first_ava[1])
try:
entry_attrs = self.backend.get_entry(
dn, [self.primary_key.name]
)
try:
return entry_attrs[self.primary_key.name][0]
except (KeyError, IndexError):
return u''
except errors.NotFound:
return unicode(dn)
@register()
class netgroup_add(LDAPCreate):
__doc__ = _('Add a new netgroup.')
has_output_params = LDAPCreate.has_output_params + output_params
msg_summary = _('Added netgroup "%(value)s"')
msg_collision = _(u'hostgroup with name "%s" already exists. ' \
u'Hostgroups and netgroups share a common namespace')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
entry_attrs.setdefault('nisdomainname', self.api.env.domain)
try:
test_dn = self.obj.get_dn(keys[-1])
netgroup = ldap.get_entry(test_dn, ['objectclass'])
if 'mepManagedEntry' in netgroup.get('objectclass', []):
raise errors.DuplicateEntry(message=unicode(self.msg_collision % keys[-1]))
else:
self.obj.handle_duplicate_entry(*keys)
except errors.NotFound:
pass
try:
# when enabled, a managed netgroup is created for every hostgroup
# make sure that we don't create a collision if the plugin is
# (temporarily) disabled
api.Object['hostgroup'].get_dn_if_exists(keys[-1])
raise errors.DuplicateEntry(message=unicode(self.msg_collision % keys[-1]))
except errors.NotFound:
pass
return dn
@register()
class netgroup_del(LDAPDelete):
__doc__ = _('Delete a netgroup.')
msg_summary = _('Deleted netgroup "%(value)s"')
@register()
class netgroup_mod(LDAPUpdate):
__doc__ = _('Modify a netgroup.')
has_output_params = LDAPUpdate.has_output_params + output_params
msg_summary = _('Modified netgroup "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, attrs_list)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(options, 'usercategory') and 'memberuser' in entry_attrs:
raise errors.MutuallyExclusiveError(
reason=_("user category cannot be set to 'all' while there "
"are allowed users")
)
if is_all(options, 'hostcategory') and 'memberhost' in entry_attrs:
raise errors.MutuallyExclusiveError(
reason=_("host category cannot be set to 'all' while there "
"are allowed hosts")
)
return dn
@register()
class netgroup_find(LDAPSearch):
__doc__ = _('Search for a netgroup.')
member_attributes = ['member', 'memberuser', 'memberhost', 'memberof']
has_output_params = LDAPSearch.has_output_params + output_params
msg_summary = ngettext(
'%(count)d netgroup matched', '%(count)d netgroups matched', 0
)
takes_options = LDAPSearch.takes_options + (
Flag('private',
exclude='webui',
flags=['no_option', 'no_output'],
),
Flag('managed',
cli_name='managed',
doc=_('search for managed groups'),
default_from=lambda private: private,
),
)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
# Do not display private mepManagedEntry netgroups by default
# If looking for managed groups, we need to omit the negation search filter
search_kw = {}
search_kw['objectclass'] = ['mepManagedEntry']
if not options['managed']:
local_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_NONE)
else:
local_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
filter = ldap.combine_filters((local_filter, filter), rules=ldap.MATCH_ALL)
return (filter, base_dn, scope)
@register()
class netgroup_show(LDAPRetrieve):
__doc__ = _('Display information about a netgroup.')
has_output_params = LDAPRetrieve.has_output_params + output_params
@register()
class netgroup_add_member(LDAPAddMember):
__doc__ = _('Add members to a netgroup.')
member_attributes = ['memberuser', 'memberhost', 'member']
has_output_params = LDAPAddMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
return add_external_pre_callback('host', ldap, dn, keys, options)
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
return add_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='memberhost',
membertype='host',
externalattr='externalhost')
@register()
class netgroup_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a netgroup.')
member_attributes = ['memberuser', 'memberhost', 'member']
has_output_params = LDAPRemoveMember.has_output_params + output_params
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
assert isinstance(dn, DN)
return remove_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='memberhost',
membertype='host',
externalattr='externalhost')
| 14,725
|
Python
|
.py
| 357
| 31.644258
| 294
| 0.590064
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,844
|
pkinit.py
|
freeipa_freeipa/ipaserver/plugins/pkinit.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
from ipalib import Object
from ipalib import _, ngettext
from ipalib.crud import Search
from ipalib.parameters import Int, Str, StrEnum
from ipalib.plugable import Registry
register = Registry()
__doc__ = _("""
Kerberos PKINIT feature status reporting tools.
Report IPA masters on which Kerberos PKINIT is enabled or disabled
EXAMPLES:
List PKINIT status on all masters:
ipa pkinit-status
Check PKINIT status on `ipa.example.com`:
ipa pkinit-status --server ipa.example.com
List all IPA masters with disabled PKINIT:
ipa pkinit-status --status='disabled'
For more info about PKINIT support see:
https://www.freeipa.org/page/V4/Kerberos_PKINIT
""")
@register()
class pkinit(Object):
"""
PKINIT Options
"""
object_name = _('pkinit')
label = _('PKINIT')
takes_params = (
Str(
'server_server?',
cli_name='server',
label=_('Server name'),
doc=_('IPA server hostname'),
),
StrEnum(
'status?',
cli_name='status',
label=_('PKINIT status'),
doc=_('Whether PKINIT is enabled or disabled'),
values=(u'enabled', u'disabled'),
flags={'virtual_attribute', 'no_create', 'no_update'}
)
)
@register()
class pkinit_status(Search):
__doc__ = _('Report PKINIT status on the IPA masters')
msg_summary = ngettext('%(count)s server matched',
'%(count)s servers matched', 0)
takes_options = Search.takes_options + (
Int(
'timelimit?',
label=_('Time Limit'),
doc=_('Time limit of search in seconds (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
Int(
'sizelimit?',
label=_('Size Limit'),
doc=_('Maximum number of entries returned (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
)
def get_pkinit_status(self, server, status):
backend = self.api.Backend.serverroles
ipa_master_config = backend.config_retrieve("IPA master")
if server is not None:
servers = [server]
else:
servers = ipa_master_config.get('ipa_master_server', [])
pkinit_servers = ipa_master_config.get('pkinit_server_server')
if pkinit_servers is None:
return
for s in servers:
pkinit_status = {
u'server_server': s,
u'status': (
u'enabled' if s in pkinit_servers else u'disabled'
)
}
if status is not None and pkinit_status[u'status'] != status:
continue
yield pkinit_status
def execute(self, *keys, **options):
if keys:
return dict(
result=[],
count=0,
truncated=False
)
server = options.get('server_server', None)
status = options.get('status', None)
if server is not None:
self.api.Object.server_role.ensure_master_exists(server)
result = sorted(self.get_pkinit_status(server, status),
key=lambda d: d.get('server_server'))
return dict(result=result, count=len(result), truncated=False)
| 3,477
|
Python
|
.py
| 102
| 24.990196
| 73
| 0.576165
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,845
|
trust.py
|
freeipa_freeipa/ipaserver/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/>.
import dbus
import dbus.mainloop.glib
import logging
import six
from ipalib.messages import (
add_message,
BrokenTrust)
from ipalib.plugable import Registry
from ipalib.request import context
from .baseldap import (
pkey_to_value,
entry_to_dict,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPObject,
LDAPQuery)
from .dns import dns_container_exists
from ipaplatform.paths import paths
from ipapython.dn import DN
from ipapython.ipautil import realm_to_suffix
from ipalib import api, Str, StrEnum, Password, Bool, _, ngettext, Int, Flag
from ipalib import Command
from ipalib import errors
from ipalib import messages
from ipalib import output
from ldap import SCOPE_SUBTREE
from time import sleep
from ipaserver.dcerpc_common import (TRUST_ONEWAY,
TRUST_BIDIRECTIONAL,
TRUST_JOIN_EXTERNAL,
LSA_TRUST_ATTRIBUTE_NON_TRANSITIVE,
trust_type_string,
trust_direction_string,
trust_status_string)
from ipaserver.plugins.privilege import principal_has_privilege
if six.PY3:
unicode = str
try:
import pysss_murmur
_murmur_installed = True
except Exception as e:
_murmur_installed = False
try:
import pysss_nss_idmap
_nss_idmap_installed = True
except Exception as e:
_nss_idmap_installed = False
if api.env.in_server:
try:
import ipaserver.dcerpc
_bindings_installed = True
except ImportError:
_bindings_installed = False
__doc__ = _("""
Cross-realm trusts
Manage trust relationship between IPA and Active Directory domains.
In order to allow users from a remote domain to access resources in IPA domain,
trust relationship needs to be established. Currently IPA supports only trusts
between IPA and Active Directory domains under control of Windows Server 2008
or later, with functional level 2008 or later.
Please note that DNS on both IPA and Active Directory domain sides should be
configured properly to discover each other. Trust relationship relies on
ability to discover special resources in the other domain via DNS records.
Examples:
1. Establish cross-realm trust with Active Directory using AD administrator
credentials:
ipa trust-add --type=ad <ad.domain> --admin <AD domain administrator> \
--password
2. List all existing trust relationships:
ipa trust-find
3. Show details of the specific trust relationship:
ipa trust-show <ad.domain>
4. Delete existing trust relationship:
ipa trust-del <ad.domain>
Once trust relationship is established, remote users will need to be mapped
to local POSIX groups in order to actually use IPA resources. The mapping
should be done via use of external membership of non-POSIX group and then
this group should be included into one of local POSIX groups.
Example:
1. Create group for the trusted domain admins' mapping and their local POSIX
group:
ipa group-add --desc='<ad.domain> admins external map' \
ad_admins_external --external
ipa group-add --desc='<ad.domain> admins' ad_admins
2. Add security identifier of Domain Admins of the <ad.domain> to the
ad_admins_external group:
ipa group-add-member ad_admins_external --external 'AD\\Domain Admins'
3. Allow members of ad_admins_external group to be associated with
ad_admins POSIX group:
ipa group-add-member ad_admins --groups ad_admins_external
4. List members of external members of ad_admins_external group to see
their SIDs:
ipa group-show ad_admins_external
GLOBAL TRUST CONFIGURATION
When IPA AD trust subpackage is installed and ipa-adtrust-install is run, a
local domain configuration (SID, GUID, NetBIOS name) is generated. These
identifiers are then used when communicating with a trusted domain of the
particular type.
1. Show global trust configuration for Active Directory type of trusts:
ipa trustconfig-show --type ad
2. Modify global configuration for all trusts of Active Directory type and set
a different fallback primary group (fallback primary group GID is used as a
primary user GID if user authenticating to IPA domain does not have any
other primary GID already set):
ipa trustconfig-mod --type ad --fallback-primary-group "another AD group"
3. Change primary fallback group back to default hidden group (any group with
posixGroup object class is allowed):
ipa trustconfig-mod --type ad --fallback-primary-group "Default SMB Group"
""")
logger = logging.getLogger(__name__)
register = Registry()
_trust_type_option = StrEnum(
'trust_type',
cli_name='type',
label=_('Trust type (ad for Active Directory, default)'),
values=(u'ad',),
default=u'ad',
autofill=True,
)
DEFAULT_RANGE_SIZE = 200000
DBUS_IFACE_TRUST = 'com.redhat.idm.trust'
CRED_STYLE_SAMBA = 1
CRED_STYLE_KERBEROS = 2
def make_trust_dn(env, trust_type, dn):
assert isinstance(dn, DN)
if trust_type:
container_dn = DN(('cn', trust_type), env.container_trusts, env.basedn)
return DN(dn, container_dn)
return dn
def find_adtrust_masters(ldap, api):
"""
Returns a list of names of IPA servers with ADTRUST component configured.
"""
try:
entries, _truncated = ldap.find_entries(
"cn=ADTRUST",
base_dn=api.env.container_masters + api.env.basedn
)
except errors.NotFound:
entries = []
return [entry.dn[1].value for entry in entries]
def verify_samba_component_presence(ldap, api):
"""
Verifies that Samba is installed and configured on this particular master.
If Samba is not available, provide a heplful hint with the list of masters
capable of running the commands.
"""
adtrust_present = api.Command['adtrust_is_enabled']()['result']
hint = _(
' Alternatively, following servers are capable of running this '
'command: %(masters)s'
)
def raise_missing_component_error(message):
masters_with_adtrust = find_adtrust_masters(ldap, api)
# If there are any masters capable of running Samba requiring commands
# let's advertise them directly
if masters_with_adtrust:
message += hint % dict(masters=', '.join(masters_with_adtrust))
raise errors.NotFound(
name=_('AD Trust setup'),
reason=message,
)
# We're ok in this case, bail out
# pylint: disable-next=used-before-assignment
if adtrust_present and _bindings_installed:
return
# First check for packages missing
elif not _bindings_installed:
error_message = _(
'Cannot perform the selected command without Samba 4 support '
'installed. Make sure you have installed server-trust-ad '
'sub-package of IPA.'
)
raise_missing_component_error(error_message)
# Packages present, but ADTRUST instance is not configured
elif not adtrust_present:
error_message = _(
'Cannot perform the selected command without Samba 4 instance '
'configured on this machine. Make sure you have run '
'ipa-adtrust-install on this server.'
)
raise_missing_component_error(error_message)
def generate_creds(trustinstance, style, **options):
"""
Generate string representing credentials using trust instance
Input:
trustinstance -- ipaserver.dcerpc.TrustInstance object
style -- style of credentials
CRED_STYLE_SAMBA -- for using with Samba bindings
CRED_STYLE_KERBEROS -- for obtaining Kerberos ticket
**options -- options with realm_admin and realm_passwd keys
Result:
a string representing credentials with first % separating
username and password
None is returned if realm_passwd key returns nothing from options
"""
creds = None
password = options.get('realm_passwd', None)
if password:
admin_name = options.get('realm_admin')
sp = []
sep = '@'
if style == CRED_STYLE_SAMBA:
sep = "\\"
sp = admin_name.split(sep)
if len(sp) == 1:
sp.insert(0, trustinstance.remote_domain.info['name'])
elif style == CRED_STYLE_KERBEROS:
sp = admin_name.split('\\')
if len(sp) > 1:
sp = [sp[1]]
else:
sp = admin_name.split(sep)
if len(sp) == 1:
sp.append(
trustinstance.remote_domain.info['dns_domain'].upper()
)
creds = u"{name}%{password}".format(name=sep.join(sp),
password=password)
return creds
def add_range(myapi, trustinstance, range_name, dom_sid, *keys, **options):
"""
First, we try to derive the parameters of the ID range based on the
information contained in the Active Directory.
If that was not successful, we go for our usual defaults (random base,
range size 200 000, ipa-ad-trust range type).
Any of these can be overridden by passing appropriate CLI options
to the trust-add command.
"""
range_size = None
range_type = None
base_id = None
# First, get information about ID space from AD
# However, we skip this step if other than ipa-ad-trust-posix
# range type is enforced
if options.get('range_type', None) in (None, u'ipa-ad-trust-posix'):
# Get the base dn
domain = keys[-1]
basedn = realm_to_suffix(domain)
# Search for information contained in
# CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System
info_filter = '(objectClass=msSFU30DomainInfo)'
info_dn = DN('CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System')\
+ basedn
# Get the domain validator
# pylint: disable=used-before-assignment
domain_validator = ipaserver.dcerpc.DomainValidator(myapi)
# pylint: enable=used-before-assignment
if not domain_validator.is_configured():
raise errors.NotFound(
reason=_('Cannot search in trusted domains without own '
'domain configured. Make sure you have run '
'ipa-adtrust-install on the IPA server first'))
creds = None
if trustinstance:
# Re-use AD administrator credentials if they were provided
creds = generate_creds(trustinstance,
style=CRED_STYLE_KERBEROS, **options)
if creds:
domain_validator._admin_creds = creds
# KDC might not get refreshed data at the first time,
# retry several times
for _retry in range(10):
info_list = domain_validator.search_in_dc(domain,
info_filter,
None,
SCOPE_SUBTREE,
basedn=info_dn,
quiet=True)
if info_list:
info = info_list[0]
break
sleep(2)
required_msSFU_attrs = ['msSFU30MaxUidNumber', 'msSFU30OrderNumber']
if not info_list:
# We were unable to gain UNIX specific info from the AD
logger.debug("Unable to gain POSIX info from the AD")
else:
if all(attr in info for attr in required_msSFU_attrs):
logger.debug("Able to gain POSIX info from the AD")
range_type = u'ipa-ad-trust-posix'
max_uid = info.get('msSFU30MaxUidNumber')
# if max_gid is missing, assume 0 and the max will
# be obtained from max_uid. We just checked that
# msSFU30MaxUidNumber is defined
max_gid = info.get('msSFU30MaxGidNumber', [b'0'])
max_id = int(max(max_uid, max_gid)[0])
base_id = int(info.get('msSFU30OrderNumber')[0])
range_size = (1 + (max_id - base_id) // DEFAULT_RANGE_SIZE)\
* DEFAULT_RANGE_SIZE
# Second, options given via the CLI options take precedence to discovery
if options.get('range_type', None):
range_type = options.get('range_type', None)
elif not range_type:
range_type = u'ipa-ad-trust'
if options.get('range_size', None):
range_size = options.get('range_size', None)
elif not range_size:
range_size = DEFAULT_RANGE_SIZE
if options.get('base_id', None):
base_id = options.get('base_id', None)
elif not base_id:
# Generate random base_id if not discovered nor given via CLI
base_id = DEFAULT_RANGE_SIZE + (
pysss_murmur.murmurhash3(
dom_sid,
len(dom_sid), 0xdeadbeef
) % 10000
) * DEFAULT_RANGE_SIZE
# Finally, add new ID range
myapi.Command['idrange_add'](range_name,
ipabaseid=base_id,
ipaidrangesize=range_size,
ipabaserid=0,
iparangetype=range_type,
ipanttrusteddomainsid=dom_sid)
# Return the values that were generated inside this function
return range_type, range_size, base_id
def fetch_trusted_domains_over_dbus(myapi, *keys, **options):
if not _bindings_installed:
return
forest_name = keys[0]
method_options = []
if options.get('realm_server', None):
method_options.extend(['--server', options['realm_server']])
if options.get('realm_admin', None):
method_options.extend(['--admin', options['realm_admin']])
if options.get('realm_passwd', None):
method_options.extend(['--password', options['realm_passwd']])
# Calling oddjobd-activated service via DBus has some quirks:
# - Oddjobd registers multiple canonical names on the same address
# - python-dbus only follows name owner changes when mainloop is in use
# See https://fedorahosted.org/oddjob/ticket/2 for details
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
try:
_ret = 0
_stdout = ''
_stderr = ''
bus = dbus.SystemBus()
intf = bus.get_object(DBUS_IFACE_TRUST, "/",
follow_name_owner_changes=True)
fetch_domains_method = intf.get_dbus_method(
'fetch_domains',
dbus_interface=DBUS_IFACE_TRUST)
# Oddjobd D-BUS method definition only accepts fixed number
# of arguments on the command line. Thus, we need to pass
# remaining ones as ''. There are 30 slots to allow for extension
# and the number comes from the 'arguments' definition in
# install/oddjob/etc/oddjobd.conf.d/oddjobd-ipa-trust.conf
method_arguments = [forest_name]
method_arguments.extend(method_options)
method_arguments.extend([''] * (30 - len(method_arguments)))
(_ret, _stdout, _stderr) = fetch_domains_method(*method_arguments)
except dbus.DBusException as e:
logger.error('Failed to call %s.fetch_domains helper.'
'DBus exception is %s.', DBUS_IFACE_TRUST, str(e))
_ret = 2
_stdout = '<not available>'
_stderr = '<not available>'
if _ret != 0:
logger.error('Helper fetch_domains was called for forest %s, '
'return code is %d', forest_name, _ret)
logger.error('Standard output from the helper:\n%s---\n', _stdout)
logger.error('Error output from the helper:\n%s--\n', _stderr)
raise errors.ServerCommandError(
server=myapi.env.host,
error=_('Fetching domains from trusted forest failed. '
'See details in the error_log')
)
return
@register()
class trust(LDAPObject):
"""
Trust object.
"""
trust_types = ('ad', 'ipa')
container_dn = api.env.container_trusts
object_name = _('trust')
object_name_plural = _('trusts')
object_class = ['ipaNTTrustedDomain', 'ipaIDObject']
default_attributes = ['cn', 'ipantflatname', 'ipanttrusteddomainsid',
'ipanttrusttype', 'ipanttrustattributes',
'ipanttrustdirection', 'ipanttrustpartner',
'ipanttrustforesttrustinfo',
'ipanttrustposixoffset',
'ipantsupportedencryptiontypes',
'ipantadditionalsuffixes']
search_display_attributes = ['cn', 'ipantflatname',
'ipanttrusteddomainsid', 'ipanttrusttype',
'ipanttrustattributes',
'ipantadditionalsuffixes']
managed_permissions = {
'System: Read Trust Information': {
# Allow reading of attributes needed for SSSD subdomains support
'non_object': True,
'ipapermlocation': DN(container_dn, api.env.basedn),
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass',
'ipantflatname', 'ipantsecurityidentifier',
'ipanttrusteddomainsid', 'ipanttrustpartner',
'ipantsidblacklistincoming', 'ipantsidblacklistoutgoing',
'ipanttrustdirection', 'ipantadditionalsuffixes',
},
},
'System: Read system trust accounts': {
'non_object': True,
'ipapermlocation': DN(container_dn, api.env.basedn),
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'uidnumber', 'gidnumber', 'krbprincipalname'
},
'default_privileges': {'ADTrust Agents'},
},
}
label = _('Trusts')
label_singular = _('Trust')
takes_params = (
Str('cn',
cli_name='realm',
label=_('Realm name'),
primary_key=True,
),
Str('ipantflatname',
cli_name='flat_name',
label=_('Domain NetBIOS name'),
flags=['no_create', 'no_update']),
Str('ipanttrusteddomainsid',
cli_name='sid',
label=_('Domain Security Identifier'),
flags=['no_create', 'no_update']),
Str('ipantsidblacklistincoming*',
cli_name='sid_blacklist_incoming',
label=_('SID blocklist incoming'),
flags=['no_create']),
Str('ipantsidblacklistoutgoing*',
cli_name='sid_blacklist_outgoing',
label=_('SID blocklist outgoing'),
flags=['no_create']),
Str('trustdirection',
label=_('Trust direction'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('trusttype',
label=_('Trust type'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('truststatus',
label=_('Trust status'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('ipantadditionalsuffixes*',
cli_name='upn_suffixes',
label=_('UPN suffixes'),
flags={'no_create', 'no_search'},
),
)
def validate_sid_blocklists(self, entry_attrs):
if not _bindings_installed:
# SID validator is not available, return
# Even if invalid SID gets in the trust entry, it won't crash
# the validation process as it is translated to SID S-0-0
return
for attr in ('ipantsidblacklistincoming', 'ipantsidblacklistoutgoing'):
values = entry_attrs.get(attr)
if not values:
continue
for value in values:
if not ipaserver.dcerpc.is_sid_valid(value):
err = _("invalid SID: {SID}").format(SID=value)
raise errors.ValidationError(name=attr, error=err)
def get_dn(self, *keys, **kwargs):
trust_type = kwargs.get('trust_type')
sdn = [('cn', x) for x in keys]
sdn.reverse()
if trust_type is None:
ldap = self.backend
trustfilter = ldap.make_filter({
'objectclass': ['ipaNTTrustedDomain', 'ipaIDObject'],
'cn': [keys[-1]]},
rules=ldap.MATCH_ALL
)
# more type of objects can be located in subtree (for example
# cross-realm principals). we need this attr do detect trust
# entries
trustfilter = ldap.combine_filters(
(trustfilter, "ipaNTTrustPartner=*"),
rules=ldap.MATCH_ALL
)
try:
result = ldap.get_entries(
DN(self.container_dn, self.env.basedn),
ldap.SCOPE_SUBTREE, trustfilter, ['']
)
except errors.NotFound:
# pylint: disable=raising-bad-type, #4772
raise self.handle_not_found(keys[-1])
if len(result) > 1:
raise errors.OnlyOneValueAllowed(attr='trust domain')
return result[0].dn
return make_trust_dn(self.env, trust_type, DN(*sdn))
def warning_if_ad_trust_dom_have_missing_SID(self, result, **options):
"""Due bug https://fedorahosted.org/freeipa/ticket/5665 there might be
AD trust domain without generated SID, warn user about it.
"""
ldap = self.api.Backend.ldap2
try:
entries, _truncated = ldap.find_entries(
base_dn=DN(self.api.env.container_adtrusts,
self.api.env.basedn),
scope=ldap.SCOPE_ONELEVEL,
attrs_list=['cn'],
filter='(&(ipaNTTrustPartner=*)'
'(!(ipaNTSecurityIdentifier=*)))',
)
except errors.NotFound:
pass
else:
for entry in entries:
add_message(
options['version'],
result,
BrokenTrust(domain=entry.single_value['cn'])
)
@register()
class trust_add(LDAPCreate):
__doc__ = _('''
Add new trust to use.
This command establishes trust relationship to another domain
which becomes 'trusted'. As result, users of the trusted domain
may access resources of this domain.
Only trusts to Active Directory domains are supported right now.
The command can be safely run multiple times against the same domain,
this will cause change to trust relationship credentials on both
sides.
Note that if the command was previously run with a specific range type,
or with automatic detection of the range type, and you want to configure a
different range type, you may need to delete first the ID range using
ipa idrange-del before retrying the command with the desired range type.
''')
range_types = {
u'ipa-ad-trust': unicode(_('Active Directory domain range')),
u'ipa-ad-trust-posix': unicode(_('Active Directory trust range with '
'POSIX attributes')),
}
takes_options = LDAPCreate.takes_options + (
_trust_type_option,
Str('realm_admin?',
cli_name='admin',
label=_("Active Directory domain administrator"),
),
Password('realm_passwd?',
cli_name='password',
label=_("Active Directory domain administrator's password"),
confirm=False,
),
Str('realm_server?',
cli_name='server',
label=_('Domain controller for the Active Directory domain '
'(optional)'),
),
Password('trust_secret?',
cli_name='trust_secret',
label=_('Shared secret for the trust'),
confirm=False,
),
Int('base_id?',
cli_name='base_id',
label=_('First Posix ID of the range reserved for the '
'trusted domain'),
),
Int('range_size?',
cli_name='range_size',
label=_('Size of the ID range reserved for the trusted domain')
),
StrEnum('range_type?',
label=_('Range type'),
cli_name='range_type',
doc=_('Type of trusted domain ID range, one of allowed ' +
'values'),
values=sorted(range_types),
),
Bool('bidirectional?',
label=_('Two-way trust'),
cli_name='two_way',
doc=(_('Establish bi-directional trust. By default trust is '
'inbound one-way only.')),
default=False,
),
Bool('external?',
label=_('External trust'),
cli_name='external',
doc=_('Establish external trust to a domain in another forest. '
'The trust is not transitive beyond the domain.'),
default=False,
),
)
msg_summary = _('Added Active Directory trust for realm "%(value)s"')
msg_summary_existing = _('Re-established trust to domain "%(value)s"')
def _format_trust_attrs(self, result, **options):
# Format the output into human-readable values
attributes = int(result['result'].get('ipanttrustattributes', [0])[0])
if not options.get('raw', False):
result['result']['trusttype'] = [trust_type_string(
result['result']['ipanttrusttype'][0], attributes)]
result['result']['trustdirection'] = [trust_direction_string(
result['result']['ipanttrustdirection'][0])]
result['result']['truststatus'] = [trust_status_string(
result['verified'])]
if attributes:
result['result'].pop('ipanttrustattributes', None)
result['result'].pop('ipanttrustauthoutgoing', None)
result['result'].pop('ipanttrustauthincoming', None)
def execute(self, *keys, **options):
ldap = self.obj.backend
verify_samba_component_presence(ldap, self.api)
full_join = self.validate_options(*keys, **options)
old_range, range_name, dom_sid = self.validate_range(*keys, **options)
result = self.execute_ad(full_join, *keys, **options)
if not old_range:
# Store the created range type, since for POSIX trusts no
# ranges for the subdomains should be added, POSIX attributes
# provide a global mapping across all subdomains
add_range(
self.api, self.trustinstance, range_name, dom_sid,
*keys, **options
)
attrs_list = self.obj.default_attributes
if options.get('all', False):
attrs_list.append('*')
trust_filter = "cn=%s" % result['value']
trusts, _truncated = ldap.find_entries(
base_dn=DN(self.api.env.container_trusts, self.api.env.basedn),
filter=trust_filter,
attrs_list=attrs_list
)
result['result'] = entry_to_dict(trusts[0], **options)
# Fetch topology of the trust forest -- we need always to do it
# for AD trusts, regardless of the type of idranges associated with it
# Note that add_new_domains_from_trust will add needed ranges for
# the algorithmic ID mapping case.
if (options.get('trust_type') == u'ad' and
options.get('trust_secret') is None):
if options.get('bidirectional'):
# Bidirectional trust allows us to use cross-realm TGT,
# so we can run the call under original user's credentials
res = fetch_domains_from_trust(self.api, self.trustinstance,
**options)
add_new_domains_from_trust(
self.api, self.trustinstance, result['result'], res,
**options)
else:
# One-way trust is more complex. We don't have cross-realm TGT
# and cannot use IPA principals to authenticate against AD.
# Instead, we have to use our trusted domain object's (TDO)
# account in AD. Access to the credentials is limited and IPA
# framework cannot access it directly. Instead, we call out to
# oddjobd-activated higher privilege process that will use TDO
# object credentials to authenticate to AD with Kerberos,
# run DCE RPC calls to do discovery and will call
# add_new_domains_from_trust() on its own.
# We only pass through the realm_server option because we need
# to reach the specified Active Directory domain controller
# No need to pass through admin credentials as we have TDO
# credentials at this point already
fetch_trusted_domains_over_dbus(self.api, result['value'],
realm_server=options.get(
'realm_server', None))
# Format the output into human-readable values unless `--raw` is given
self._format_trust_attrs(result, **options)
del result['verified']
return result
def validate_options(self, *keys, **options):
trusted_realm_domain = keys[-1]
if not _murmur_installed and 'base_id' not in options:
raise errors.ValidationError(
name=_('missing base_id'),
error=_(
'pysss_murmur is not available on the server '
'and no base-id is given.'
)
)
if 'trust_type' not in options:
raise errors.RequirementError(name='trust_type')
if options['trust_type'] != u'ad':
raise errors.ValidationError(
name=_('trust type'),
error=_('only "ad" is supported')
)
# Detect IPA-AD domain clash
if self.api.env.domain.lower() == trusted_realm_domain.lower():
raise errors.ValidationError(
name=_('domain'),
error=_('Cannot establish a trust to AD deployed in the same '
'domain as IPA. Such setup is not supported.')
)
# If domain name and realm does not match, IPA server is not be able
# to establish trust with Active Directory.
realm_not_matching_domain = (
self.api.env.domain.upper() != self.api.env.realm
)
if options['trust_type'] == u'ad' and realm_not_matching_domain:
raise errors.ValidationError(
name=_('Realm-domain mismatch'),
error=_('To establish trust with Active Directory, the '
'domain name and the realm name of the IPA server '
'must match')
)
self.trustinstance = ipaserver.dcerpc.TrustDomainJoins(self.api)
if not self.trustinstance.configured:
raise errors.NotFound(
name=_('AD Trust setup'),
reason=_(
'Cannot perform join operation without own domain '
'configured. Make sure you have run ipa-adtrust-install '
'on the IPA server first'
)
)
# Obtain a list of IPA realm domains
result = self.api.Command.realmdomains_show()['result']
realm_domains = result['associateddomain']
# Do not allow the AD's trusted realm domain in the list
# of our realm domains
if trusted_realm_domain.lower() in realm_domains:
raise errors.ValidationError(
name=_('AD Trust setup'),
error=_(
'Trusted domain %(domain)s is included among '
'IPA realm domains. It needs to be removed '
'prior to establishing the trust. See the '
'"ipa realmdomains-mod --del-domain" command.'
) % dict(domain=trusted_realm_domain)
)
self.realm_server = options.get('realm_server')
self.realm_admin = options.get('realm_admin')
self.realm_passwd = options.get('realm_passwd')
if self.realm_admin:
names = self.realm_admin.split('@')
if len(names) > 1:
# realm admin name is in UPN format, user@realm, check that
# realm is the same as the one that we are attempting to trust
if trusted_realm_domain.lower() != names[-1].lower():
raise errors.ValidationError(
name=_('AD Trust setup'),
error=_(
'Trusted domain and administrator account use '
'different realms'
)
)
self.realm_admin = names[0]
if not self.realm_passwd:
raise errors.ValidationError(
name=_('AD Trust setup'),
error=_('Realm administrator password should be specified')
)
return True
return False
def validate_range(self, *keys, **options):
# If a range for this trusted domain already exists,
# '--base-id' or '--range-size' options should not be specified
range_name = keys[-1].upper() + '_id_range'
range_type = options.get('range_type')
try:
old_range = self.api.Command['idrange_show'](range_name, raw=True)
except errors.NotFound:
old_range = None
if options.get('trust_type') == u'ad':
if range_type and range_type not in (u'ipa-ad-trust',
u'ipa-ad-trust-posix'):
raise errors.ValidationError(
name=_('id range type'),
error=_(
'Only the ipa-ad-trust and ipa-ad-trust-posix are '
'allowed values for --range-type when adding an AD '
'trust.'
))
base_id = options.get('base_id')
range_size = options.get('range_size')
if old_range and (base_id or range_size):
raise errors.ValidationError(
name=_('id range'),
error=_(
'An id range already exists for this trust. '
'You should either delete the old range, or '
'exclude --base-id/--range-size options from the command.'
)
)
# If a range for this trusted domain already exists,
# domain SID must also match
self.trustinstance.populate_remote_domain(
keys[-1],
self.realm_server,
self.realm_admin,
self.realm_passwd
)
dom_sid = self.trustinstance.remote_domain.info.get('sid', None)
if dom_sid is None:
raise errors.RemoteRetrieveError(
reason=_('Unable to read domain information, check {}'
).format(paths.VAR_LOG_HTTPD_ERROR))
if old_range:
old_dom_sid = old_range['result']['ipanttrusteddomainsid'][0]
old_range_type = old_range['result']['iparangetype'][0]
if old_dom_sid != dom_sid:
raise errors.ValidationError(
name=_('range exists'),
error=_(
'ID range with the same name but different domain SID '
'already exists. The ID range for the new trusted '
'domain must be created manually.'
)
)
if range_type and range_type != old_range_type:
raise errors.ValidationError(
name=_('range type change'),
error=_('ID range for the trusted domain already '
'exists, but it has a different type. Please '
'remove the old range manually, or do not '
'enforce type via --range-type option.'))
return old_range, range_name, dom_sid
def execute_ad(self, full_join, *keys, **options):
# Join domain using full credentials and with random trustdom
# secret (will be generated by the join method)
# First see if the trust is already in place
# Force retrieval of the trust object by not passing trust_type
try:
dn = self.obj.get_dn(keys[-1])
except errors.NotFound:
dn = None
trust_type = TRUST_ONEWAY
if options.get('bidirectional', False):
trust_type = TRUST_BIDIRECTIONAL
# If we are forced to establish external trust, allow it
if options.get('external', False):
self.trustinstance.allow_behavior(TRUST_JOIN_EXTERNAL)
# 1. Full access to the remote domain. Use admin credentials and
# generate random trustdom password to do work on both sides
if full_join:
try:
result = self.trustinstance.join_ad_full_credentials(
keys[-1],
self.realm_server,
self.realm_admin,
self.realm_passwd,
trust_type
)
except errors.NotFound:
error_message = _("Unable to resolve domain controller for "
"{domain} domain. "
).format(domain=keys[-1])
instructions = []
if dns_container_exists(self.obj.backend):
try:
dns_zone = self.api.Command.dnszone_show(
keys[-1])['result']
if (('idnsforwardpolicy' in dns_zone) and
dns_zone['idnsforwardpolicy'][0] == u'only'):
instructions.append(
_("Forward policy is defined for it in "
"IPA DNS, perhaps forwarder points to "
"incorrect host?")
)
except (errors.NotFound, KeyError):
_instruction = _(
"IPA manages DNS, please verify your DNS "
"configuration and make sure that service "
"records of the '{domain}' domain can be "
"resolved. Examples how to configure DNS "
"with CLI commands or the Web UI can be "
"found in the documentation. "
)
instructions.append(
_instruction.format(domain=keys[-1])
)
else:
_instruction = _(
"Since IPA does not manage DNS records, ensure "
"DNS is configured to resolve '{domain}' "
"domain from IPA hosts and back."
)
instructions.append(
_instruction.format(domain=keys[-1])
)
raise errors.NotFound(
reason=error_message,
instructions=instructions
)
if result is None:
raise errors.ValidationError(
name=_('AD Trust setup'),
error=_('Unable to verify write permissions to the AD')
)
ret = dict(
value=pkey_to_value(
self.trustinstance.remote_domain.info['dns_domain'],
options),
verified=result['verified']
)
if dn:
ret['summary'] = self.msg_summary_existing % ret
return ret
# 2. We don't have access to the remote domain and trustdom password
# is provided. Do the work on our side and inform what to do on remote
# side.
if options.get('trust_secret'):
result = self.trustinstance.join_ad_ipa_half(
keys[-1],
self.realm_server,
options['trust_secret'],
trust_type
)
ret = dict(
value=pkey_to_value(
self.trustinstance.remote_domain.info['dns_domain'],
options),
verified=result['verified']
)
if dn:
ret['summary'] = self.msg_summary_existing % ret
return ret
else:
raise errors.ValidationError(
name=_('AD Trust setup'),
error=_('Not enough arguments specified to perform trust '
'setup'))
@register()
class trust_del(LDAPDelete):
__doc__ = _('Delete a trust.')
msg_summary = _('Deleted trust "%(value)s"')
@register()
class trust_mod(LDAPUpdate):
__doc__ = _("""
Modify a trust (for future use).
Currently only the default option to modify the LDAP attributes is
available. More specific options will be added in coming releases.
""")
msg_summary = _('Modified trust "%(value)s" '
'(change will be effective in 60 seconds)')
def pre_callback(self, ldap, dn, e_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
self.obj.validate_sid_blocklists(e_attrs)
return dn
@register()
class trust_find(LDAPSearch):
__doc__ = _('Search for trusts.')
has_output_params = (LDAPSearch.has_output_params +
(Str('ipanttrusttype'), Str('ipanttrustattributes')))
msg_summary = ngettext(
'%(count)d trust matched', '%(count)d trusts matched', 0
)
# Since all trusts types are stored within separate containers
# under 'cn=trusts', search needs to be done on a sub-tree scope
def pre_callback(self, ldap, filters, attrs_list,
base_dn, scope, *args, **options):
# list only trust, not trust domains
return (filters, base_dn, ldap.SCOPE_SUBTREE)
def execute(self, *args, **options):
result = super(trust_find, self).execute(*args, **options)
self.obj.warning_if_ad_trust_dom_have_missing_SID(result, **options)
return result
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
for attrs in entries:
# Translate ipanttrusttype to trusttype if --raw not used
trust_type = attrs.single_value.get('ipanttrusttype', None)
attributes = attrs.single_value.get('ipanttrustattributes', 0)
if not options.get('raw', False) and trust_type is not None:
attrs['trusttype'] = [
trust_type_string(trust_type, attributes)
]
del attrs['ipanttrusttype']
if attributes:
del attrs['ipanttrustattributes']
return truncated
@register()
class trust_show(LDAPRetrieve):
__doc__ = _('Display information about a trust.')
has_output_params = (LDAPRetrieve.has_output_params +
(Str('ipanttrusttype'),
Str('ipanttrustdirection'),
Str('ipanttrustattributes')))
def execute(self, *keys, **options):
result = super(trust_show, self).execute(*keys, **options)
self.obj.warning_if_ad_trust_dom_have_missing_SID(result, **options)
return result
def post_callback(self, ldap, dn, e_attrs, *keys, **options):
assert isinstance(dn, DN)
# Translate ipanttrusttype to trusttype
# and ipanttrustdirection to trustdirection
# if --raw not used
if not options.get('raw', False):
trust_type = e_attrs.single_value.get('ipanttrusttype', None)
attributes = e_attrs.single_value.get('ipanttrustattributes', 0)
if trust_type is not None:
e_attrs['trusttype'] = [
trust_type_string(trust_type, attributes)
]
del e_attrs['ipanttrusttype']
dir_str = e_attrs.single_value.get('ipanttrustdirection', None)
if dir_str is not None:
e_attrs['trustdirection'] = [trust_direction_string(dir_str)]
del e_attrs['ipanttrustdirection']
if attributes:
del e_attrs['ipanttrustattributes']
return dn
_trustconfig_dn = {
u'ad': DN(('cn', api.env.domain),
api.env.container_cifsdomains, api.env.basedn),
}
@register()
class trustconfig(LDAPObject):
"""
Trusts global configuration object
"""
object_name = _('trust configuration')
default_attributes = [
'cn', 'ipantsecurityidentifier', 'ipantflatname', 'ipantdomainguid',
'ipantfallbackprimarygroup',
]
label = _('Global Trust Configuration')
label_singular = _('Global Trust Configuration')
takes_params = (
Str('cn',
label=_('Domain'),
flags=['no_update'],
),
Str('ipantsecurityidentifier',
label=_('Security Identifier'),
flags=['no_update'],
),
Str('ipantflatname',
label=_('NetBIOS name'),
flags=['no_update'],
),
Str('ipantdomainguid',
label=_('Domain GUID'),
flags=['no_update'],
),
Str('ipantfallbackprimarygroup',
cli_name='fallback_primary_group',
label=_('Fallback primary group'),
),
Str(
'ad_trust_agent_server*',
label=_('IPA AD trust agents'),
doc=_('IPA servers configured as AD trust agents'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'ad_trust_controller_server*',
label=_('IPA AD trust controllers'),
doc=_('IPA servers configured as AD trust controllers'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
)
def get_dn(self, *keys, **kwargs):
trust_type = kwargs.get('trust_type')
if trust_type is None:
raise errors.RequirementError(name='trust_type')
try:
return _trustconfig_dn[kwargs['trust_type']]
except KeyError:
raise errors.ValidationError(
name='trust_type',
error=_("unsupported trust type")
)
def _normalize_groupdn(self, entry_attrs):
"""
Checks that group with given name/DN exists and updates the entry_attrs
"""
if 'ipantfallbackprimarygroup' not in entry_attrs:
return
group = entry_attrs['ipantfallbackprimarygroup']
if isinstance(group, (list, tuple)):
group = group[0]
if group is None:
return
try:
dn = DN(group)
# group is in a form of a DN
try:
self.backend.get_entry(dn)
except errors.NotFound:
raise self.api.Object['group'].handle_not_found(group)
# DN is valid, we can just return
return
except ValueError:
# The search is performed for groups with "posixgroup" objectclass
# and not "ipausergroup" so that it can also match groups like
# "Default SMB Group" which does not have this objectclass.
try:
group_entry = self.backend.find_entry_by_attr(
self.api.Object['group'].primary_key.name,
group,
['posixgroup'],
[''],
DN(self.api.env.container_group, self.api.env.basedn))
except errors.NotFound:
raise self.api.Object['group'].handle_not_found(group)
else:
entry_attrs['ipantfallbackprimarygroup'] = [group_entry.dn]
def _convert_groupdn(self, entry_attrs, options):
"""
Convert an group dn into a name. As we use CN as user RDN, its value
can be extracted from the DN without further LDAP queries.
"""
if options.get('raw', False):
return
try:
groupdn = entry_attrs['ipantfallbackprimarygroup'][0]
except (IndexError, KeyError):
groupdn = None
if groupdn is None:
return
assert isinstance(groupdn, DN)
entry_attrs['ipantfallbackprimarygroup'] = [groupdn[0][0].value]
@register()
class trustconfig_mod(LDAPUpdate):
__doc__ = _('Modify global trust configuration.')
takes_options = LDAPUpdate.takes_options + (_trust_type_option,)
msg_summary = _('Modified "%(value)s" trust configuration')
has_output = output.simple_entry
def pre_callback(self, ldap, dn, e_attrs, attrs_list, *keys, **options):
self.obj._normalize_groupdn(e_attrs)
return dn
def execute(self, *keys, **options):
result = super(trustconfig_mod, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['trust_type'], options)
return result
def post_callback(self, ldap, dn, e_attrs, *keys, **options):
self.obj._convert_groupdn(e_attrs, options)
self.api.Object.config.show_servroles_attributes(
e_attrs, "AD trust agent", "AD trust controller", **options)
return dn
@register()
class trustconfig_show(LDAPRetrieve):
__doc__ = _('Show global trust configuration.')
takes_options = LDAPRetrieve.takes_options + (_trust_type_option,)
has_output = output.simple_entry
def execute(self, *keys, **options):
result = super(trustconfig_show, self).execute(*keys, **options)
result['value'] = pkey_to_value(options['trust_type'], options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj._convert_groupdn(entry_attrs, options)
self.api.Object.config.show_servroles_attributes(
entry_attrs, "AD trust agent", "AD trust controller", **options)
return dn
if _nss_idmap_installed:
_idmap_type_dict = {
pysss_nss_idmap.ID_USER: 'user',
pysss_nss_idmap.ID_GROUP: 'group',
pysss_nss_idmap.ID_BOTH: 'both',
}
def idmap_type_string(level):
string = _idmap_type_dict.get(int(level), 'unknown')
return unicode(string)
@register()
class trust_resolve(Command):
NO_CLI = True
__doc__ = _('Resolve security identifiers of users and groups '
'in trusted domains')
takes_options = (
Str('sids+',
label = _('Security Identifiers (SIDs)'),
),
)
has_output_params = (
Str('name', label=_('Name')),
Str('sid', label=_('SID')),
)
has_output = (
output.ListOfEntries('result'),
)
def execute(self, *keys, **options):
result = list()
if not _nss_idmap_installed:
return dict(result=result)
try:
NAME_KEY = pysss_nss_idmap.NAME_KEY
TYPE_KEY = pysss_nss_idmap.TYPE_KEY
sids = [str(x) for x in options['sids']]
xlate = pysss_nss_idmap.getnamebysid(sids)
for sid in xlate:
entry = dict()
entry['sid'] = [unicode(sid)]
entry['name'] = [unicode(xlate[sid][NAME_KEY])]
entry['type'] = [idmap_type_string(xlate[sid][TYPE_KEY])]
result.append(entry)
except ValueError:
pass
return dict(result=result)
@register()
class adtrust_is_enabled(Command):
NO_CLI = True
__doc__ = _('Determine whether ipa-adtrust-install has been run on this '
'system')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
adtrust_dn = DN(
('cn', 'ADTRUST'),
('cn', self.api.env.host),
('cn', 'masters'),
('cn', 'ipa'),
('cn', 'etc'),
self.api.env.basedn
)
try:
ldap.get_entry(adtrust_dn)
except errors.NotFound:
return dict(result=False)
return dict(result=True)
@register()
class compat_is_enabled(Command):
NO_CLI = True
__doc__ = _('Determine whether Schema Compatibility plugin is configured '
'to serve trusted domain users and groups')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
users_dn = DN(
('cn', 'users'),
('cn', 'Schema Compatibility'),
('cn', 'plugins'),
('cn', 'config')
)
groups_dn = DN(
('cn', 'groups'),
('cn', 'Schema Compatibility'),
('cn', 'plugins'),
('cn', 'config')
)
try:
users_entry = ldap.get_entry(users_dn)
except errors.NotFound:
return dict(result=False)
attr = users_entry.get('schema-compat-lookup-nsswitch')
if not attr or 'user' not in attr:
return dict(result=False)
try:
groups_entry = ldap.get_entry(groups_dn)
except errors.NotFound:
return dict(result=False)
attr = groups_entry.get('schema-compat-lookup-nsswitch')
if not attr or 'group' not in attr:
return dict(result=False)
return dict(result=True)
@register()
class sidgen_was_run(Command):
"""
This command tries to determine whether the sidgen task was run during
ipa-adtrust-install. It does that by simply checking the "editors" group
for the presence of the ipaNTSecurityIdentifier attribute - if the
attribute is present, the sidgen task was run.
Since this command relies on the existence of the "editors" group, it will
fail loudly in case this group does not exist.
"""
NO_CLI = True
__doc__ = _('Determine whether ipa-adtrust-install has been run with '
'sidgen task')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
editors_dn = DN(
('cn', 'editors'),
('cn', 'groups'),
('cn', 'accounts'),
api.env.basedn
)
try:
editors_entry = ldap.get_entry(editors_dn)
except errors.NotFound:
raise errors.NotFound(
name=_('sidgen_was_run'),
reason=_(
'This command relies on the existence of the "editors" '
'group, but this group was not found.'
)
)
attr = editors_entry.get('ipaNTSecurityIdentifier')
if not attr:
return dict(result=False)
return dict(result=True)
@register()
class trustdomain(LDAPObject):
"""
Object representing a domain of the AD trust.
"""
parent_object = 'trust'
trust_type_idx = {'2': u'ad'}
object_name = _('trust domain')
object_name_plural = _('trust domains')
object_class = ['ipaNTTrustedDomain']
default_attributes = ['cn', 'ipantflatname', 'ipanttrusteddomainsid',
'ipanttrustpartner', 'ipantadditionalsuffixes']
search_display_attributes = ['cn', 'ipantflatname',
'ipanttrusteddomainsid',
'ipantadditionalsuffixes']
label = _('Trusted domains')
label_singular = _('Trusted domain')
takes_params = (
Str('cn',
label=_('Domain name'),
cli_name='domain',
primary_key=True),
Str('ipantflatname?',
cli_name='flat_name',
label=_('Domain NetBIOS name')),
Str('ipanttrusteddomainsid?',
cli_name='sid',
label=_('Domain Security Identifier')),
Flag('domain_enabled',
label=_('Domain enabled'),
flags={'virtual_attribute',
'no_create', 'no_update', 'no_search'}),
)
# LDAPObject.get_dn() only passes all but last element of keys and no
# kwargs to the parent object's get_dn() no matter what you pass to it.
# Make own get_dn() as we really need all elements to construct proper dn.
def get_dn(self, *keys, **kwargs):
sdn = [('cn', x) for x in keys]
sdn.reverse()
trust_type = kwargs.get('trust_type')
if not trust_type:
trust_type = u'ad'
dn = make_trust_dn(self.env, trust_type, DN(*sdn))
return dn
@register()
class trustdomain_find(LDAPSearch):
__doc__ = _('Search domains of the trust')
def pre_callback(self, ldap, filters, attrs_list, base_dn,
scope, *args, **options):
return (filters, base_dn, ldap.SCOPE_SUBTREE)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
trust_dn = self.obj.get_dn(args[0], trust_type=u'ad')
trust_entry = ldap.get_entry(trust_dn)
blocklist = trust_entry.get('ipantsidblacklistincoming')
for entry in entries:
sid = entry.get('ipanttrusteddomainsid', [None])[0]
if sid is None:
continue
if sid in blocklist:
entry['domain_enabled'] = [False]
else:
entry['domain_enabled'] = [True]
return truncated
@register()
class trustdomain_mod(LDAPUpdate):
__doc__ = _('Modify trustdomain of the trust')
NO_CLI = True
takes_options = LDAPUpdate.takes_options + (_trust_type_option,)
@register()
class trustdomain_add(LDAPCreate):
__doc__ = _('Allow access from the trusted domain')
NO_CLI = True
takes_options = LDAPCreate.takes_options + (_trust_type_option,)
def pre_callback(self, ldap, dn, e_attrs, attrs_list, *keys, **options):
# ipaNTTrustPartner must always be set to the name of the trusted
# domain. See MS-ADTS 6.1.6.7.13
e_attrs['ipanttrustpartner'] = [dn[0]['cn']]
return dn
@register()
class trustdomain_del(LDAPDelete):
__doc__ = _('Remove information about the domain associated '
'with the trust.')
msg_summary = _('Removed information about the trusted domain '
'"%(value)s"')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
verify_samba_component_presence(ldap, self.api)
# Note that pre-/post- callback handling for LDAPDelete is causing
# pre_callback to always receive empty keys. We need to catch the case
# when root domain is being deleted
for domain in keys[1]:
try:
self.obj.get_dn_if_exists(keys[0], domain, trust_type=u'ad')
except errors.NotFound:
if keys[0].lower() == domain:
raise errors.ValidationError(
name='domain',
error=_("cannot delete root domain of the trust, "
"use trust-del to delete the trust itself"))
raise self.obj.handle_not_found(keys[0], domain)
try:
self.api.Command.trustdomain_enable(keys[0], domain)
except errors.AlreadyActive:
pass
result = super(trustdomain_del, self).execute(*keys, **options)
result['value'] = pkey_to_value(keys[1], options)
return result
def fetch_domains_from_trust(myapi, trustinstance, **options):
"""
Contact trust forest root DC and fetch trusted forest topology information.
:param myapi: API instance
:param trustinstance: Initialized instance of `dcerpc.TrustDomainJoins`
class
:param options: options passed from API command's `execute()` method
:returns: dict containing forest domain information and forest-wide UPN
suffixes (if any)
"""
forest_root_name = trustinstance.remote_domain.info['dns_forest']
# We want to use Kerberos if we have admin credentials even with SMB calls
# as eventually use of NTLMSSP will be deprecated for trusted domain
# operations If admin credentials are missing, 'creds' will be None and
# fetch_domains will use HTTP/ipa.master@IPA.REALM principal, e.g. Kerberos
# authentication as well.
creds = generate_creds(trustinstance, style=CRED_STYLE_KERBEROS, **options)
server = options.get('realm_server', None)
domains = ipaserver.dcerpc.fetch_domains(
myapi, trustinstance.local_flatname, forest_root_name, creds=creds,
server=server)
return domains
def add_new_domains_from_trust(myapi, trustinstance, trust_entry,
domains, **options):
result = []
if not domains:
return result
trust_name = trust_entry['cn'][0]
# trust range must exist by the time add_new_domains_from_trust is called
range_name = trust_name.upper() + '_id_range'
old_range = myapi.Command.idrange_show(range_name, raw=True)['result']
idrange_type = old_range['iparangetype'][0]
suffixes = list()
suffixes.extend(y['cn']
for x, y in six.iteritems(domains['suffixes'])
if x not in domains['domains'])
try:
dn = myapi.Object.trust.get_dn(trust_name, trust_type=u'ad')
ldap = myapi.Backend.ldap2
entry = ldap.get_entry(dn)
tlns = entry.get('ipantadditionalsuffixes', [])
tlns.extend(x for x in suffixes if x not in tlns)
entry['ipantadditionalsuffixes'] = tlns
ftidata = domains.get('ftinfo_data', None)
if ftidata is not None:
entry['ipanttrustforesttrustinfo'] = [ftidata]
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
is_nontransitive = int(trust_entry.get('ipanttrustattributes',
[0])[0]) & LSA_TRUST_ATTRIBUTE_NON_TRANSITIVE
if is_nontransitive:
return result
for dom in six.itervalues(domains['domains']):
dom['trust_type'] = u'ad'
try:
name = dom['cn']
del dom['cn']
if 'all' in options:
dom['all'] = options['all']
if 'raw' in options:
dom['raw'] = options['raw']
try:
res = myapi.Command.trustdomain_add(trust_name, name, **dom)
result.append(res['result'])
except errors.DuplicateEntry:
# Ignore updating duplicate entries
pass
if idrange_type != u'ipa-ad-trust-posix':
range_name = name.upper() + '_id_range'
dom['range_type'] = u'ipa-ad-trust'
add_range(myapi, trustinstance,
range_name, dom['ipanttrusteddomainsid'],
name, **dom)
except errors.DuplicateEntry:
# Ignore updating duplicate entries
pass
return result
@register()
class trust_fetch_domains(LDAPRetrieve):
__doc__ = _('Refresh list of the domains associated with the trust')
has_output = output.standard_list_of_entries
takes_options = LDAPRetrieve.takes_options + (
Str('realm_admin?',
cli_name='admin',
label=_("Active Directory domain administrator"),
),
Password('realm_passwd?',
cli_name='password',
label=_("Active Directory domain administrator's password"),
confirm=False,
),
Str('realm_server?',
cli_name='server',
label=_('Domain controller for the Active Directory domain '
'(optional)'),
),
)
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
verify_samba_component_presence(ldap, self.api)
# Check first that the trust actually exists
result = self.api.Command.trust_show(keys[0], all=True, raw=True)
self.obj.warning_if_ad_trust_dom_have_missing_SID(result, **options)
result = dict()
result['result'] = []
result['count'] = 0
result['truncated'] = False
# For one-way trust and external trust fetch over DBus.
# We don't get the list in this case.
# With privilege separation we also cannot authenticate as
# HTTP/ principal because we have no access to its key material.
# Thus, we'll use DBus call out to oddjobd helper in all cases
fetch_trusted_domains_over_dbus(self.api, *keys, **options)
result['summary'] = unicode(_('List of trust domains successfully '
'refreshed. Use trustdomain-find '
'command to list them.'))
return result
@register()
class trust_enable_agent(Command):
__doc__ = _("Configure this server as a trust agent.")
NO_CLI = True
has_output = output.standard_value
takes_args = (
Str(
'remote_cn',
cli_name='remote_name',
label=_('Remote server name'),
doc=_('Remote IPA server hostname'),
),
)
takes_options = (
Flag('enable_compat',
doc=_('Enable support for trusted domains for old clients'),
default=False),
)
def execute(self, *keys, **options):
# the server must be the local host
# This check is needed because the forward method may failover
# to a master different from the one specified
if keys[0] != api.env.host:
raise errors.ValidationError(
name='cn', error=_("must be \"%s\"") % api.env.host)
# the user must have the Replication Administrators privilege
privilege = u'Replication Administrators'
op_account = getattr(context, 'principal', None)
if not principal_has_privilege(self.api, op_account, privilege):
raise errors.ACIError(
info=_("not allowed to remotely add agent"))
# Trust must be configured
if options[u'enable_compat']:
method_arguments = "--enable-compat"
else:
method_arguments = ""
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
obj = bus.get_object('org.freeipa.server', '/',
follow_name_owner_changes=True)
server = dbus.Interface(obj, 'org.freeipa.server')
ret, stdout, stderr = server.trust_enable_agent(method_arguments)
result = dict(
result=(ret == 0),
value=keys[0],
)
for line in stdout.splitlines() + stderr.splitlines():
messages.add_message(options['version'],
result,
messages.ExternalCommandOutput(line=line))
return result
@register()
class trustdomain_enable(LDAPQuery):
__doc__ = _('Allow use of IPA resources by the domain of the trust')
has_output = output.standard_value
msg_summary = _('Enabled trust domain "%(value)s"')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
verify_samba_component_presence(ldap, self.api)
if keys[0].lower() == keys[1].lower():
raise errors.ValidationError(
name='domain',
error=_("Root domain of the trust is always enabled "
"for the existing trust")
)
try:
trust_dn = self.obj.get_dn(keys[0], trust_type=u'ad')
trust_entry = ldap.get_entry(trust_dn)
except errors.NotFound:
raise self.api.Object[self.obj.parent_object].handle_not_found(
keys[0])
dn = self.obj.get_dn(keys[0], keys[1], trust_type=u'ad')
try:
entry = ldap.get_entry(dn)
sid = entry.single_value.get('ipanttrusteddomainsid', None)
if sid in trust_entry['ipantsidblacklistincoming']:
trust_entry['ipantsidblacklistincoming'].remove(sid)
ldap.update_entry(trust_entry)
else:
raise errors.AlreadyActive()
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
return dict(
result=True,
value=pkey_to_value(keys[1], options),
)
@register()
class trustdomain_disable(LDAPQuery):
__doc__ = _('Disable use of IPA resources by the domain of the trust')
has_output = output.standard_value
msg_summary = _('Disabled trust domain "%(value)s"')
def execute(self, *keys, **options):
ldap = self.api.Backend.ldap2
verify_samba_component_presence(ldap, self.api)
if keys[0].lower() == keys[1].lower():
raise errors.ValidationError(
name='domain',
error=_("cannot disable root domain of the trust, "
"use trust-del to delete the trust itself")
)
try:
trust_dn = self.obj.get_dn(keys[0], trust_type=u'ad')
trust_entry = ldap.get_entry(trust_dn)
except errors.NotFound:
raise self.api.Object[self.obj.parent_object].handle_not_found(
keys[0])
dn = self.obj.get_dn(keys[0], keys[1], trust_type=u'ad')
try:
entry = ldap.get_entry(dn)
sid = entry.single_value.get('ipanttrusteddomainsid', None)
if sid not in trust_entry['ipantsidblacklistincoming']:
trust_entry['ipantsidblacklistincoming'].append(sid)
ldap.update_entry(trust_entry)
else:
raise errors.AlreadyInactive()
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
return dict(
result=True,
value=pkey_to_value(keys[1], options),
)
| 72,115
|
Python
|
.py
| 1,655
| 32.001813
| 79
| 0.577997
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,846
|
xmlserver.py
|
freeipa_freeipa/ipaserver/plugins/xmlserver.py
|
# Authors:
# Jason Gerard DeRose <jderose@redhat.com>
# Rob Crittenden <rcritten@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/>.
"""
Loads WSGI server plugins.
"""
from ipalib import Registry, api
register = Registry()
if api.env.context in ('server', 'lite'):
from ipaserver.rpcserver import (
wsgi_dispatch, xmlserver, jsonserver_i18n_messages, jsonserver_kerb,
jsonserver_session, login_kerberos, login_x509, login_password,
change_password, sync_token, xmlserver_session)
register()(wsgi_dispatch)
register()(xmlserver)
register()(jsonserver_i18n_messages)
register()(jsonserver_kerb)
register()(jsonserver_session)
register()(login_kerberos)
register()(login_x509)
register()(login_password)
register()(change_password)
register()(sync_token)
register()(xmlserver_session)
| 1,545
|
Python
|
.py
| 40
| 35.7
| 76
| 0.748
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,847
|
hbactest.py
|
freeipa_freeipa/ipaserver/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/>.
import logging
from ipalib import api, errors, output, util
from ipalib import Command, Str, Flag, Int
from ipalib import _
from ipapython.dn import DN
from ipalib.plugable import Registry
from ipalib.messages import VersionMissing
if api.env.in_server:
try:
import ipaserver.dcerpc
_dcerpc_bindings_installed = True
except ImportError:
_dcerpc_bindings_installed = False
import six
try:
import pyhbac
except ImportError:
raise errors.SkipPluginModule(reason=_('pyhbac is not installed.'))
if six.PY3:
unicode = str
__doc__ = _(r"""
Simulate use of Host-based access controls
HBAC rules control who can access what services on what hosts.
You can use HBAC to control which users or groups can access a service,
or group of services, on a target host.
Since applying HBAC rules implies use of a production environment,
this plugin aims to provide simulation of HBAC rules evaluation without
having access to the production environment.
Test user coming to a service on a named host against
existing enabled rules.
ipa hbactest --user= --host= --service=
[--rules=rules-list] [--nodetail] [--enabled] [--disabled]
[--sizelimit= ]
--user, --host, and --service are mandatory, others are optional.
If --rules is specified simulate enabling of the specified rules and test
the login of the user using only these rules.
If --enabled is specified, all enabled HBAC rules will be added to simulation
If --disabled is specified, all disabled HBAC rules will be added to simulation
If --nodetail is specified, do not return information about rules matched/not matched.
If both --rules and --enabled are specified, apply simulation to --rules _and_
all IPA enabled rules.
If no --rules specified, simulation is run against all IPA enabled rules.
By default there is a IPA-wide limit to number of entries fetched, you can change it
with --sizelimit option.
EXAMPLES:
1. Use all enabled HBAC rules in IPA database to simulate:
$ ipa hbactest --user=a1a --host=bar --service=sshd
--------------------
Access granted: True
--------------------
Not matched rules: my-second-rule
Not matched rules: my-third-rule
Not matched rules: myrule
Matched rules: allow_all
2. Disable detailed summary of how rules were applied:
$ ipa hbactest --user=a1a --host=bar --service=sshd --nodetail
--------------------
Access granted: True
--------------------
3. Test explicitly specified HBAC rules:
$ ipa hbactest --user=a1a --host=bar --service=sshd \\
--rules=myrule --rules=my-second-rule
---------------------
Access granted: False
---------------------
Not matched rules: my-second-rule
Not matched rules: myrule
4. Use all enabled HBAC rules in IPA database + explicitly specified rules:
$ ipa hbactest --user=a1a --host=bar --service=sshd \\
--rules=myrule --rules=my-second-rule --enabled
--------------------
Access granted: True
--------------------
Not matched rules: my-second-rule
Not matched rules: my-third-rule
Not matched rules: myrule
Matched rules: allow_all
5. Test all disabled HBAC rules in IPA database:
$ ipa hbactest --user=a1a --host=bar --service=sshd --disabled
---------------------
Access granted: False
---------------------
Not matched rules: new-rule
6. Test all disabled HBAC rules in IPA database + explicitly specified rules:
$ ipa hbactest --user=a1a --host=bar --service=sshd \\
--rules=myrule --rules=my-second-rule --disabled
---------------------
Access granted: False
---------------------
Not matched rules: my-second-rule
Not matched rules: my-third-rule
Not matched rules: myrule
7. Test all (enabled and disabled) HBAC rules in IPA database:
$ ipa hbactest --user=a1a --host=bar --service=sshd \\
--enabled --disabled
--------------------
Access granted: True
--------------------
Not matched rules: my-second-rule
Not matched rules: my-third-rule
Not matched rules: myrule
Not matched rules: new-rule
Matched rules: allow_all
HBACTEST AND TRUSTED DOMAINS
When an external trusted domain is configured in IPA, HBAC rules are also applied
on users accessing IPA resources from the trusted domain. Trusted domain users and
groups (and their SIDs) can be then assigned to external groups which can be
members of POSIX groups in IPA which can be used in HBAC rules and thus allowing
access to resources protected by the HBAC system.
hbactest plugin is capable of testing access for both local IPA users and users
from the trusted domains, either by a fully qualified user name or by user SID.
Such user names need to have a trusted domain specified as a short name
(DOMAIN\Administrator) or with a user principal name (UPN), Administrator@ad.test.
Please note that hbactest executed with a trusted domain user as --user parameter
can be only run by members of "trust admins" group.
EXAMPLES:
1. Test if a user from a trusted domain specified by its shortname matches any
rule:
$ ipa hbactest --user 'DOMAIN\Administrator' --host `hostname` --service sshd
--------------------
Access granted: True
--------------------
Matched rules: allow_all
Matched rules: can_login
2. Test if a user from a trusted domain specified by its domain name matches
any rule:
$ ipa hbactest --user 'Administrator@domain.com' --host `hostname` --service sshd
--------------------
Access granted: True
--------------------
Matched rules: allow_all
Matched rules: can_login
3. Test if a user from a trusted domain specified by its SID matches any rule:
$ ipa hbactest --user S-1-5-21-3035198329-144811719-1378114514-500 \\
--host `hostname` --service sshd
--------------------
Access granted: True
--------------------
Matched rules: allow_all
Matched rules: can_login
4. Test if other user from a trusted domain specified by its SID matches any rule:
$ ipa hbactest --user S-1-5-21-3035198329-144811719-1378114514-1203 \\
--host `hostname` --service sshd
--------------------
Access granted: True
--------------------
Matched rules: allow_all
Not matched rules: can_login
5. Test if other user from a trusted domain specified by its shortname matches
any rule:
$ ipa hbactest --user 'DOMAIN\Otheruser' --host `hostname` --service sshd
--------------------
Access granted: True
--------------------
Matched rules: allow_all
Not matched rules: can_login
""")
logger = logging.getLogger(__name__)
register = Registry()
def _convert_to_ipa_rule(rule):
# convert a dict with a rule to an pyhbac rule
ipa_rule = pyhbac.HbacRule(rule['cn'][0])
ipa_rule.enabled = rule['ipaenabledflag'][0]
# Following code attempts to process rule systematically
structure = \
(('user', 'memberuser', 'user', 'group', ipa_rule.users),
('host', 'memberhost', 'host', 'hostgroup', ipa_rule.targethosts),
('sourcehost', 'sourcehost', 'host', 'hostgroup', ipa_rule.srchosts),
('service', 'memberservice', 'hbacsvc', 'hbacsvcgroup', ipa_rule.services),
)
for element in structure:
category = '%scategory' % (element[0])
if (category in rule and rule[category][0] == u'all') or (element[0] == 'sourcehost'):
# rule applies to all elements
# sourcehost is always set to 'all'
element[4].category = set([pyhbac.HBAC_CATEGORY_ALL])
else:
# rule is about specific entities
# Check if there are explicitly listed entities
attr_name = '%s_%s' % (element[1], element[2])
if attr_name in rule:
element[4].names = rule[attr_name]
# Now add groups of entities if they are there
attr_name = '%s_%s' % (element[1], element[3])
if attr_name in rule:
element[4].groups = rule[attr_name]
if 'externalhost' in rule:
ipa_rule.srchosts.names.extend(rule['externalhost'])
return ipa_rule
@register()
class hbactest(Command):
__doc__ = _('Simulate use of Host-based access controls')
has_output = (
output.summary,
output.Output('warning', (list, tuple, type(None)), _('Warning')),
output.Output('matched', (list, tuple, type(None)), _('Matched rules')),
output.Output('notmatched', (list, tuple, type(None)), _('Not matched rules')),
output.Output('error', (list, tuple, type(None)), _('Non-existent or invalid rules')),
output.Output('value', bool, _('Result of simulation'), ['no_display']),
)
takes_options = (
Str('user',
cli_name='user',
label=_('User name'),
primary_key=True,
),
Str('sourcehost?',
deprecated=True,
cli_name='srchost',
label=_('Source host'),
flags={'no_option'},
),
Str('targethost',
cli_name='host',
label=_('Target host'),
),
Str('service',
cli_name='service',
label=_('Service'),
),
Str('rules*',
cli_name='rules',
label=_('Rules to test. If not specified, --enabled is assumed'),
),
Flag('nodetail?',
cli_name='nodetail',
label=_('Hide details which rules are matched, not matched, or invalid'),
),
Flag('enabled?',
cli_name='enabled',
label=_('Include all enabled IPA rules into test [default]'),
),
Flag('disabled?',
cli_name='disabled',
label=_('Include all disabled IPA rules into test'),
),
Int('sizelimit?',
label=_('Size Limit'),
doc=_('Maximum number of rules to process when no --rules is specified'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
)
def canonicalize(self, host):
"""
Canonicalize the host name -- add default IPA domain if that is missing
"""
if host.find('.') == -1:
return u'%s.%s' % (host, self.env.domain)
return host
def execute(self, *args, **options):
# First receive all needed information:
# 1. HBAC rules (whether enabled or disabled)
# 2. Required options are (user, target host, service)
# 3. Options: rules to test (--rules, --enabled, --disabled), request for detail output
rules = []
result = {
'warning':None, 'matched':None, 'notmatched':None, 'error':None
}
# Use all enabled IPA rules by default
all_enabled = True
all_disabled = False
# We need a local copy of test rules in order find incorrect ones
testrules = {}
if 'rules' in options:
testrules = list(options['rules'])
# When explicit rules are provided, disable assumptions
all_enabled = False
all_disabled = False
sizelimit = None
if 'sizelimit' in options:
sizelimit = int(options['sizelimit'])
# Check if --disabled is specified, include all disabled IPA rules
if options['disabled']:
all_disabled = True
all_enabled = False
# Finally, if enabled is specified implicitly, override above decisions
if options['enabled']:
all_enabled = True
hbacset = []
if len(testrules) == 0:
hbacrules = self.api.Command.hbacrule_find(
sizelimit=sizelimit, no_members=False)
hbacset = hbacrules['result']
for message in hbacrules['messages']:
if message['code'] != VersionMissing.errno:
result.setdefault('messages', []).append(message)
else:
for rule in testrules:
try:
hbacset.append(self.api.Command.hbacrule_show(rule)['result'])
except Exception:
pass
# We have some rules, import them
# --enabled will import all enabled rules (default)
# --disabled will import all disabled rules
# --rules will implicitly add the rules from a rule list
for rule in hbacset:
ipa_rule = _convert_to_ipa_rule(rule)
if ipa_rule.name in testrules:
ipa_rule.enabled = True
rules.append(ipa_rule)
testrules.remove(ipa_rule.name)
elif all_enabled and ipa_rule.enabled:
# Option --enabled forces to include all enabled IPA rules into test
rules.append(ipa_rule)
elif all_disabled and not ipa_rule.enabled:
# Option --disabled forces to include all disabled IPA rules into test
ipa_rule.enabled = True
rules.append(ipa_rule)
# Check if there are unresolved rules left
if len(testrules) > 0:
# Error, unresolved rules are left in --rules
return {'summary' : unicode(_(u'Unresolved rules in --rules')),
'error': testrules, 'matched': None, 'notmatched': None,
'warning' : None, 'value' : False}
# Rules are converted to pyhbac format, build request and then test it
request = pyhbac.HbacRequest()
if options['user'] != u'all':
# check first if this is not a trusted domain user
if _dcerpc_bindings_installed:
# pylint: disable=used-before-assignment
is_valid_sid = ipaserver.dcerpc.is_sid_valid(options['user'])
# pylint: enable=used-before-assignment
else:
is_valid_sid = False
components = util.normalize_name(options['user'])
if is_valid_sid or 'domain' in components or 'flatname' in components:
# this is a trusted domain user
if not _dcerpc_bindings_installed:
raise errors.NotFound(reason=_(
'Cannot perform external member validation without '
'Samba 4 support installed. Make sure you have installed '
'server-trust-ad sub-package of IPA on the server'))
domain_validator = ipaserver.dcerpc.DomainValidator(self.api)
if not domain_validator.is_configured():
raise errors.NotFound(reason=_(
'Cannot search in trusted domains without own domain configured. '
'Make sure you have run ipa-adtrust-install on the IPA server first'))
user_sid, group_sids = domain_validator.get_trusted_domain_user_and_groups(options['user'])
request.user.name = user_sid
# Now search for all external groups that have this user or
# any of its groups in its external members. Found entires
# memberOf links will be then used to gather all groups where
# this group is assigned, including the nested ones
filter_sids = "(&(objectclass=ipaexternalgroup)(|(ipaExternalMember=%s)))" \
% ")(ipaExternalMember=".join(group_sids + [user_sid])
ldap = self.api.Backend.ldap2
group_container = DN(api.env.container_group, api.env.basedn)
try:
entries, _truncated = ldap.find_entries(
filter_sids, ['memberof'], group_container)
except errors.NotFound:
request.user.groups = []
else:
groups = []
for entry in entries:
memberof_dns = entry.get('memberof', [])
for memberof_dn in memberof_dns:
if memberof_dn.endswith(group_container):
groups.append(memberof_dn[0][0].value)
request.user.groups = sorted(set(groups))
else:
# try searching for a local user
try:
request.user.name = options['user']
search_result = self.api.Command.user_show(request.user.name)['result']
groups = search_result['memberof_group']
if 'memberofindirect_group' in search_result:
groups += search_result['memberofindirect_group']
request.user.groups = sorted(set(groups))
except Exception:
pass
if options['service'] != u'all':
try:
request.service.name = options['service']
service_result = self.api.Command.hbacsvc_show(request.service.name)['result']
if 'memberof_hbacsvcgroup' in service_result:
request.service.groups = service_result['memberof_hbacsvcgroup']
except Exception:
pass
if options['targethost'] != u'all':
try:
request.targethost.name = self.canonicalize(options['targethost'])
tgthost_result = self.api.Command.host_show(request.targethost.name)['result']
groups = tgthost_result['memberof_hostgroup']
if 'memberofindirect_hostgroup' in tgthost_result:
groups += tgthost_result['memberofindirect_hostgroup']
request.targethost.groups = sorted(set(groups))
except Exception:
pass
matched_rules = []
notmatched_rules = []
error_rules = []
warning_rules = []
if not options['nodetail']:
# Validate runs rules one-by-one and reports failed ones
for ipa_rule in rules:
try:
res = request.evaluate([ipa_rule])
if res == pyhbac.HBAC_EVAL_ALLOW:
matched_rules.append(ipa_rule.name)
if res == pyhbac.HBAC_EVAL_DENY:
notmatched_rules.append(ipa_rule.name)
except pyhbac.HbacError as e:
code, rule_name = e.args
if code == pyhbac.HBAC_EVAL_ERROR:
error_rules.append(rule_name)
logger.info('Native IPA HBAC rule "%s" parsing error: '
'%s',
rule_name, pyhbac.hbac_result_string(code))
except (TypeError, IOError) as info:
logger.error('Native IPA HBAC module error: %s', info)
access_granted = len(matched_rules) > 0
else:
res = request.evaluate(rules)
access_granted = (res == pyhbac.HBAC_EVAL_ALLOW)
result['summary'] = _('Access granted: %s') % (access_granted)
if len(matched_rules) > 0:
result['matched'] = matched_rules
if len(notmatched_rules) > 0:
result['notmatched'] = notmatched_rules
if len(error_rules) > 0:
result['error'] = error_rules
if len(warning_rules) > 0:
result['warning'] = warning_rules
result['value'] = access_granted
return result
| 20,463
|
Python
|
.py
| 447
| 35.659955
| 107
| 0.593742
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,848
|
idp.py
|
freeipa_freeipa/ipaserver/plugins/idp.py
|
#
# Copyright (C) 2021 FreeIPA Contributors see COPYING for license
#
import logging
import string
from urllib.parse import urlparse
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve)
from ipalib import api, errors, Password, Str, StrEnum, _, ngettext
from ipalib.plugable import Registry
from ipapython.dn import DN
from ipapython.ipautil import template_str
from copy import deepcopy
from itertools import chain
logger = logging.getLogger(__name__)
__doc__ = _("""
External Identity Provider References
""") + _("""
Manage External Identity Provider References.
""") + _("""
IPA supports the use of an external Identity Provider for OAuth2.0 Device Flow
authentication.
""") + _("""
EXAMPLES:
""") + _("""
Add a new external Identity Provider reference:
ipa idp-add MyIdP --client-id jhkQty13 \
--auth-uri https://oauth2.idp.com/auth \
--token-uri https://oauth2.idp.com/token --secret
""") + _("""
Add a new external Identity Provider reference using github predefined
endpoints:
ipa idp-add MyIdp --client-id jhkQty13 --provider github --secret
""") + _("""
Find all external Identity Provider references whose entries include the string
"test.com":
ipa idp-find test.com
""") + _("""
Examine the configuration of an external Identity Provider reference:
ipa idp-show MyIdP
""") + _("""
Change the secret:
ipa idp-mod MyIdP --secret
""") + _("""
Delete an external Identity Provider reference:
ipa idp-del MyIdP
""")
register = Registry()
def normalize_baseurl(url):
if url.startswith('https://'):
return url[len('https://'):]
return url
def validate_uri(ugettext, uri):
try:
parsed = urlparse(uri, 'https')
except Exception:
return _('Invalid URI: not an https scheme')
if not parsed.netloc:
return _('Invalid URI: missing netloc')
return None
@register()
class idp(LDAPObject):
"""
Identity Provider object.
"""
container_dn = api.env.container_idp
object_name = _('Identity Provider reference')
object_name_plural = _('Identity Provider references')
object_class = ['ipaidp']
default_attributes = [
'cn', 'ipaidpauthendpoint', 'ipaidpdevauthendpoint',
'ipaidpuserinfoendpoint', 'ipaidpkeysendpoint',
'ipaidptokenendpoint', 'ipaidpissuerurl',
'ipaidpclientid', 'ipaidpscope', 'ipaidpsub',
]
search_attributes = [
'cn', 'ipaidpauthendpoint', 'ipaidpdevauthendpoint',
'ipaidptokenendpoint', 'ipaidpuserinfoendpoint',
'ipaidpkeysendpoint', 'ipaidpscope', 'ipaidpsub',
]
allow_rename = True
label = _('Identity Provider references')
label_singular = _('Identity Provider reference')
takes_params = (
Str('cn',
cli_name='name',
label=_('Identity Provider reference name'),
primary_key=True,
),
Str('ipaidpauthendpoint?',
validate_uri,
cli_name='auth_uri',
label=_('Authorization URI'),
doc=_('OAuth 2.0 authorization endpoint'),
),
Str('ipaidpdevauthendpoint?',
validate_uri,
cli_name='dev_auth_uri',
label=_('Device authorization URI'),
doc=_('Device authorization endpoint'),
),
Str('ipaidptokenendpoint?',
validate_uri,
cli_name='token_uri',
label=_('Token URI'),
doc=_('Token endpoint'),
),
Str('ipaidpuserinfoendpoint?',
validate_uri,
cli_name='userinfo_uri',
label=_('User info URI'),
doc=_('User information endpoint'),
),
Str('ipaidpkeysendpoint?',
validate_uri,
cli_name='keys_uri',
label=_('JWKS URI'),
doc=_('JWKS endpoint'),
),
Str('ipaidpissuerurl?',
cli_name='issuer_url',
label=_('OIDC URL'),
doc=_(
'The Identity Provider OIDC URL'),
),
Str('ipaidpclientid',
cli_name='client_id',
label=_('Client identifier'),
doc=_(
'OAuth 2.0 client identifier'),
),
Password('ipaidpclientsecret?',
cli_name='secret',
label=_('Secret'),
doc=_('OAuth 2.0 client secret'),
confirm=True,
flags={'no_display'},
),
Str('ipaidpscope?',
cli_name='scope',
label=_('Scope'),
doc=_('OAuth 2.0 scope. Multiple scopes separated by space'),
),
Str('ipaidpsub?',
cli_name='idp_user_id',
label=_('External IdP user identifier attribute'),
doc=_('Attribute for user identity in OAuth 2.0 userinfo'),
),
)
permission_filter_objectclasses = ['ipaidp']
managed_permissions = {
'System: Add External IdP server': {
'ipapermright': {'add'},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermtargetfilter': {
'(objectclass=ipaidp)'},
'default_privileges': {'External IdP server Administrators'}
},
'System: Read External IdP server': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipaidpauthendpoint',
'ipaidpdevauthendpoint', 'ipaidpuserinfoendpoint',
'ipaidptokenendpoint', 'ipaidpkeysendpoint',
'ipaidpissuerurl', 'ipaidpclientid', 'ipaidpscope',
'ipaidpsub',
},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermtargetfilter': {
'(objectclass=ipaidp)'},
'default_privileges': {'External IdP server Administrators'}
},
'System: Modify External IdP server': {
'ipapermright': {'write'},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipaidpauthendpoint',
'ipaidpdevauthendpoint', 'ipaidpuserinfoendpoint',
'ipaidptokenendpoint', 'ipaidpkeysendpoint',
'ipaidpissuerurl', 'ipaidpclientid', 'ipaidpscope',
'ipaidpclientsecret', 'ipaidpsub',
},
'default_privileges': {'External IdP server Administrators'}
},
'System: Delete External IdP server': {
'ipapermright': {'delete'},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermtargetfilter': {
'(objectclass=ipaidp)'},
'default_privileges': {'External IdP server Administrators'}
},
'System: Read External IdP server client secret': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermlocation': DN(container_dn, api.env.basedn),
'ipapermdefaultattr': {
'cn', 'objectclass', 'ipaidpauthendpoint',
'ipaidpdevauthendpoint', 'ipaidpuserinfoendpoint',
'ipaidptokenendpoint', 'ipaidpissuerurl',
'ipaidpkeysendpoint', 'ipaidpclientid', 'ipaidpscope',
'ipaidpclientsecret', 'ipaidpsub',
},
'ipapermtargetfilter': {
'(objectclass=ipaidp)'},
}
}
@register()
class idp_add(LDAPCreate):
__doc__ = _('Add a new Identity Provider reference.')
msg_summary = _('Added Identity Provider reference "%(value)s"')
# List of pre-populated idp endpoints
# key = provider,
# value = dictionary of overidden attributes
idp_providers = {
'google': {
'ipaidpauthendpoint':
'https://accounts.google.com/o/oauth2/auth',
'ipaidpdevauthendpoint':
'https://oauth2.googleapis.com/device/code',
'ipaidptokenendpoint':
'https://oauth2.googleapis.com/token',
'ipaidpuserinfoendpoint':
'https://openidconnect.googleapis.com/v1/userinfo',
'ipaidpkeysendpoint':
'https://www.googleapis.com/oauth2/v3/certs',
'ipaidpscope': 'openid email',
'ipaidpsub': 'email'},
'github': {
'ipaidpauthendpoint':
'https://github.com/login/oauth/authorize',
'ipaidpdevauthendpoint':
'https://github.com/login/device/code',
'ipaidptokenendpoint':
'https://github.com/login/oauth/access_token',
'ipaidpuserinfoendpoint':
'https://api.github.com/user',
'ipaidpscope': 'user',
'ipaidpsub': 'login'},
'microsoft': {
'ipaidpauthendpoint':
'https://login.microsoftonline.com/${ipaidporg}/oauth2/v2.0/'
'authorize',
'ipaidpdevauthendpoint':
'https://login.microsoftonline.com/${ipaidporg}/oauth2/v2.0/'
'devicecode',
'ipaidptokenendpoint':
'https://login.microsoftonline.com/${ipaidporg}/oauth2/v2.0/'
'token',
'ipaidpuserinfoendpoint':
'https://graph.microsoft.com/oidc/userinfo',
'ipaidpkeysendpoint':
'https://login.microsoftonline.com/common/discovery/v2.0/keys',
'ipaidpscope': 'openid email',
'ipaidpsub': 'email',
},
'okta': {
'ipaidpauthendpoint':
'https://${ipaidpbaseurl}/oauth2/v1/authorize',
'ipaidpdevauthendpoint':
'https://${ipaidpbaseurl}/oauth2/v1/device/authorize',
'ipaidptokenendpoint':
'https://${ipaidpbaseurl}/oauth2/v1/token',
'ipaidpuserinfoendpoint':
'https://${ipaidpbaseurl}/oauth2/v1/userinfo',
'ipaidpscope': 'openid email',
'ipaidpsub': 'email'},
'keycloak': {
'ipaidpauthendpoint':
'https://${ipaidpbaseurl}/realms/${ipaidporg}/protocol/'
'openid-connect/auth',
'ipaidpdevauthendpoint':
'https://${ipaidpbaseurl}/realms/${ipaidporg}/protocol/'
'openid-connect/auth/device',
'ipaidptokenendpoint':
'https://${ipaidpbaseurl}/realms/${ipaidporg}/protocol/'
'openid-connect/token',
'ipaidpuserinfoendpoint':
'https://${ipaidpbaseurl}/realms/${ipaidporg}/protocol/'
'openid-connect/userinfo',
'ipaidpscope': 'openid email',
'ipaidpsub': 'email'},
}
takes_options = LDAPCreate.takes_options + (
StrEnum(
'ipaidpprovider?',
cli_name='provider',
label=_('IdP provider template'),
doc=_('Choose a pre-defined template to use'),
flags={'virtual_attribute', 'no_create', 'no_update', 'nosearch'},
values=tuple(idp_providers.keys()),
),
Str('ipaidporg?',
cli_name='organization',
label=_('Organization'),
doc=_('Organization ID or Realm name for IdP provider templates'),
flags={'virtual_attribute', 'no_create', 'no_update', 'nosearch'}),
Str('ipaidpbaseurl?',
cli_name='base_url',
label=_('Base URL'),
doc=_('Base URL for IdP provider templates'),
normalizer=normalize_baseurl,
flags={'virtual_attribute', 'no_create', 'no_update', 'nosearch'}),
)
def _convert_provider_to_endpoints(self, entry_attrs,
provider=None, elements=None):
"""
Converts provider options to auth-uri and token-uri
"""
if provider:
if provider not in self.idp_providers:
raise errors.ValidationError(
name='provider',
error=_('unknown provider')
)
# For each string in the template check if a variable
# is required, it is provided as an option
points = deepcopy(self.idp_providers[provider])
r = string.Template.pattern
for (k,v) in points.items():
# build list of variables to be replaced
subs = list(chain.from_iterable(
(filter(None, s) for s in r.findall(v))))
if subs:
for s in subs:
if s not in elements:
raise errors.ValidationError(
name=self.options[s].cli_name,
error=_('value is missing'))
points[k] = template_str(v, elements)
elif k in elements:
points[k] = elements[k]
entry_attrs.update(points)
def get_options(self):
# Some URIs are not mandatory as they can be built from the value of
# provider.
for option in super(idp_add, self).get_options():
if option.name in ('ipaidpauthendpoint', 'ipaidpdevauthendpoint',
'ipaidptokenendpoint', 'ipaidpuserinfoendpoint',
'ipaidpkeysendpoint'):
yield option.clone(required=False, alwaysask=False)
else:
yield option
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
# The valid calls are
# ipa idp-add --provider provider IDP [client details]
# ipa idp-add --dev-auth-uri auth --token-uri token-uri IDP
auth = options.get('ipaidpauthendpoint')
devauth = options.get('ipaidpdevauthendpoint')
token = options.get('ipaidptokenendpoint')
userinfo = options.get('ipaidpuserinfoendpoint')
jwks = options.get('ipaidpkeysendpoint')
provider = options.get('ipaidpprovider')
# If the provider is supplied, reject individual endpoints
if any([devauth, auth, token, userinfo, jwks]):
if provider:
raise errors.MutuallyExclusiveError(
reason=_('cannot specify both individual endpoints '
'and IdP provider'))
# If there is no --provider, individual endpoints required
if not provider and not devauth:
raise errors.RequirementError(name='dev-auth-uri or provider')
if not provider and not auth:
raise errors.RequirementError(name='auth-uri or provider')
if not provider and not token:
raise errors.RequirementError(name='token-uri or provider')
if not provider and not userinfo:
raise errors.RequirementError(name='userinfo-uri or provider')
# if the command is called with --provider we need to add
# ipaidpdevauthendpoint, ipaidpauthendpoint, and ipaidptokenendpoint
# to the attrs list in order to display the resulting value in
# the command output
for endpoint in ['ipaidpauthendpoint', 'ipaidpdevauthendpoint',
'ipaidptokenendpoint', 'ipaidpuserinfoendpoint',
'ipaidpkeysendpoint']:
if endpoint not in attrs_list:
attrs_list.append(endpoint)
self._convert_provider_to_endpoints(entry_attrs,
provider=provider,
elements=options)
return dn
@register()
class idp_del(LDAPDelete):
__doc__ = _('Delete an Identity Provider reference.')
msg_summary = _('Deleted Identity Provider reference "%(value)s"')
@register()
class idp_mod(LDAPUpdate):
__doc__ = _('Modify an Identity Provider reference.')
msg_summary = _('Modified Identity Provider reference "%(value)s"')
@register()
class idp_find(LDAPSearch):
__doc__ = _('Search for Identity Provider references.')
msg_summary = ngettext(
'%(count)d Identity Provider reference matched',
'%(count)d Identity Provider references matched', 0
)
def get_options(self):
# do not propose --client-id or --secret in ipa idp-find
for option in super(idp_find, self).get_options():
if option.name in ('ipaidpclientsecret', 'ipaidpclientid'):
option = option.clone(flags={'no_option'})
yield option
@register()
class idp_show(LDAPRetrieve):
__doc__ = _('Display information about an Identity Provider '
'reference.')
| 16,805
|
Python
|
.py
| 410
| 29.907317
| 80
| 0.57259
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,849
|
internal.py
|
freeipa_freeipa/ipaserver/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 ipalib import Command
from ipalib import Str
from ipalib.frontend import Local
from ipalib.output import Output
from ipalib.text import _
from ipalib.util import json_serialize
from ipalib.plugable import Registry
__doc__ = _("""
Plugins not accessible directly through the CLI, commands used internally
""")
register = Registry()
@register()
class json_metadata(Command):
__doc__ = _('Export plugin meta-data for the webUI.')
NO_CLI = True
takes_args = (
Str('objname?',
doc=_('Name of object to export'),
),
Str('methodname?',
doc=_('Name of method to export'),
),
)
takes_options = (
Str('object?',
doc=_('Name of object to export'),
),
Str('method?',
doc=_('Name of method to export'),
),
Str('command?',
doc=_('Name of command to export'),
),
)
has_output = (
Output('objects', dict, doc=_('Dict of JSON encoded IPA Objects')),
Output('methods', dict, doc=_('Dict of JSON encoded IPA Methods')),
Output('commands', dict, doc=_('Dict of JSON encoded IPA Commands')),
)
def execute(self, objname=None, methodname=None, **options):
objects = dict()
methods = dict()
commands = dict()
empty = True
try:
if not objname:
objname = options['object']
if objname in self.api.Object:
o = self.api.Object[objname]
objects = dict([(o.name, json_serialize(o))])
elif objname == "all":
objects = dict(
(o.name, json_serialize(o)) for o in self.api.Object()
if o is self.api.Object[o.name]
)
empty = False
except KeyError:
pass
try:
if not methodname:
methodname = options['method']
if (methodname in self.api.Method and
not isinstance(self.api.Method[methodname], Local)):
m = self.api.Method[methodname]
methods = dict([(m.name, json_serialize(m))])
elif methodname == "all":
methods = dict(
(m.name, json_serialize(m)) for m in self.api.Method()
if (m is self.api.Method[m.name] and
not isinstance(m, Local))
)
empty = False
except KeyError:
pass
try:
cmdname = options['command']
if (cmdname in self.api.Command and
not isinstance(self.api.Command[cmdname], Local)):
c = self.api.Command[cmdname]
commands = dict([(c.name, json_serialize(c))])
elif cmdname == "all":
commands = dict(
(c.name, json_serialize(c)) for c in self.api.Command()
if (c is self.api.Command[c.name] and
not isinstance(c, Local))
)
empty = False
except KeyError:
pass
if empty:
objects = dict(
(o.name, json_serialize(o)) for o in self.api.Object()
if o is self.api.Object[o.name]
)
methods = dict(
(m.name, json_serialize(m)) for m in self.api.Method()
if (m is self.api.Method[m.name] and
not isinstance(m, Local))
)
commands = dict(
(c.name, json_serialize(c)) for c in self.api.Command()
if (c is self.api.Command[c.name] and
not isinstance(c, Local))
)
retval = dict([
("objects", objects),
("methods", methods),
("commands", commands),
])
return retval
@register()
class i18n_messages(Command):
__doc__ = _('Internationalization messages')
NO_CLI = True
messages = {
"ajax": {
"401": {
"message": _("Your session has expired. Please log in again."),
},
},
"actions": {
"apply": _("Apply"),
"automember_rebuild": _("Rebuild auto membership"),
"automember_rebuild_confirm": _(
"Are you sure you want to rebuild auto membership? In case of "
"a high number of users, hosts or groups, the operation "
"may require high CPU usage."
),
"automember_rebuild_success": _("Automember rebuild membership task completed"),
"confirm": _("Are you sure you want to proceed with the action?"),
"delete_confirm": _("Are you sure you want to delete ${object}?"),
"disable_confirm": _("Are you sure you want to disable ${object}?"),
"enable_confirm": _("Are you sure you want to enable ${object}?"),
"title": _("Actions"),
},
"association": {
"add_title_default": _("Add"),
"added": _("${count} item(s) added"),
"direct_membership": _("Direct Membership"),
"filter_placeholder": _("Filter available ${other_entity}"),
"indirect_membership": _("Indirect Membership"),
"no_entries": _("No entries."),
"paging": _("Showing ${start} to ${end} of ${total} entries."),
"remove_title_default": _("Remove"),
"removed": _("${count} item(s) removed"),
"show_results": _("Show Results"),
},
"authtype": {
"auth_indicators": _("Authentication indicators"),
"auth_indicator": _("Authentication indicator"),
"config_tooltip": _("<p>Implicit method (password) will be used if no method is chosen.</p><p><strong>Password + Two-factor:</strong> LDAP and Kerberos allow authentication with either one of the authentication types but Kerberos uses pre-authentication method which requires to use armor ccache.</p><p><strong>RADIUS with another type:</strong> Kerberos always use RADIUS, but LDAP never does. LDAP only recognize the password and two-factor authentication options.</p>"),
"custom_auth_ind_title": _("Add Custom Authentication Indicator"),
"otp": _("OTP"),
"type_otp": _("Two factor authentication (password + OTP)"),
"type_password": _("Password"),
"type_radius": _("RADIUS"),
"type_pkinit": _("PKINIT"),
"type_hardened": _("Hardened Password (by SPAKE or FAST)"),
"type_idp": _("External Identity Provider"),
"type_passkey": _("Passkey"),
"type_disabled": _("Disable per-user override"),
"user_tooltip": _("<p>Per-user setting, overwrites the global setting if any option is checked.</p><p><strong>Password + Two-factor:</strong> LDAP and Kerberos allow authentication with either one of the authentication types but Kerberos uses pre-authentication method which requires to use armor ccache.</p><p><strong>RADIUS with another type:</strong> Kerberos always use RADIUS, but LDAP never does. LDAP only recognize the password and two-factor authentication options.</p>"),
},
"buttons": {
"about": _("About"),
"activate": _("Activate"),
"add": _("Add"),
"add_and_add_another": _("Add and Add Another"),
"add_and_close": _("Add and Close"),
"add_and_edit": _("Add and Edit"),
"add_many": _("Add Many"),
"apply": _("Apply"),
"back": _("Back"),
"cancel": _("Cancel"),
"clear": _("Clear"),
"clear_title": _("Clear all fields on the page."),
"close": _("Close"),
"disable": _("Disable"),
"download": _("Download"),
"download_title": _("Download certificate as PEM formatted file."),
"edit": _("Edit"),
"enable": _("Enable"),
"filter": _("Filter"),
"find": _("Find"),
"get": _("Get"),
"hide": _("Hide"),
"issue": _("Issue"),
"match": _("Match"),
"match_title": _("Match users according to certificate."),
"migrate": _("Migrate"),
"ok": _("OK"),
"refresh": _("Refresh"),
"refresh_title": _("Reload current settings from the server."),
"remove": _("Delete"),
"remove_hold": _("Remove hold"),
"reset": _("Reset"),
"reset_password": _("Reset Password"),
"reset_password_and_login": _("Reset Password and Log in"),
"restore": _("Restore"),
"retry": _("Retry"),
"revert": _("Revert"),
"revert_title": ("Undo all unsaved changes."),
"revoke": _("Revoke"),
"save": _("Save"),
"set": _("Set"),
"show": _("Show"),
"stage": _("Stage"),
"unapply": ("Un-apply"),
"update": _("Update"),
"view": _("View"),
},
"customization": {
"customization": _("Customization"),
"table_pagination": _("Pagination Size"),
},
"details": {
"collapse_all": _("Collapse All"),
"expand_all": _("Expand All"),
"general": _("General"),
"identity": _("Identity Settings"),
"record": _("Record Settings"),
"settings": _("${entity} ${primary_key} Settings"),
"to_top": _("Back to Top"),
"updated": _("${entity} ${primary_key} updated"),
},
"dialogs": {
"add_confirmation": _("${entity} successfully added"),
"add_custom_value": _("Add custom value"),
"add_title_default": _("Add"),
"available": _("Available"),
"batch_error_message": _("Some operations failed."),
"batch_error_title": _("Operations Error"),
"confirmation": _("Confirmation"),
"custom_value": _("Custom value"),
"dirty_message": _("This page has unsaved changes. Please save or revert."),
"dirty_title": _("Unsaved Changes"),
"edit_title": _("Edit ${entity}"),
"hide_details": _("Hide details"),
"about_title": _("About"),
"about_message": _("${product}, version: ${version}"),
"prospective": _("Prospective"),
"redirection": _("Redirection"),
"remove_empty": _("Select entries to be removed."),
"remove_title_default": _("Remove"),
"result": _("Result"),
"show_details": _("Show details"),
"success": _("Success"),
"validation_title": _("Validation error"),
"validation_message": _("Input form contains invalid or missing values."),
},
"error_report": {
"options": _("Please try the following options:"),
"problem_persists": _("If the problem persists please contact the system administrator."),
"refresh": _("Refresh the page."),
"reload": _("Reload the browser."),
"main_page": _("Return to the main page and retry the operation"),
"title": _("An error has occurred (${error})"),
},
"errors": {
"error": _("Error"),
"http_error": _("HTTP Error"),
"internal_error": _("Internal Error"),
"ipa_error": _("IPA Error"),
"no_response": _("No response"),
"unknown_error": _("Unknown Error"),
"url": _("URL"),
},
"facet_groups": {
"managedby": _("${primary_key} is managed by:"),
"member": _("${primary_key} members:"),
"memberof": _("${primary_key} is a member of:"),
"membermanager": _("${primary_key} member managers:"),
},
"facets": {
"details": _("Settings"),
"search": _("Search"),
},
"false": _("False"),
"keytab": {
"add_groups_create": _(
"Allow user groups to create keytab of '${primary_key}'"
),
"add_groups_retrieve": _(
"Allow user groups to retrieve keytab of '${primary_key}'"
),
"add_hostgroups_create": _(
"Allow host groups to create keytab of '${primary_key}'"
),
"add_hostgroups_retrieve": _(
"Allow host groups to retrieve keytab of '${primary_key}'"
),
"add_hosts_create": _(
"Allow hosts to create keytab of '${primary_key}'"
),
"add_hosts_retrieve": _(
"Allow hosts to retrieve keytab of '${primary_key}'"
),
"add_users_create": _(
"Allow users to create keytab of '${primary_key}'"
),
"add_users_retrieve": _(
"Allow users to retrieve keytab of '${primary_key}'"
),
"allowed_to_create": _("Allowed to create keytab"),
"allowed_to_retrieve": _("Allowed to retrieve keytab"),
"remove_groups_create": _(
"Disallow user groups to create keytab of '${primary_key}'"
),
"remove_groups_retrieve": _(
"Disallow user groups to retrieve keytab of '${primary_key}'"
),
"remove_hostgroups_create": _(
"Disallow host groups to create keytab of '${primary_key}'"
),
"remove_hostgroups_retrieve": _(
"Disallow host groups to retrieve keytab of '${primary_key}'"
),
"remove_hosts_create": _(
"Disallow hosts to create keytab of '${primary_key}'"
),
"remove_hosts_retrieve": _(
"Disallow hosts to retrieve keytab of '${primary_key}'"
),
"remove_users_create": _(
"Disallow users to create keytab of '${primary_key}'"
),
"remove_users_retrieve": _(
"Disallow users to retrieve keytab of '${primary_key}'"
),
},
"krbaliases": {
"adder_title": _("Add Kerberos Principal Alias"),
"add_krbal_label": _("New kerberos principal alias"),
"remove_title": _("Remove Kerberos Alias"),
"remove_message": _("Do you want to remove kerberos alias ${alias}?"),
},
"krbauthzdata": {
"inherited": _("Inherited from server configuration"),
"mspac": _("MS-PAC"),
"override": _("Override inherited settings"),
"pad": _("PAD"),
},
"login": {
"authenticating": _("Authenticating"),
"cert_auth_failed": _(
"Authentication with personal certificate failed"),
"cert_msg": _(
"<i class=\"fa fa-info-circle\"></i> To log in with "
"<strong>certificate</strong>, please make sure you have "
"valid personal certificate. "
),
"continue_msg": _("Continue to next page"),
"form_auth": _(
"<i class=\"fa fa-info-circle\"></i> To log in with "
"<strong>username and password</strong>, enter them in the "
"corresponding fields, then click 'Log in'."),
"form_auth_failed": _("Login failed due to an unknown reason"),
"header": _("Logged In As"),
"krb_auth_failed": _("Authentication with Kerberos failed"),
"krb_auth_msg": _(
"<i class=\"fa fa-info-circle\"></i> To log in with "
"<strong>Kerberos</strong>, please make sure you have valid "
"tickets (obtainable via kinit) and <a href='${protocol}//"
"${host}/ipa/config/ssbrowser.html'>configured</a> the browser"
" correctly, then click 'Log in'."),
"loading": _("Loading"),
"krbprincipal_expired": _(
"Kerberos Principal you entered is expired"),
"loading_md": _("Loading data"),
"login": _("Log in"),
"login_certificate": _("Log In Using Certificate"),
"login_certificate_desc": _("Log in using personal certificate"),
"logout": _("Log out"),
"logout_error": _("Log out error"),
"password": _("Password"),
"password_and_otp": _("Password or Password+One-Time Password"),
"redirect_msg": _("You will be redirected in ${count}s"),
"sync_otp_token": _("Sync OTP Token"),
"synchronizing": _("Synchronizing"),
"username": _("Username"),
"user_locked": _("The user account you entered is locked"),
},
"measurement_units": {
"number_of_passwords": _("number of passwords"),
"seconds": _("seconds"),
},
"migration": {
"migrating": _("Migrating"),
"migration_error_msg": _(
"There was a problem with your request. Please, try again "
"later."),
"migration_failure_msg": _(
"Password migration was not successful"),
"migration_info_msg": _(
"<h1>Password Migration</h1><p>If you have been sent here by "
"your administrator, your personal information is being "
"migrated to a new identity management solution (IPA).</p><p>"
"Please, enter your credentials in the form to complete the "
"process. Upon successful login your kerberos account will be "
"activated.</p>"),
"migration_invalid_password": _(
"The password or username you entered is incorrect"),
"migration_success": _("Password migration was successful"),
},
"objects": {
"aci": {
"attribute": _("Attribute"),
},
"acidelegation": {
"add": _("Add delegation"),
"remove": _("Remove delegations"),
},
"acipermission": {
"add": _("Add permission"),
"add_privileges": _(
"Add privileges into permission '${primary_key}'"
),
"remove": _("Remove permissions"),
"remove_privileges": _(
"Remove privileges from permission '${primary_key}'"
),
},
"aciprivilege": {
"add": _("Add privilege"),
"add_into_permissions": _(
"Add privilege '${primary_key}' into permissions"
),
"add_roles": _(
"Add roles into privilege '${primary_key}'"
),
"remove": _("Remove privileges"),
"remove_from_permissions": _(
"Remove privilege '${primary_key}' from permissions"
),
"remove_roles": _(
"Remove roles from privilege '${primary_key}'"
),
},
"acirole": {
"identity": _("Role Settings"),
"add": _("Add role"),
"add_groups": _(
"Add user groups into role '${primary_key}'"
),
"add_hosts": _(
"Add hosts into role '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into role '${primary_key}'"
),
"add_into_privileges": _(
"Add role '${primary_key}' into privileges"
),
"add_services": _(
"Add services into role '${primary_key}'"
),
"add_users": _(
"Add users into role '${primary_key}'"
),
"remove": _("Remove roles"),
"remove_from_privileges": _(
"Remove role '${primary_key}' from privileges"
),
"remove_groups": _(
"Remove user groups from role '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from role '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from role '${primary_key}'"
),
"remove_services": _(
"Remove services from role '${primary_key}'"
),
"remove_users": _(
"Remove users from role '${primary_key}'"
),
},
"aciselfservice": {
"add": _("Add self service permission"),
"remove": _("Remove self service permissions"),
},
"automember": {
"add": _("Add rule"),
"add_inc_condition": _(
"Add inclusive condition into '${primary_key}'"
),
"add_exc_condition": _(
"Add exclusive condition into '${primary_key}'"
),
"attribute": _("Attribute"),
"default_group_confirm": _(
"Are you sure you want to change default group?"
),
"default_host_group": _("Default host group"),
"default_user_group": _("Default user group"),
"exclusive": _("Exclusive"),
"expression": _("Expression"),
"hostgrouprule": _("Host group rule"),
"hostgrouprules": _("Host group rules"),
"inclusive": _("Inclusive"),
"remove": _("Remove auto membership rules"),
"remove_exc_conditions": _(
"Remove exclusive conditions from rule '${primary_key}'"
),
"remove_inc_conditions": _(
"Remove inclusive conditions from rule '${primary_key}'"
),
"usergrouprule": _("User group rule"),
"usergrouprules": _("User group rules"),
},
"automountkey": {
"add": _("Add automount key"),
"remove": _("Remove automount keys"),
},
"automountlocation": {
"add": _("Add automount location"),
"identity": _("Automount Location Settings"),
"remove": _("Remove automount locations"),
},
"automountmap": {
"add": _("Add automount map"),
"map_type": _("Map Type"),
"direct": _("Direct"),
"indirect": _("Indirect"),
"remove": _("Remove automount maps"),
},
"ca": {
"add": _("Add certificate authority"),
"remove": _("Remove certificate authorities"),
},
"caacl": {
"add": _("Add CA ACL"),
"add_ca": _(
"Add Certificate Authorities into CA ACL "
"'${primary_key}'"
),
"add_groups": _(
"Add user groups into CA ACL '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into CA ACL '${primary_key}'"
),
"add_hosts": _(
"Add hosts into CA ACL '${primary_key}'"
),
"add_profiles": _(
"Add certificate profiles into CA ACL '${primary_key}'"
),
"add_services": _(
"Add services into CA ACL '${primary_key}'"
),
"add_users": _(
"Add users into CA ACL '${primary_key}'"
),
"all": _("All"),
"any_ca": _("Any CA"),
"any_host": _("Any Host"),
"any_service": _("Any Service"),
"any_profile": _("Any Profile"),
"anyone": _("Anyone"),
"ipaenabledflag": _("Rule status"),
"no_ca_msg": _("If no CAs are specified, requests to the default CA are allowed."),
"profile": _("Profiles"),
"remove": _("Remove CA ACLs"),
"remove_ca": _(
"Remove Certificate Authorities from CA ACL "
"'${primary_key}'"
),
"remove_groups": _(
"Remove user groups from CA ACL '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from CA ACL '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from CA ACL '${primary_key}'"
),
"remove_profiles": _(
"Remove certificate profiles from CA ACL '${primary_key}'"
),
"remove_services": _(
"Remove services from CA ACL '${primary_key}'"
),
"remove_users": _(
"Remove users from CA ACL '${primary_key}'"
),
"specified_cas": _("Specified CAs"),
"specified_hosts": _("Specified Hosts and Groups"),
"specified_profiles": _("Specified Profiles"),
"specified_services": _("Specified Services and Groups"),
"specified_users": _("Specified Users and Groups"),
"who": _("Permitted to have certificates issued"),
},
"caprofile": {
"remove": _("Remove certificate profiles"),
},
"cert": {
"aa_compromise": _("AA Compromise"),
"add_principal": _("Add principal"),
"affiliation_changed": _("Affiliation Changed"),
"ca": _("CA"),
"ca_compromise": _("CA Compromise"),
"certificate": _("Certificate"),
"certificates": _("Certificates"),
"certificate_hold": _("Certificate Hold"),
"cessation_of_operation": _("Cessation of Operation"),
"common_name": _("Common Name"),
"download": _("Download"),
"delete_cert_end": _("the certificate with serial number "),
"expires_on": _("Expires On"),
"find_issuedon_from": _("Issued on from"),
"find_issuedon_to": _("Issued on to"),
"find_max_serial_number": _("Maximum serial number"),
"find_min_serial_number": _("Minimum serial number"),
"find_revocation_reason": _("Revocation reason"),
"find_revokedon_from": _("Revoked on from"),
"find_revokedon_to": _("Revoked on to"),
"find_subject": _("Subject"),
"find_validnotafter_from": _("Valid not after from"),
"find_validnotafter_to": _("Valid not after to"),
"find_validnotbefore_from": _("Valid not before from"),
"find_validnotbefore_to": _("Valid not before to"),
"fingerprints": _("Fingerprints"),
"get_certificate": _("Get Certificate"),
"hold_removed": _("Certificate Hold Removed"),
"issue_for_host": _(
"Issue new certificate for host '${primary_key}'"
),
"issue_for_service": _(
"Issue new certificate for service '${primary_key}'"
),
"issue_for_user": _(
"Issue new certificate for user '${primary_key}'"
),
"issue_certificate_generic": _("Issue new certificate"),
"issued_by": _("Issued By"),
"issued_on": _("Issued On"),
"issued_to": _("Issued To"),
"key_compromise": _("Key Compromise"),
"missing": _("No Valid Certificate"),
"new_certificate": _("New Certificate"),
"new_cert_format": _("Certificate in base64 or PEM format"),
"note": _("Note"),
"organization": _("Organization"),
"organizational_unit": _("Organizational Unit"),
"present": _("${count} certificate(s) present"),
"privilege_withdrawn": _("Privilege Withdrawn"),
"reason": _("Reason for Revocation"),
"remove_hold": _("Remove hold"),
"remove_certificate_hold_simple": _("Remove certificate hold"),
"remove_certificate_hold_confirmation": _("Do you want to remove the certificate hold?"),
"remove_from_crl": _("Remove from CRL"),
"request_message": _("<ol> <li>Create a certificate database or use an existing one. To create a new database:<br/> <code># certutil -N -d <database path></code> </li> <li>Create a CSR with subject <em>CN=<${cn_name}>,O=<realm></em>, for example:<br/> <code># certutil -R -d <database path> -a -g <key size> -s 'CN=${cn},O=${realm}'${san}</code> </li> <li> Copy and paste the CSR (from <em>-----BEGIN NEW CERTIFICATE REQUEST-----</em> to <em>-----END NEW CERTIFICATE REQUEST-----</em>) into the text area below: </li> </ol>"),
"request_message_san": _(" -8 '${cn}'"),
"requested": _("Certificate requested"),
"revocation_reason": _("Revocation reason"),
"revoke_certificate_simple": _("Revoke certificate"),
"revoke_confirmation": _("Do you want to revoke this certificate? Select a reason from the pull-down list."),
"revoked": _("Certificate Revoked"),
"revoked_status": _("REVOKED"),
"serial_number": _("Serial Number"),
"serial_number_hex": _("Serial Number (hex)"),
"sha1_fingerprint": _("SHA1 Fingerprint"),
"sha256_fingerprint": _("SHA256 Fingerprint"),
"status": _("Status"),
"superseded": _("Superseded"),
"unspecified": _("Unspecified"),
"valid": _("Valid Certificate Present"),
"valid_from": _("Valid from"),
"valid_to": _("Valid to"),
"validity": _("Validity"),
"view_certificate": _("Certificate for ${entity} ${primary_key}"),
"view_certificate_btn": _("View Certificate"),
},
"certmap_match": {
"cert_data": _("Certificate Data"),
"cert_for_match": _("Certificate For Match"),
"facet_label": _("Certificate Mapping Match"),
"domain": _("Domain"),
"matched_users": _("Matched Users"),
"userlogin": _("User Login"),
},
"certmap": {
"add": _("Add certificate identity mapping rule"),
"adder_title": _("Add certificate mapping data"),
"data_label": _("Certificate mapping data"),
"certificate": _("Certificate"),
"conf_str": _("Configuration string"),
"deleter_content": _("Do you want to remove certificate mapping data ${data}?"),
"deleter_title": _("Remove certificate mapping data"),
"issuer": _("Issuer"),
"issuer_subject": _("Issuer and subject"),
"remove": _("Remove certificate identity mapping rules"),
"subject": _("Subject"),
"version": _("Version"),
},
"config": {
"group": _("Group Options"),
"search": _("Search Options"),
"selinux": _("SELinux Options"),
"server": _("Server Options"),
"service": _("Service Options"),
"user": _("User Options"),
},
"delegation": {
},
"dnsconfig": {
"forward_first": _("Forward first"),
"forward_none": _("Forwarding disabled"),
"forward_only": _("Forward only"),
"options": _("Options"),
"update_dns": _("Update System DNS Records"),
"update_dns_dialog_msg": _("Do you want to update system DNS records?"),
"updated_dns": _("System DNS records updated"),
},
"dnsforwardzone": {
"add": _("Add DNS forward zone"),
"remove": _("Remove DNS forward zones"),
},
"dnsrecord": {
"add": _("Add DNS resource record"),
"data": _("Data"),
"deleted_no_data": _("DNS record was deleted because it contained no data."),
"other": _("Other Record Types"),
"ptr_redir_address_err": _("Address not valid, can't redirect"),
"ptr_redir_create": _("Create dns record"),
"ptr_redir_creating": _("Creating record."),
"ptr_redir_creating_err": _("Record creation failed."),
"ptr_redir_record": _("Checking if record exists."),
"ptr_redir_record_err": _("Record not found."),
"ptr_redir_title": _("Redirection to PTR record"),
"ptr_redir_zone": _("Zone found: ${zone}"),
"ptr_redir_zone_err": _("Target reverse zone not found."),
"ptr_redir_zones": _("Fetching DNS zones."),
"ptr_redir_zones_err": _("An error occurred while fetching dns zones."),
"redirection_dnszone": _("You will be redirected to DNS Zone."),
"remove": _("Remove DNS resource records"),
"standard": _("Standard Record Types"),
"title": _("Records for DNS Zone"),
"type": _("Record Type"),
},
"dnszone": {
"add": _("Add DNS zone"),
"add_permission": _("Add permission"),
"add_permission_confirm":_("Are you sure you want to add permission for DNS Zone ${object}?"),
"identity": _("DNS Zone Settings"),
"remove": _("Remove DNS zones"),
"remove_permission": _("Remove Permission"),
"remove_permission_confirm": _("Are you sure you want to remove permission for DNS Zone ${object}?"),
"skip_dns_check": _("Skip DNS check"),
"skip_overlap_check": _("Skip overlap check"),
"soamname_change_message": _("Do you want to check if new authoritative nameserver address is in DNS"),
"soamname_change_title": _("Authoritative nameserver change"),
},
"domainlevel": {
"label": _("Domain Level"),
"label_singular": _("Domain Level"),
"ipadomainlevel": _("Level"),
"set": _("Set Domain Level"),
},
"group": {
"add": _("Add user group"),
"add_groups": _(
"Add user groups into user group '${primary_key}'"
),
"add_into_groups": _(
"Add user group '${primary_key}' into user groups"
),
"add_into_hbac": _(
"Add user group '${primary_key}' into HBAC rules"
),
"add_into_netgroups": _(
"Add user group '${primary_key}' into netgroups"
),
"add_into_roles": _(
"Add user group '${primary_key}' into roles"
),
"add_into_sudo": _(
"Add user group '${primary_key}' into sudo rules"
),
"add_services": _(
"Add services into user group '${primary_key}'"
),
"add_users": _(
"Add users into user group '${primary_key}'"
),
"add_membermanager_group": _(
"Add groups as member managers for user group "
"'${primary_key}'"
),
"remove_membermanager_group": _(
"Remove groups from member managers for user group "
"'${primary_key}'"
),
"add_membermanager_user": _(
"Add users as member managers for user group "
"'${primary_key}'"
),
"remove_membermanager_user": _(
"Remove users from member managers for user group "
"'${primary_key}'"
),
"add_idoverride_user": _(
"Add user ID override into user group '${primary_key}'"
),
"details": _("Group Settings"),
"external": _("External"),
"groups": _("Groups"),
"group_categories": _("Group categories"),
"make_external": _("Change to external group"),
"make_posix": _("Change to POSIX group"),
"nonposix": _("Non-POSIX"),
"posix": _("POSIX"),
"remove": _("Remove user groups"),
"remove_from_groups": _(
"Remove user group '${primary_key}' from user groups"
),
"remove_from_netgroups": _(
"Remove user group '${primary_key}' from netgroups"
),
"remove_from_roles": _(
"Remove user group '${primary_key}' from roles"
),
"remove_from_hbac": _(
"Remove user group '${primary_key}' from HBAC rules"
),
"remove_from_sudo": _(
"Remove user group '${primary_key}' from sudo rules"
),
"remove_groups": _(
"Remove user groups from user group '${primary_key}'"
),
"remove_services": _(
"Remove services from user group '${primary_key}'"
),
"remove_users": _(
"Remove users from user group '${primary_key}'"
),
"remove_idoverride_users": _(
"Remove user ID overrides from user group '${primary_key}'"
),
"type": _("Group Type"),
"user_groups": _("User Groups"),
},
"hbacrule": {
"add": _("Add HBAC rule"),
"add_groups": _(
"Add user groups into HBAC rule '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into HBAC rule '${primary_key}'"
),
"add_hosts": _(
"Add hosts into HBAC rule '${primary_key}'"
),
"add_servicegroups": _(
"Add HBAC service groups into HBAC rule "
"'${primary_key}'"
),
"add_services": _(
"Add HBAC services into HBAC rule '${primary_key}'"
),
"add_users": _(
"Add users into HBAC rule '${primary_key}'"
),
"any_host": _("Any Host"),
"any_service": _("Any Service"),
"anyone": _("Anyone"),
"host": _("Accessing"),
"ipaenabledflag": _("Rule status"),
"remove": _("Remove HBAC rules"),
"remove_groups": _(
"Remove user groups from HBAC rule '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from HBAC rule '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from HBAC rule '${primary_key}'"
),
"remove_servicegroups": _(
"Remove HBAC service groups from HBAC rule "
"'${primary_key}'"
),
"remove_services": _(
"Remove HBAC services from HBAC rule '${primary_key}'"
),
"remove_users": _(
"Remove users from HBAC rule '${primary_key}'"
),
"service": _("Via Service"),
"specified_hosts": _("Specified Hosts and Groups"),
"specified_services": _("Specified Services and Groups"),
"specified_users": _("Specified Users and Groups"),
"user": _("Who"),
},
"hbacsvc": {
"add": _("Add HBAC service"),
"add_hbacsvcgroups": _(
"Add HBAC service '${primary_key}' into HBAC service "
"groups"
),
"remove": _("Remove HBAC services"),
"remove_from_hbacsvcgroups": _(
"Remove HBAC service '${primary_key}' from HBAC service "
"groups"
),
},
"hbacsvcgroup": {
"add": _("Add HBAC service group"),
"add_hbacsvcs": _(
"Add HBAC services into HBAC service group "
"'${primary_key}'"
),
"remove": _("Remove HBAC service groups"),
"remove_hbacsvcs": _(
"Remove HBAC services from HBAC service group "
"'${primary_key}'"
),
"services": _("Services"),
},
"hbactest": {
"access_denied": _("Access Denied"),
"access_granted": _("Access Granted"),
"include_disabled": _("Include Disabled"),
"include_enabled": _("Include Enabled"),
"label": _("HBAC Test"),
"matched": _("Matched"),
"missing_values": _("Missing values: "),
"new_test": _("New Test"),
"rules": _("Rules"),
"run_test": _("Run Test"),
"specify_external": _("Specify external ${entity}"),
"unmatched": _("Unmatched"),
},
"host": {
"add": _("Add host"),
"add_hosts_managing": _(
"Add hosts managing host '${primary_key}'"
),
"add_into_groups": _(
"Add host '${primary_key}' into host groups"
),
"add_into_hbac": _(
"Add host '${primary_key}' into HBAC rules"
),
"add_into_netgroups": _(
"Add host '${primary_key}' into netgroups"
),
"add_into_roles": _(
"Add host '${primary_key}' into roles"
),
"add_into_sudo": _(
"Add host '${primary_key}' into sudo rules"
),
"certificate": _("Host Certificate"),
"cn": _("Host Name"),
"delete_key_unprovision": _("Delete Key, Unprovision"),
"details": _("Host Settings"),
"enrolled": _("Enrolled"),
"enrollment": _("Enrollment"),
"fqdn": _("Fully Qualified Host Name"),
"generate_otp": _("Generate OTP"),
"generated_otp": _("Generated OTP"),
"keytab": _("Kerberos Key"),
"keytab_missing": _("Kerberos Key Not Present"),
"keytab_present": _("Kerberos Key Present, Host Provisioned"),
"password": _("One-Time Password"),
"password_missing": _("One-Time Password Not Present"),
"password_present": _("One-Time Password Present"),
"password_reset_button": _("Reset OTP"),
"password_reset_title": _("Reset One-Time Password"),
"password_set_button": _("Set OTP"),
"password_set_success": _("OTP set"),
"password_set_title": _("Set One-Time Password"),
"remove": _("Remove hosts"),
"remove_hosts_managing": _(
"Remove hosts managing host '${primary_key}'"
),
"remove_from_groups": _(
"Remove host '${primary_key}' from host groups"
),
"remove_from_netgroups": _(
"Remove host '${primary_key}' from netgroups"
),
"remove_from_roles": _(
"Remove host '${primary_key}' from roles"
),
"remove_from_hbac": _(
"Remove host '${primary_key}' from HBAC rules"
),
"remove_from_sudo": _(
"Remove host '${primary_key}' from sudo rules"
),
"status": _("Status"),
"unprovision": _("Unprovision"),
"unprovision_confirmation": _("Are you sure you want to unprovision this host?"),
"unprovision_title": _("Unprovisioning host"),
"unprovisioned": _("Host unprovisioned"),
},
"hostgroup": {
"add": _("Add host group"),
"add_hosts": _(
"Add hosts into host group '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into host group '${primary_key}'"
),
"add_into_hostgroups": _(
"Add host group '${primary_key}' into host groups"
),
"add_into_hbac": _(
"Add host group '${primary_key}' into HBAC rules"
),
"add_into_netgroups": _(
"Add host group '${primary_key}' into netgroups"
),
"add_into_sudo": _(
"Add host group '${primary_key}' into sudo rules"
),
"add_membermanager_group": _(
"Add groups as member managers for host group "
"'${primary_key}'"
),
"remove_membermanager_group": _(
"Remove groups from member managers for host group "
"'${primary_key}'"
),
"add_membermanager_user": _(
"Add users as member managers for host group "
"'${primary_key}'"
),
"remove_membermanager_user": _(
"Remove users from member managers for host group "
"'${primary_key}'"
),
"host_group": _("Host Groups"),
"identity": _("Host Group Settings"),
"remove": _("Remove host groups"),
"remove_from_hostgroups": _(
"Remove host group '${primary_key}' from host groups"
),
"remove_from_netgroups": _(
"Remove host group '${primary_key}' from netgroups"
),
"remove_from_hbac": _(
"Remove host group '${primary_key}' from HBAC rules"
),
"remove_from_sudo": _(
"Remove host group '${primary_key}' from sudo rules"
),
"remove_hosts": _(
"Remove hosts from host group '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from host group '${primary_key}'"
),
},
"idp": {
"template_keycloak": _("Keycloak or Red Hat SSO"),
"template_google": _("Google"),
"template_github": _("Github"),
"template_microsoft": _("Microsoft or Azure"),
"template_okta": _("Okta"),
"label_idpclient": _("OAuth 2.0 client details"),
"label_idp": _("Identity provider details"),
"verify_secret": _("Verify secret"),
},
"idoverrideuser": {
"anchor_label": _("User to override"),
"anchor_tooltip": _("Enter trusted or IPA user login. Note: search doesn't list users from trusted domains."),
"anchor_tooltip_ad": _("Enter trusted user login."),
"profile": _("Profile"),
},
"idoverridegroup": {
"anchor_label": _("Group to override"),
"anchor_tooltip": _("Enter trusted or IPA group name. Note: search doesn't list groups from trusted domains."),
"anchor_tooltip_ad": _("Enter trusted group name."),
},
"idview": {
"add": _("Add ID view"),
"add_group": _("Add group ID override"),
"add_user": _("Add user ID override"),
"appliesto_tab": _("${primary_key} applies to:"),
"appliedtohosts": _("Applied to hosts"),
"appliedtohosts_title": _("Applied to hosts"),
"apply_hostgroups": _("Apply to host groups"),
"apply_hostgroups_title": _(
"Apply ID view '${primary_key}' on hosts of host groups"
),
"apply_hosts": _("Apply to hosts"),
"apply_hosts_title": _(
"Apply ID view '${primary_key}' on hosts"
),
"ipaassignedidview": _("Assigned ID View"),
"overrides_tab": _("${primary_key} overrides:"),
"remove": _("Remove ID views"),
"remove_users": _("Remove user ID overrides"),
"remove_groups": _("Remove group ID overrides"),
"unapply_hostgroups": _("Un-apply from host groups"),
"unapply_hostgroups_all_title": _("Un-apply ID Views from hosts of hostgroups"),
"unapply_hosts": _("Un-apply"),
"unapply_hosts_all": _("Un-apply from hosts"),
"unapply_hosts_all_title": _("Un-apply ID Views from hosts"),
"unapply_hosts_confirm": _("Are you sure you want to un-apply ID view from selected entries?"),
"unapply_hosts_title": _(
"Un-apply ID view '${primary_key}' from hosts"
),
},
"krbtpolicy": {
"identity": _("Kerberos Ticket Policy"),
},
"netgroup": {
"add": _("Add netgroup"),
"add_into_netgroups": _(
"Add netgroup '${primary_key}' into netgroups"
),
"add_netgroups": _(
"Add netgroups into netgroup '${primary_key}'"
),
"add_groups": _(
"Add user groups into netgroup '${primary_key}'"
),
"add_hosts": _(
"Add hosts into netgroup '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into netgroup '${primary_key}'"
),
"add_users": _(
"Add users into netgroup '${primary_key}'"
),
"any_host": _("Any Host"),
"anyone": _("Anyone"),
"external": _("External"),
"host": _("Host"),
"hostgroups": _("Host Groups"),
"hosts": _("Hosts"),
"identity": _("Netgroup Settings"),
"netgroups": _("Netgroups"),
"remove": _("Remove netgroups"),
"remove_from_netgroups": _(
"Remove netgroup '${primary_key}' from netgroups"
),
"remove_groups": _(
"Remove user groups from netgroup '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from netgroup '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from netgroup '${primary_key}'"
),
"remove_netgroups": _(
"Remove netgroups from netgroup '${primary_key}'"
),
"remove_users": _(
"Remove users from netgroup '${primary_key}'"
),
"specified_hosts": _("Specified Hosts and Groups"),
"specified_users": _("Specified Users and Groups"),
"user": _("User"),
"usergroups": _("User Groups"),
"users": _("Users"),
},
"otptoken": {
"add": _("Add OTP token"),
"add_users_managing": _(
"Add users managing OTP token '${primary_key}'"
),
"app_link": _("You can use <a href=\"${link}\" target=\"_blank\">FreeOTP<a/> as a software OTP token application."),
"config_title": _("Configure your token"),
"config_instructions": _("Configure your token by scanning the QR code below. Click on the QR code if you see this on the device you want to configure."),
"details": _("OTP Token Settings"),
"disable": _("Disable token"),
"enable": _("Enable token"),
"remove": _("Remove OTP tokens"),
"remove_users_managing": _(
"Remove users managing OTP token '${primary_key}'"
),
"show_qr": _("Show QR code"),
"show_uri": _("Show configuration uri"),
"type_hotp": _("Counter-based (HOTP)"),
"type_totp": _("Time-based (TOTP)"),
},
"passkey": {
"adder_title": _("Add Passkey"),
"data_label": _("Passkey"),
"deleter_content": _(
"Do you want to remove passkey ${passkey}?"),
"deleter_title": _("Remove Passkey"),
"type_discoverable": _("(discoverable) "),
"type_serverside": _("(server-side) ")
},
"passkeyconfig": {
"options": _("Options")
},
"permission": {
"add_custom_attr": _("Add Custom Attribute"),
"attribute": _("Attribute"),
"filter": _("Filter"),
"identity": _("Permission settings"),
"managed": _("Attribute breakdown"),
"target": _("Target"),
},
"privilege": {
"identity": _("Privilege Settings"),
},
"publickey": {
"set_dialog_help": _("Public key:"),
"set_dialog_title": _("Set public key"),
"show_set_key": _("Show/Set key"),
"status_mod_ns": _("Modified: key not set"),
"status_mod_s": _("Modified"),
"status_new_ns": _("New: key not set"),
"status_new_s": _("New: key set"),
},
"pwpolicy": {
"add": _("Add password policy"),
"identity": _("Password Policy"),
"remove": _("Remove password policies"),
},
"idrange": {
"add": _("Add ID range"),
"details": _("Range Settings"),
"ipaautoprivategroups": _("Auto private groups"),
"ipabaseid": _("Base ID"),
"ipabaserid": _("Primary RID base"),
"ipaidrangesize": _("Range size"),
"ipanttrusteddomainsid": _("Domain SID"),
"ipasecondarybaserid": _("Secondary RID base"),
"remove": _("Remove ID ranges"),
"type": _("Range type"),
"type_ad": _("Active Directory domain"),
"type_ad_posix": _("Active Directory domain with POSIX attributes"),
"type_detect": _("Detect"),
"type_local": _("Local domain"),
"type_ipa": _("IPA trust"),
"type_winsync": _("Active Directory winsync"),
},
"radiusproxy": {
"add": _("Add RADIUS server"),
"details": _("RADIUS Proxy Server Settings"),
"remove": _("Remove RADIUS servers"),
},
"realmdomains": {
"identity": _("Realm Domains"),
"check_dns": _("Check DNS"),
"check_dns_confirmation": _("Do you also want to perform DNS check?"),
"force_update": _("Force Update"),
},
"selfservice": {
},
"selinuxusermap": {
"add": _("Add SELinux user map"),
"add_groups": _(
"Add user groups into SELinux user map '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into SELinux user map '${primary_key}'"
),
"add_hosts": _(
"Add hosts into SELinux user map '${primary_key}'"
),
"add_users": _(
"Add users into SELinux user map '${primary_key}'"
),
"any_host": _("Any Host"),
"anyone": _("Anyone"),
"host": _("Host"),
"remove": _("Remove selinux user maps"),
"remove_groups": _(
"Remove user groups from SELinux user map '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from SELinux user map '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from SELinux user map '${primary_key}'"
),
"remove_users": _(
"Remove users from SELinux user map '${primary_key}'"
),
"specified_hosts": _("Specified Hosts and Groups"),
"specified_users": _("Specified Users and Groups"),
"user": _("User"),
},
"server_role": {
"label": _("Server Roles"),
"label_singular": _("Server Role"),
},
"servers": {
"svc_warning_title": _("Warning: Consider service replication"),
"svc_warning_message": _("It is strongly recommended to keep the following services installed on more than one server:"),
"remove_server": _("Delete Server"),
"remove_server_msg": _("Deleting a server removes it permanently from the topology. Note that this is a non-reversible action.")
},
"service": {
"add": _("Add service"),
"add_hosts_managing": _(
"Add hosts managing service '${primary_key}'"
),
"add_into_roles": _(
"Add service '${primary_key}' into roles"
),
"certificate": _("Service Certificate"),
"delete_key_unprovision": _("Delete Key, Unprovision"),
"details": _("Service Settings"),
"host": _("Host Name"),
"missing": _("Kerberos Key Not Present"),
"provisioning": _("Provisioning"),
"remove": _("Remove services"),
"remove_from_roles": _(
"Remove service '${primary_key}' from roles"
),
"remove_hosts_managing": _(
"Remove hosts managing service '${primary_key}'"
),
"service": _("Service"),
"status": _("Status"),
"unprovision": _("Unprovision"),
"unprovision_confirmation": _("Are you sure you want to unprovision this service?"),
"unprovision_title": _("Unprovisioning service"),
"unprovisioned": _("Service unprovisioned"),
"valid": _("Kerberos Key Present, Service Provisioned"),
},
"sshkeystore": {
"keys": _("SSH public keys"),
"set_dialog_help": _("SSH public key:"),
"set_dialog_title": _("Set SSH key"),
"show_set_key": _("Show/Set key"),
"status_mod_ns": _("Modified: key not set"),
"status_mod_s": _("Modified"),
"status_new_ns": _("New: key not set"),
"status_new_s": _("New: key set"),
},
"stageuser": {
"activate_confirm": _("Are you sure you want to activate selected users?"),
"activate_one_confirm": _("Are you sure you want to activate ${object}?"),
"activate_success": _("${count} user(s) activated"),
"add": _("Add stage user"),
"label": _("Stage users"),
"preserved_label": _("Preserved users"),
"preserved_remove": _("Remove preserved users"),
"remove": _("Remove stage users"),
"stage_confirm": _("Are you sure you want to stage selected users?"),
"stage_success": _("${count} users(s) staged"),
"stage_one_confirm": _("Are you sure you want to stage ${object}?"),
"undel_confirm": _("Are you sure you want to restore selected users?"),
"undel_one_confirm": _("Are you sure you want to restore ${object}?"),
"undel_success": _("${count} user(s) restored"),
"user_categories": _("User categories"),
},
"subid": {
"add": _("Add subid"),
"assigned_subids": _("Assigned subids"),
"baseid": _("Base ID"),
"dna_remaining": _("DNA remaining"),
"ipaowner": _("Owner"),
"ipasubgidcount": _("SubGID range size"),
"ipasubgidnumber": _("SubGID range start"),
"ipasubuidcount": _("SubUID range size"),
"ipasubuidnumber": _("SubUID range start"),
"rangesize": _("Range size"),
"remaining_subids": _("Remaining subids"),
"stats": _("Subordinate ID Statistics"),
},
"sudocmd": {
"add": _("Add sudo command"),
"add_into_sudocmdgroups": _(
"Add sudo command '${primary_key}' into sudo command "
"groups"
),
"groups": _("Groups"),
"remove": _("Remove sudo commands"),
"remove_from_sudocmdgroups": _(
"Remove sudo command '${primary_key}' from sudo command "
"groups"
),
},
"sudocmdgroup": {
"add": _("Add sudo command group"),
"add_sudocmds": _(
"Add sudo commands into sudo command group "
"'${primary_key}'"
),
"commands": _("Commands"),
"remove": _("Remove sudo command groups"),
"remove_sudocmds": _(
"Remove sudo commands from sudo command group "
"'${primary_key}'"
),
},
"sudorule": {
"add": _("Add sudo rule"),
"add_option": _("Add sudo option"),
"add_allow_cmds": _(
"Add allow sudo commands into sudo rule "
"'${primary_key}'"
),
"add_allow_cmdgroups": _(
"Add allow sudo command groups into sudo rule "
"'${primary_key}'"
),
"add_deny_cmds": _(
"Add deny sudo commands into sudo rule "
"'${primary_key}'"
),
"add_deny_cmdgroups": _(
"Add deny sudo command groups into sudo rule "
"'${primary_key}'"
),
"add_groups": _(
"Add user groups into sudo rule '${primary_key}'"
),
"add_hostgroups": _(
"Add host groups into sudo rule '${primary_key}'"
),
"add_hosts": _(
"Add hosts into sudo rule '${primary_key}'"
),
"add_runas_users": _(
"Add RunAs users into sudo rule '${primary_key}'"
),
"add_runas_usergroups": _(
"Add RunAs user groups into sudo rule '${primary_key}'"
),
"add_runas_groups": _(
"Add RunAs groups into sudo rule '${primary_key}'"
),
"add_users": _(
"Add users into sudo rule '${primary_key}'"
),
"allow": _("Allow"),
"any_command": _("Any Command"),
"any_group": _("Any Group"),
"any_host": _("Any Host"),
"anyone": _("Anyone"),
"command": _("Run Commands"),
"deny": _("Deny"),
"external": _("External"),
"host": _("Access this host"),
"ipaenabledflag": _("Rule status"),
"option_added": _("Option added"),
"option_removed": _("${count} option(s) removed"),
"options": _("Options"),
"remove": _("Remove sudo rules"),
"remove_allow_cmds": _(
"Remove allow sudo commands from sudo rule "
"'${primary_key}'"
),
"remove_allow_cmdgroups": _(
"Remove allow sudo command groups from sudo rule "
"'${primary_key}'"
),
"remove_deny_cmds": _(
"Remove deny sudo commands from sudo rule "
"'${primary_key}'"
),
"remove_deny_cmdgroups": _(
"Remove deny sudo command groups from sudo rule "
"'${primary_key}'"
),
"remove_groups": _(
"Remove user groups from sudo rule '${primary_key}'"
),
"remove_hostgroups": _(
"Remove host groups from sudo rule '${primary_key}'"
),
"remove_hosts": _(
"Remove hosts from sudo rule '${primary_key}'"
),
"remove_runas_users": _(
"Remove RunAs users from sudo rule '${primary_key}'"
),
"remove_runas_usergroups": _(
"Remove RunAs user groups from sudo rule '${primary_key}'"
),
"remove_runas_groups": _(
"Remove RunAs groups from sudo rule '${primary_key}'"
),
"remove_users": _(
"Remove users from sudo rule '${primary_key}'"
),
"runas": _("As Whom"),
"specified_commands": _("Specified Commands and Groups"),
"specified_groups": _("Specified Groups"),
"specified_hosts": _("Specified Hosts and Groups"),
"specified_users": _("Specified Users and Groups"),
"user": _("Who"),
},
"sudooptions": {
"remove": _("Remove sudo options"),
},
"topology": {
"autogenerated": _("Autogenerated"),
"segment_details": _("Segment details"),
"replication_config": _("Replication configuration"),
"insufficient_domain_level" : _("Managed topology requires minimal domain level ${domainlevel}"),
},
"topologylocation": {
"add": _("Add IPA location"),
"add_server": _(
"Add IPA server into IPA location '${primary_key}'"
),
"remove": _("Remove IPA locations"),
"remove_servers": _(
"Remove IPA servers from IPA location '${primary_key}'"
),
},
"topologysegment": {
"add": _("Add topology segment"),
"remove": _("Remove topology segments"),
},
"trust": {
"account": _("Account"),
"add": _("Add trust"),
"admin_account": _("Administrative account"),
"blocklists": _("SID blocklists"),
"details": _("Trust Settings"),
"domain": _("Domain"),
"establish_using": _("Establish using"),
"fetch_domains": _("Fetch domains"),
"ipantflatname": _("Domain NetBIOS name"),
"ipanttrusteddomainsid": _("Domain Security Identifier"),
"preshared_password": _("Pre-shared password"),
"remove": _("Remove trusts"),
"remove_domains": _("Remove domains"),
"trustdirection": _("Trust direction"),
"truststatus": _("Trust status"),
"trusttype": _("Trust type"),
"ipantadditionalsuffixes": _("Alternative UPN suffixes"),
},
'smb_attributes': {
"title": _(
"User attributes for SMB services"
),
"ipantlogonscript_tooltip": _(
"Path to a script executed on a Windows system at logon"
),
"ipantprofilepath_tooltip": _(
"Path to a user profile, in UNC format \\\\server\\share\\"
),
"ipanthomedirectory_tooltip": _(
"Path to a user home directory, in UNC format"
),
"ipanthomedirectorydrive_tooltip": _(
"Drive to mount a home directory"
),
},
"trustconfig": {
"options": _("Options"),
},
"user": {
"account": _("Account Settings"),
"account_status": _("Account Status"),
"activeuser_label": _("Active users"),
"add": _("Add user"),
"add_into_groups": _(
"Add user '${primary_key}' into user groups"
),
"add_into_hbac": _(
"Add user '${primary_key}' into HBAC rules"
),
"add_into_netgroups": _(
"Add user '${primary_key}' into netgroups"
),
"add_into_roles": _(
"Add user '${primary_key}' into roles"
),
"add_into_sudo": _(
"Add user '${primary_key}' into sudo rules"
),
"auto_subid": _("Auto assign subordinate ids"),
"auto_subid_confirm": _(
"Are you sure you want to auto-assign a subordinate id "
"to user ${object}?"
),
"contact": _("Contact Settings"),
"delete_mode": _("Delete mode"),
"employee": _("Employee Information"),
"error_changing_status": _("Error changing account status"),
"krbpasswordexpiration": _("Password expiration"),
"mailing": _("Mailing Address"),
"misc": _("Misc. Information"),
"mode_delete": _("delete"),
"mode_preserve": _("preserve"),
"noprivate": _("No private group"),
"remove": _("Remove users"),
"remove_from_groups": _(
"Remove user '${primary_key}' from user groups"
),
"remove_from_netgroups": _(
"Remove user '${primary_key}' from netgroups"
),
"remove_from_roles": _(
"Remove user '${primary_key}' from roles"
),
"remove_from_hbac": _(
"Remove user '${primary_key}' from HBAC rules"
),
"remove_from_sudo": _(
"Remove user '${primary_key}' from sudo rules"
),
"status_confirmation": _("Are you sure you want to ${action} the user?<br/>The change will take effect immediately."),
"status_link": _("Click to ${action}"),
"unlock": _("Unlock"),
"unlock_confirm": _("Are you sure you want to unlock user ${object}?"),
},
"vault": {
"add": _("Add vault"),
"add_member_groups": _(
"Add user groups into members of vault '${primary_key}'"
),
"add_member_services": _(
"Add services into members of vault '${primary_key}'"
),
"add_member_users": _(
"Add users into members of vault '${primary_key}'"
),
"add_owner_groups": _(
"Add user groups into owners of vault '${primary_key}'"
),
"add_owner_services": _(
"Add services into owners of vault '${primary_key}'"
),
"add_owner_users": _(
"Add users into owners of vault '${primary_key}'"
),
"add_warn_arch_ret": _(
"Secrets can be added/retrieved to vault only by using "
"vault-archive and vault-retrieve from CLI."
),
"add_warn_standard": _(
"Content of 'standard' vaults can be seen by users with "
"higher privileges (admins)."
),
"asymmetric_type": _("Asymmetric"),
"config_title": _("Vaults Config"),
"group": _("Group"),
"members": _("Members"),
"my_vaults_title": _("My User Vaults"),
"owners": _("Owners"),
"remove": _("Remove vaults"),
"remove_member_groups": _(
"Remove user groups from members of vault '${primary_key}'"
),
"remove_member_services": _(
"Remove services from members of vault '${primary_key}'"
),
"remove_member_users": _(
"Remove users from members of vault '${primary_key}'"
),
"remove_owner_groups": _(
"Remove user groups from owners of vault '${primary_key}'"
),
"remove_owner_services": _(
"Remove services from owners of vault '${primary_key}'"
),
"remove_owner_users": _(
"Remove users from owners of vault '${primary_key}'"
),
"service": _("Service"),
"service_vaults_title": _("Service Vaults"),
"shared": _("Shared"),
"shared_vaults_title": _("Shared Vaults"),
"standard_type": _("Standard"),
"symmetric_type": _("Symmetric"),
"type": _("Vault Type"),
"type_tooltip": _(
"Only standard vaults can be created in WebUI, use CLI "
"for other types of vaults."
),
"user": _("User"),
"user_vaults_title": _("User Vaults"),
},
},
"password": {
"current_password": _("Current Password"),
"current_password_required": _("Current password is required"),
"expires_in": _("Your password expires in ${days} days."),
"first_otp": _("First OTP"),
"invalid_password": _(
"The password or username you entered is incorrect"),
"new_password": _("New Password"),
"new_password_required": _("New password is required"),
"otp": _("OTP"),
"otp_info":
_("<i class=\"fa fa-info-circle\"></i> <strong>"
"OTP (One-Time Password):</strong>"
"Generate new OTP code for each OTP field."),
"otp_reset_info":
_("<i class=\"fa fa-info-circle\"></i> <strong>"
"OTP (One-Time Password):</strong>"
"Leave blank if you are not using OTP tokens "
"for authentication."),
"otp_long": _("One-Time Password"),
"otp_sync_fail": _("Token synchronization failed"),
"otp_sync_invalid": _("The username, password or token codes are not correct"),
"otp_sync_success":_("Token was synchronized"),
"password": _("Password"),
"password_and_otp": _("Password or Password+One-Time Password"),
"password_change_complete": _("Password change complete"),
"password_expired": _(
"Your password has expired. Please enter a new password."),
"password_must_match": _("Passwords must match"),
"reset_failure": _("Password reset was not successful."),
"reset_password": _("Reset Password"),
"reset_password_sentence": _("Reset your password."),
"second_otp": _("Second OTP"),
"token_id": _("Token ID"),
"verify_password": _("Verify Password"),
},
"profile-menu": {
"about": _("About"),
"configuration": _("Customization"),
"logout": _("Log out"),
"password_reset": _("Change password"),
"profile": _("Profile"),
},
"search": {
"delete_confirm": _("Are you sure you want to delete selected entries?"),
"deleted": _("${count} item(s) deleted"),
"disable_confirm": _("Are you sure you want to disable selected entries?"),
"disabled": _("${count} item(s) disabled"),
"enable_confirm": _("Are you sure you want to enable selected entries?"),
"enabled": _("${count} item(s) enabled"),
"partial_delete": _("Some entries were not deleted"),
"placeholder": _("Search"),
"placeholder_filter": _("Filter"),
"quick_links": _("Quick Links"),
"select_all": _("Select All"),
"truncated": _("Query returned more results than the configured size limit. Displaying the first ${counter} results."),
"unselect_all": _("Unselect All"),
},
"ssbrowser-page": {
"header": _(
"<h1>Browser Kerberos Setup</h1>\n"
"\n"
),
"firefox-header": _(
"<h2>Firefox</h2>\n"
"\n"
"<p>\n"
" You can configure Firefox to use Kerberos for "
"Single Sign-on. The following instructions will guide you in "
"configuring your web browser to send your Kerberos "
"credentials to the appropriate Key Distribution Center which "
"enables Single Sign-on.\n"
"</p>\n"
"\n"
),
"firefox-actions": _(
"<ol>\n"
"<li>\n"
"<p>\n"
"<a href=\"ca.crt\" id=\"ca-link\" class=\"btn btn-default\">"
"Import Certificate Authority certificate</a>\n"
"</p>\n"
"<p>\n"
" Make sure you select <b>all three</b> "
"checkboxes.\n"
"</p>\n"
"</li>\n"
"<li>\n"
" In the address bar of Firefox, type <code>"
"about:config</code> to display the list of current "
"configuration options.\n"
"</li>\n"
"<li>\n"
" In the Filter field, type <code>negotiate"
"</code> to restrict the list of options.\n"
"</li>\n"
"<li>\n"
" Double-click the <code>network.negotiate-auth"
".trusted-uris</code> entry to display the Enter string value "
"dialog box.\n"
"</li>\n"
"<li>\n"
" Enter the name of the domain against which "
"you want to authenticate, for example, <code class=\""
"example-domain\">.example.com</code>.\n"
"</li>\n"
"<li><a href=\"../ui/index.html\" id=\"return-link\" class=\""
"btn btn-default\">Return to Web UI</a></li>\n"
"</ol>\n"
"\n"
),
"chrome-header": _(
"<h2>Chrome</h2>\n"
"\n"
"<p>\n"
" You can configure Chrome to use Kerberos for "
"Single Sign-on. The following instructions will guide you in "
"configuring your web browser to send your Kerberos "
"credentials to the appropriate Key Distribution Center which "
"enables Single Sign-on.\n"
"</p>\n"
"\n"
),
"chrome-certificate": _(
"<h3>Import CA Certificate</h3>\n"
"<ol>\n"
"<li>\n"
" Download the <a href=\"ca.crt\">CA "
"certificate</a>. Alternatively, if the host is also an IdM "
"client, you can find the certificate in /etc/ipa/ca.crt.\n"
"</li>\n"
"<li>\n"
" Click the menu button with the <em>Customize "
"and control Google Chrome</em> tooltip, which is by default "
"in the top right-hand corner of Chrome, and click <em>"
"Settings</em>.\n"
"</li>\n"
"<li>\n"
" Click <em>Show advanced settings</em> to "
"display more options, and then click the <em>Manage "
"certificates</em> button located under the HTTPS/SSL heading."
"\n"
"</li>\n"
"<li>\n"
" In the <em>Authorities</em> tab, click the "
"<em>Import</em> button at the bottom.\n"
"</li>\n"
"<li>Select the CA certificate file that you downloaded in the"
" first step.</li>\n"
"</ol>\n"
"\n"
),
"chrome-spnego": _(
"<h3>\n"
" Enable SPNEGO (Simple and Protected GSSAPI "
"Negotiation Mechanism) to Use Kerberos Authentication\n"
" in Chrome\n"
"</h3>\n"
"<ol>\n"
"<li>\n"
" Make sure you have the necessary directory "
"created by running:\n"
"<div><code>\n"
" [root@client]# mkdir -p /etc/opt/chrome/"
"policies/managed/\n"
"</code></div>\n"
"</li>\n"
"<li>\n"
" Create a new <code>/etc/opt/chrome/policies/"
"managed/mydomain.json</code> file with write privileges "
"limited to the system administrator or root, and include the "
"following line:\n"
"<div><code>\n"
" { \"AuthServerWhitelist\": \"*<span "
"class=\"example-domain\">.example.com</span>\" }\n"
"</code></div>\n"
"<div>\n"
" You can do this by running:\n"
"</div>\n"
"<div><code>\n"
" [root@server]# echo \'{ \""
"AuthServerWhitelist\": \"*<span class=\"example-domain\">"
".example.com</span>\" }' > /etc/opt/chrome/policies/managed/"
"mydomain.json\n"
"</code></div>\n"
"</li>\n"
"</ol>\n"
"<ol>\n"
"<p>\n"
"<strong>Note:</strong> If using Chromium, use <code>/etc/"
"chromium/policies/managed/</code> instead of <code>/etc/opt/"
"chrome/policies/managed/</code> for the two SPNEGO Chrome "
"configuration steps above.\n"
"</p>\n"
"</ol>\n"
"\n"
),
"ie-header": _(
"<h2>Internet Explorer</h2>\n"
"<p><strong>WARNING:</strong> Internet Explorer is no longer a"
" supported browser.</p>\n"
"<p>\n"
" Once you are able to log into the workstation "
"with your kerberos key you are now able to use that ticket in"
" Internet Explorer.\n"
"</p>\n"
"<p>\n"
),
"ie-actions": _(
"<strong>Log into the Windows machine using an account of your"
" Kerberos realm (administrative domain)</strong>\n"
"</p>\n"
"<p>\n"
"<strong>In Internet Explorer, click Tools, and then click "
"Internet Options.</strong>\n"
"</p>\n"
"<div>\n"
"<ol>\n"
"<li>Click the Security tab</li>\n"
"<li>Click Local intranet</li>\n"
"<li>Click Sites </li>\n"
"<li>Click Advanced </li>\n"
"<li>Add your domain to the list</li>\n"
"</ol>\n"
"<ol>\n"
"<li>Click the Security tab</li>\n"
"<li>Click Local intranet</li>\n"
"<li>Click Custom Level</li>\n"
"<li>Select Automatic logon only in Intranet zone</li>\n"
"</ol>\n"
"\n"
"<ol>\n"
"<li> Visit a kerberized web site using IE (You must use the "
"fully-qualified Domain Name in the URL)</li>\n"
"<li><strong> You are all set.</strong></li>\n"
"</ol>\n"
"</div>\n"
"\n"
),
},
"status": {
"disable": _("Disable"),
"disabled": _("Disabled"),
"enable": _("Enable"),
"enabled": _("Enabled"),
"label": _("Status"),
"working": _("Working"),
},
"tabs": {
"audit": _("Audit"),
"authentication": _("Authentication"),
"automember": _("Automember"),
"automount": _("Automount"),
"cert": _("Certificates"),
"dns": _("DNS"),
"hbac": _("Host-Based Access Control"),
"identity": _("Identity"),
"ipaserver": _("IPA Server"),
"network_services": _("Network Services"),
"policy": _("Policy"),
"role": _("Role-Based Access Control"),
"subid": _("Subordinate IDs"),
"sudo": _("Sudo"),
"topology": _("Topology"),
"trust": _("Trusts"),
},
"true": _("True"),
"unauthorized-page": _(
"<h1>Unable to verify your Kerberos credentials</h1>\n"
"<p>\n"
" Please make sure that you have valid Kerberos "
"tickets (obtainable via <strong>kinit</strong>), and that you"
" have configured your browser correctly.\n"
"</p>\n"
"\n"
"<h2>Browser configuration</h2>\n"
"\n"
"<div id=\"first-time\">\n"
"<p>\n"
" If this is your first time, please <a href="
"\"ssbrowser.html\">configure your browser</a>.\n"
"</p>\n"
"</div>\n"
),
"widget": {
"api_browser": _("API Browser"),
"first": _("First"),
"last": _("Last"),
"next": _("Next"),
"page": _("Page"),
"prev": _("Prev"),
"undo": _("Undo"),
"undo_title": _("Undo this change."),
"undo_all": _("Undo All"),
"undo_all_title": _("Undo all changes in this field."),
"validation": {
"error": _("Text does not match field pattern"),
"datetime": _("Must be an UTC date/time value (e.g., \"2014-01-20 17:58:01Z\")"),
"decimal": _("Must be a decimal number"),
"format": _("Format error"),
"integer": _("Must be an integer"),
"ip_address": _('Not a valid IP address'),
"ip_v4_address": _('Not a valid IPv4 address'),
"ip_v6_address": _('Not a valid IPv6 address'),
"max_value": _("Maximum value is ${value}"),
"min_value": _("Minimum value is ${value}"),
"net_address": _("Not a valid network address (examples: 2001:db8::/64, 192.0.2.0/24)"),
"parse": _("Parse error"),
"positive_number": _("Must be a positive number"),
"port": _("'${port}' is not a valid port"),
"required": _("Required field"),
"unsupported": _("Unsupported value"),
},
},
}
has_output = (
Output('texts', dict, doc=_('Dict of I18N messages')),
)
def execute(self, **options):
return dict(texts=json_serialize(self.messages))
| 92,232
|
Python
|
.py
| 2,019
| 29.840515
| 572
| 0.449797
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,850
|
batch.py
|
freeipa_freeipa/ipaserver/plugins/batch.py
|
# Authors:
# Adam Young <ayoung@redhat.com>
# Rob Crittenden <rcritten@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/>.
import logging
import six
from ipalib import api, errors
from ipalib import Command
from ipalib.frontend import Local
from ipalib.parameters import Str, Dict
from ipalib.output import Output
from ipalib.text import _
from ipalib.request import context
from ipalib.plugable import Registry
__doc__ = _("""
Plugin to make multiple ipa calls via one remote procedure call
To run this code in the lite-server
curl -H "Content-Type:application/json" -H "Accept:application/json" -H "Accept-Language:en" --negotiate -u : --cacert /etc/ipa/ca.crt -d @batch_request.json -X POST http://localhost:8888/ipa/json
where the contents of the file batch_request.json follow the below example
{"method":"batch","params":[[
{"method":"group_find","params":[[],{}]},
{"method":"user_find","params":[[],{"whoami":"true","all":"true"}]},
{"method":"user_show","params":[["admin"],{"all":true}]}
],{}],"id":1}
The format of the response is nested the same way. At the top you will see
"error": null,
"id": 1,
"result": {
"count": 3,
"results": [
And then a nested response for each IPA command method sent in the request
""")
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
register = Registry()
@register()
class batch(Command):
__doc__ = _('Make multiple ipa calls via one remote procedure call')
NO_CLI = True
takes_args = (
Dict('methods*',
doc=_('Nested Methods to execute'),
),
)
takes_options = (
Str('keeponly*',
doc=_('Keep specified attributes in the output, '
'remove everything else.'),
),
)
has_output = (
Output('count', int, doc=''),
Output('results', (list, tuple), doc='')
)
def _validate_request(self, request):
"""
Check that an individual request in a batch is parseable and the
commands exists.
"""
if 'method' not in request:
raise errors.RequirementError(name='method')
if 'params' not in request:
raise errors.RequirementError(name='params')
name = request['method']
if (name not in self.api.Command or
isinstance(self.api.Command[name], Local)):
raise errors.CommandError(name=name)
# If params are not formated as a tuple(list, dict)
# the following lines will raise an exception
# that triggers an internal server error
# Raise a ConversionError instead to report the issue
# to the client
try:
a, kw = request['params']
newkw = dict((str(k), v) for k, v in kw.items())
api.Command[name].args_options_2_params(*a, **newkw)
except (AttributeError, ValueError, TypeError):
raise errors.ConversionError(
name='params',
error=_(u'must contain a tuple (list, dict)'))
except Exception as e:
raise errors.ConversionError(
name='params',
error=str(e))
def _repr_iter(self, **params):
"""
Iterate through the request and use the Command _repr_intr so
that sensitive information (passwords) is not exposed.
In case of a malformatted request redact the entire thing.
"""
exceptions = False
for arg in (params.get('methods', [])):
try:
self._validate_request(arg)
except Exception:
# redact the whole request since we don't know what's in it
exceptions = True
yield u'********'
continue
name = arg['method']
a, kw = arg['params']
newkw = dict((str(k), v) for k, v in kw.items())
param = api.Command[name].args_options_2_params(
*a, **newkw)
yield '{}({})'.format(
api.Command[name].name,
', '.join(api.Command[name]._repr_iter(**param))
)
if exceptions:
logger.debug('batch: %s',
', '.join(super(batch, self)._repr_iter(**params)))
def execute(self, methods=None, **options):
results = []
op_account = getattr(context, 'principal', '[autobind]')
keeponly = options.get("keeponly", None)
for arg in (methods or []):
params = dict()
name = None
try:
self._validate_request(arg)
name = arg['method']
a, kw = arg['params']
newkw = dict((str(k), v) for k, v in kw.items())
params = api.Command[name].args_options_2_params(
*a, **newkw)
newkw.setdefault('version', options['version'])
result = api.Command[name](*a, **newkw)
logger.info(
'%s: batch: %s(%s): SUCCESS',
op_account,
name,
', '.join(api.Command[name]._repr_iter(**params))
)
result['error'] = None
res = result.get('result', None)
if keeponly is not None and isinstance(res, dict):
result["result"] = dict(
filter(lambda x: x[0] in keeponly, res.items())
)
except Exception as e:
if (isinstance(e, errors.RequirementError) or
isinstance(e, errors.CommandError) or
isinstance(e, errors.ConversionError)):
logger.info(
'%s: batch: %s',
op_account,
e.__class__.__name__
)
else:
logger.info(
'%s: batch: %s(%s): %s',
op_account, name,
', '.join(api.Command[name]._repr_iter(**params)),
e.__class__.__name__
)
if isinstance(e, errors.PublicError):
reported_error = e
else:
reported_error = errors.InternalError()
result = dict(
error=reported_error.strerror,
error_code=reported_error.errno,
error_name=unicode(type(reported_error).__name__),
error_kw=reported_error.kw,
)
results.append(result)
return dict(count=len(results) , results=results)
| 7,487
|
Python
|
.py
| 183
| 29.939891
| 240
| 0.54989
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,851
|
__init__.py
|
freeipa_freeipa/ipaserver/plugins/__init__.py
|
# Authors: Jason Gerard DeRose <jderose@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/>.
"""
Sub-package containing all server plugins.
"""
| 826
|
Python
|
.py
| 20
| 40.25
| 71
| 0.775155
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,852
|
hbacsvcgroup.py
|
freeipa_freeipa/ipaserver/plugins/hbacsvcgroup.py
|
# Authors:
# Rob Crittenden <rcritten@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 ipalib import api, Str
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPUpdate,
LDAPRetrieve,
LDAPSearch,
LDAPDelete,
LDAPAddMember,
LDAPRemoveMember)
from ipalib import _, ngettext
__doc__ = _("""
HBAC Service Groups
HBAC service groups can contain any number of individual services,
or "members". Every group must have a description.
EXAMPLES:
Add a new HBAC service group:
ipa hbacsvcgroup-add --desc="login services" login
Add members to an HBAC service group:
ipa hbacsvcgroup-add-member --hbacsvcs=sshd --hbacsvcs=login login
Display information about a named group:
ipa hbacsvcgroup-show login
Delete an HBAC service group:
ipa hbacsvcgroup-del login
""")
register = Registry()
topic = 'hbac'
@register()
class hbacsvcgroup(LDAPObject):
"""
HBAC service group object.
"""
container_dn = api.env.container_hbacservicegroup
object_name = _('HBAC service group')
object_name_plural = _('HBAC service groups')
object_class = ['ipaobject', 'ipahbacservicegroup']
permission_filter_objectclasses = ['ipahbacservicegroup']
default_attributes = [ 'cn', 'description', 'member' ]
uuid_attribute = 'ipauniqueid'
attribute_members = {
'member': ['hbacsvc'],
}
managed_permissions = {
'System: Read HBAC Service Groups': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'ipauniqueid',
'member', 'o', 'objectclass', 'ou', 'owner', 'seealso',
'memberuser', 'memberhost',
},
},
'System: Add HBAC Service Groups': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=hbacservicegroups,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Add HBAC service groups";allow (add) groupdn = "ldap:///cn=Add HBAC service groups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Delete HBAC Service Groups': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=hbacservicegroups,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Delete HBAC service groups";allow (delete) groupdn = "ldap:///cn=Delete HBAC service groups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Manage HBAC Service Group Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=hbacservicegroups,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Manage HBAC service group membership";allow (write) groupdn = "ldap:///cn=Manage HBAC service group membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
}
label = _('HBAC Service Groups')
label_singular = _('HBAC Service Group')
takes_params = (
Str('cn',
cli_name='name',
label=_('Service group name'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('HBAC service group description'),
),
)
@register()
class hbacsvcgroup_add(LDAPCreate):
__doc__ = _('Add a new HBAC service group.')
msg_summary = _('Added HBAC service group "%(value)s"')
@register()
class hbacsvcgroup_del(LDAPDelete):
__doc__ = _('Delete an HBAC service group.')
msg_summary = _('Deleted HBAC service group "%(value)s"')
@register()
class hbacsvcgroup_mod(LDAPUpdate):
__doc__ = _('Modify an HBAC service group.')
msg_summary = _('Modified HBAC service group "%(value)s"')
@register()
class hbacsvcgroup_find(LDAPSearch):
__doc__ = _('Search for an HBAC service group.')
msg_summary = ngettext(
'%(count)d HBAC service group matched', '%(count)d HBAC service groups matched', 0
)
@register()
class hbacsvcgroup_show(LDAPRetrieve):
__doc__ = _('Display information about an HBAC service group.')
@register()
class hbacsvcgroup_add_member(LDAPAddMember):
__doc__ = _('Add members to an HBAC service group.')
@register()
class hbacsvcgroup_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from an HBAC service group.')
| 5,495
|
Python
|
.py
| 137
| 33.89781
| 277
| 0.651692
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,853
|
certprofile.py
|
freeipa_freeipa/ipaserver/plugins/certprofile.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import re
from ipalib import api, Bool, Str
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject, LDAPSearch, LDAPCreate,
LDAPDelete, LDAPUpdate, LDAPRetrieve)
from ipalib.request import context
from ipalib import ngettext
from ipalib.text import _
from ipapython.dogtag import INCLUDED_PROFILES
from ipapython.version import API_VERSION
from ipalib import errors
__doc__ = _("""
Manage Certificate Profiles
Certificate Profiles are used by Certificate Authority (CA) in the signing of
certificates to determine if a Certificate Signing Request (CSR) is acceptable,
and if so what features and extensions will be present on the certificate.
The Certificate Profile format is the property-list format understood by the
Dogtag or Red Hat Certificate System CA.
PROFILE ID SYNTAX:
A Profile ID is a string without spaces or punctuation starting with a letter
and followed by a sequence of letters, digits or underscore ("_").
EXAMPLES:
Import a profile that will not store issued certificates:
ipa certprofile-import ShortLivedUserCert \\
--file UserCert.profile --desc "User Certificates" \\
--store=false
Delete a certificate profile:
ipa certprofile-del ShortLivedUserCert
Show information about a profile:
ipa certprofile-show ShortLivedUserCert
Save profile configuration to a file:
ipa certprofile-show caIPAserviceCert --out caIPAserviceCert.cfg
Search for profiles that do not store certificates:
ipa certprofile-find --store=false
PROFILE CONFIGURATION FORMAT:
The profile configuration format is the raw property-list format
used by Dogtag Certificate System. The XML format is not supported.
The following restrictions apply to profiles managed by IPA:
- When importing a profile the "profileId" field, if present, must
match the ID given on the command line.
- The "classId" field must be set to "caEnrollImpl"
- The "auth.instance_id" field must be set to "raCertAuth"
- The "certReqInputImpl" input class and "certOutputImpl" output
class must be used.
""")
register = Registry()
def ca_enabled_check(_api):
"""Raise NotFound if CA is not enabled.
This function is defined in multiple plugins to avoid circular imports
(cert depends on certprofile, so we cannot import cert here).
"""
if not _api.Command.ca_is_enabled()['result']:
raise errors.NotFound(reason=_('CA is not configured'))
profile_id_pattern = re.compile(r'^[a-zA-Z]\w*$')
def validate_profile_id(ugettext, value):
"""Ensure profile ID matches form required by CA."""
if profile_id_pattern.match(value) is None:
return _('invalid Profile ID')
else:
return None
@register()
class certprofile(LDAPObject):
"""
Certificate Profile object.
"""
container_dn = api.env.container_certprofile
object_name = _('Certificate Profile')
object_name_plural = _('Certificate Profiles')
object_class = ['ipacertprofile']
default_attributes = [
'cn', 'description', 'ipacertprofilestoreissued'
]
search_attributes = [
'cn', 'description', 'ipacertprofilestoreissued'
]
label = _('Certificate Profiles')
label_singular = _('Certificate Profile')
takes_params = (
Str('cn', validate_profile_id,
primary_key=True,
cli_name='id',
label=_('Profile ID'),
doc=_('Profile ID for referring to this profile'),
),
Str('config',
label=_('Profile configuration'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('description',
required=True,
cli_name='desc',
label=_('Profile description'),
doc=_('Brief description of this profile'),
),
Bool('ipacertprofilestoreissued',
default=True,
cli_name='store',
label=_('Store issued certificates'),
doc=_('Whether to store certs issued using this profile'),
),
)
permission_filter_objectclasses = ['ipacertprofile']
managed_permissions = {
'System: Read Certificate Profiles': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn',
'description',
'ipacertprofilestoreissued',
'objectclass',
},
},
'System: Import Certificate Profile': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=certprofiles,cn=ca,$SUFFIX")(version 3.0;acl "permission:Import Certificate Profile";allow (add) groupdn = "ldap:///cn=Import Certificate Profile,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Delete Certificate Profile': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=certprofiles,cn=ca,$SUFFIX")(version 3.0;acl "permission:Delete Certificate Profile";allow (delete) groupdn = "ldap:///cn=Delete Certificate Profile,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Modify Certificate Profile': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cn',
'description',
'ipacertprofilestoreissued',
},
'replaces': [
'(targetattr = "cn || description || ipacertprofilestoreissued")(target = "ldap:///cn=*,cn=certprofiles,cn=ca,$SUFFIX")(version 3.0;acl "permission:Modify Certificate Profile";allow (write) groupdn = "ldap:///cn=Modify Certificate Profile,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
}
@register()
class certprofile_find(LDAPSearch):
__doc__ = _("Search for Certificate Profiles.")
msg_summary = ngettext(
'%(count)d profile matched', '%(count)d profiles matched', 0
)
def execute(self, *args, **kwargs):
ca_enabled_check(self.api)
return super(certprofile_find, self).execute(*args, **kwargs)
@register()
class certprofile_show(LDAPRetrieve):
__doc__ = _("Display the properties of a Certificate Profile.")
takes_options = LDAPRetrieve.takes_options + (
Str('out?',
doc=_('Write profile configuration to file'),
),
)
def execute(self, *keys, **options):
ca_enabled_check(self.api)
result = super(certprofile_show, self).execute(*keys, **options)
if 'out' in options:
with self.api.Backend.ra_certprofile as profile_api:
result['result']['config'] = profile_api.read_profile(keys[0])
return result
@register()
class certprofile_import(LDAPCreate):
__doc__ = _("Import a Certificate Profile.")
msg_summary = _('Imported profile "%(value)s"')
takes_options = (
Str(
'file',
label=_('Filename of a raw profile. The XML format is not supported.'),
cli_name='file',
flags=('virtual_attribute',),
noextrawhitespace=False,
),
)
PROFILE_ID_PATTERN = re.compile(r'^profileId=([a-zA-Z]\w*)', re.MULTILINE)
def pre_callback(self, ldap, dn, entry, entry_attrs, *keys, **options):
ca_enabled_check(self.api)
context.profile = options['file']
matches = self.PROFILE_ID_PATTERN.findall(options['file'])
if len(matches) == 0:
# no profileId found, use CLI value as profileId.
context.profile = u'profileId=%s\n%s' % (keys[0], context.profile)
elif len(matches) > 1:
raise errors.ValidationError(
name='file',
error=_(
"Profile data specifies profileId multiple times: "
"%(values)s"
) % dict(values=matches)
)
elif keys[0] != matches[0]:
raise errors.ValidationError(
name='file',
error=_(
"Profile ID '%(cli_value)s' "
"does not match profile data '%(file_value)s'"
) % dict(cli_value=keys[0], file_value=matches[0])
)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
"""Import the profile into Dogtag and enable it.
If the operation fails, remove the LDAP entry.
"""
try:
with self.api.Backend.ra_certprofile as profile_api:
profile_api.create_profile(context.profile)
profile_api.enable_profile(keys[0])
except BaseException:
# something went wrong ; delete entry
ldap.delete_entry(dn)
raise
return dn
@register()
class certprofile_del(LDAPDelete):
__doc__ = _("Delete a Certificate Profile.")
msg_summary = _('Deleted profile "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
ca_enabled_check(self.api)
if keys[0] in [p.profile_id for p in INCLUDED_PROFILES]:
raise errors.ValidationError(name='profile_id',
error=_("Predefined profile '%(profile_id)s' cannot be deleted")
% {'profile_id': keys[0]}
)
return dn
def post_callback(self, ldap, dn, *keys, **options):
with self.api.Backend.ra_certprofile as profile_api:
profile_api.disable_profile(keys[0])
profile_api.delete_profile(keys[0])
return dn
@register()
class certprofile_mod(LDAPUpdate):
__doc__ = _("Modify Certificate Profile configuration.")
msg_summary = _('Modified Certificate Profile "%(value)s"')
takes_options = LDAPUpdate.takes_options + (
Str(
'file?',
label=_('File containing profile configuration'),
cli_name='file',
flags=('virtual_attribute',),
noextrawhitespace=False,
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
ca_enabled_check(self.api)
# Once a profile id is set it cannot be changed
if 'cn' in entry_attrs:
raise errors.ProtectedEntryError(label='certprofile', key=keys[0],
reason=_('Certificate profiles cannot be renamed'))
if 'file' in options:
# ensure operator has permission to update a certprofile
if not ldap.can_write(dn, 'ipacertprofilestoreissued'):
raise errors.ACIError(info=_(
"Insufficient privilege to modify a certificate profile."))
with self.api.Backend.ra_certprofile as profile_api:
profile_api.disable_profile(keys[0])
try:
profile_api.update_profile(keys[0], options['file'])
finally:
profile_api.enable_profile(keys[0])
return dn
def execute(self, *keys, **options):
try:
return super(certprofile_mod, self).execute(*keys, **options)
except errors.EmptyModlist:
if 'file' in options:
# The profile data in Dogtag was updated.
# Do not fail; return result of certprofile-show instead
return self.api.Command.certprofile_show(keys[0],
version=API_VERSION)
else:
# This case is actually an error; re-raise
raise
| 11,814
|
Python
|
.py
| 280
| 33.153571
| 290
| 0.620148
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,854
|
realmdomains.py
|
freeipa_freeipa/ipaserver/plugins/realmdomains.py
|
# Authors:
# Ana Krivokapic <akrivoka@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/>.
import six
from ipalib import api, errors, messages
from ipalib import Str, Flag
from ipalib import _
from ipalib.plugable import Registry
from .baseldap import LDAPObject, LDAPUpdate, LDAPRetrieve
from ipalib.util import has_soa_or_ns_record, validate_domain_name
from ipalib.util import detect_dns_zone_realm_type
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Realm domains
Manage the list of domains associated with IPA realm.
This list is useful for Domain Controllers from other realms which have
established trust with this IPA realm. They need the information to know
which request should be forwarded to KDC of this IPA realm.
Automatic management: a domain is automatically added to the realm domains
list when a new DNS Zone managed by IPA is created. Same applies for deletion.
Externally managed DNS: domains which are not managed in IPA server DNS
need to be manually added to the list using ipa realmdomains-mod command.
EXAMPLES:
Display the current list of realm domains:
ipa realmdomains-show
Replace the list of realm domains:
ipa realmdomains-mod --domain=example.com
ipa realmdomains-mod --domain={example1.com,example2.com,example3.com}
Add a domain to the list of realm domains:
ipa realmdomains-mod --add-domain=newdomain.com
Delete a domain from the list of realm domains:
ipa realmdomains-mod --del-domain=olddomain.com
""")
register = Registry()
def _domain_name_normalizer(d):
return d.lower().rstrip('.')
def _domain_name_validator(ugettext, value):
try:
validate_domain_name(value, allow_slash=False)
except ValueError as e:
return unicode(e)
return None
@register()
class realmdomains(LDAPObject):
"""
List of domains associated with IPA realm.
"""
container_dn = api.env.container_realm_domains
permission_filter_objectclasses = ['domainrelatedobject']
object_name = _('Realm domains')
search_attributes = ['associateddomain']
default_attributes = ['associateddomain']
managed_permissions = {
'System: Read Realm Domains': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'associateddomain',
},
},
'System: Modify Realm Domains': {
'ipapermbindruletype': 'permission',
'ipapermright': {'write'},
'ipapermdefaultattr': {
'associatedDomain',
},
'default_privileges': {'DNS Administrators'},
},
}
label = _('Realm Domains')
label_singular = _('Realm Domains')
takes_params = (
Str('associateddomain+',
_domain_name_validator,
normalizer=_domain_name_normalizer,
cli_name='domain',
label=_('Domain'),
),
Str('add_domain?',
_domain_name_validator,
normalizer=_domain_name_normalizer,
cli_name='add_domain',
label=_('Add domain'),
),
Str('del_domain?',
_domain_name_validator,
normalizer=_domain_name_normalizer,
cli_name='del_domain',
label=_('Delete domain'),
),
)
@register()
class realmdomains_mod(LDAPUpdate):
__doc__ = _("""
Modify realm domains
DNS check: When manually adding a domain to the list, a DNS check is
performed by default. It ensures that the domain is associated with
the IPA realm, by checking whether the domain has a _kerberos TXT record
containing the IPA realm name. This check can be skipped by specifying
--force option.
Removal: when a realm domain which has a matching DNS zone managed by
IPA is being removed, a corresponding _kerberos TXT record in the zone is
removed automatically as well. Other records in the zone or the zone
itself are not affected.
""")
takes_options = LDAPUpdate.takes_options + (
Flag('force',
label=_('Force'),
doc=_('Force adding domain even if not in DNS'),
),
)
def validate_domains(self, domains, force):
"""
Validates the list of domains as candidates for additions to the
realmdomains list.
Requirements:
- Each domain has SOA or NS record
- Each domain belongs to the current realm
"""
# Unless forced, check that each domain has SOA or NS records
if not force:
invalid_domains = [
d for d in domains
if not has_soa_or_ns_record(d)
]
if invalid_domains:
raise errors.ValidationError(
name='domain',
error= _(
"DNS zone for each realmdomain must contain "
"SOA or NS records. No records found for: %s"
) % ','.join(invalid_domains)
)
# Check realm alliegence for each domain
domains_with_realm = [
(domain, detect_dns_zone_realm_type(self.api, domain))
for domain in domains
]
foreign_domains = [
domain for domain, realm in domains_with_realm
if realm == 'foreign'
]
unknown_domains = [
domain for domain, realm in domains_with_realm
if realm == 'unknown'
]
# If there are any foreing realm domains, bail out
if foreign_domains:
raise errors.ValidationError(
name='domain',
error=_(
'The following domains do not belong '
'to this realm: %(domains)s'
) % dict(domains=','.join(foreign_domains))
)
# If there are any unknown domains, error out,
# asking for _kerberos TXT records
# Note: This can be forced, since realmdomains-mod
# is called from dnszone-add where we know that
# the domain being added belongs to our realm
if not force and unknown_domains:
raise errors.ValidationError(
name='domain',
error=_(
'The realm of the following domains could '
'not be detected: %(domains)s. If these are '
'domains that belong to the this realm, please '
'create a _kerberos TXT record containing "%(realm)s" '
'in each of them.'
) % dict(domains=','.join(unknown_domains),
realm=self.api.env.realm)
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
associateddomain = entry_attrs.get('associateddomain')
add_domain = entry_attrs.get('add_domain')
del_domain = entry_attrs.get('del_domain')
force = options.get('force')
current_domain = self.api.env.domain
# User specified the list of domains explicitly
if associateddomain:
if add_domain or del_domain:
raise errors.MutuallyExclusiveError(
reason=_(
"The --domain option cannot be used together "
"with --add-domain or --del-domain. Use --domain "
"to specify the whole realm domain list explicitly, "
"to add/remove individual domains, use "
"--add-domain/del-domain.")
)
# Make sure our domain is included in the list
if current_domain not in associateddomain:
raise errors.ValidationError(
name='realmdomain list',
error=_("IPA server domain cannot be omitted")
)
# Validate that each domain satisfies the requirements
# for realmdomain
self.validate_domains(domains=associateddomain, force=force)
return dn
# If --add-domain or --del-domain options were provided, read
# the curent list from LDAP, modify it, and write the changes back
domains = ldap.get_entry(dn)['associateddomain']
if add_domain:
self.validate_domains(domains=[add_domain], force=force)
del entry_attrs['add_domain']
domains.append(add_domain)
if del_domain:
if del_domain == current_domain:
raise errors.ValidationError(
name='del_domain',
error=_("IPA server domain cannot be deleted")
)
del entry_attrs['del_domain']
try:
domains.remove(del_domain)
except ValueError:
raise errors.AttrValueNotFound(
attr='associateddomain',
value=del_domain
)
entry_attrs['associateddomain'] = domains
return dn
def execute(self, *keys, **options):
dn = self.obj.get_dn(*keys, **options)
ldap = self.obj.backend
domains_old = set(ldap.get_entry(dn)['associateddomain'])
result = super(realmdomains_mod, self).execute(*keys, **options)
domains_new = set(ldap.get_entry(dn)['associateddomain'])
domains_added = domains_new - domains_old
domains_deleted = domains_old - domains_new
# Add a _kerberos TXT record for zones that correspond with
# domains which were added
for domain in domains_added:
# Skip our own domain
if domain == api.env.domain:
continue
try:
self.api.Command['dnsrecord_add'](
unicode(domain),
u'_kerberos',
txtrecord=api.env.realm
)
except (errors.EmptyModlist, errors.NotFound,
errors.ValidationError) as error:
# If creation of the _kerberos TXT record failed, prompt
# for manual intervention
messages.add_message(
options['version'],
result,
messages.KerberosTXTRecordCreationFailure(
domain=domain,
error=unicode(error),
realm=self.api.env.realm
)
)
# Delete _kerberos TXT record from zones that correspond with
# domains which were deleted
for domain in domains_deleted:
# Skip our own domain
if domain == api.env.domain:
continue
try:
self.api.Command['dnsrecord_del'](
unicode(domain),
u'_kerberos',
txtrecord=api.env.realm
)
except (errors.AttrValueNotFound, errors.NotFound,
errors.ValidationError) as error:
# If deletion of the _kerberos TXT record failed, prompt
# for manual intervention
messages.add_message(
options['version'],
result,
messages.KerberosTXTRecordDeletionFailure(
domain=domain, error=unicode(error)
)
)
return result
@register()
class realmdomains_show(LDAPRetrieve):
__doc__ = _('Display the list of realm domains.')
| 12,427
|
Python
|
.py
| 301
| 30.385382
| 80
| 0.593403
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,855
|
hbacrule.py
|
freeipa_freeipa/ipaserver/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 ipalib import api, errors
from ipalib import AccessTime, Str, StrEnum, Bool
from ipalib.plugable import Registry
from .baseldap import (
pkey_to_value,
external_host_param,
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPRetrieve,
LDAPUpdate,
LDAPSearch,
LDAPQuery,
LDAPAddMember,
LDAPRemoveMember)
from ipalib import _, ngettext
from ipalib import output
from ipapython.dn import DN
__doc__ = _("""
Host-based access control
Control who can access what services on what hosts. You
can use HBAC to control which users or groups can
access a service, or group of services, on a target host.
You can also specify a category of users and target hosts.
This is currently limited to "all", but might be expanded in the
future.
Target hosts in HBAC rules must be hosts managed by IPA.
The available services and groups of services are controlled by the
hbacsvc and hbacsvcgroup plug-ins respectively.
EXAMPLES:
Create a rule, "test1", that grants all users access to the host "server" from
anywhere:
ipa hbacrule-add --usercat=all test1
ipa hbacrule-add-host --hosts=server.example.com test1
Display the properties of a named HBAC rule:
ipa hbacrule-show test1
Create a rule for a specific service. This lets the user john access
the sshd service on any machine from any machine:
ipa hbacrule-add --hostcat=all john_sshd
ipa hbacrule-add-user --users=john john_sshd
ipa hbacrule-add-service --hbacsvcs=sshd john_sshd
Create a rule for a new service group. This lets the user john access
the FTP service on any machine from any machine:
ipa hbacsvcgroup-add ftpers
ipa hbacsvc-add sftp
ipa hbacsvcgroup-add-member --hbacsvcs=ftp --hbacsvcs=sftp ftpers
ipa hbacrule-add --hostcat=all john_ftp
ipa hbacrule-add-user --users=john john_ftp
ipa hbacrule-add-service --hbacsvcgroups=ftpers john_ftp
Disable a named HBAC rule:
ipa hbacrule-disable test1
Remove a named HBAC rule:
ipa hbacrule-del allow_server
""")
register = Registry()
# AccessTime support is being removed for now.
#
# You can also control the times that the rule is active.
#
# The access time(s) of a host are cumulative and are not guaranteed to be
# applied in the order displayed.
#
# Specify that the rule "test1" be active every day between 0800 and 1400:
# ipa hbacrule-add-accesstime --time='periodic daily 0800-1400' test1
#
# Specify that the rule "test1" be active once, from 10:32 until 10:33 on
# December 16, 2010:
# ipa hbacrule-add-accesstime --time='absolute 201012161032 ~ 201012161033' test1
topic = 'hbac'
def validate_type(ugettext, type):
if type.lower() == 'deny':
raise errors.ValidationError(name='type', error=_('The deny type has been deprecated.'))
def is_all(options, attribute):
"""
See if options[attribute] is lower-case 'all' in a safe way.
"""
if attribute in options and options[attribute] is not None:
if type(options[attribute]) in (list, tuple):
value = options[attribute][0].lower()
else:
value = options[attribute].lower()
if value == 'all':
return True
return False
@register()
class hbacrule(LDAPObject):
"""
HBAC object.
"""
container_dn = api.env.container_hbac
object_name = _('HBAC rule')
object_name_plural = _('HBAC rules')
object_class = ['ipaassociation', 'ipahbacrule']
permission_filter_objectclasses = ['ipahbacrule']
default_attributes = [
'cn', 'ipaenabledflag',
'description', 'usercategory', 'hostcategory',
'servicecategory', 'ipaenabledflag',
'memberuser', 'sourcehost', 'memberhost', 'memberservice',
'externalhost',
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
allow_rename = True
attribute_members = {
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
'sourcehost': ['host', 'hostgroup'],
'memberservice': ['hbacsvc', 'hbacsvcgroup'],
}
managed_permissions = {
'System: Read HBAC Rules': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'accessruletype', 'accesstime', 'cn', 'description',
'externalhost', 'hostcategory', 'ipaenabledflag',
'ipauniqueid', 'memberhost', 'memberservice', 'memberuser',
'servicecategory', 'sourcehost', 'sourcehostcategory',
'usercategory', 'objectclass', 'member',
},
},
'System: Add HBAC Rule': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Add HBAC rule";allow (add) groupdn = "ldap:///cn=Add HBAC rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Delete HBAC Rule': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Delete HBAC rule";allow (delete) groupdn = "ldap:///cn=Delete HBAC rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Manage HBAC Rule Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'externalhost', 'memberhost', 'memberservice', 'memberuser'
},
'replaces': [
'(targetattr = "memberuser || externalhost || memberservice || memberhost")(target = "ldap:///ipauniqueid=*,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Manage HBAC rule membership";allow (write) groupdn = "ldap:///cn=Manage HBAC rule membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
'System: Modify HBAC Rule': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'accessruletype', 'accesstime', 'cn', 'description',
'hostcategory', 'ipaenabledflag', 'servicecategory',
'sourcehost', 'sourcehostcategory', 'usercategory'
},
'replaces': [
'(targetattr = "servicecategory || sourcehostcategory || cn || description || ipaenabledflag || accesstime || usercategory || hostcategory || accessruletype || sourcehost")(target = "ldap:///ipauniqueid=*,cn=hbac,$SUFFIX")(version 3.0;acl "permission:Modify HBAC rule";allow (write) groupdn = "ldap:///cn=Modify HBAC rule,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'HBAC Administrator'},
},
}
label = _('HBAC Rules')
label_singular = _('HBAC Rule')
takes_params = (
Str('cn',
cli_name='name',
label=_('Rule name'),
primary_key=True,
),
StrEnum('accessruletype', validate_type,
cli_name='type',
doc=_('Rule type (allow)'),
label=_('Rule type'),
values=(u'allow', u'deny'),
default=u'allow',
autofill=True,
exclude='webui',
flags=['no_option', 'no_output'],
),
# FIXME: {user,host,service}categories should expand in the future
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the rule applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the rule applies to'),
values=(u'all', ),
),
StrEnum('sourcehostcategory?',
deprecated=True,
cli_name='srchostcat',
label=_('Source host category'),
doc=_('Source host category the rule applies to'),
values=(u'all', ),
flags={'no_option'},
),
StrEnum('servicecategory?',
cli_name='servicecat',
label=_('Service category'),
doc=_('Service category the rule applies to'),
values=(u'all', ),
),
# AccessTime('accesstime?',
# cli_name='time',
# label=_('Access time'),
# ),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Bool('ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
),
Str('memberuser_user?',
label=_('Users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_group?',
label=_('User Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_host?',
label=_('Hosts'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_hostgroup?',
label=_('Host Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('sourcehost_host?',
deprecated=True,
label=_('Source Hosts'),
flags=['no_create', 'no_update', 'no_search', 'no_option'],
),
Str('sourcehost_hostgroup?',
deprecated=True,
label=_('Source Host Groups'),
flags=['no_create', 'no_update', 'no_search', 'no_option'],
),
Str('memberservice_hbacsvc?',
label=_('HBAC Services'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberservice_hbacsvcgroup?',
label=_('HBAC Service Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
external_host_param,
)
@register()
class hbacrule_add(LDAPCreate):
__doc__ = _('Create a new HBAC rule.')
msg_summary = _('Added HBAC rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# HBAC rules are enabled by default
entry_attrs['ipaenabledflag'] = True
return dn
@register()
class hbacrule_del(LDAPDelete):
__doc__ = _('Delete an HBAC rule.')
msg_summary = _('Deleted HBAC rule "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
kw = dict(seealso=str(dn), pkey_only=True)
_entries = api.Command.selinuxusermap_find(None, **kw)
if _entries['count']:
raise errors.DependentEntry(key=keys[0], label=self.api.Object['selinuxusermap'].label_singular, dependent=_entries['result'][0]['cn'][0])
return dn
@register()
class hbacrule_mod(LDAPUpdate):
__doc__ = _('Modify an HBAC rule.')
msg_summary = _('Modified HBAC rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, attrs_list)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(options, 'usercategory') and 'memberuser' in entry_attrs:
raise errors.MutuallyExclusiveError(
reason=_("user category cannot be set to 'all' while there "
"are allowed users")
)
if is_all(options, 'hostcategory') and 'memberhost' in entry_attrs:
raise errors.MutuallyExclusiveError(
reason=_("host category cannot be set to 'all' while there "
"are allowed hosts")
)
if (is_all(options, 'servicecategory')
and 'memberservice' in entry_attrs):
raise errors.MutuallyExclusiveError(
reason=_("service category cannot be set to 'all' while "
"there are allowed services")
)
return dn
@register()
class hbacrule_find(LDAPSearch):
__doc__ = _('Search for HBAC rules.')
msg_summary = ngettext(
'%(count)d HBAC rule matched', '%(count)d HBAC rules matched', 0
)
@register()
class hbacrule_show(LDAPRetrieve):
__doc__ = _('Display the properties of an HBAC rule.')
@register()
class hbacrule_enable(LDAPQuery):
__doc__ = _('Enable an HBAC rule.')
msg_summary = _('Enabled HBAC rule "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [True]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class hbacrule_disable(LDAPQuery):
__doc__ = _('Disable an HBAC rule.')
msg_summary = _('Disabled HBAC rule "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [False]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
# @register()
class hbacrule_add_accesstime(LDAPQuery):
"""
Add an access time to an HBAC rule.
"""
takes_options = (
AccessTime('accesstime',
cli_name='time',
label=_('Access time'),
),
)
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
entry_attrs = ldap.get_entry(dn, ['accesstime'])
entry_attrs.setdefault('accesstime', []).append(
options['accesstime']
)
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
except errors.NotFound:
raise self.obj.handle_not_found(cn)
return dict(result=True)
# @register()
class hbacrule_remove_accesstime(LDAPQuery):
"""
Remove access time to HBAC rule.
"""
takes_options = (
AccessTime('accesstime?',
cli_name='time',
label=_('Access time'),
),
)
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
entry_attrs = ldap.get_entry(dn, ['accesstime'])
try:
entry_attrs.setdefault('accesstime', []).remove(
options['accesstime']
)
ldap.update_entry(entry_attrs)
except (ValueError, errors.EmptyModlist):
pass
except errors.NotFound:
raise self.obj.handle_not_found(cn)
return dict(result=True)
@register()
class hbacrule_add_user(LDAPAddMember):
__doc__ = _('Add users and groups to an HBAC rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if ('usercategory' in entry_attrs and
entry_attrs['usercategory'][0].lower() == 'all'):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when user category='all'"))
return dn
@register()
class hbacrule_remove_user(LDAPRemoveMember):
__doc__ = _('Remove users and groups from an HBAC rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class hbacrule_add_host(LDAPAddMember):
__doc__ = _('Add target hosts and hostgroups to an HBAC rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if ('hostcategory' in entry_attrs and
entry_attrs['hostcategory'][0].lower() == 'all'):
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be added when host category='all'"))
return dn
@register()
class hbacrule_remove_host(LDAPRemoveMember):
__doc__ = _('Remove target hosts and hostgroups from an HBAC rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class hbacrule_add_sourcehost(LDAPAddMember):
__doc__ = _('Add source hosts and hostgroups to an HBAC rule.')
NO_CLI = True
member_attributes = ['sourcehost']
member_count_out = ('%i object added.', '%i objects added.')
def validate(self, **kw):
raise errors.DeprecationError(name='hbacrule_add_sourcehost')
@register()
class hbacrule_remove_sourcehost(LDAPRemoveMember):
__doc__ = _('Remove source hosts and hostgroups from an HBAC rule.')
NO_CLI = True
member_attributes = ['sourcehost']
member_count_out = ('%i object removed.', '%i objects removed.')
def validate(self, **kw):
raise errors.DeprecationError(name='hbacrule_remove_sourcehost')
@register()
class hbacrule_add_service(LDAPAddMember):
__doc__ = _('Add services to an HBAC rule.')
member_attributes = ['memberservice']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if ('servicecategory' in entry_attrs and
entry_attrs['servicecategory'][0].lower() == 'all'):
raise errors.MutuallyExclusiveError(reason=_(
"services cannot be added when service category='all'"))
return dn
@register()
class hbacrule_remove_service(LDAPRemoveMember):
__doc__ = _('Remove service and service groups from an HBAC rule.')
member_attributes = ['memberservice']
member_count_out = ('%i object removed.', '%i objects removed.')
| 19,972
|
Python
|
.py
| 502
| 31.657371
| 373
| 0.609785
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,856
|
sudocmdgroup.py
|
freeipa_freeipa/ipaserver/plugins/sudocmdgroup.py
|
# Authors:
# Jr Aquino <jr.aquino@citrixonline.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 ipalib import api
from ipalib import Str
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember)
from ipalib import _, ngettext
__doc__ = _("""
Groups of Sudo Commands
Manage groups of Sudo Commands.
EXAMPLES:
Add a new Sudo Command Group:
ipa sudocmdgroup-add --desc='administrators commands' admincmds
Remove a Sudo Command Group:
ipa sudocmdgroup-del admincmds
Manage Sudo Command Group membership, commands:
ipa sudocmdgroup-add-member --sudocmds=/usr/bin/less --sudocmds=/usr/bin/vim admincmds
Manage Sudo Command Group membership, commands:
ipa sudocmdgroup-remove-member --sudocmds=/usr/bin/less admincmds
Show a Sudo Command Group:
ipa sudocmdgroup-show admincmds
""")
register = Registry()
topic = 'sudo'
@register()
class sudocmdgroup(LDAPObject):
"""
Sudo Command Group object.
"""
container_dn = api.env.container_sudocmdgroup
object_name = _('sudo command group')
object_name_plural = _('sudo command groups')
object_class = ['ipaobject', 'ipasudocmdgrp']
permission_filter_objectclasses = ['ipasudocmdgrp']
default_attributes = [
'cn', 'description', 'member',
]
uuid_attribute = 'ipauniqueid'
attribute_members = {
'member': ['sudocmd'],
}
managed_permissions = {
'System: Read Sudo Command Groups': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'ipauniqueid',
'member', 'o', 'objectclass', 'ou', 'owner', 'seealso',
'memberuser', 'memberhost',
},
},
'System: Add Sudo Command Group': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=sudocmdgroups,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Add Sudo command group";allow (add) groupdn = "ldap:///cn=Add Sudo command group,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Delete Sudo Command Group': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=sudocmdgroups,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Delete Sudo command group";allow (delete) groupdn = "ldap:///cn=Delete Sudo command group,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Modify Sudo Command Group': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'description'},
'default_privileges': {'Sudo Administrator'},
},
'System: Manage Sudo Command Group Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=sudocmdgroups,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Manage Sudo command group membership";allow (write) groupdn = "ldap:///cn=Manage Sudo command group membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
}
label = _('Sudo Command Groups')
label_singular = _('Sudo Command Group')
takes_params = (
Str('cn',
cli_name='sudocmdgroup_name',
label=_('Sudo Command Group'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Group description'),
),
Str('membercmd_sudocmd?',
label=_('Commands'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('membercmd_sudocmdgroup?',
label=_('Sudo Command Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
)
@register()
class sudocmdgroup_add(LDAPCreate):
__doc__ = _('Create new Sudo Command Group.')
msg_summary = _('Added Sudo Command Group "%(value)s"')
@register()
class sudocmdgroup_del(LDAPDelete):
__doc__ = _('Delete Sudo Command Group.')
msg_summary = _('Deleted Sudo Command Group "%(value)s"')
@register()
class sudocmdgroup_mod(LDAPUpdate):
__doc__ = _('Modify Sudo Command Group.')
msg_summary = _('Modified Sudo Command Group "%(value)s"')
@register()
class sudocmdgroup_find(LDAPSearch):
__doc__ = _('Search for Sudo Command Groups.')
msg_summary = ngettext(
'%(count)d Sudo Command Group matched',
'%(count)d Sudo Command Groups matched', 0
)
@register()
class sudocmdgroup_show(LDAPRetrieve):
__doc__ = _('Display Sudo Command Group.')
@register()
class sudocmdgroup_add_member(LDAPAddMember):
__doc__ = _('Add members to Sudo Command Group.')
@register()
class sudocmdgroup_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from Sudo Command Group.')
| 6,037
|
Python
|
.py
| 155
| 32.329032
| 273
| 0.6382
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,857
|
join.py
|
freeipa_freeipa/ipaserver/plugins/join.py
|
# Authors:
# Rob Crittenden <rcritten@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 logging
import six
from ipalib import Registry, api
from ipalib import Command, Str
from ipalib import errors
from ipalib import _
from ipalib.constants import FQDN
__doc__ = _("""
Joining an IPA domain
""")
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
register = Registry()
def validate_host(ugettext, cn):
"""
Require at least one dot in the hostname (to support localhost.localdomain)
"""
dots = len(cn.split('.'))
if dots < 2:
return 'Fully-qualified hostname required'
return None
@register()
class join(Command):
__doc__ = _('Join an IPA domain')
NO_CLI = True
takes_args = (
Str('cn',
validate_host,
cli_name='hostname',
doc=_("The hostname to register as"),
default_from=lambda: FQDN,
autofill=True,
#normalizer=lamda value: value.lower(),
),
)
takes_options = (
Str('realm',
doc=_("The IPA realm"),
default_from=lambda: api.env.realm,
autofill=True,
),
Str('nshardwareplatform?',
cli_name='platform',
doc=_('Hardware platform of the host (e.g. Lenovo T61)'),
),
Str('nsosversion?',
cli_name='os',
doc=_('Operating System and version of the host (e.g. Fedora 9)'),
),
)
has_output = tuple()
use_output_validation = False
def execute(self, hostname, **kw):
"""
Execute the machine join operation.
Returns the entry as it will be created in LDAP.
:param hostname: The name of the host joined
:param kw: Keyword arguments for the other attributes.
"""
assert 'cn' not in kw
ldap = self.api.Backend.ldap2
# realm parameter is not supported by host_{add,mod}
kw.pop('realm', None)
try:
# First see if the host exists
show_kw = {'fqdn': hostname, 'all': True}
attrs_list = api.Command['host_show'](**show_kw)['result']
dn = attrs_list['dn']
# No error raised so far means that host entry exists
logger.info('Host entry for %s already exists, '
'joining may fail on the client side '
'if not forced', hostname)
# If no principal name is set yet we need to try to add
# one.
if 'krbprincipalname' not in attrs_list:
service = "host/%s@%s" % (hostname, api.env.realm)
api.Command['host_mod'](hostname, **kw,
krbprincipalname=service)
logger.info('No principal set, setting to %s', service)
# It exists, can we write the password attributes?
allowed = ldap.can_write(dn, 'krblastpwdchange')
if not allowed:
raise errors.ACIError(info=_("Insufficient 'write' privilege "
"to the 'krbLastPwdChange' attribute of entry '%s'.") % dn)
# Reload the attrs_list and dn so that we return update values
attrs_list = api.Command['host_show'](**show_kw)['result']
dn = attrs_list['dn']
except errors.NotFound:
attrs_list = api.Command['host_add'](hostname, **kw,
force=True)['result']
dn = attrs_list['dn']
config = api.Command['config_show']()['result']
attrs_list['ipacertificatesubjectbase'] =\
config['ipacertificatesubjectbase']
return dn, attrs_list
| 4,417
|
Python
|
.py
| 114
| 30.061404
| 79
| 0.600094
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,858
|
privilege.py
|
freeipa_freeipa/ipaserver/plugins/privilege.py
|
# Authors:
# Rob Crittenden <rcritten@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 .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember,
LDAPAddReverseMember,
LDAPRemoveReverseMember)
from ipalib import api, _, ngettext, errors
from ipalib.plugable import Registry
from ipalib import Str
from ipalib import output
from ipapython.dn import DN
__doc__ = _("""
Privileges
A privilege combines permissions into a logical task. A permission provides
the rights to do a single task. There are some IPA operations that require
multiple permissions to succeed. A privilege is where permissions are
combined in order to perform a specific task.
For example, adding a user requires the following permissions:
* Creating a new user entry
* Resetting a user password
* Adding the new user to the default IPA users group
Combining these three low-level tasks into a higher level task in the
form of a privilege named "Add User" makes it easier to manage Roles.
A privilege may not contain other privileges.
See role and permission for additional information.
""")
register = Registry()
def validate_permission_to_privilege(api, permission):
ldap = api.Backend.ldap2
ldapfilter = ldap.combine_filters(rules='&', filters=[
'(objectClass=ipaPermissionV2)', '(!(ipaPermBindRuleType=permission))',
ldap.make_filter_from_attr('cn', permission, rules='|')])
try:
entries, _truncated = ldap.find_entries(
filter=ldapfilter,
attrs_list=['cn', 'ipapermbindruletype'],
base_dn=DN(api.env.container_permission, api.env.basedn),
size_limit=1)
except errors.NotFound:
pass
else:
entry = entries[0]
message = _('cannot add permission "%(perm)s" with bindtype '
'"%(bindtype)s" to a privilege')
raise errors.ValidationError(
name='permission',
error=message % {
'perm': entry.single_value['cn'],
'bindtype': entry.single_value.get(
'ipapermbindruletype', 'permission')})
def principal_has_privilege(api, principal, privilege):
"""
Validate that the principal is a member of the specified privilege.
If principal is None, use currently bound LDAP DN for validation.
cn=Directory Manager is explicitly allowed
"""
privilege_dn = api.Object.privilege.get_dn(privilege)
ldap = api.Backend.ldap2
if principal is None:
dn_or_princ = DN(ldap.conn.whoami_s()[4:])
if dn_or_princ == DN('cn=Directory Manager'):
return True
else:
dn_or_princ = principal
# First try: Check if there is a principal that has the needed
# privilege.
filter = ldap.make_filter({
'krbprincipalname': dn_or_princ,
'memberof': privilege_dn},
rules=ldap.MATCH_ALL)
try:
ldap.find_entries(base_dn=api.env.basedn, filter=filter)
return True
except errors.NotFound:
pass
# Do not run ID override check for the user that has no Kerberos principal
if principal is None:
return False
# Second try: Check if there is an idoverride for the principal as
# ipaOriginalUid that has the needed privilege.
filter = ldap.make_filter(
{
'objectClass': ['ipaOverrideAnchor', 'nsmemberof'],
'ipaOriginalUid': principal,
'memberOf': privilege_dn
},
rules=ldap.MATCH_ALL)
_dn = DN(('cn', api.packages[0].idviews.DEFAULT_TRUST_VIEW_NAME),
api.env.container_views + api.env.basedn)
try:
ldap.find_entries(base_dn=_dn, filter=filter)
except errors.NotFound:
return False
return True
@register()
class privilege(LDAPObject):
"""
Privilege object.
"""
container_dn = api.env.container_privilege
object_name = _('privilege')
object_name_plural = _('privileges')
object_class = ['nestedgroup', 'groupofnames']
permission_filter_objectclasses = ['groupofnames']
default_attributes = ['cn', 'description', 'member', 'memberof']
attribute_members = {
'member': ['role'],
'memberof': ['permission'],
}
reverse_members = {
'member': ['permission'],
}
allow_rename = True
managed_permissions = {
'System: Read Privileges': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'member', 'memberof',
'o', 'objectclass', 'ou', 'owner', 'seealso', 'memberuser',
'memberhost',
},
'default_privileges': {'RBAC Readers'},
},
'System: Add Privileges': {
'ipapermright': {'add'},
'default_privileges': {'Delegation Administrator'},
},
'System: Modify Privileges': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'o', 'ou', 'owner',
'seealso',
},
'default_privileges': {'Delegation Administrator'},
},
'System: Remove Privileges': {
'ipapermright': {'delete'},
'default_privileges': {'Delegation Administrator'},
},
}
label = _('Privileges')
label_singular = _('Privilege')
takes_params = (
Str('cn',
cli_name='name',
label=_('Privilege name'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Privilege description'),
),
)
@register()
class privilege_add(LDAPCreate):
__doc__ = _('Add a new privilege.')
msg_summary = _('Added privilege "%(value)s"')
@register()
class privilege_del(LDAPDelete):
__doc__ = _('Delete a privilege.')
msg_summary = _('Deleted privilege "%(value)s"')
@register()
class privilege_mod(LDAPUpdate):
__doc__ = _('Modify a privilege.')
msg_summary = _('Modified privilege "%(value)s"')
@register()
class privilege_find(LDAPSearch):
__doc__ = _('Search for privileges.')
msg_summary = ngettext(
'%(count)d privilege matched', '%(count)d privileges matched', 0
)
@register()
class privilege_show(LDAPRetrieve):
__doc__ = _('Display information about a privilege.')
@register()
class privilege_add_member(LDAPAddMember):
__doc__ = _('Add members to a privilege.')
NO_CLI=True
@register()
class privilege_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a privilege')
NO_CLI=True
@register()
class privilege_add_permission(LDAPAddReverseMember):
__doc__ = _('Add permissions to a privilege.')
show_command = 'privilege_show'
member_command = 'permission_add_member'
reverse_attr = 'permission'
member_attr = 'privilege'
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of permissions added'),
),
)
def pre_callback(self, ldap, dn, *keys, **options):
if options.get('permission'):
# We can only add permissions with bind rule type set to
# "permission" (or old-style permissions)
validate_permission_to_privilege(self.api, options['permission'])
return dn
@register()
class privilege_remove_permission(LDAPRemoveReverseMember):
__doc__ = _('Remove permissions from a privilege.')
show_command = 'privilege_show'
member_command = 'permission_remove_member'
reverse_attr = 'permission'
member_attr = 'privilege'
permission_count_out = ('%i permission removed.', '%i permissions removed.')
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output(
'completed',
type=int,
doc=_('Number of permissions removed'),
),
)
| 9,056
|
Python
|
.py
| 251
| 29.262948
| 80
| 0.637319
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,859
|
caacl.py
|
freeipa_freeipa/ipaserver/plugins/caacl.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import six
from ipalib import api, errors, output
from ipalib import Bool, Str, StrEnum
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject, LDAPSearch, LDAPCreate, LDAPDelete, LDAPQuery,
LDAPUpdate, LDAPRetrieve, LDAPAddMember, LDAPRemoveMember,
global_output_params, pkey_to_value)
from .hbacrule import is_all
from ipalib import _, ngettext
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Manage CA ACL rules.
This plugin is used to define rules governing which CAs and profiles
may be used to issue certificates to particular principals or groups
of principals.
SUBJECT PRINCIPAL SCOPE:
For a certificate request to be allowed, the principal(s) that are
the subject of a certificate request (not necessarily the principal
actually requesting the certificate) must be included in the scope
of a CA ACL that also includes the target CA and profile.
Users can be included by name, group or the "all users" category.
Hosts can be included by name, hostgroup or the "all hosts"
category. Services can be included by service name or the "all
services" category. CA ACLs may be associated with a single type of
principal, or multiple types.
CERTIFICATE AUTHORITY SCOPE:
A CA ACL can be associated with one or more CAs by name, or by the
"all CAs" category. For compatibility reasons, a CA ACL with no CA
association implies an association with the 'ipa' CA (and only this
CA).
PROFILE SCOPE:
A CA ACL can be associated with one or more profiles by Profile ID.
The Profile ID is a string without spaces or punctuation starting
with a letter and followed by a sequence of letters, digits or
underscore ("_").
EXAMPLES:
Create a CA ACL "test" that grants all users access to the
"UserCert" profile on all CAs:
ipa caacl-add test --usercat=all --cacat=all
ipa caacl-add-profile test --certprofiles UserCert
Display the properties of a named CA ACL:
ipa caacl-show test
Create a CA ACL to let user "alice" use the "DNP3" profile on "DNP3-CA":
ipa caacl-add alice_dnp3
ipa caacl-add-ca alice_dnp3 --cas DNP3-CA
ipa caacl-add-profile alice_dnp3 --certprofiles DNP3
ipa caacl-add-user alice_dnp3 --user=alice
Disable a CA ACL:
ipa caacl-disable test
Remove a CA ACL:
ipa caacl-del test
""")
register = Registry()
@register()
class caacl(LDAPObject):
"""
CA ACL object.
"""
container_dn = api.env.container_caacl
object_name = _('CA ACL')
object_name_plural = _('CA ACLs')
object_class = ['ipaassociation', 'ipacaacl']
permission_filter_objectclasses = ['ipacaacl']
default_attributes = [
'cn', 'description', 'ipaenabledflag',
'ipacacategory', 'ipamemberca',
'ipacertprofilecategory', 'ipamembercertprofile',
'usercategory', 'memberuser',
'hostcategory', 'memberhost',
'servicecategory', 'memberservice',
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
attribute_members = {
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
'memberservice': ['service'],
'ipamemberca': ['ca'],
'ipamembercertprofile': ['certprofile'],
}
managed_permissions = {
'System: Read CA ACLs': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'description', 'ipaenabledflag',
'ipacacategory', 'ipamemberca',
'ipacertprofilecategory', 'ipamembercertprofile',
'usercategory', 'memberuser',
'hostcategory', 'memberhost',
'servicecategory', 'memberservice',
'ipauniqueid',
'objectclass', 'member',
},
},
'System: Add CA ACL': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Add CA ACL";allow (add) groupdn = "ldap:///cn=Add CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Delete CA ACL': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Delete CA ACL";allow (delete) groupdn = "ldap:///cn=Delete CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Manage CA ACL Membership': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'ipacacategory', 'ipamemberca',
'ipacertprofilecategory', 'ipamembercertprofile',
'usercategory', 'memberuser',
'hostcategory', 'memberhost',
'servicecategory', 'memberservice'
},
'replaces': [
'(targetattr = "ipamemberca || ipamembercertprofile || memberuser || memberservice || memberhost || ipacacategory || ipacertprofilecategory || usercategory || hostcategory || servicecategory")(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Manage CA ACL membership";allow (write) groupdn = "ldap:///cn=Manage CA ACL membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Modify CA ACL': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cn', 'description', 'ipaenabledflag',
},
'replaces': [
'(targetattr = "cn || description || ipaenabledflag")(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Modify CA ACL";allow (write) groupdn = "ldap:///cn=Modify CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
}
label = _('CA ACLs')
label_singular = _('CA ACL')
takes_params = (
Str('cn',
cli_name='name',
label=_('ACL name'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Bool('ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
),
StrEnum('ipacacategory?',
cli_name='cacat',
label=_('CA category'),
doc=_('CA category the ACL applies to'),
values=(u'all', ),
),
StrEnum('ipacertprofilecategory?',
cli_name='profilecat',
label=_('Profile category'),
doc=_('Profile category the ACL applies to'),
values=(u'all', ),
),
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the ACL applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the ACL applies to'),
values=(u'all', ),
),
StrEnum('servicecategory?',
cli_name='servicecat',
label=_('Service category'),
doc=_('Service category the ACL applies to'),
values=(u'all', ),
),
Str('ipamemberca_ca?',
label=_('CAs'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('ipamembercertprofile_certprofile?',
label=_('Profiles'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_user?',
label=_('Users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_group?',
label=_('User Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_host?',
label=_('Hosts'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_hostgroup?',
label=_('Host Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberservice_service?',
label=_('Services'),
flags=['no_create', 'no_update', 'no_search'],
),
)
@register()
class caacl_add(LDAPCreate):
__doc__ = _('Create a new CA ACL.')
msg_summary = _('Added CA ACL "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
# CA ACLs are enabled by default
entry_attrs['ipaenabledflag'] = [True]
return dn
@register()
class caacl_del(LDAPDelete):
__doc__ = _('Delete a CA ACL.')
msg_summary = _('Deleted CA ACL "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
if keys[0] == 'hosts_services_caIPAserviceCert':
raise errors.ProtectedEntryError(
label=_("CA ACL"),
key=keys[0],
reason=_("default CA ACL can be only disabled"))
return dn
@register()
class caacl_mod(LDAPUpdate):
__doc__ = _('Modify a CA ACL.')
msg_summary = _('Modified CA ACL "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, attrs_list)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(options, 'ipacacategory') and 'ipamemberca' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=_(
"CA category cannot be set to 'all' "
"while there are allowed CAs"))
if (is_all(options, 'ipacertprofilecategory')
and 'ipamembercertprofile' in entry_attrs):
raise errors.MutuallyExclusiveError(reason=_(
"profile category cannot be set to 'all' "
"while there are allowed profiles"))
if is_all(options, 'usercategory') and 'memberuser' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=_(
"user category cannot be set to 'all' "
"while there are allowed users"))
if is_all(options, 'hostcategory') and 'memberhost' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=_(
"host category cannot be set to 'all' "
"while there are allowed hosts"))
if is_all(options, 'servicecategory') and 'memberservice' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=_(
"service category cannot be set to 'all' "
"while there are allowed services"))
return dn
@register()
class caacl_find(LDAPSearch):
__doc__ = _('Search for CA ACLs.')
msg_summary = ngettext(
'%(count)d CA ACL matched', '%(count)d CA ACLs matched', 0
)
@register()
class caacl_show(LDAPRetrieve):
__doc__ = _('Display the properties of a CA ACL.')
@register()
class caacl_enable(LDAPQuery):
__doc__ = _('Enable a CA ACL.')
msg_summary = _('Enabled CA ACL "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [True]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class caacl_disable(LDAPQuery):
__doc__ = _('Disable a CA ACL.')
msg_summary = _('Disabled CA ACL "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [False]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class caacl_add_user(LDAPAddMember):
__doc__ = _('Add users and groups to a CA ACL.')
member_attributes = ['memberuser']
member_count_out = (
_('%i user or group added.'),
_('%i users or groups added.'))
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(entry_attrs, 'usercategory'):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when user category='all'"))
return dn
@register()
class caacl_remove_user(LDAPRemoveMember):
__doc__ = _('Remove users and groups from a CA ACL.')
member_attributes = ['memberuser']
member_count_out = (
_('%i user or group removed.'),
_('%i users or groups removed.'))
@register()
class caacl_add_host(LDAPAddMember):
__doc__ = _('Add target hosts and hostgroups to a CA ACL.')
member_attributes = ['memberhost']
member_count_out = (
_('%i host or hostgroup added.'),
_('%i hosts or hostgroups added.'))
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(entry_attrs, 'hostcategory'):
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be added when host category='all'"))
return dn
@register()
class caacl_remove_host(LDAPRemoveMember):
__doc__ = _('Remove target hosts and hostgroups from a CA ACL.')
member_attributes = ['memberhost']
member_count_out = (
_('%i host or hostgroup removed.'),
_('%i hosts or hostgroups removed.'))
@register()
class caacl_add_service(LDAPAddMember):
__doc__ = _('Add services to a CA ACL.')
member_attributes = ['memberservice']
member_count_out = (_('%i service added.'), _('%i services added.'))
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(entry_attrs, 'servicecategory'):
raise errors.MutuallyExclusiveError(reason=_(
"services cannot be added when service category='all'"))
return dn
@register()
class caacl_remove_service(LDAPRemoveMember):
__doc__ = _('Remove services from a CA ACL.')
member_attributes = ['memberservice']
member_count_out = (_('%i service removed.'), _('%i services removed.'))
caacl_output_params = global_output_params + (
Str('ipamembercertprofile',
label=_('Failed profiles'),
),
Str('ipamemberca',
label=_('Failed CAs'),
),
)
@register()
class caacl_add_profile(LDAPAddMember):
__doc__ = _('Add profiles to a CA ACL.')
has_output_params = caacl_output_params
member_attributes = ['ipamembercertprofile']
member_count_out = (_('%i profile added.'), _('%i profiles added.'))
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(entry_attrs, 'ipacertprofilecategory'):
raise errors.MutuallyExclusiveError(reason=_(
"profiles cannot be added when profile category='all'"))
return dn
@register()
class caacl_remove_profile(LDAPRemoveMember):
__doc__ = _('Remove profiles from a CA ACL.')
has_output_params = caacl_output_params
member_attributes = ['ipamembercertprofile']
member_count_out = (_('%i profile removed.'), _('%i profiles removed.'))
@register()
class caacl_add_ca(LDAPAddMember):
__doc__ = _('Add CAs to a CA ACL.')
has_output_params = caacl_output_params
member_attributes = ['ipamemberca']
member_count_out = (_('%i CA added.'), _('%i CAs added.'))
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if is_all(entry_attrs, 'ipacacategory'):
raise errors.MutuallyExclusiveError(reason=_(
"CAs cannot be added when CA category='all'"))
return dn
@register()
class caacl_remove_ca(LDAPRemoveMember):
__doc__ = _('Remove CAs from a CA ACL.')
has_output_params = caacl_output_params
member_attributes = ['ipamemberca']
member_count_out = (_('%i CA removed.'), _('%i CAs removed.'))
| 18,002
|
Python
|
.py
| 444
| 32.04955
| 417
| 0.602005
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,860
|
service.py
|
freeipa_freeipa/ipaserver/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/>.
import logging
from cryptography.hazmat.primitives import hashes
import six
from ipalib import api, errors, messages
from ipalib import StrEnum, Bool, Str, Flag
from ipalib.parameters import Principal, Certificate
from ipalib.plugable import Registry
from .baseldap import (
host_is_master,
add_missing_object_class,
pkey_to_value,
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember,
LDAPQuery,
LDAPAddAttribute,
LDAPRemoveAttribute,
LDAPAddAttributeViaOption,
LDAPRemoveAttributeViaOption,
DNA_MAGIC)
from ipalib import x509
from ipalib import _, ngettext
from ipalib import util
from ipalib import output
from ipapython import kerberos
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
if six.PY3:
unicode = str
__doc__ = _("""
Services
A IPA service represents a service that runs on a host. The IPA service
record can store a Kerberos principal, an SSL certificate, or both.
An IPA service can be managed directly from a machine, provided that
machine has been given the correct permission. This is true even for
machines other than the one the service is associated with. For example,
requesting an SSL certificate using the host service principal credentials
of the host. To manage a service using host credentials you need to
kinit as the host:
# kinit -kt /etc/krb5.keytab host/ipa.example.com@EXAMPLE.COM
Adding an IPA service allows the associated service to request an SSL
certificate or keytab, but this is performed as a separate step; they
are not produced as a result of adding the service.
Only the public aspect of a certificate is stored in a service record;
the private key is not stored.
EXAMPLES:
Add a new IPA service:
ipa service-add HTTP/web.example.com
Allow a host to manage an IPA service certificate:
ipa service-add-host --hosts=web.example.com HTTP/web.example.com
ipa role-add-member --hosts=web.example.com certadmin
Override a default list of supported PAC types for the service:
ipa service-mod HTTP/web.example.com --pac-type=MS-PAC
A typical use case where overriding the PAC type is needed is NFS.
Currently the related code in the Linux kernel can only handle Kerberos
tickets up to a maximal size. Since the PAC data can become quite large it
is recommended to set --pac-type=NONE for NFS services.
Delete an IPA service:
ipa service-del HTTP/web.example.com
Find all IPA services associated with a host:
ipa service-find web.example.com
Find all HTTP services:
ipa service-find HTTP
Disable the service Kerberos key and SSL certificate:
ipa service-disable HTTP/web.example.com
Request a certificate for an IPA service:
ipa cert-request --principal=HTTP/web.example.com example.csr
""") + _("""
Allow user to create a keytab:
ipa service-allow-create-keytab HTTP/web.example.com --users=tuser1
""") + _("""
Generate and retrieve a keytab for an IPA service:
ipa-getkeytab -s ipa.example.com -p HTTP/web.example.com -k /etc/httpd/httpd.keytab
""")
logger = logging.getLogger(__name__)
register = Registry()
output_params = (
Flag('has_keytab',
label=_('Keytab'),
),
Str('managedby_host',
label='Managed by',
),
Str('ipaallowedtoperform_read_keys_user',
label=_('Users allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_group',
label=_('Groups allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_host',
label=_('Hosts allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_read_keys_hostgroup',
label=_('Host Groups allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_write_keys_user',
label=_('Users allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_group',
label=_('Groups allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_host',
label=_('Hosts allowed to create keytab'),
),
Str('ipaallowedtoperform_write_keys_hostgroup',
label=_('Host Groups allowed to create keytab'),
),
Str('ipaallowedtoperform_read_keys',
label=_('Failed allowed to retrieve keytab'),
),
Str('ipaallowedtoperform_write_keys',
label=_('Failed allowed to create keytab'),
),
Str('ipaallowedtoperform_write_delegation_user',
label=_('Users allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_group',
label=_('Groups allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_host',
label=_('Hosts allowed to add resource delegation')),
Str('ipaallowedtoperform_write_delegation_hostgroup',
label=_('Host Groups allowed to add resource delegation')),
)
ticket_flags_params = (
Bool('ipakrbrequirespreauth?',
cli_name='requires_pre_auth',
label=_('Requires pre-authentication'),
doc=_('Pre-authentication is required for the service'),
flags=['virtual_attribute', 'no_search'],
),
Bool('ipakrbokasdelegate?',
cli_name='ok_as_delegate',
label=_('Trusted for delegation'),
doc=_('Client credentials may be delegated to the service'),
flags=['virtual_attribute', 'no_search'],
),
Bool('ipakrboktoauthasdelegate?',
cli_name='ok_to_auth_as_delegate',
label=_('Trusted to authenticate as user'),
doc=_('The service is allowed to authenticate on behalf of a client'),
flags=['virtual_attribute', 'no_search'],
),
)
_ticket_flags_map = {
'ipakrbrequirespreauth': 0x00000080,
'ipakrbokasdelegate': 0x00100000,
'ipakrboktoauthasdelegate': 0x00200000,
}
_ticket_flags_default = _ticket_flags_map['ipakrbrequirespreauth']
def validate_realm(ugettext, principal):
"""
Check that the principal's realm matches IPA realm if present
"""
realm = principal.realm
if realm is not None and realm != api.env.realm:
raise errors.RealmMismatch()
def validate_auth_indicator(entry):
new_value = entry.get('krbprincipalauthind', None)
if not new_value:
return
# The following services are considered internal IPA services
# and shouldn't be allowed to have auth indicators.
# https://pagure.io/freeipa/issue/8206
pkey = api.Object['service'].get_primary_key_from_dn(entry.dn)
if pkey == str(entry.dn):
# krbcanonicalname may not be set yet if this is a host entry,
# try krbprincipalname
if 'krbprincipalname' in entry:
pkey = entry['krbprincipalname']
principal = kerberos.Principal(pkey)
server = api.Command.server_find(principal.hostname)['result']
if server:
prefixes = ("host", "cifs", "ldap", "HTTP")
else:
prefixes = ("cifs",)
if principal.service_name in prefixes:
raise errors.ValidationError(
name='krbprincipalauthind',
error=_('authentication indicators not allowed '
'in service "%s"' % principal.service_name)
)
def normalize_principal(value):
"""
Ensure that the name in the principal is lower-case. The realm is
upper-case by convention but it isn't required.
The principal is validated at this point.
"""
try:
principal = kerberos.Principal(value, realm=api.env.realm)
except ValueError:
raise errors.ValidationError(
name='principal', reason=_("Malformed principal"))
return unicode(principal)
def revoke_certs(certs):
"""
revoke the certificates removed from host/service entry
:param certs: Output of a 'cert_find' command.
"""
for cert in certs:
if 'cacn' not in cert:
# Cert is known to IPA, but has no associated CA.
# If it was issued by 3rd-party CA, we can't revoke it.
# If it was issued by a Dogtag lightweight CA that was
# subsequently deleted, we can't revoke it via IPA.
# We could go directly to Dogtag to revoke it, but the
# issuer's cert should have been revoked so never mind.
continue
if cert['revoked']:
# cert is already revoked
continue
try:
api.Command['cert_revoke'](
cert['serial_number'],
cacn=cert['cacn'],
revocation_reason=4,
)
except errors.NotImplementedError:
# some CA's might not implement revoke
pass
def set_certificate_attrs(entry_attrs):
"""
Set individual attributes from some values from a certificate.
entry_attrs is a dict of an entry
returns nothing
"""
if 'usercertificate' not in entry_attrs:
return
if type(entry_attrs['usercertificate']) in (list, tuple):
cert = entry_attrs['usercertificate'][0]
else:
cert = entry_attrs['usercertificate']
entry_attrs['subject'] = unicode(DN(cert.subject))
entry_attrs['serial_number'] = unicode(cert.serial_number)
entry_attrs['serial_number_hex'] = u'0x%X' % cert.serial_number
entry_attrs['issuer'] = unicode(DN(cert.issuer))
entry_attrs['valid_not_before'] = x509.format_datetime(
cert.not_valid_before_utc)
entry_attrs['valid_not_after'] = x509.format_datetime(
cert.not_valid_after_utc)
entry_attrs['sha1_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA1()))
entry_attrs['sha256_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA256()))
def check_required_principal(ldap, principal):
"""
Raise an error if the host of this principal is an IPA master and one
of the principals required for proper execution.
"""
if not principal.is_service:
# bypass check if principal is not a service principal,
# see https://pagure.io/freeipa/issue/7793
return
try:
host_is_master(ldap, principal.hostname)
except errors.ValidationError:
service_types = {'http', 'ldap', 'dns', 'dogtagldap'}
if principal.service_name.lower() in service_types:
raise errors.ValidationError(
name='principal',
error=_('{} is required by the IPA master').format(principal)
)
def update_krbticketflags(ldap, entry_attrs, attrs_list, options, existing):
add = remove = 0
for (name, value) in _ticket_flags_map.items():
if name not in options:
continue
if options[name]:
add |= value
else:
remove |= value
if not add and not remove:
return
if 'krbticketflags' not in entry_attrs and existing:
old_entry_attrs = ldap.get_entry(entry_attrs.dn, ['krbticketflags'])
else:
old_entry_attrs = entry_attrs
try:
ticket_flags = old_entry_attrs.single_value['krbticketflags']
ticket_flags = int(ticket_flags)
except (KeyError, ValueError):
ticket_flags = _ticket_flags_default
ticket_flags |= add
ticket_flags &= ~remove
entry_attrs['krbticketflags'] = [ticket_flags]
attrs_list.append('krbticketflags')
def set_kerberos_attrs(entry_attrs, options):
if options.get('raw', False):
return
try:
ticket_flags = entry_attrs.single_value.get('krbticketflags',
_ticket_flags_default)
ticket_flags = int(ticket_flags)
except ValueError:
return
all_opt = options.get('all', False)
for (name, value) in _ticket_flags_map.items():
if name in options or all_opt:
entry_attrs[name] = bool(ticket_flags & value)
def rename_ipaallowedtoperform_from_ldap(entry_attrs, options):
if options.get('raw', False):
return
for subtype in ('read_keys', 'write_keys', 'write_delegation'):
name = 'ipaallowedtoperform;%s' % subtype
if name in entry_attrs:
new_name = 'ipaallowedtoperform_%s' % subtype
entry_attrs[new_name] = entry_attrs.pop(name)
def rename_ipaallowedtoperform_to_ldap(entry_attrs):
for subtype in ('read_keys', 'write_keys', 'write_delegation'):
name = 'ipaallowedtoperform_%s' % subtype
if name in entry_attrs:
new_name = 'ipaallowedtoperform;%s' % subtype
entry_attrs[new_name] = entry_attrs.pop(name)
@register()
class service(LDAPObject):
"""
Service object.
"""
container_dn = api.env.container_service
object_name = _('service')
object_name_plural = _('services')
object_class = [
'krbprincipal', 'krbprincipalaux', 'krbticketpolicyaux', 'ipaobject',
'ipaservice', 'pkiuser'
]
possible_objectclasses = ['ipakrbprincipal', 'ipaallowedoperations',
'resourcedelegation']
permission_filter_objectclasses = ['ipaservice']
search_attributes = ['krbprincipalname', 'managedby', 'ipakrbauthzdata']
default_attributes = [
'krbprincipalname', 'krbcanonicalname', 'usercertificate', 'managedby',
'ipakrbauthzdata', 'memberof', 'ipaallowedtoperform',
'krbprincipalauthind', 'memberprincipal']
uuid_attribute = 'ipauniqueid'
attribute_members = {
'managedby': ['host'],
'memberof': ['role'],
'ipaallowedtoperform_read_keys': ['user', 'group', 'host', 'hostgroup'],
'ipaallowedtoperform_write_keys': ['user', 'group', 'host', 'hostgroup'],
'ipaallowedtoperform_write_delegation':
['user', 'group', 'host', 'hostgroup'],
}
bindable = True
relationships = {
'managedby': ('Managed by', 'man_by_', 'not_man_by_'),
'ipaallowedtoperform_read_keys': ('Allow to retrieve keytab by', 'retrieve_keytab_by_', 'not_retrieve_keytab_by_'),
'ipaallowedtoperform_write_keys': ('Allow to create keytab by', 'write_keytab_by_', 'not_write_keytab_by'),
'ipaallowedtoperform_write_delegation':
('Allow to modify resource delegation ACL',
'write_delegation_by_', 'not_write_delegation_by'),
}
password_attributes = [('krbprincipalkey', 'has_keytab')]
managed_permissions = {
'System: Read Services': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass',
'ipauniqueid', 'managedby', 'memberof', 'usercertificate',
'krbprincipalname', 'krbcanonicalname', 'krbprincipalaliases',
'krbprincipalexpiration', 'krbpasswordexpiration',
'krblastpwdchange', 'ipakrbauthzdata', 'ipakrbprincipalalias',
'krbobjectreferences', 'krbprincipalauthind', 'memberprincipal',
},
},
'System: Add Services': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///krbprincipalname=*,cn=services,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Services";allow (add) groupdn = "ldap:///cn=Add Services,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Service Administrators'},
},
'System: Manage Service Keytab': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'krblastpwdchange', 'krbprincipalkey'},
'replaces': [
'(targetattr = "krbprincipalkey || krblastpwdchange")(target = "ldap:///krbprincipalname=*,cn=services,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Manage service keytab";allow (write) groupdn = "ldap:///cn=Manage service keytab,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Service Administrators', 'Host Administrators'},
},
'System: Manage Service Keytab Permissions': {
'ipapermright': {'read', 'search', 'compare', 'write'},
'ipapermdefaultattr': {
'ipaallowedtoperform;write_keys',
'ipaallowedtoperform;read_keys', 'objectclass'
},
'default_privileges': {'Service Administrators', 'Host Administrators'},
},
'System: Modify Services': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'usercertificate', 'krbprincipalauthind'},
'replaces': [
'(targetattr = "usercertificate")(target = "ldap:///krbprincipalname=*,cn=services,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Services";allow (write) groupdn = "ldap:///cn=Modify Services,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Service Administrators'},
},
'System: Manage Service Principals': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'krbprincipalname', 'krbcanonicalname'},
'default_privileges': {
'Service Administrators',
},
},
'System: Remove Services': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///krbprincipalname=*,cn=services,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Services";allow (delete) groupdn = "ldap:///cn=Remove Services,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Service Administrators'},
},
'System: Read POSIX details of SMB services': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'uid', 'gecos', 'gidnumber',
'homedirectory', 'loginshell', 'uidnumber',
'ipantsecurityidentifier',
},
},
'System: Manage Service Resource Delegation Permissions': {
'ipapermright': {'read', 'search', 'compare', 'write'},
'ipapermdefaultattr': {
'ipaallowedtoperform;write_delegation',
'objectclass'
},
'default_privileges': {'Service Administrators',
'Host Administrators'},
},
'System: Manage Service Resource Delegation': {
'ipapermright': {'write', 'delete'},
'ipapermdefaultattr': {'memberPrincipal', 'objectclass'},
'default_privileges': {'Service Administrators',
'Host Administrators'},
}
}
label = _('Services')
label_singular = _('Service')
takes_params = (
Principal(
'krbcanonicalname',
validate_realm,
cli_name='canonical_principal',
label=_('Principal name'),
doc=_('Service principal'),
primary_key=True,
normalizer=normalize_principal,
require_service=True
),
Principal(
'krbprincipalname*',
validate_realm,
cli_name='principal',
label=_('Principal alias'),
doc=_('Service principal alias'),
normalizer=normalize_principal,
require_service=True,
flags={'no_create'}
),
Str(
'memberprincipal*',
cli_name='principal',
label=_('Delegation principal'),
doc=_('Delegation principal'),
normalizer=normalize_principal,
flags={'no_create', 'no_update', 'no_search'}
),
Certificate('usercertificate*',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded service certificate'),
flags=['no_search',],
),
Str('subject',
label=_('Subject'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('serial_number',
label=_('Serial Number'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('serial_number_hex',
label=_('Serial Number (hex)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('issuer',
label=_('Issuer'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('valid_not_before',
label=_('Not Before'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('valid_not_after',
label=_('Not After'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('sha1_fingerprint',
label=_('Fingerprint (SHA1)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('sha256_fingerprint',
label=_('Fingerprint (SHA256)'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('revocation_reason?',
label=_('Revocation reason'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
StrEnum('ipakrbauthzdata*',
cli_name='pac_type',
label=_('PAC type'),
doc=_("Override default list of supported PAC types."
" Use 'NONE' to disable PAC support for this service,"
" e.g. this might be necessary for NFS services."),
values=(u'MS-PAC', u'PAD', u'NONE'),
),
StrEnum(
'krbprincipalauthind*',
cli_name='auth_ind',
label=_('Authentication Indicators'),
doc=_("Defines an allow list for Authentication Indicators."
" Use 'otp' to allow OTP-based 2FA authentications."
" Use 'radius' to allow RADIUS-based 2FA authentications."
" Use 'pkinit' to allow PKINIT-based 2FA authentications."
" Use 'hardened' to allow brute-force hardened password"
" authentication by SPAKE or FAST."
" Use 'idp' to allow authentication against an external"
" Identity Provider supporting OAuth 2.0 Device"
" Authorization Flow (RFC 8628)."
" Use 'passkey' to allow passkey-based 2FA authentications."
" With no indicator specified,"
" all authentication mechanisms are allowed."),
values=(u'radius', u'otp', u'pkinit', u'hardened', u'idp',
u'passkey'),
),
) + ticket_flags_params
def validate_ipakrbauthzdata(self, entry):
new_value = entry.get('ipakrbauthzdata', [])
if not new_value:
return
if not isinstance(new_value, (list, tuple)):
new_value = set([new_value])
else:
new_value = set(new_value)
if u'NONE' in new_value and len(new_value) > 1:
raise errors.ValidationError(name='ipakrbauthzdata',
error=_('NONE value cannot be combined with other PAC types'))
def get_dn(self, *keys, **kwargs):
key = keys[0]
if isinstance(key, str):
key = kerberos.Principal(key)
key = unicode(normalize_principal(key))
parent_dn = DN(self.container_dn, self.api.env.basedn)
true_rdn = 'krbprincipalname'
return self.backend.make_dn_from_attr(
true_rdn, key, parent_dn
)
def get_primary_key_from_dn(self, dn):
"""
If the entry has krbcanonicalname set return the value of the
attribute. If the attribute is not found, assume old-style entry which
should have only single value of krbprincipalname and return it.
Otherwise return input DN.
"""
assert isinstance(dn, DN)
try:
entry_attrs = self.backend.get_entry(
dn, [self.primary_key.name]
)
try:
return entry_attrs[self.primary_key.name][0]
except (KeyError, IndexError):
return ''
except errors.NotFound:
pass
try:
return dn['krbprincipalname']
except KeyError:
return unicode(dn)
def populate_krbcanonicalname(self, entry_attrs, options):
if options.get('raw', False):
return
entry_attrs.setdefault(
'krbcanonicalname', entry_attrs['krbprincipalname'])
@register()
class service_add(LDAPCreate):
__doc__ = _('Add a new IPA service.')
msg_summary = _('Added service "%(value)s"')
member_attributes = ['managedby']
has_output_params = LDAPCreate.has_output_params + output_params
takes_options = LDAPCreate.takes_options + (
Flag('force',
label=_('Force'),
doc=_('force principal name even if host not in DNS'),
),
Flag('skip_host_check',
label=_('Skip host check'),
doc=_('force service to be created even when host '
'object does not exist to manage it'),
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
principal = keys[-1]
hostname = principal.hostname
if principal.is_host and not options['force']:
raise errors.HostService()
if not options['skip_host_check']:
try:
hostresult = self.api.Command['host_show'](hostname)['result']
except errors.NotFound:
raise errors.NotFound(reason=_(
"The host '%s' does not exist to add a service to.") %
hostname)
self.obj.validate_ipakrbauthzdata(entry_attrs)
validate_auth_indicator(entry_attrs)
if not options.get('force', False):
# We know the host exists if we've gotten this far but we
# really want to discourage creating services for hosts that
# don't exist in DNS.
util.verify_host_resolvable(hostname)
if not (options['skip_host_check'] or 'managedby' in entry_attrs):
entry_attrs['managedby'] = hostresult['dn']
# Enforce ipaKrbPrincipalAlias to aid case-insensitive searches
# as krbPrincipalName/krbCanonicalName are case-sensitive in Kerberos
# schema
entry_attrs['ipakrbprincipalalias'] = keys[-1]
# Objectclass ipakrbprincipal providing ipakrbprincipalalias is not in
# in a list of default objectclasses, add it manually
entry_attrs['objectclass'].append('ipakrbprincipal')
# set krbcanonicalname attribute to enable principal canonicalization
util.set_krbcanonicalname(entry_attrs)
update_krbticketflags(ldap, entry_attrs, attrs_list, options, False)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return dn
@register()
class service_add_smb(LDAPCreate):
__doc__ = _('Add a new SMB service.')
msg_summary = _('Added service "%(value)s"')
member_attributes = ['managedby']
has_output_params = LDAPCreate.has_output_params + output_params
smb_takes_args = (
Str('fqdn', util.hostname_validator,
cli_name='hostname',
label=_('Host name'),
primary_key=True,
normalizer=util.normalize_hostname,
flags={'virtual_attribute', 'no_display', 'no_update',
'no_search'},
),
Str('ipantflatname?',
cli_name='netbiosname',
label=_('SMB service NetBIOS name'),
flags={'virtual_attribute', 'no_display', 'no_update',
'no_search'},
),
)
takes_options = LDAPCreate.takes_options
def get_args(self):
"""
Rewrite arguments to service-add-smb command to make sure we accept
hostname instead of a principal as we'll be constructing the principal
ourselves
"""
for arg in self.smb_takes_args:
yield arg
for arg in super(service_add_smb, self).get_args():
if arg not in self.smb_takes_args and not arg.primary_key:
yield arg
def get_options(self):
"""
Rewrite options to service-add-smb command to filter out cannonical
principal which is autoconstructed. Also filter out options which
make no sense for SMB service.
"""
excluded = ('ipakrbauthzdata', 'krbprincipalauthind',
'ipakrbrequirespreauth')
for arg in self.takes_options:
yield arg
for arg in super(service_add_smb, self).get_options():
check = all([arg not in self.takes_options,
not arg.primary_key,
arg.name not in excluded])
if check:
yield arg
def pre_callback(self, ldap, dn, entry_attrs, attrs_list,
*keys, **options):
assert isinstance(dn, DN)
hostname = keys[0]
if len(keys) == 2:
netbiosname = keys[1]
else:
# By default take leftmost label from the host name
netbiosname = DNSName.from_text(hostname)[0].decode().upper()
# SMB service requires existence of the host object
# because DCE RPC calls authenticated with GSSAPI are using
# host/.. principal by default for validation
try:
hostresult = self.api.Command['host_show'](hostname)['result']
except errors.NotFound:
raise errors.NotFound(reason=_(
"The host '%s' does not exist to add a service to.") %
hostname)
# We cannot afford the host not being resolvable even for
# clustered environments with CTDB because the target name
# has to exist even in that case
util.verify_host_resolvable(hostname)
smbaccount = '{name}$'.format(name=netbiosname)
smbprincipal = 'cifs/{hostname}'.format(hostname=hostname)
entry_attrs['krbprincipalname'] = [
str(kerberos.Principal(smbprincipal, realm=self.api.env.realm)),
str(kerberos.Principal(smbaccount, realm=self.api.env.realm))]
entry_attrs['krbcanonicalname'] = entry_attrs['krbprincipalname'][0]
# Rewrite DN using proper rdn and new canonical name because when
# LDAPCreate.execute() was called, it set DN to krbcanonicalname=$value
dn = DN(('krbprincipalname', entry_attrs['krbcanonicalname']),
DN(self.obj.container_dn, api.env.basedn))
# Enforce ipaKrbPrincipalAlias to aid case-insensitive searches as
# krbPrincipalName/krbCanonicalName are case-sensitive in Kerberos
# schema
entry_attrs['ipakrbprincipalalias'] = entry_attrs['krbcanonicalname']
for o in ('ipakrbprincipal', 'ipaidobject', 'krbprincipalaux',
'posixaccount'):
if o not in entry_attrs['objectclass']:
entry_attrs['objectclass'].append(o)
entry_attrs['uid'] = ['/'.join(
kerberos.Principal(smbprincipal).components)]
entry_attrs['uid'].append(smbaccount)
entry_attrs['cn'] = netbiosname
entry_attrs['homeDirectory'] = '/dev/null'
entry_attrs['uidNumber'] = DNA_MAGIC
entry_attrs['gidNumber'] = DNA_MAGIC
self.obj.validate_ipakrbauthzdata(entry_attrs)
if 'managedby' not in entry_attrs:
entry_attrs['managedby'] = hostresult['dn']
update_krbticketflags(ldap, entry_attrs, attrs_list, options, False)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return dn
@register()
class service_del(LDAPDelete):
__doc__ = _('Delete an IPA service.')
msg_summary = _('Deleted service "%(value)s"')
member_attributes = ['managedby']
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
# In the case of services we don't want IPA master services to be
# deleted. This is a limited few though. If the user has their own
# custom services allow them to manage them.
check_required_principal(ldap, keys[-1])
if self.api.Command.ca_is_enabled()['result']:
certs = self.api.Command.cert_find(service=keys)['result']
revoke_certs(certs)
return dn
@register()
class service_mod(LDAPUpdate):
__doc__ = _('Modify an existing IPA service.')
msg_summary = _('Modified service "%(value)s"')
takes_options = LDAPUpdate.takes_options
has_output_params = LDAPUpdate.has_output_params + output_params
member_attributes = ['managedby']
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
self.obj.validate_ipakrbauthzdata(entry_attrs)
validate_auth_indicator(entry_attrs)
# verify certificates
certs = entry_attrs.get('usercertificate') or []
# revoke removed certificates
ca_is_enabled = self.api.Command.ca_is_enabled()['result']
if 'usercertificate' in options and ca_is_enabled:
try:
entry_attrs_old = ldap.get_entry(dn, ['usercertificate'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
old_certs = entry_attrs_old.get('usercertificate', [])
removed_certs = set(old_certs) - set(certs)
for cert in removed_certs:
rm_certs = api.Command.cert_find(
certificate=cert.public_bytes(x509.Encoding.DER),
service=keys)['result']
revoke_certs(rm_certs)
if certs:
entry_attrs['usercertificate'] = certs
update_krbticketflags(ldap, entry_attrs, attrs_list, options, True)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
set_certificate_attrs(entry_attrs)
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return dn
@register()
class service_find(LDAPSearch):
__doc__ = _('Search for IPA services.')
msg_summary = ngettext(
'%(count)d service matched', '%(count)d services matched', 0
)
member_attributes = ['managedby']
sort_result_entries = False
takes_options = LDAPSearch.takes_options
has_output_params = LDAPSearch.has_output_params + output_params
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
# lisp style!
custom_filter = '(&(objectclass=ipaService)' \
'(!(|(krbprincipalname=kadmin/*)' \
'(krbprincipalname=K/M@*)' \
'(krbprincipalname=krbtgt/*))' \
')' \
')'
if options.get('pkey_only', False):
attrs_list.append('krbprincipalname')
return (
ldap.combine_filters((custom_filter, filter), rules=ldap.MATCH_ALL),
base_dn, scope
)
def post_callback(self, ldap, entries, truncated, *args, **options):
# we have to sort entries manually instead of relying on inherited
# mechanisms
def sort_key(x):
if 'krbcanonicalname' in x:
return x['krbcanonicalname'][0]
else:
return x['krbprincipalname'][0]
entries.sort(key=sort_key)
if options.get('pkey_only', False):
return truncated
for entry_attrs in entries:
self.obj.get_password_attributes(ldap, entry_attrs.dn, entry_attrs)
principal = entry_attrs['krbprincipalname']
if isinstance(principal, (tuple, list)):
principal = principal[0]
try:
set_certificate_attrs(entry_attrs)
except errors.CertificateFormatError as e:
self.add_message(
messages.CertificateInvalid(
subject=principal,
reason=e
)
)
logger.error("Invalid certificate: %s", e)
del(entry_attrs['usercertificate'])
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return truncated
@register()
class service_show(LDAPRetrieve):
__doc__ = _('Display information about an IPA service.')
member_attributes = ['managedby']
takes_options = LDAPRetrieve.takes_options + (
Str('out?',
doc=_('file to store certificate in'),
),
)
has_output_params = LDAPRetrieve.has_output_params + output_params
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.get_password_attributes(ldap, dn, entry_attrs)
principal = entry_attrs['krbprincipalname']
if isinstance(principal, (tuple, list)):
principal = principal[0]
try:
set_certificate_attrs(entry_attrs)
except errors.CertificateFormatError as e:
self.add_message(
messages.CertificateInvalid(
subject=principal,
reason=e,
)
)
logger.error("Invalid certificate: %s", e)
del(entry_attrs['usercertificate'])
set_kerberos_attrs(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return dn
@register()
class service_add_host(LDAPAddMember):
__doc__ = _('Add hosts that can manage this service.')
member_attributes = ['managedby']
has_output_params = LDAPAddMember.has_output_params + output_params
@register()
class service_remove_host(LDAPRemoveMember):
__doc__ = _('Remove hosts that can manage this service.')
member_attributes = ['managedby']
has_output_params = LDAPRemoveMember.has_output_params + output_params
@register()
class service_allow_retrieve_keytab(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to retrieve a keytab'
' of this service.')
member_attributes = ['ipaallowedtoperform_read_keys']
has_output_params = LDAPAddMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return (completed, dn)
@register()
class service_disallow_retrieve_keytab(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to retrieve a '
'keytab of this service.')
member_attributes = ['ipaallowedtoperform_read_keys']
has_output_params = LDAPRemoveMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return (completed, dn)
@register()
class service_allow_create_keytab(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to create a keytab '
'of this service.')
member_attributes = ['ipaallowedtoperform_write_keys']
has_output_params = LDAPAddMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return (completed, dn)
@register()
class service_disallow_create_keytab(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to create a '
'keytab of this service.')
member_attributes = ['ipaallowedtoperform_write_keys']
has_output_params = LDAPRemoveMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
self.obj.populate_krbcanonicalname(entry_attrs, options)
return (completed, dn)
@register()
class service_disable(LDAPQuery):
__doc__ = _('Disable the Kerberos key and SSL certificate of a service.')
has_output = output.standard_value
msg_summary = _('Disabled service "%(value)s"')
has_output_params = LDAPQuery.has_output_params + output_params
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
entry_attrs = ldap.get_entry(dn, ['usercertificate'])
check_required_principal(ldap, keys[-1])
# See if we do any work at all here and if not raise an exception
done_work = False
if self.api.Command.ca_is_enabled()['result']:
certs = self.api.Command.cert_find(service=keys)['result']
if len(certs) > 0:
revoke_certs(certs)
# Remove the usercertificate altogether
entry_attrs['usercertificate'] = None
ldap.update_entry(entry_attrs)
done_work = True
self.obj.get_password_attributes(ldap, dn, entry_attrs)
if entry_attrs['has_keytab']:
ldap.remove_principal_key(dn)
done_work = True
if not done_work:
raise errors.AlreadyInactive()
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class service_add_cert(LDAPAddAttributeViaOption):
__doc__ = _('Add new certificates to a service')
msg_summary = _('Added certificates to service principal "%(value)s"')
attribute = 'usercertificate'
@register()
class service_remove_cert(LDAPRemoveAttributeViaOption):
__doc__ = _('Remove certificates from a service')
msg_summary = _('Removed certificates from service principal "%(value)s"')
attribute = 'usercertificate'
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
for cert in options.get('usercertificate', []):
revoke_certs(api.Command.cert_find(
certificate=cert,
service=keys)['result'])
return dn
@register()
class service_add_principal(LDAPAddAttribute):
__doc__ = _('Add new principal alias to a service')
msg_summary = _('Added new aliases to the service principal "%(value)s"')
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.check_principal_realm_in_trust_namespace(self.api, *keys)
util.ensure_krbcanonicalname_set(ldap, entry_attrs)
return dn
@register()
class service_remove_principal(LDAPRemoveAttribute):
__doc__ = _('Remove principal alias from a service')
msg_summary = _('Removed aliases to the service principal "%(value)s"')
attribute = 'krbprincipalname'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.ensure_last_krbprincipalname(ldap, entry_attrs, *keys)
return dn
@register()
class service_add_delegation(LDAPAddAttribute):
__doc__ = _('Add new resource delegation to a service')
msg_summary = _('Added new resource delegation to '
'the service principal "%(value)s"')
attribute = 'memberprincipal'
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
util.check_principal_realm_supported(
self.api, *keys, attr_name=self.attribute)
if self.attribute in entry_attrs:
add_missing_object_class(ldap, 'resourcedelegation', dn)
return dn
@register()
class service_remove_delegation(LDAPRemoveAttribute):
__doc__ = _('Remove resource delegation from a service')
msg_summary = _('Removed resource delegation from '
'the service principal "%(value)s"')
attribute = 'memberprincipal'
@register()
class service_allow_add_delegation(LDAPAddMember):
__doc__ = _('Allow users, groups, hosts or host groups to handle a '
'resource delegation of this service.')
member_attributes = ['ipaallowedtoperform_write_delegation']
has_output_params = LDAPAddMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
add_missing_object_class(ldap, u'ipaallowedoperations', dn)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
@register()
class service_disallow_add_delegation(LDAPRemoveMember):
__doc__ = _('Disallow users, groups, hosts or host groups to handle a '
'resource delegation of this service.')
member_attributes = ['ipaallowedtoperform_write_delegation']
has_output_params = LDAPRemoveMember.has_output_params + output_params
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
rename_ipaallowedtoperform_to_ldap(found)
rename_ipaallowedtoperform_to_ldap(not_found)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
rename_ipaallowedtoperform_from_ldap(entry_attrs, options)
rename_ipaallowedtoperform_from_ldap(failed, options)
return (completed, dn)
| 48,861
|
Python
|
.py
| 1,097
| 35.466727
| 285
| 0.632546
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,861
|
serverrole.py
|
freeipa_freeipa/ipaserver/plugins/serverrole.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from ipalib.crud import Retrieve, Search
from ipalib.errors import NotFound
from ipalib.frontend import Object
from ipalib.parameters import Flag, Int, Str, StrEnum
from ipalib.plugable import Registry
from ipalib import _, ngettext
__doc__ = _("""
IPA server roles
""") + _("""
Get status of roles (DNS server, CA, etc.) provided by IPA masters.
""") + _("""
The status of a role is either enabled, configured, or absent.
""") + _("""
EXAMPLES:
""") + _("""
Show status of 'DNS server' role on a server:
ipa server-role-show ipa.example.com "DNS server"
""") + _("""
Show status of all roles containing 'AD' on a server:
ipa server-role-find --server ipa.example.com --role="AD trust controller"
""") + _("""
Show status of all configured roles on a server:
ipa server-role-find ipa.example.com
""") + _("""
Show implicit IPA master role:
ipa server-role-find --include-master
""")
register = Registry()
@register()
class server_role(Object):
"""
association between certain role (e.g. DNS server) and its status with
an IPA master
"""
backend_name = 'serverroles'
object_name = _('server role')
object_name_plural = _('server roles')
default_attributes = [
'role', 'status'
]
label = _('IPA Server Roles')
label_singular = _('IPA Server Role')
takes_params = (
Str(
'server_server',
cli_name='server',
label=_('Server name'),
doc=_('IPA server hostname'),
),
Str(
'role_servrole',
cli_name='role',
label=_("Role name"),
doc=_("IPA server role name"),
flags={u'virtual_attribute'}
),
StrEnum(
'status?',
cli_name='status',
label=_('Role status'),
doc=_('Status of the role'),
values=(u'enabled', u'configured', u'hidden', u'absent'),
default=u'enabled',
flags={'virtual_attribute', 'no_create', 'no_update'}
)
)
def ensure_master_exists(self, fqdn):
server_obj = self.api.Object.server
try:
server_obj.get_dn_if_exists(fqdn)
except NotFound:
raise server_obj.handle_not_found(fqdn)
@register()
class server_role_show(Retrieve):
__doc__ = _('Show role status on a server')
obj_name = 'server_role'
attr_name = 'show'
def get_args(self):
for arg in super(server_role_show, self).get_args():
yield arg
for param in self.obj.params():
if param.name != u'status':
yield param.clone()
def execute(self, *keys, **options):
self.obj.ensure_master_exists(keys[0])
role_status = self.obj.backend.server_role_retrieve(
server_server=keys[0], role_servrole=keys[1])
return dict(result=role_status[0], value=None)
@register()
class server_role_find(Search):
__doc__ = _('Find a server role on a server(s)')
obj_name = 'server_role'
attr_name = 'find'
msg_summary = ngettext('%(count)s server role matched',
'%(count)s server roles matched', 0)
takes_options = Search.takes_options + (
Int(
'timelimit?',
label=_('Time Limit'),
doc=_('Time limit of search in seconds (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
Int(
'sizelimit?',
label=_('Size Limit'),
doc=_('Maximum number of entries returned (0 is unlimited)'),
flags=['no_display'],
minvalue=0,
autofill=False,
),
Flag(
'include_master',
doc=_('Include IPA master entries'),
)
)
def execute(self, *keys, **options):
if keys:
return dict(
result=[],
count=0,
truncated=False
)
server = options.get('server_server', None)
role_name = options.get('role_servrole', None)
status = options.get('status', None)
if server is not None:
self.obj.ensure_master_exists(server)
role_status = self.obj.backend.server_role_search(
server_server=server,
role_servrole=role_name,
status=status)
# Don't display "IPA master" information unless the role is
# requested explicitly. All servers are considered IPA masters,
# except for replicas during installation.
if options.get('include_master') or role_name == "IPA master":
result = role_status
else:
result = [
r for r in role_status
if r[u'role_servrole'] != "IPA master"
]
return dict(
result=result,
count=len(result),
truncated=False,
)
@register()
class servrole(Object):
"""
Server role object
"""
object_name = _('role')
object_name_plural = _('roles')
takes_params = (
Str(
'name',
primary_key=True,
label=_("Role name"),
doc=_("IPA role name"),
flags=(u'virtual_attribute',)
),
)
| 5,384
|
Python
|
.py
| 167
| 23.94012
| 78
| 0.562343
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,862
|
otp.py
|
freeipa_freeipa/ipaserver/plugins/otp.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from ipalib.text import _
__doc__ = _('One time password commands')
| 141
|
Python
|
.py
| 5
| 26.8
| 66
| 0.738806
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,863
|
certmap.py
|
freeipa_freeipa/ipaserver/plugins/certmap.py
|
# Authors:
# Florence Blanc-Renaud <flo@redhat.com>
#
# Copyright (C) 2017 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 logging
import dbus
import six
from cryptography import x509 as crypto_x509
from ipalib import api, errors, x509
from ipalib.crud import Search
from ipalib.frontend import Object
from ipalib.parameters import Bool, DNSNameParam, Flag, Int, Str, Certificate
from ipalib.plugable import Registry
from .baseldap import (
LDAPCreate,
LDAPDelete,
LDAPObject,
LDAPQuery,
LDAPRetrieve,
LDAPSearch,
LDAPUpdate,
pkey_to_value)
from ipalib import _, ngettext
from ipalib import output
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
__doc__ = _("""
Certificate Identity Mapping
""") + _("""
Manage Certificate Identity Mapping configuration and rules.
""") + _("""
IPA supports the use of certificates for authentication. Certificates can
either be stored in the user entry (full certificate in the usercertificate
attribute), or simply linked to the user entry through a mapping.
This code enables the management of the rules allowing to link a
certificate to a user entry.
""") + _("""
EXAMPLES:
""") + _("""
Display the Certificate Identity Mapping global configuration:
ipa certmapconfig-show
""") + _("""
Modify Certificate Identity Mapping global configuration:
ipa certmapconfig-mod --promptusername=TRUE
""") + _("""
Create a new Certificate Identity Mapping Rule:
ipa certmaprule-add rule1 --desc="Link certificate with subject and issuer"
""") + _("""
Modify a Certificate Identity Mapping Rule:
ipa certmaprule-mod rule1 --maprule="<ALT-SEC-ID-I-S:altSecurityIdentities>"
""") + _("""
Disable a Certificate Identity Mapping Rule:
ipa certmaprule-disable rule1
""") + _("""
Enable a Certificate Identity Mapping Rule:
ipa certmaprule-enable rule1
""") + _("""
Display information about a Certificate Identity Mapping Rule:
ipa certmaprule-show rule1
""") + _("""
Find all Certificate Identity Mapping Rules with the specified domain:
ipa certmaprule-find --domain example.com
""") + _("""
Delete a Certificate Identity Mapping Rule:
ipa certmaprule-del rule1
""")
register = Registry()
def check_maprule_is_for_trusted_domain(api_inst, options, entry_attrs):
"""
Check that the certmap rule references altSecurityIdentities and
associateddomain in options is a trusted domain.
:param api_inst: API instance
:param options: options passed to the command
at least ipacertmapmaprule and
associateddomain options are expected for the check
:raises: ValidationError if altSecurityIdentities is present in the
rule but no Active Directory trusted domain listed in
associated domains
"""
is_trusted_domain_required = False
# If no explicit option passed, fallback to the content of the entry.
# This helps to catch cases when an associated domain value is removed
# while the rule requires its presence.
#
# In certmap-mod pre-callback we pass LDAPEntry instance instead of a dict
# LDAEntry.get() returns lists, even for single valued attrs. Using
# LDAPEntry.single_value would give us a single-valued result instead.
maprule_entry = entry_attrs
if not isinstance(maprule_entry, dict):
maprule_entry = entry_attrs.single_value
maprule = options.get('ipacertmapmaprule',
maprule_entry.get('ipacertmapmaprule'))
if maprule:
if 'altsecurityidentities' in maprule.lower():
is_trusted_domain_required = True
if is_trusted_domain_required:
domains = options.get('associateddomain',
entry_attrs.get('associateddomain'))
if domains:
trusted_domains = api_inst.Object.config.gather_trusted_domains()
trust_suffix_namespace = {dom_name.lower() for dom_name in
trusted_domains}
candidates = {str(dom).lower() for dom in domains}
invalid = candidates - trust_suffix_namespace
if invalid == candidates or len(trust_suffix_namespace) == 0:
raise errors.ValidationError(
name=_('domain'),
error=_('The domain(s) "%s" cannot be used to apply '
'altSecurityIdentities check.') %
", ".join(list(invalid))
)
else:
raise errors.ValidationError(
name=_('domain'),
error=_('The mapping rule with altSecurityIdentities '
'should be applied to a trusted Active Directory '
'domain but no domain was associated with the rule.')
)
def check_associateddomain_is_trusted(api_inst, options):
"""
Check that the associateddomain in options are either IPA domain or
a trusted domain.
:param api_inst: API instance
:param associateddomain: domains to be checked
:raises: ValidationError if the domain is neither IPA domain nor trusted
"""
domains = options.get('associateddomain')
if domains:
trusted_domains = api_inst.Object.config.gather_trusted_domains()
trust_suffix_namespace = {dom_name.lower() for dom_name in
trusted_domains}
trust_suffix_namespace.add(api_inst.env.domain.lower())
for dom in domains:
if not str(dom).lower() in trust_suffix_namespace:
raise errors.ValidationError(
name=_('domain'),
error=_('The domain %s is neither IPA domain nor a trusted'
'domain.') % dom
)
@register()
class certmapconfig(LDAPObject):
"""
Certificate Identity Mapping configuration object
"""
object_name = _('Certificate Identity Mapping configuration options')
default_attributes = ['ipacertmappromptusername']
container_dn = api.env.container_certmap
label = _('Certificate Identity Mapping Global Configuration')
label_singular = _('Certificate Identity Mapping Global Configuration')
takes_params = (
Bool(
'ipacertmappromptusername',
cli_name='promptusername',
label=_('Prompt for the username'),
doc=_('Prompt for the username when multiple identities'
' are mapped to a certificate'),
),
)
permission_filter_objectclasses = ['ipacertmapconfigobject']
managed_permissions = {
'System: Read Certmap Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipacertmappromptusername',
'cn',
},
},
'System: Modify Certmap Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'write'},
'ipapermdefaultattr': {
'ipacertmappromptusername',
},
'default_privileges': {
'Certificate Identity Mapping Administrators'},
},
}
@register()
class certmapconfig_mod(LDAPUpdate):
__doc__ = _('Modify Certificate Identity Mapping configuration.')
@register()
class certmapconfig_show(LDAPRetrieve):
__doc__ = _('Show the current Certificate Identity Mapping configuration.')
@register()
class certmaprule(LDAPObject):
"""
Certificate Identity Mapping Rules
"""
label = _('Certificate Identity Mapping Rules')
label_singular = _('Certificate Identity Mapping Rule')
object_name = _('Certificate Identity Mapping Rule')
object_name_plural = _('Certificate Identity Mapping Rules')
object_class = ['ipacertmaprule']
container_dn = api.env.container_certmaprules
default_attributes = [
'cn', 'description',
'ipacertmapmaprule',
'ipacertmapmatchrule',
'associateddomain',
'ipacertmappriority',
'ipaenabledflag'
]
search_attributes = [
'cn', 'description',
'ipacertmapmaprule',
'ipacertmapmatchrule',
'associateddomain',
'ipacertmappriority',
'ipaenabledflag'
]
takes_params = (
Str(
'cn',
cli_name='rulename',
primary_key=True,
label=_('Rule name'),
doc=_('Certificate Identity Mapping Rule name'),
),
Str(
'description?',
cli_name='desc',
label=_('Description'),
doc=_('Certificate Identity Mapping Rule description'),
),
Str(
'ipacertmapmaprule?',
cli_name='maprule',
label=_('Mapping rule'),
doc=_('Rule used to map the certificate with a user entry'),
),
Str(
'ipacertmapmatchrule?',
cli_name='matchrule',
label=_('Matching rule'),
doc=_('Rule used to check if a certificate can be used for'
' authentication'),
),
DNSNameParam(
'associateddomain*',
cli_name='domain',
label=_('Domain name'),
doc=_('Domain where the user entry will be searched'),
),
Int(
'ipacertmappriority?',
cli_name='priority',
label=_('Priority'),
doc=_('Priority of the rule (higher number means lower priority'),
minvalue=0,
),
Flag(
'ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
default=True
),
)
permission_filter_objectclasses = ['ipacertmaprule']
managed_permissions = {
'System: Add Certmap Rules': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'add'},
'default_privileges': {
'Certificate Identity Mapping Administrators'},
},
'System: Read Certmap Rules': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description',
'ipacertmapmaprule', 'ipacertmapmatchrule', 'associateddomain',
'ipacertmappriority', 'ipaenabledflag',
},
},
'System: Delete Certmap Rules': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'delete'},
'default_privileges': {
'Certificate Identity Mapping Administrators'},
},
'System: Modify Certmap Rules': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'write'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'description',
'ipacertmapmaprule', 'ipacertmapmatchrule', 'associateddomain',
'ipacertmappriority', 'ipaenabledflag',
},
'default_privileges': {
'Certificate Identity Mapping Administrators'},
},
}
@register()
class certmaprule_add(LDAPCreate):
__doc__ = _('Create a new Certificate Identity Mapping Rule.')
msg_summary = _('Added Certificate Identity Mapping Rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
check_associateddomain_is_trusted(self.api, options)
check_maprule_is_for_trusted_domain(self.api, options, entry_attrs)
return dn
@register()
class certmaprule_mod(LDAPUpdate):
__doc__ = _('Modify a Certificate Identity Mapping Rule.')
msg_summary = _('Modified Certificate Identity Mapping Rule "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
check_associateddomain_is_trusted(self.api, options)
# For update of the existing certmaprule we need to retrieve
# content of the LDAP entry because modification may affect two cases:
# - altSecurityIdentities might be removed by the modification
# - trusted domains may be removed by the modification while they
# should be in place
#
# For both these cases we need to know actual content of the entry but
# LDAPUpdate.execute() provides us with entry_attrs built from the
# options, not the original content.
entry = ldap.get_entry(dn)
check_maprule_is_for_trusted_domain(self.api, options, entry)
return dn
@register()
class certmaprule_find(LDAPSearch):
__doc__ = _('Search for Certificate Identity Mapping Rules.')
msg_summary = ngettext(
'%(count)d Certificate Identity Mapping Rule matched',
'%(count)d Certificate Identity Mapping Rules matched', 0
)
@register()
class certmaprule_show(LDAPRetrieve):
__doc__ = _('Display information about a Certificate Identity Mapping'
' Rule.')
@register()
class certmaprule_del(LDAPDelete):
__doc__ = _('Delete a Certificate Identity Mapping Rule.')
msg_summary = _('Deleted Certificate Identity Mapping Rule "%(value)s"')
@register()
class certmaprule_enable(LDAPQuery):
__doc__ = _('Enable a Certificate Identity Mapping Rule.')
msg_summary = _('Enabled Certificate Identity Mapping Rule "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [True]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class certmaprule_disable(LDAPQuery):
__doc__ = _('Disable a Certificate Identity Mapping Rule.')
msg_summary = _('Disabled Certificate Identity Mapping Rule "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [False]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return dict(
result=True,
value=pkey_to_value(cn, options),
)
DBUS_SSSD_NAME = 'org.freedesktop.sssd.infopipe'
DBUS_PROPERTY_IF = 'org.freedesktop.DBus.Properties'
DBUS_SSSD_USERS_PATH = '/org/freedesktop/sssd/infopipe/Users'
DBUS_SSSD_USERS_IF = 'org.freedesktop.sssd.infopipe.Users'
DBUS_SSSD_USER_IF = 'org.freedesktop.sssd.infopipe.Users.User'
class _sssd:
"""
Auxiliary class for SSSD infopipe DBus.
"""
def __init__(self):
"""
Initialize the Users object and interface.
:raise RemoteRetrieveError: if DBus error occurs
"""
try:
self._bus = dbus.SystemBus()
self._users_obj = self._bus.get_object(
DBUS_SSSD_NAME, DBUS_SSSD_USERS_PATH)
self._users_iface = dbus.Interface(
self._users_obj, DBUS_SSSD_USERS_IF)
except dbus.DBusException as e:
logger.error(
'Failed to initialize DBus interface %s. DBus '
'exception is %s.', DBUS_SSSD_USERS_IF, e
)
raise errors.RemoteRetrieveError(
reason=_('Failed to connect to sssd over SystemBus. '
'See details in the error_log'))
def list_users_by_cert(self, cert):
"""
Look for users matching the cert.
Call Users.ListByCertificate interface and return a dict
with key = domain, value = list of uids
corresponding to the users matching the provided cert
:param cert: DER cert, Certificate instances (IPACertificate)
:raise RemoteRetrieveError: if DBus error occurs
"""
if isinstance(cert, crypto_x509.Certificate):
cert_pem = cert.public_bytes(x509.Encoding.PEM)
else:
cert_obj = x509.load_der_x509_certificate(cert)
cert_pem = cert_obj.public_bytes(x509.Encoding.PEM)
try:
# bug 3306 in sssd returns 0 entry when max_entries = 0
# Temp workaround is to use a non-null value, not too high
# to avoid reserving unneeded memory
max_entries = dbus.UInt32(100)
user_paths = self._users_iface.ListByCertificate(
cert_pem, max_entries)
users = dict()
for user_path in user_paths:
user_obj = self._bus.get_object(DBUS_SSSD_NAME, user_path)
user_iface = dbus.Interface(user_obj, DBUS_PROPERTY_IF)
user_login = user_iface.Get(DBUS_SSSD_USER_IF, 'name')
# Extract name@domain
items = user_login.split('@')
domain = api.env.realm if len(items) < 2 else items[1]
name = items[0]
# Retrieve the list of users for the given domain,
# or initialize to an empty list
# and add the name
users_for_dom = users.setdefault(domain, list())
users_for_dom.append(name)
return users
except dbus.DBusException as e:
err_name = e.get_dbus_name()
# If there is no matching user, do not consider this as an
# exception and return an empty list
if err_name == 'org.freedesktop.sssd.Error.NotFound':
return dict()
logger.error(
'Failed to use interface %s. DBus '
'exception is %s.', DBUS_SSSD_USERS_IF, e)
raise errors.RemoteRetrieveError(
reason=_('Failed to find users over SystemBus. '
' See details in the error_log'))
@register()
class certmap(Object):
"""
virtual object for certmatch_map API
"""
takes_params = (
DNSNameParam(
'domain',
label=_('Domain'),
flags={'no_search'},
),
Str(
'uid*',
label=_('User logins'),
flags={'no_search'},
),
)
@register()
class certmap_match(Search):
__doc__ = _("""
Search for users matching the provided certificate.
This command relies on SSSD to retrieve the list of matching users and
may return cached data. For more information on purging SSSD cache,
please refer to sss_cache documentation.
""")
msg_summary = ngettext('%(count)s user matched',
'%(count)s users matched', 0)
def get_summary_default(self, output):
"""
Need to sum the numbre of matching users for each domain.
"""
count = sum(len(entry['uid']) for entry in output['result'])
return self.msg_summary % dict(count=count)
def get_args(self):
for arg in super(certmap_match, self).get_args():
if arg.name == 'criteria':
continue
yield arg
yield Certificate(
'certificate',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded user certificate'),
flags=['virtual_attribute']
)
def execute(self, *args, **options):
"""
Search for users matching the provided certificate.
The search is performed using SSSD's DBus interface
Users.ListByCertificate.
SSSD does the lookup based on certificate mapping rules, using
IPA domain and trusted domains.
:raise RemoteRetrieveError: if DBus returns an exception
"""
sssd = _sssd()
cert = args[0]
users = sssd.list_users_by_cert(cert)
result = [{'domain': domain, 'uid': userlist}
for (domain, userlist) in users.items()]
count = len(result)
return dict(
result=result,
count=count,
truncated=False,
)
| 21,278
|
Python
|
.py
| 536
| 30.634328
| 79
| 0.616148
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,864
|
selinuxusermap.py
|
freeipa_freeipa/ipaserver/plugins/selinuxusermap.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
import re
from ipalib import api, errors
from ipalib import Str, StrEnum, Bool
from ipalib.plugable import Registry
from .baseldap import (
pkey_to_value,
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPQuery,
LDAPAddMember,
LDAPRemoveMember)
from ipalib import _, ngettext
from ipalib import output
from .hbacrule import is_all
from ipapython.dn import DN
from ipaplatform.constants import constants as platformconstants
__doc__ = _("""
SELinux User Mapping
Map IPA users to SELinux users by host.
Hosts, hostgroups, users and groups can be either defined within
the rule or it may point to an existing HBAC rule. When using
--hbacrule option to selinuxusermap-find an exact match is made on the
HBAC rule name, so only one or zero entries will be returned.
EXAMPLES:
Create a rule, "test1", that sets all users to xguest_u:s0 on the host "server":
ipa selinuxusermap-add --usercat=all --selinuxuser=xguest_u:s0 test1
ipa selinuxusermap-add-host --hosts=server.example.com test1
Create a rule, "test2", that sets all users to guest_u:s0 and uses an existing HBAC rule for users and hosts:
ipa selinuxusermap-add --usercat=all --hbacrule=webserver --selinuxuser=guest_u:s0 test2
Display the properties of a rule:
ipa selinuxusermap-show test2
Create a rule for a specific user. This sets the SELinux context for
user john to unconfined_u:s0-s0:c0.c1023 on any machine:
ipa selinuxusermap-add --hostcat=all --selinuxuser=unconfined_u:s0-s0:c0.c1023 john_unconfined
ipa selinuxusermap-add-user --users=john john_unconfined
Disable a rule:
ipa selinuxusermap-disable test1
Enable a rule:
ipa selinuxusermap-enable test1
Find a rule referencing a specific HBAC rule:
ipa selinuxusermap-find --hbacrule=allow_some
Remove a rule:
ipa selinuxusermap-del john_unconfined
SEEALSO:
The list controlling the order in which the SELinux user map is applied
and the default SELinux user are available in the config-show command.
""")
register = Registry()
notboth_err = _('HBAC rule and local members cannot both be set')
def validate_selinuxuser(ugettext, user):
"""
An SELinux user has 3 components: user:MLS:MCS. user and MLS are required.
user traditionally ends with _u but this is not mandatory.
The regex is {name}
The MLS part can only be:
Level: {mls}
MaxLevel: {mls_max}
Then MCS could be {mcs}
MaxCat: {mcs_max}
Returns a message on invalid, returns nothing on valid.
""".format(
name=platformconstants.SELINUX_USER_REGEX,
mls=platformconstants.SELINUX_MLS_REGEX,
mls_max=platformconstants.SELINUX_MLS_MAX,
mcs=platformconstants.SELINUX_MCS_REGEX,
mcs_max=platformconstants.SELINUX_MCS_MAX,
)
SELINUX_MCS_MAX = platformconstants.SELINUX_MCS_MAX
SELINUX_MCS_REGEX = platformconstants.SELINUX_MCS_REGEX
SELINUX_MLS_MAX = platformconstants.SELINUX_MLS_MAX
SELINUX_MLS_REGEX = platformconstants.SELINUX_MLS_REGEX
SELINUX_USER_REGEX = platformconstants.SELINUX_USER_REGEX
regex_name = re.compile(SELINUX_USER_REGEX)
regex_mls = re.compile(SELINUX_MLS_REGEX)
regex_mcs = re.compile(SELINUX_MCS_REGEX)
# If we add in ::: we don't have to check to see if some values are
# empty
(name, mls, mcs, _ignore) = (user + ':::').split(':', 3)
if not regex_name.match(name):
return _('Invalid SELinux user name, must match {}').format(
SELINUX_USER_REGEX)
def _validate_level(level, level_regex, upper_limit):
if not level_regex.match(level):
return False
for m in re.finditer(r'\d+', level):
if int(m.group()) > upper_limit:
return False
return True
if not mls or not _validate_level(mls, regex_mls, SELINUX_MLS_MAX):
return _(
'Invalid MLS value, must match {mls}, where max level '
'{mls_max}').format(mls=SELINUX_MLS_REGEX, mls_max=SELINUX_MLS_MAX)
if mcs and not _validate_level(mcs, regex_mcs, SELINUX_MCS_MAX):
return _(
'Invalid MCS value, must match {mcs}, where max category '
'{mcs_max}').format(mcs=SELINUX_MCS_REGEX, mcs_max=SELINUX_MCS_MAX)
return None
def validate_selinuxuser_inlist(ldap, user):
"""
Ensure the user is in the list of allowed SELinux users.
Returns nothing if the user is found, raises an exception otherwise.
"""
config = ldap.get_ipa_config()
item = config.get('ipaselinuxusermaporder', [])
if len(item) != 1:
raise errors.NotFound(reason=_('SELinux user map list not '
'found in configuration'))
userlist = item[0].split('$')
if user not in userlist:
raise errors.NotFound(
reason=_('SELinux user %(user)s not found in '
'ordering list (in config)') % dict(user=user))
@register()
class selinuxusermap(LDAPObject):
"""
SELinux User Map object.
"""
container_dn = api.env.container_selinux
object_name = _('SELinux User Map rule')
object_name_plural = _('SELinux User Map rules')
object_class = ['ipaassociation', 'ipaselinuxusermap']
permission_filter_objectclasses = ['ipaselinuxusermap']
default_attributes = [
'cn', 'ipaenabledflag',
'description', 'usercategory', 'hostcategory',
'ipaenabledflag', 'memberuser', 'memberhost',
'seealso', 'ipaselinuxuser',
]
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
attribute_members = {
'memberuser': ['user', 'group'],
'memberhost': ['host', 'hostgroup'],
}
managed_permissions = {
'System: Read SELinux User Maps': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'accesstime', 'cn', 'description', 'hostcategory',
'ipaenabledflag', 'ipaselinuxuser', 'ipauniqueid',
'memberhost', 'memberuser', 'seealso', 'usercategory',
'objectclass', 'member',
},
},
'System: Add SELinux User Maps': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Add SELinux User Maps";allow (add) groupdn = "ldap:///cn=Add SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
'System: Modify SELinux User Maps': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cn', 'ipaenabledflag', 'ipaselinuxuser', 'memberhost',
'memberuser', 'seealso'
},
'replaces': [
'(targetattr = "cn || memberuser || memberhost || seealso || ipaselinuxuser || ipaenabledflag")(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Modify SELinux User Maps";allow (write) groupdn = "ldap:///cn=Modify SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
'System: Remove SELinux User Maps': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///ipauniqueid=*,cn=usermap,cn=selinux,$SUFFIX")(version 3.0;acl "permission:Remove SELinux User Maps";allow (delete) groupdn = "ldap:///cn=Remove SELinux User Maps,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'SELinux User Map Administrators'},
},
}
# These maps will not show as members of other entries
label = _('SELinux User Maps')
label_singular = _('SELinux User Map')
takes_params = (
Str('cn',
cli_name='name',
label=_('Rule name'),
primary_key=True,
),
Str('ipaselinuxuser', validate_selinuxuser,
cli_name='selinuxuser',
label=_('SELinux User'),
),
Str('seealso?',
cli_name='hbacrule',
label=_('HBAC Rule'),
doc=_('HBAC Rule that defines the users, groups and hostgroups'),
),
StrEnum('usercategory?',
cli_name='usercat',
label=_('User category'),
doc=_('User category the rule applies to'),
values=(u'all', ),
),
StrEnum('hostcategory?',
cli_name='hostcat',
label=_('Host category'),
doc=_('Host category the rule applies to'),
values=(u'all', ),
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Bool('ipaenabledflag?',
label=_('Enabled'),
flags=['no_option'],
),
Str('memberuser_user?',
label=_('Users'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberuser_group?',
label=_('User Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_host?',
label=_('Hosts'),
flags=['no_create', 'no_update', 'no_search'],
),
Str('memberhost_hostgroup?',
label=_('Host Groups'),
flags=['no_create', 'no_update', 'no_search'],
),
)
def _normalize_seealso(self, seealso):
"""
Given a HBAC rule name verify its existence and return the dn.
"""
if not seealso:
return None
try:
dn = DN(seealso)
return str(dn)
except ValueError:
try:
entry_attrs = self.backend.find_entry_by_attr(
self.api.Object['hbacrule'].primary_key.name,
seealso,
self.api.Object['hbacrule'].object_class,
[''],
DN(self.api.Object['hbacrule'].container_dn, api.env.basedn))
seealso = entry_attrs.dn
except errors.NotFound:
raise errors.NotFound(reason=_('HBAC rule %(rule)s not found') % dict(rule=seealso))
return seealso
def _convert_seealso(self, ldap, entry_attrs, **options):
"""
Convert an HBAC rule dn into a name
"""
if options.get('raw', False):
return
if 'seealso' in entry_attrs:
hbac_attrs = ldap.get_entry(entry_attrs['seealso'][0], ['cn'])
entry_attrs['seealso'] = hbac_attrs['cn'][0]
@register()
class selinuxusermap_add(LDAPCreate):
__doc__ = _('Create a new SELinux User Map.')
msg_summary = _('Added SELinux User Map "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# rules are enabled by default
entry_attrs['ipaenabledflag'] = True
validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])
def is_to_be_set(x):
"""hbacrule is not allowed when usercat or hostcat is set"""
return x in entry_attrs and entry_attrs[x] is not None
are_local_members_to_be_set = any(is_to_be_set(attr)
for attr in ('usercategory',
'hostcategory'))
is_hbacrule_to_be_set = is_to_be_set('seealso')
if is_hbacrule_to_be_set and are_local_members_to_be_set:
raise errors.MutuallyExclusiveError(reason=notboth_err)
if is_hbacrule_to_be_set:
entry_attrs['seealso'] = self.obj._normalize_seealso(entry_attrs['seealso'])
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_del(LDAPDelete):
__doc__ = _('Delete a SELinux User Map.')
msg_summary = _('Deleted SELinux User Map "%(value)s"')
@register()
class selinuxusermap_mod(LDAPUpdate):
__doc__ = _('Modify a SELinux User Map.')
msg_summary = _('Modified SELinux User Map "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
_entry_attrs = ldap.get_entry(dn, attrs_list)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
def is_to_be_deleted(x):
return (
(x in _entry_attrs and x in entry_attrs)
and entry_attrs[x] is None
)
# makes sure the local members and hbacrule is not set at the same time
# memberuser or memberhost could have been set using --setattr
def is_to_be_set(x):
return (
(
(x in _entry_attrs and _entry_attrs[x] is not None) or
(x in entry_attrs and entry_attrs[x] is not None)
)
and not is_to_be_deleted(x)
)
are_local_members_to_be_set = any(is_to_be_set(attr)
for attr in ('usercategory',
'hostcategory',
'memberuser',
'memberhost'))
is_hbacrule_to_be_set = is_to_be_set('seealso')
# this can disable all modifications if hbacrule and local members were
# set at the same time bypassing this commad, e.g. using ldapmodify
if are_local_members_to_be_set and is_hbacrule_to_be_set:
raise errors.MutuallyExclusiveError(reason=notboth_err)
if (is_all(entry_attrs, 'usercategory')
and 'memberuser' in entry_attrs):
raise errors.MutuallyExclusiveError(
reason="user category cannot be set to 'all' while there "
"are allowed users"
)
if (is_all(entry_attrs, 'hostcategory')
and 'memberhost' in entry_attrs):
raise errors.MutuallyExclusiveError(
reason="host category cannot be set to 'all' while there "
"are allowed hosts"
)
if 'ipaselinuxuser' in entry_attrs:
validate_selinuxuser_inlist(ldap, entry_attrs['ipaselinuxuser'])
if 'seealso' in entry_attrs:
entry_attrs['seealso'] = self.obj._normalize_seealso(
entry_attrs['seealso']
)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_find(LDAPSearch):
__doc__ = _('Search for SELinux User Maps.')
msg_summary = ngettext(
'%(count)d SELinux User Map matched', '%(count)d SELinux User Maps matched', 0
)
def execute(self, *args, **options):
# If searching on hbacrule we need to find the uuid to search on
if options.get('seealso'):
hbacrule = options['seealso']
# If a complete DN is passed we can skip calling hbacrule-show
try:
tmpdn = DN(hbacrule)
except ValueError:
tmpdn = DN()
if DN(api.env.container_hbac, api.env.basedn) not in tmpdn:
try:
hbac = api.Command['hbacrule_show'](hbacrule,
all=True)['result']
dn = hbac['dn']
except errors.NotFound:
return dict(count=0, result=[], truncated=False)
else:
dn = tmpdn
options['seealso'] = dn
return super(selinuxusermap_find, self).execute(*args, **options)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
for attrs in entries:
self.obj._convert_seealso(ldap, attrs, **options)
return truncated
@register()
class selinuxusermap_show(LDAPRetrieve):
__doc__ = _('Display the properties of a SELinux User Map rule.')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._convert_seealso(ldap, entry_attrs, **options)
return dn
@register()
class selinuxusermap_enable(LDAPQuery):
__doc__ = _('Enable an SELinux User Map rule.')
msg_summary = _('Enabled SELinux User Map "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [True]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
raise errors.AlreadyActive()
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class selinuxusermap_disable(LDAPQuery):
__doc__ = _('Disable an SELinux User Map rule.')
msg_summary = _('Disabled SELinux User Map "%(value)s"')
has_output = output.standard_value
def execute(self, cn, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(cn)
try:
entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
except errors.NotFound:
raise self.obj.handle_not_found(cn)
entry_attrs['ipaenabledflag'] = [False]
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
raise errors.AlreadyInactive()
return dict(
result=True,
value=pkey_to_value(cn, options),
)
@register()
class selinuxusermap_add_user(LDAPAddMember):
__doc__ = _('Add users and groups to an SELinux User Map rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if ('usercategory' in entry_attrs and
entry_attrs['usercategory'][0].lower() == 'all'):
raise errors.MutuallyExclusiveError(
reason=_("users cannot be added when user category='all'"))
if 'seealso' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=notboth_err)
return dn
@register()
class selinuxusermap_remove_user(LDAPRemoveMember):
__doc__ = _('Remove users and groups from an SELinux User Map rule.')
member_attributes = ['memberuser']
member_count_out = ('%i object removed.', '%i objects removed.')
@register()
class selinuxusermap_add_host(LDAPAddMember):
__doc__ = _('Add target hosts and hostgroups to an SELinux User Map rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object added.', '%i objects added.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
try:
entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
dn = entry_attrs.dn
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if ('hostcategory' in entry_attrs and
entry_attrs['hostcategory'][0].lower() == 'all'):
raise errors.MutuallyExclusiveError(
reason=_("hosts cannot be added when host category='all'"))
if 'seealso' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=notboth_err)
return dn
@register()
class selinuxusermap_remove_host(LDAPRemoveMember):
__doc__ = _('Remove target hosts and hostgroups from an SELinux User Map rule.')
member_attributes = ['memberhost']
member_count_out = ('%i object removed.', '%i objects removed.')
| 21,387
|
Python
|
.py
| 495
| 33.719192
| 326
| 0.608137
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,865
|
passkeyconfig.py
|
freeipa_freeipa/ipaserver/plugins/passkeyconfig.py
|
#
# Copyright (C) 2022 FreeIPA Contributors see COPYING for license
#
import logging
from ipalib import api
from ipalib.parameters import Bool
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPRetrieve,
LDAPUpdate)
from ipalib import _
logger = logging.getLogger(__name__)
__doc__ = _("""
Passkey configuration
""") + _("""
Manage Passkey configuration.
""") + _("""
IPA supports the use of passkeys for authentication. A passkey
device has to be registered to SSSD and the resulting authentication mapping
stored in the user entry.
The passkey authentication supports the following configuration option:
require user verification. When set, the method for user verification depends
on the type of device (PIN, fingerprint, external pad...)
""") + _("""
EXAMPLES:
""") + _("""
Display the Passkey configuration:
ipa passkeyconfig-show
""") + _("""
Modify the Passkey configuration to always require user verification:
ipa passkeyconfig-mod --require-user-verification=TRUE
""")
register = Registry()
@register()
class passkeyconfig(LDAPObject):
"""
Passkey configuration object
"""
object_name = _('Passkey configuration options')
default_attributes = ['iparequireuserverification']
container_dn = api.env.container_passkey
label = _('Passkey Configuration')
label_singular = _('Passkey Configuration')
takes_params = (
Bool(
'iparequireuserverification',
cli_name="require_user_verification",
label=_("Require user verification"),
doc=_('Require user verification during authentication'),
),
)
permission_filter_objectclasses = ['ipapasskeyconfigobject']
managed_permissions = {
'System: Read Passkey Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'iparequireuserverification',
'cn',
},
},
'System: Modify Passkey Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'write'},
'ipapermdefaultattr': {
'iparequireuserverification',
},
'default_privileges': {
'Passkey Administrators'},
},
}
@register()
class passkeyconfig_mod(LDAPUpdate):
__doc__ = _("Modify Passkey configuration.")
@register()
class passkeyconfig_show(LDAPRetrieve):
__doc__ = _("Show the current Passkey configuration.")
| 2,627
|
Python
|
.py
| 79
| 27.506329
| 77
| 0.666009
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,866
|
otpconfig.py
|
freeipa_freeipa/ipaserver/plugins/otpconfig.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/>.
from ipalib import _, api, Int
from ipalib.plugable import Registry
from .baseldap import DN, LDAPObject, LDAPUpdate, LDAPRetrieve
__doc__ = _("""
OTP configuration
Manage the default values that IPA uses for OTP tokens.
EXAMPLES:
Show basic OTP configuration:
ipa otpconfig-show
Show all OTP configuration options:
ipa otpconfig-show --all
Change maximum TOTP authentication window to 10 minutes:
ipa otpconfig-mod --totp-auth-window=600
Change maximum TOTP synchronization window to 12 hours:
ipa otpconfig-mod --totp-sync-window=43200
Change maximum HOTP authentication window to 5:
ipa hotpconfig-mod --hotp-auth-window=5
Change maximum HOTP synchronization window to 50:
ipa hotpconfig-mod --hotp-sync-window=50
""")
register = Registry()
topic = 'otp'
@register()
class otpconfig(LDAPObject):
object_name = _('OTP configuration options')
default_attributes = [
'ipatokentotpauthwindow',
'ipatokentotpsyncwindow',
'ipatokenhotpauthwindow',
'ipatokenhotpsyncwindow',
]
container_dn = DN(('cn', 'otp'), ('cn', 'etc'))
permission_filter_objectclasses = ['ipatokenotpconfig']
managed_permissions = {
'System: Read OTP Configuration': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipatokentotpauthwindow', 'ipatokentotpsyncwindow',
'ipatokenhotpauthwindow', 'ipatokenhotpsyncwindow',
'cn',
},
},
}
label = _('OTP Configuration')
label_singular = _('OTP Configuration')
takes_params = (
Int('ipatokentotpauthwindow',
cli_name='totp_auth_window',
label=_('TOTP authentication Window'),
doc=_('TOTP authentication time variance (seconds)'),
minvalue=5,
),
Int('ipatokentotpsyncwindow',
cli_name='totp_sync_window',
label=_('TOTP Synchronization Window'),
doc=_('TOTP synchronization time variance (seconds)'),
minvalue=5,
),
Int('ipatokenhotpauthwindow',
cli_name='hotp_auth_window',
label=_('HOTP Authentication Window'),
doc=_('HOTP authentication skip-ahead'),
minvalue=1,
),
Int('ipatokenhotpsyncwindow',
cli_name='hotp_sync_window',
label=_('HOTP Synchronization Window'),
doc=_('HOTP synchronization skip-ahead'),
minvalue=1,
),
)
def get_dn(self, *keys, **kwargs):
return self.container_dn + api.env.basedn
@register()
class otpconfig_mod(LDAPUpdate):
__doc__ = _('Modify OTP configuration options.')
@register()
class otpconfig_show(LDAPRetrieve):
__doc__ = _('Show the current OTP configuration.')
| 3,703
|
Python
|
.py
| 99
| 31.131313
| 71
| 0.668621
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,867
|
cert.py
|
freeipa_freeipa/ipaserver/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
import collections
import datetime
import itertools
import logging
from operator import attrgetter
import cryptography.x509
from cryptography.hazmat.primitives import hashes, serialization
from dns import resolver, reversename
import six
from ipalib import Command, Str, Int, Flag, StrEnum, SerialNumber
from ipalib import api
from ipalib import errors, messages
from ipalib import x509
from ipalib import ngettext
from ipalib.constants import IPA_CA_CN, IPA_CA_RECORD
from ipalib.crud import Create, PKQuery, Retrieve, Search
from ipalib.frontend import Method, Object
from ipalib.parameters import (
Bytes, Certificate, CertificateSigningRequest, DateTime, DNParam,
DNSNameParam, Principal
)
from ipalib.plugable import Registry
from .virtual import VirtualCommand
from .baseldap import pkey_to_value
from .certprofile import validate_profile_id
from ipalib.text import _
from ipalib.request import context
from ipalib import output
from ipapython import dnsutil, kerberos
from ipapython.dn import DN
from ipapython.ipautil import datetime_from_utctimestamp
from ipaserver.plugins.service import normalize_principal, validate_realm
from ipaserver.masters import (
ENABLED_SERVICE, CONFIGURED_SERVICE, HIDDEN_SERVICE, is_service_enabled
)
try:
import pyhbac
except ImportError:
raise errors.SkipPluginModule(reason=_('pyhbac is not installed.'))
if six.PY3:
unicode = str
__doc__ = _("""
IPA certificate operations
""") + _("""
Implements a set of commands for managing server SSL certificates.
""") + _("""
Certificate requests exist in the form of a Certificate Signing Request (CSR)
in PEM format.
""") + _("""
The dogtag CA uses just the CN value of the CSR and forces the rest of the
subject to values configured in the server.
""") + _("""
A certificate is stored with a service principal and a service principal
needs a host.
""") + _("""
In order to request a certificate:
""") + _("""
* The host must exist
* The service must exist (or you use the --add option to automatically add it)
""") + _("""
SEARCHING:
""") + _("""
Certificates may be searched on by certificate subject, serial number,
revocation reason, validity dates and the issued date.
""") + _("""
When searching on dates the _from date does a >= search and the _to date
does a <= search. When combined these are done as an AND.
""") + _("""
Dates are treated as GMT to match the dates in the certificates.
""") + _("""
The date format is YYYY-mm-dd.
""") + _("""
EXAMPLES:
""") + _("""
Request a new certificate and add the principal:
ipa cert-request --add --principal=HTTP/lion.example.com example.csr
""") + _("""
Retrieve an existing certificate:
ipa cert-show 1032
""") + _("""
Revoke a certificate (see RFC 5280 for reason details):
ipa cert-revoke --revocation-reason=6 1032
""") + _("""
Remove a certificate from revocation hold status:
ipa cert-remove-hold 1032
""") + _("""
Check the status of a signing request:
ipa cert-status 10
""") + _("""
Search for certificates by hostname:
ipa cert-find --subject=ipaserver.example.com
""") + _("""
Search for revoked certificates by reason:
ipa cert-find --revocation-reason=5
""") + _("""
Search for certificates based on issuance date
ipa cert-find --issuedon-from=2013-02-01 --issuedon-to=2013-02-07
""") + _("""
Search for certificates owned by a specific user:
ipa cert-find --user=user
""") + _("""
Examine a certificate:
ipa cert-find --file=cert.pem --all
""") + _("""
Verify that a certificate is owned by a specific user:
ipa cert-find --file=cert.pem --user=user
""") + _("""
IPA currently immediately issues (or declines) all certificate requests so
the status of a request is not normally useful. This is for future use
or the case where a CA does not immediately issue a certificate.
""") + _("""
The following revocation reasons are supported:
""") + _(""" * 0 - unspecified
""") + _(""" * 1 - keyCompromise
""") + _(""" * 2 - cACompromise
""") + _(""" * 3 - affiliationChanged
""") + _(""" * 4 - superseded
""") + _(""" * 5 - cessationOfOperation
""") + _(""" * 6 - certificateHold
""") + _(""" * 8 - removeFromCRL
""") + _(""" * 9 - privilegeWithdrawn
""") + _(""" * 10 - aACompromise
""") + _("""
Note that reason code 7 is not used. See RFC 5280 for more details:
""") + _("""
http://www.ietf.org/rfc/rfc5280.txt
""")
logger = logging.getLogger(__name__)
USER, HOST, KRBTGT, SERVICE = range(4)
register = Registry()
PKIDATE_FORMAT = '%Y-%m-%d'
def _acl_make_request(principal_type, principal, ca_id, profile_id):
"""Construct HBAC request for the given principal, CA and profile"""
req = pyhbac.HbacRequest()
req.targethost.name = ca_id
req.service.name = profile_id
if principal_type == 'user':
req.user.name = principal.username
elif principal_type == 'host':
req.user.name = principal.hostname
elif principal_type == 'service':
req.user.name = unicode(principal)
groups = []
if principal_type == 'user':
user_obj = api.Command.user_show(
str(principal.username))['result']
groups = user_obj.get('memberof_group', [])
groups += user_obj.get('memberofindirect_group', [])
elif principal_type == 'host':
host_obj = api.Command.host_show(
str(principal.hostname))['result']
groups = host_obj.get('memberof_hostgroup', [])
groups += host_obj.get('memberofindirect_hostgroup', [])
req.user.groups = sorted(set(groups))
return req
def _acl_make_rule(principal_type, obj):
"""Turn CA ACL object into HBAC rule.
``principal_type``
String in {'user', 'host', 'service'}
"""
rule = pyhbac.HbacRule(obj['cn'][0])
rule.enabled = obj['ipaenabledflag'][0]
rule.srchosts.category = {pyhbac.HBAC_CATEGORY_ALL}
# add CA(s)
if 'ipacacategory' in obj and obj['ipacacategory'][0].lower() == 'all':
rule.targethosts.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
# For compatibility with pre-lightweight-CAs CA ACLs,
# no CA members implies the host authority (only)
rule.targethosts.names = obj.get('ipamemberca_ca', [IPA_CA_CN])
# add profiles
if ('ipacertprofilecategory' in obj
and obj['ipacertprofilecategory'][0].lower() == 'all'):
rule.services.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
attr = 'ipamembercertprofile_certprofile'
rule.services.names = obj.get(attr, [])
# add principals and principal's groups
category_attr = '{}category'.format(principal_type)
if category_attr in obj and obj[category_attr][0].lower() == 'all':
rule.users.category = {pyhbac.HBAC_CATEGORY_ALL}
else:
if principal_type == 'user':
rule.users.names = obj.get('memberuser_user', [])
rule.users.groups = obj.get('memberuser_group', [])
elif principal_type == 'host':
rule.users.names = obj.get('memberhost_host', [])
rule.users.groups = obj.get('memberhost_hostgroup', [])
elif principal_type == 'service':
rule.users.names = [
unicode(principal)
for principal in obj.get('memberservice_service', [])
]
return rule
def acl_evaluate(principal, ca_id, profile_id):
if principal.is_user:
principal_type = 'user'
elif principal.is_host:
principal_type = 'host'
else:
principal_type = 'service'
req = _acl_make_request(principal_type, principal, ca_id, profile_id)
acls = api.Command.caacl_find(no_members=False)['result']
rules = [_acl_make_rule(principal_type, obj) for obj in acls]
return req.evaluate(rules) == pyhbac.HBAC_EVAL_ALLOW
def normalize_pkidate(value):
return datetime.datetime.strptime(value, PKIDATE_FORMAT)
def convert_pkidatetime(value):
if isinstance(value, str):
value = int(value)
return x509.format_datetime(datetime_from_utctimestamp(value, units=1000))
def normalize_serial_number(num):
"""
Convert a SN given in decimal or hexadecimal.
Returns the number or None if conversion fails.
"""
# plain decimal or hexa with radix prefix
try:
num = int(num, 0)
except ValueError:
try:
# hexa without prefix
num = int(num, 16)
except ValueError:
pass
return unicode(num)
def ca_enabled_check(_api):
if not _api.Command.ca_is_enabled()['result']:
raise errors.NotFound(reason=_('CA is not configured'))
def caacl_check(principal, ca, profile_id):
if not acl_evaluate(principal, ca, profile_id):
raise errors.ACIError(info=_(
"Principal '%(principal)s' "
"is not permitted to use CA '%(ca)s' "
"with profile '%(profile_id)s' for certificate issuance."
) % dict(
principal=unicode(principal),
ca=ca,
profile_id=profile_id
)
)
def ca_kdc_check(api_instance, hostname):
master_dn = api_instance.Object.server.get_dn(unicode(hostname))
kdc_dn = DN(('cn', 'KDC'), master_dn)
wanted = {ENABLED_SERVICE, CONFIGURED_SERVICE, HIDDEN_SERVICE}
try:
kdc_entry = api_instance.Backend.ldap2.get_entry(
kdc_dn, ['ipaConfigString'])
if not wanted.intersection(kdc_entry['ipaConfigString']):
raise errors.NotFound(
reason=_("enabledService/configuredService not in "
"ipaConfigString kdc entry"))
except errors.NotFound:
raise errors.ACIError(
info=_("Host '%(hostname)s' is not an active KDC")
% dict(hostname=hostname))
def bind_principal_can_manage_cert(cert):
"""Check that the bind principal can manage the given cert.
``cert``
A python-cryptography ``Certificate`` object.
"""
op_account = getattr(context, 'principal', None)
if op_account is None:
return False
bind_principal = kerberos.Principal(op_account)
if not bind_principal.is_host:
return False
hostname = bind_principal.hostname
# Verify that hostname matches subject of cert.
# We check the "most-specific" CN value.
cns = cert.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.COMMON_NAME)
if len(cns) == 0:
return False # no CN in subject
else:
return hostname == cns[-1].value
class BaseCertObject(Object):
takes_params = (
Str(
'cacn?',
cli_name='ca',
default=IPA_CA_CN,
autofill=True,
label=_('Issuing CA'),
doc=_('Name of issuing CA'),
flags={'no_create', 'no_update', 'no_search'},
),
Certificate(
'certificate',
label=_("Certificate"),
doc=_("Base-64 encoded certificate."),
flags={'no_create', 'no_update', 'no_search'},
),
Bytes(
'certificate_chain*',
label=_("Certificate chain"),
doc=_("X.509 certificate chain"),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'subject',
label=_('Subject'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_rfc822name*',
label=_('Subject email address'),
flags={'no_create', 'no_update', 'no_search'},
),
DNSNameParam(
'san_dnsname*',
label=_('Subject DNS name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_x400address*',
label=_('Subject X.400 address'),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'san_directoryname*',
label=_('Subject directory name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_edipartyname*',
label=_('Subject EDI Party name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_uri*',
label=_('Subject URI'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_ipaddress*',
label=_('Subject IP Address'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_oid*',
label=_('Subject OID'),
flags={'no_create', 'no_update', 'no_search'},
),
Principal(
'san_other_upn*',
label=_('Subject UPN'),
flags={'no_create', 'no_update', 'no_search'},
),
Principal(
'san_other_kpn*',
label=_('Subject Kerberos principal name'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'san_other*',
label=_('Subject Other Name'),
flags={'no_create', 'no_update', 'no_search'},
),
DNParam(
'issuer',
label=_('Issuer'),
doc=_('Issuer DN'),
flags={'no_create', 'no_update', 'no_search'},
),
DateTime(
'valid_not_before',
label=_('Not Before'),
flags={'no_create', 'no_update', 'no_search'},
),
DateTime(
'valid_not_after',
label=_('Not After'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'sha1_fingerprint',
label=_('Fingerprint (SHA1)'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'sha256_fingerprint',
label=_('Fingerprint (SHA256)'),
flags={'no_create', 'no_update', 'no_search'},
),
SerialNumber(
'serial_number',
label=_('Serial number'),
doc=_('Serial number in decimal or if prefixed with 0x in hexadecimal'),
normalizer=normalize_serial_number,
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'serial_number_hex',
label=_('Serial number (hex)'),
flags={'no_create', 'no_update', 'no_search'},
),
)
def _parse(self, obj, full=True):
"""Extract certificate-specific data into a result object.
``obj``
Result object containing certificate, into which extracted
data will be inserted.
``full``
Whether to include all fields, or only the ones we guess
people want to see most of the time. Also add
recognised otherNames to the generic ``san_other``
attribute when ``True`` in addition to the specialised
attribute.
Raise ``ValueError`` if the certificate is malformed.
(Note: only the main certificate structure and Subject Alt
Name extension are examined.)
"""
if 'certificate' in obj:
cert = x509.load_der_x509_certificate(
base64.b64decode(obj['certificate']))
obj['subject'] = DN(cert.subject)
obj['issuer'] = DN(cert.issuer)
obj['serial_number'] = str(cert.serial_number)
obj['serial_number_hex'] = '0x%X' % cert.serial_number
obj['valid_not_before'] = x509.format_datetime(
cert.not_valid_before_utc)
obj['valid_not_after'] = x509.format_datetime(
cert.not_valid_after_utc)
if full:
obj['sha1_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA1()))
obj['sha256_fingerprint'] = x509.to_hex_with_colons(
cert.fingerprint(hashes.SHA256()))
general_names = x509.process_othernames(
cert.san_general_names)
for gn in general_names:
try:
self._add_san_attribute(obj, full, gn)
except Exception:
# Invalid GeneralName (i.e. not a valid X.509 cert);
# don't fail but log something about it
logger.warning(
"Encountered bad GeneralName; skipping", exc_info=True)
def _add_san_attribute(self, obj, full, gn):
name_type_map = {
cryptography.x509.RFC822Name:
('san_rfc822name', attrgetter('value')),
cryptography.x509.DNSName: ('san_dnsname', attrgetter('value')),
# cryptography.x509.???: 'san_x400address',
cryptography.x509.DirectoryName:
('san_directoryname', lambda x: DN(x.value)),
# cryptography.x509.???: 'san_edipartyname',
cryptography.x509.UniformResourceIdentifier:
('san_uri', attrgetter('value')),
cryptography.x509.IPAddress:
('san_ipaddress', attrgetter('value')),
cryptography.x509.RegisteredID:
('san_oid', attrgetter('value.dotted_string')),
cryptography.x509.OtherName: ('san_other', _format_othername),
x509.UPN: ('san_other_upn', attrgetter('name')),
x509.KRB5PrincipalName: ('san_other_kpn', attrgetter('name')),
}
default_attrs = {
'san_rfc822name', 'san_dnsname', 'san_other_upn', 'san_other_kpn',
}
if type(gn) not in name_type_map:
return
attr_name, format_name = name_type_map[type(gn)]
if full or attr_name in default_attrs:
attr_value = self.params[attr_name].type(format_name(gn))
obj.setdefault(attr_name, []).append(attr_value)
if full and attr_name.startswith('san_other_'):
# also include known otherName in generic otherName attribute
attr_value = self.params['san_other'].type(_format_othername(gn))
obj.setdefault('san_other', []).append(attr_value)
def _format_othername(on):
"""Format a python-cryptography OtherName for display."""
return u'{}:{}'.format(
on.type_id.dotted_string,
base64.b64encode(on.value).decode('ascii')
)
class BaseCertMethod(Method):
def get_options(self):
yield self.obj.params['cacn'].clone(query=True)
yield from super(BaseCertMethod, self).get_options()
@register()
class certreq(BaseCertObject):
takes_params = BaseCertObject.takes_params + (
Str(
'request_type',
default=u'pkcs10',
autofill=True,
flags={'no_option', 'no_update', 'no_search'},
),
Str(
'profile_id?', validate_profile_id,
label=_("Profile ID"),
doc=_("Certificate Profile to use"),
flags={'no_update', 'no_search'},
),
Str(
'cert_request_status',
label=_('Request status'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'request_id',
label=_('Request id'),
primary_key=True,
flags={'no_create', 'no_update', 'no_search', 'no_output'},
),
)
_chain_flag = Flag(
'chain',
default=False,
doc=_('Include certificate chain in output'),
)
@register()
class cert_request(Create, BaseCertMethod, VirtualCommand):
__doc__ = _('Submit a certificate signing request.')
obj_name = 'certreq'
attr_name = 'request'
takes_args = (
CertificateSigningRequest(
'csr',
label=_('CSR'),
cli_name='csr_file',
),
)
operation="request certificate"
takes_options = (
Principal(
'principal',
validate_realm,
label=_('Principal'),
doc=_('Principal for this certificate (e.g. HTTP/test.example.com)'),
normalizer=normalize_principal
),
Flag(
'add',
doc=_(
"automatically add the principal if it doesn't exist "
"(service principals only)"),
),
_chain_flag,
)
def get_args(self):
# FIXME: the 'no_create' flag is ignored for positional arguments
for arg in super(cert_request, self).get_args():
if arg.name == 'request_id':
continue
yield arg
def execute(self, csr, all=False, raw=False, chain=False, **kw):
ca_enabled_check(self.api)
ldap = self.api.Backend.ldap2
realm = unicode(self.api.env.realm)
add = kw.get('add')
request_type = kw.get('request_type')
profile_id = kw.get('profile_id', self.Backend.ra.DEFAULT_PROFILE)
# Check that requested authority exists (done before CA ACL
# enforcement so that user gets better error message if
# referencing nonexistant CA) and look up authority ID.
#
ca = kw['cacn']
ca_obj = api.Command.ca_show(ca, all=all, chain=chain)['result']
ca_id = ca_obj['ipacaid'][0]
"""
Access control is partially handled by the ACI titled
'Hosts can modify service userCertificate'. This is for the case
where a machine binds using a host/ prinicpal. It can only do the
request if the target hostname is in the managedBy attribute which
is managed using the add/del member commands.
Binding with a user principal one needs to be in the request_certs
taskgroup (directly or indirectly via role membership).
"""
principal_arg = kw.get('principal')
if principal_to_principal_type(principal_arg) == KRBTGT:
principal_obj = None
principal = principal_arg
# Allow krbtgt to use only the KDC certprofile
if profile_id != self.Backend.ra.KDC_PROFILE:
raise errors.ACIError(
info=_("krbtgt certs can use only the %s profile") % (
self.Backend.ra.KDC_PROFILE))
# Allow only our own realm krbtgt for now; no trusted realms.
if principal != kerberos.Principal((u'krbtgt', realm),
realm=realm):
raise errors.NotFound("Not our realm's krbtgt")
else:
principal_obj = self.lookup_or_add_principal(principal_arg, add)
if 'krbcanonicalname' in principal_obj:
principal = principal_obj['krbcanonicalname'][0]
else:
principal = principal_obj['krbprincipalname'][0]
principal_string = unicode(principal)
principal_type = principal_to_principal_type(principal)
op_account = getattr(context, 'principal', None)
if op_account is None:
# Can the bound principal request certs for another principal?
# the virtual operation check will rely on LDAP ACIs, no need
# for the Kerberos principal here.
# Force the principal that cannot be matched in normal deployments
op_account = '<unknown>@<UNKNOWN>'
bind_principal = kerberos.Principal(op_account)
bind_principal_string = unicode(bind_principal)
bind_principal_type = principal_to_principal_type(bind_principal)
if (bind_principal_string != principal_string and
bind_principal_type != HOST):
# Can the bound principal request certs for another principal?
self.check_access()
try:
self.check_access("request certificate ignore caacl")
bypass_caacl = True
except errors.ACIError:
bypass_caacl = False
if not bypass_caacl:
if principal_type == KRBTGT:
ca_kdc_check(self.api, bind_principal.hostname)
else:
caacl_check(principal, ca, profile_id)
try:
ext_san = csr.extensions.get_extension_for_oid(
cryptography.x509.oid.ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
except cryptography.x509.extensions.ExtensionNotFound:
ext_san = None
# Ensure that the DN in the CSR matches the principal
#
# We only look at the "most specific" CN value
cns = csr.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.COMMON_NAME)
if len(cns) == 0:
raise errors.ValidationError(name='csr',
error=_("No Common Name was found in subject of request."))
cn = cns[-1].value # "most specific" is end of list
if principal_type in (SERVICE, HOST):
if not _dns_name_matches_principal(cn, principal, principal_obj):
raise errors.ValidationError(
name='csr',
error=_(
"hostname in subject of request '%(cn)s' does not "
"match name or aliases of principal '%(principal)s'"
) % dict(cn=cn, principal=principal))
elif principal_type == KRBTGT and not bypass_caacl:
if cn.lower() != bind_principal.hostname.lower():
raise errors.ACIError(
info=_("hostname in subject of request '%(cn)s' "
"does not match principal hostname "
"'%(hostname)s'") % dict(
cn=cn, hostname=bind_principal.hostname))
elif principal_type == USER:
# check user name
if cn != principal.username:
raise errors.ValidationError(
name='csr',
error=_("DN commonName does not match user's login")
)
# check email address
#
# fail if any email addr from DN does not appear in ldap entry
email_addrs = csr.subject.get_attributes_for_oid(
cryptography.x509.oid.NameOID.EMAIL_ADDRESS)
csr_emails = [attr.value for attr in email_addrs]
if not _emails_are_valid(csr_emails,
principal_obj.get('mail', [])):
raise errors.ValidationError(
name='csr',
error=_(
"DN emailAddress does not match "
"any of user's email addresses")
)
if principal_type != KRBTGT:
# We got this far so the principal entry exists, can we write it?
dn = principal_obj.dn
if not ldap.can_write(dn, "usercertificate"):
raise errors.ACIError(
info=_("Insufficient 'write' privilege to the "
"'userCertificate' attribute of entry '%s'.") % dn)
# During SAN validation, we collect IPAddressName values,
# and *qualified* DNS names, and then ensure that all
# IPAddressName values correspond to one of the DNS names.
#
san_ipaddrs = set()
san_dnsnames = set()
# Validate the subject alt name, if any
if ext_san is not None:
generalnames = x509.process_othernames(ext_san.value)
else:
generalnames = []
for gn in generalnames:
if isinstance(gn, cryptography.x509.general_name.DNSName):
if principal.is_user:
raise errors.ValidationError(
name='csr',
error=_(
"subject alt name type %s is forbidden "
"for user principals") % "DNSName"
)
name = gn.value
# Special case: if the DNS name is ipa-ca.$DOMAIN and if the
# subject principal is the HTTP service for an IPA server
# then allow the name.
if name == f'{IPA_CA_RECORD}.{self.api.env.domain}' \
and principal.is_service \
and principal.service_name == 'HTTP':
try:
self.api.Command.server_show(principal.hostname)
except errors.NotFound:
pass # not an IPA server; proceed as usual
else:
# subject principal is an IPA server, so the
# ipa-ca.$DOMAIN name is allowed
continue
if _dns_name_matches_principal(name, principal, principal_obj):
san_dnsnames.add(name)
continue # nothing more to check for this alt name
# no match yet; check for an alternative principal with
# same realm and service type as subject principal.
components = list(principal.components)
components[-1] = name
alt_principal = kerberos.Principal(components, principal.realm)
alt_principal_obj = None
try:
if principal_type == HOST:
alt_principal_obj = api.Command['host_show'](
name, all=True)['result']
elif principal_type == KRBTGT:
alt_principal = kerberos.Principal(
(u'host', name), principal.realm)
elif principal_type == SERVICE:
alt_principal_obj = api.Command['service_show'](
alt_principal, all=True)['result']
except errors.NotFound:
# We don't want to issue any certificates referencing
# machines we don't know about. Nothing is stored in this
# host record related to this certificate.
raise errors.NotFound(reason=_('The service principal for '
'subject alt name %s in certificate request does not '
'exist') % name)
if alt_principal_obj is not None:
# We found an alternative principal.
# First check that the DNS name does in fact match this
# principal. Because we used the DNSName value as the
# basis for the search, this may seem redundant. Actually,
# we only perform this check to distinguish between
# qualified and unqualified DNS names.
#
# We collect only fully qualified names for the purposes of
# IPAddressName validation, because it is undecidable
# whether 'ninja' refers to 'ninja.my.domain.' or 'ninja.'.
# Remember that even a TLD can have an A record!
#
if _dns_name_matches_principal(
name, alt_principal, alt_principal_obj):
san_dnsnames.add(name)
else:
# Unqualified SAN DNS names are a valid use case.
# We don't add them to san_dnsnames for IPAddress
# validation, but we don't reject the request either.
pass
# Now check write access and caacl
altdn = alt_principal_obj['dn']
if not ldap.can_write(altdn, "usercertificate"):
raise errors.ACIError(info=_(
"Insufficient privilege to create a certificate "
"with subject alt name '%s'.") % name)
if not bypass_caacl:
if principal_type == KRBTGT:
ca_kdc_check(self.api, alt_principal.hostname)
else:
caacl_check(alt_principal, ca, profile_id)
elif isinstance(gn, (x509.KRB5PrincipalName, x509.UPN)):
if principal_type == KRBTGT:
principal_obj = dict()
principal_obj['krbprincipalname'] = [
kerberos.Principal((u'krbtgt', realm), realm)]
if not _principal_name_matches_principal(
gn.name, principal_obj):
raise errors.ValidationError(
name='csr',
error=_(
"Principal '%s' in subject alt name does not "
"match requested principal") % gn.name)
elif isinstance(gn, cryptography.x509.general_name.RFC822Name):
if principal_type == USER:
if not _emails_are_valid([gn.value],
principal_obj.get('mail', [])):
raise errors.ValidationError(
name='csr',
error=_(
"RFC822Name does not match "
"any of user's email addresses")
)
else:
raise errors.ValidationError(
name='csr',
error=_(
"subject alt name type %s is forbidden "
"for non-user principals") % "RFC822Name"
)
elif isinstance(gn, cryptography.x509.general_name.IPAddress):
if principal.is_user:
raise errors.ValidationError(
name='csr',
error=_(
"subject alt name type %s is forbidden "
"for user principals") % "IPAddress"
)
# collect the value; we will validate it after we
# finish iterating all the SAN values
san_ipaddrs.add(gn.value)
else:
raise errors.ACIError(
info=_("Subject alt name type %s is forbidden")
% type(gn).__name__)
if san_ipaddrs:
_validate_san_ips(san_ipaddrs, san_dnsnames)
# Request the certificate
try:
# re-serialise to PEM, in case the user-supplied data has
# extraneous material that will cause Dogtag to freak out
# keep it as string not bytes, it is required later
csr_pem = csr.public_bytes(
serialization.Encoding.PEM).decode('utf-8')
result = self.Backend.ra.request_certificate(
csr_pem, profile_id, ca_id, request_type=request_type)
except errors.HTTPRequestError as e:
if e.status == 409: # pylint: disable=no-member
raise errors.CertificateOperationError(
error=_("CA '%s' is disabled") % ca)
else:
raise e
if not raw:
try:
self.obj._parse(result, all)
except ValueError as e:
self.add_message(
messages.CertificateInvalid(
subject=principal,
reason=e,
)
)
result['request_id'] = result['request_id']
result['cacn'] = ca_obj['cn'][0]
# Success? Then add it to the principal's entry
# (unless the profile tells us not to)
profile = api.Command['certprofile_show'](profile_id)
store = profile['result']['ipacertprofilestoreissued'][0]
if store and 'certificate' in result:
cert = result.get('certificate')
kwargs = dict(addattr=u'usercertificate={}'.format(cert))
# note: we call different commands for the different
# principal types because handling of 'userCertificate'
# vs. 'userCertificate;binary' varies by plugin.
if principal_type == SERVICE:
api.Command['service_mod'](principal_string, **kwargs)
elif principal_type == HOST:
api.Command['host_mod'](principal.hostname, **kwargs)
elif principal_type == USER:
api.Command['user_mod'](principal.username, **kwargs)
elif principal_type == KRBTGT:
logger.error("Profiles used to store cert should't be "
"used for krbtgt certificates")
if 'certificate_chain' in ca_obj:
cert = x509.load_der_x509_certificate(
base64.b64decode(result['certificate']))
cert = cert.public_bytes(serialization.Encoding.DER)
result['certificate_chain'] = [cert] + ca_obj['certificate_chain']
return dict(
result=result,
value=pkey_to_value(result['request_id'], kw),
)
def lookup_principal(self, principal):
"""
Look up a principal's account. Only works for users, hosts, services.
"""
return self.api.Backend.ldap2.find_entry_by_attr(
'krbprincipalname', principal, 'krbprincipalaux',
base_dn=DN(self.api.env.container_accounts, self.api.env.basedn)
)
def lookup_or_add_principal(self, principal, add):
"""
Look up a principal or add it if it does not exist.
Only works for users, hosts, services. krbtgt must be
handled separately.
Only service principals get added, and only when ``add`` is
``True``. If ``add`` is requested for a nonexistant user or
host, raise ``OperationNotSupportedForPrincipalTypes``.
:param principal: ``kerberos.Principal`` to look up
:param add: whether to add the principal if not found; bool
:return: an ``LDAPEntry``
"""
try:
return self.lookup_principal(principal)
except errors.NotFound:
if add:
if principal.is_service and not principal.is_host:
self.api.Command.service_add(
str(principal), all=True, force=True)
return self.lookup_principal(principal) # we want an LDAPEntry
else:
if principal.is_user:
princtype_str = _('user')
else:
princtype_str = _('host')
raise errors.OperationNotSupportedForPrincipalType(
operation=_("'add' option"),
principal_type=princtype_str)
else:
raise errors.NotFound(
reason=_("The principal for this request doesn't exist."))
def _emails_are_valid(csr_emails, principal_emails):
"""
Checks if any email address from certificate request does not
appear in ldap entry, comparing the domain part case-insensitively.
"""
def lower_domain(email):
email_splitted = email.split('@', 1)
if len(email_splitted) > 1:
email_splitted[1] = email_splitted[1].lower()
return '@'.join(email_splitted)
principal_emails_lower = set(map(lower_domain, principal_emails))
csr_emails_lower = set(map(lower_domain, csr_emails))
return csr_emails_lower.issubset(principal_emails_lower)
def principal_to_principal_type(principal):
if principal.is_user:
return USER
elif principal.is_host:
return HOST
elif principal.service_name == 'krbtgt':
return KRBTGT
else:
return SERVICE
def _dns_name_matches_principal(name, principal, principal_obj):
"""
Ensure that a DNS name matches the given principal.
:param name: The DNS name to match
:param principal: The subject ``Principal``
:param principal_obj: The subject principal's LDAP object
:return: True if name matches, otherwise False
"""
if principal_obj is None:
return False
for alias in principal_obj.get('krbprincipalname', []):
# we can only compare them if both subject principal and
# the alias are service or host principals
if not (alias.is_service and principal.is_service):
continue
# ignore aliases with different realm or service name from
# subject principal
if alias.realm != principal.realm:
continue
if alias.service_name != principal.service_name:
continue
# now compare DNS name to alias hostname
if name.lower() == alias.hostname.lower():
return True # we have a match
return False
def _principal_name_matches_principal(name, principal_obj):
"""
Ensure that a stringy principal name (e.g. from UPN
or KRB5PrincipalName OtherName) matches the given principal.
"""
try:
principal = kerberos.Principal(name)
except ValueError:
return False
return principal in principal_obj.get('krbprincipalname', [])
def _validate_san_ips(san_ipaddrs, san_dnsnames):
"""
Check the IP addresses in a CSR subjectAltName.
Raise a ValidationError if the subjectAltName in a CSR includes
any IP addresses that do not match a DNS name in the SAN. Matching means
the following:
* One of the DNS names in the SAN resolves (possibly via a single CNAME -
no CNAME chains allowed) to an A or AAAA record containing that
IP address.
* The IP address has a reverse DNS record pointing to that A or AAAA
record.
* All of the DNS records (A, AAAA, CNAME, and PTR) are managed by this IPA
instance.
:param san_ipaddrs: The IP addresses in the subjectAltName
:param san_dnsnames: The DNS names in the subjectAltName
:raises: errors.ValidationError if the SAN containes a non-matching IP
address.
"""
san_ip_set = frozenset(unicode(ip) for ip in san_ipaddrs)
# Build a dict of IPs that are reachable from the SAN dNSNames
reachable = {}
for name in san_dnsnames:
_san_ip_update_reachable(reachable, name, cname_depth=1)
# Each iPAddressName must be reachable from a dNSName
unreachable_ips = san_ip_set - six.viewkeys(reachable)
if len(unreachable_ips) > 0:
raise errors.ValidationError(
name='csr',
error=_(
"IP address in subjectAltName (%s) unreachable from DNS names"
) % ', '.join(unreachable_ips)
)
# Collect PTR records for each IP address
ptrs_by_ip = {}
for ip in san_ipaddrs:
ptrs = _ip_ptr_records(unicode(ip))
if len(ptrs) > 0:
ptrs_by_ip[unicode(ip)] = set(s.rstrip('.') for s in ptrs)
# Each iPAddressName must have a corresponding PTR record.
missing_ptrs = san_ip_set - six.viewkeys(ptrs_by_ip)
if len(missing_ptrs) > 0:
raise errors.ValidationError(
name='csr',
error=_(
"IP address in subjectAltName (%s) does not have PTR record"
) % ', '.join(missing_ptrs)
)
# PTRs and forward records must form a loop
for ip, ptrs in ptrs_by_ip.items():
# PTR value must appear in the set of names that resolve to
# this IP address (via A/AAAA records)
if len(ptrs - reachable.get(ip, set())) > 0:
raise errors.ValidationError(
name='csr',
error=_(
"PTR record for SAN IP (%s) does not match A/AAAA records"
) % ip
)
def _san_ip_update_reachable(reachable, dnsname, cname_depth):
"""
Update dict of reachable IPs and the names that reach them.
:param reachable: the dict to update. Keys are IP addresses,
values are sets of DNS names.
:param dnsname: the DNS name to resolve
:param cname_depth: How many levels of CNAME indirection are permitted.
"""
fqdn = dnsutil.DNSName(dnsname).make_absolute()
try:
zone = dnsutil.DNSName(dnsutil.zone_for_name(fqdn))
except resolver.NoNameservers:
return # if there's no zone, there are no records
name = fqdn.relativize(zone)
try:
result = api.Command['dnsrecord_show'](zone, name)['result']
except errors.NotFound as nf:
logger.debug("Skipping IPs for %s: %s", dnsname, nf)
return # nothing to do
for ip in itertools.chain(result.get('arecord', ()),
result.get('aaaarecord', ())):
# add this forward relationship to the 'reachable' dict
names = reachable.get(ip, set())
names.add(dnsname.rstrip('.'))
reachable[ip] = names
if cname_depth > 0:
for cname in result.get('cnamerecord', []):
if not cname.endswith('.'):
cname = u'%s.%s' % (cname, zone)
_san_ip_update_reachable(reachable, cname, cname_depth - 1)
def _ip_ptr_records(ip):
"""
Look up PTR record(s) for IP address.
:return: a ``set`` of IP addresses, possibly empty.
"""
rname = dnsutil.DNSName(reversename.from_address(ip))
try:
zone = dnsutil.DNSName(dnsutil.zone_for_name(rname))
name = rname.relativize(zone)
result = api.Command['dnsrecord_show'](zone, name)['result']
except resolver.NoNameservers:
ptrs = set() # if there's no zone, there are no records
except errors.NotFound:
ptrs = set()
else:
ptrs = set(result.get('ptrrecord', []))
return ptrs
@register()
class cert_status(Retrieve, BaseCertMethod, VirtualCommand):
__doc__ = _('Check the status of a certificate signing request.')
obj_name = 'certreq'
attr_name = 'status'
operation = "certificate status"
def execute(self, request_id, **kw):
ca_enabled_check(self.api)
self.check_access()
# Dogtag requests are uniquely identified by their number;
# furthermore, Dogtag (as at v10.3.4) does not report the
# target CA in request data, so we cannot check. So for
# now, there is nothing we can do with the 'cacn' option
# but check if the specified CA exists.
self.api.Command.ca_show(kw['cacn'])
return dict(
result=self.Backend.ra.check_request_status(str(request_id)),
value=pkey_to_value(request_id, kw),
)
@register()
class cert(BaseCertObject):
takes_params = BaseCertObject.takes_params + (
Str(
'status',
label=_('Status'),
flags={'no_create', 'no_update', 'no_search'},
),
Flag(
'revoked',
label=_('Revoked'),
flags={'no_create', 'no_update', 'no_search'},
),
Int(
'revocation_reason',
label=_('Revocation reason'),
doc=_('Reason for revoking the certificate (0-10). Type '
'"ipa help cert" for revocation reason details. '),
minvalue=0,
maxvalue=10,
flags={'no_create', 'no_update'},
),
)
def get_params(self):
for param in super(cert, self).get_params():
if param.name == 'serial_number':
param = param.clone(primary_key=True)
elif param.name in ('certificate', 'issuer'):
param = param.clone(flags=param.flags - {'no_search'})
yield param
for owner, search_key in self._owners():
yield search_key.clone_rename(
'owner_{0}'.format(owner.name),
required=False,
multivalue=True,
primary_key=False,
label=_("Owner %s") % owner.object_name,
flags={'no_create', 'no_update', 'no_search'},
)
def _owners(self):
for obj_name, search_key in [('user', None),
('host', None),
('service', 'krbprincipalname')]:
obj = self.api.Object[obj_name]
if search_key is None:
pkey = obj.primary_key
else:
pkey = obj.params[search_key]
yield obj, pkey
def _fill_owners(self, obj):
dns = obj.pop('owner', None)
if dns is None:
return
for owner, _search_key in self._owners():
container_dn = DN(owner.container_dn, self.api.env.basedn)
name = 'owner_' + owner.name
for dn in dns:
if dn.endswith(container_dn, 1):
value = owner.get_primary_key_from_dn(dn)
obj.setdefault(name, []).append(value)
class CertMethod(BaseCertMethod):
def get_options(self):
yield from super(CertMethod, self).get_options()
for o in self.has_output:
if isinstance(o, (output.Entry, output.ListOfEntries)):
yield Flag(
'no_members',
doc=_("Suppress processing of membership attributes."),
exclude='webui',
flags={'no_output'},
)
break
@register()
class cert_show(Retrieve, CertMethod, VirtualCommand):
__doc__ = _('Retrieve an existing certificate.')
takes_options = (
Str('out?',
label=_('Output filename'),
doc=_('File to store the certificate in.'),
exclude='webui',
),
_chain_flag,
)
operation="retrieve certificate"
def execute(self, serial_number, all=False, raw=False, no_members=False,
chain=False, **options):
ca_enabled_check(self.api)
# Dogtag lightweight CAs have shared serial number domain, so
# we don't tell Dogtag the issuer (but we check the cert after).
#
result = self.Backend.ra.get_certificate(serial_number)
cert = x509.load_der_x509_certificate(
base64.b64decode(result['certificate']))
try:
self.check_access()
except errors.ACIError as acierr:
logger.debug("Not granted by ACI to retrieve certificate, "
"looking at principal")
if not bind_principal_can_manage_cert(cert):
raise acierr
ca_obj = api.Command.ca_show(
options['cacn'],
all=all,
chain=chain,
)['result']
if DN(cert.issuer) != DN(ca_obj['ipacasubjectdn'][0]):
# DN of cert differs from what we requested
raise errors.NotFound(
reason=_("Certificate with serial number %(serial)s "
"issued by CA '%(ca)s' not found")
% dict(serial=serial_number, ca=options['cacn']))
der_cert = base64.b64decode(result['certificate'])
if all or not no_members:
ldap = self.api.Backend.ldap2
filter = ldap.make_filter_from_attr('usercertificate', der_cert)
try:
entries = ldap.get_entries(base_dn=self.api.env.basedn,
filter=filter,
attrs_list=[''])
except errors.EmptyResult:
entries = []
for entry in entries:
result.setdefault('owner', []).append(entry.dn)
if not raw:
result['certificate'] = result['certificate'].replace('\r\n', '')
self.obj._parse(result, all)
result['revoked'] = ('revocation_reason' in result)
self.obj._fill_owners(result)
result['cacn'] = ca_obj['cn'][0]
if 'certificate_chain' in ca_obj:
result['certificate_chain'] = (
[der_cert] + ca_obj['certificate_chain'])
return dict(result=result, value=pkey_to_value(serial_number, options))
@register()
class cert_revoke(PKQuery, CertMethod, VirtualCommand):
__doc__ = _('Revoke a certificate.')
operation = "revoke certificate"
def get_options(self):
# FIXME: The default is 0. Is this really an Int param?
yield self.obj.params['revocation_reason'].clone(
default=0,
autofill=True,
)
yield from super(cert_revoke, self).get_options()
def execute(self, serial_number, **kw):
ca_enabled_check(self.api)
# Make sure that the cert specified by issuer+serial exists.
# Will raise NotFound if it does not.
resp = api.Command.cert_show(serial_number, cacn=kw['cacn'])
try:
self.check_access()
except errors.ACIError as acierr:
logger.debug("Not granted by ACI to revoke certificate, "
"looking at principal")
try:
cert = x509.load_der_x509_certificate(
base64.b64decode(resp['result']['certificate']))
if not bind_principal_can_manage_cert(cert):
raise acierr
except errors.NotImplementedError:
raise acierr
revocation_reason = kw['revocation_reason']
if revocation_reason == 7:
raise errors.CertificateOperationError(error=_('7 is not a valid revocation reason'))
return dict(
# Dogtag lightweight CAs have shared serial number domain, so
# we don't tell Dogtag the issuer (but we already checked that
# the given serial was issued by the named ca).
result=self.Backend.ra.revoke_certificate(
serial_number,
revocation_reason=revocation_reason)
)
@register()
class cert_remove_hold(PKQuery, CertMethod, VirtualCommand):
__doc__ = _('Take a revoked certificate off hold.')
operation = "certificate remove hold"
def execute(self, serial_number, **kw):
ca_enabled_check(self.api)
# Make sure that the cert specified by issuer+serial exists.
# Will raise NotFound if it does not.
api.Command.cert_show(serial_number, cacn=kw['cacn'])
self.check_access()
return dict(
# Dogtag lightweight CAs have shared serial number domain, so
# we don't tell Dogtag the issuer (but we already checked that
# the given serial was issued by the named ca).
result=self.Backend.ra.take_certificate_off_hold(
serial_number
)
)
@register()
class cert_find(Search, CertMethod):
__doc__ = _('Search for existing certificates.')
takes_options = (
Str('subject?',
label=_('Subject'),
doc=_('Match cn attribute in subject'),
autofill=False,
),
SerialNumber('min_serial_number?',
doc=_("minimum serial number"),
autofill=False,
),
SerialNumber('max_serial_number?',
doc=_("maximum serial number"),
autofill=False,
),
Flag('exactly?',
doc=_('match the common name exactly'),
autofill=False,
),
DateTime('validnotafter_from?',
doc=_('Valid not after from this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('validnotafter_to?',
doc=_('Valid not after to this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('validnotbefore_from?',
doc=_('Valid not before from this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('validnotbefore_to?',
doc=_('Valid not before to this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('issuedon_from?',
doc=_('Issued on from this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('issuedon_to?',
doc=_('Issued on to this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('revokedon_from?',
doc=_('Revoked on from this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
DateTime('revokedon_to?',
doc=_('Revoked on to this date (YYYY-mm-dd)'),
normalizer=normalize_pkidate,
autofill=False,
),
StrEnum(
'status?',
doc=_("Status of the certificate"),
values=(u'VALID', u'INVALID', u'REVOKED', u'EXPIRED',
u'REVOKED_EXPIRED'),
),
Flag('pkey_only?',
label=_("Primary key only"),
doc=_("Results should contain primary key attribute only "
"(\"certificate\")"),
),
Int('timelimit?',
label=_('Time Limit'),
doc=_('Time limit of search in seconds (0 is unlimited)'),
minvalue=0,
),
Int('sizelimit?',
label=_("Size Limit"),
doc=_("Maximum number of entries returned (0 is unlimited)"),
minvalue=0,
),
)
msg_summary = ngettext(
'%(count)d certificate matched', '%(count)d certificates matched', 0
)
def get_options(self):
for option in super(cert_find, self).get_options():
if option.name == 'no_members':
option = option.clone(default=True,
flags=set(option.flags) | {'no_option'})
elif option.name == 'cacn':
# make CA optional, so that user may directly
# specify Issuer DN instead
option = option.clone(default=None, autofill=None)
yield option
for owner, search_key in self.obj._owners():
yield search_key.clone_rename(
'{0}'.format(owner.name),
required=False,
multivalue=True,
primary_key=False,
query=True,
cli_name='{0}s'.format(owner.name),
doc=(_("Search for certificates with these owner %s.") %
owner.object_name_plural),
label=owner.object_name,
)
yield search_key.clone_rename(
'no_{0}'.format(owner.name),
required=False,
multivalue=True,
primary_key=False,
query=True,
cli_name='no_{0}s'.format(owner.name),
doc=(_("Search for certificates without these owner %s.") %
owner.object_name_plural),
label=owner.object_name,
)
def _get_cert_key(self, cert):
return (DN(cert.issuer), cert.serial_number)
def _cert_search(self, pkey_only, **options):
result = collections.OrderedDict()
try:
cert = options['certificate']
except KeyError:
return result, False, False
obj = {'serial_number': cert.serial_number}
if not pkey_only:
obj['certificate'] = base64.b64encode(
cert.public_bytes(x509.Encoding.DER)).decode('ascii')
result[self._get_cert_key(cert)] = obj
return result, False, True
def _ca_search(self, raw, pkey_only, exactly, **options):
ra_options = {}
for name in ('revocation_reason',
'issuer',
'subject',
'min_serial_number', 'max_serial_number',
'validnotafter_from', 'validnotafter_to',
'validnotbefore_from', 'validnotbefore_to',
'issuedon_from', 'issuedon_to',
'revokedon_from', 'revokedon_to',
'status'):
try:
value = options[name]
except KeyError:
continue
if isinstance(value, datetime.datetime):
value = value.strftime(PKIDATE_FORMAT)
elif isinstance(value, DN):
value = unicode(value)
ra_options[name] = value
if exactly:
ra_options['exactly'] = True
if 'sizelimit' in options:
# sizelimit = 0 means return everything, drop it and let
# ra_find() handle the value.
if options['sizelimit'] > 0:
ra_options['sizelimit'] = options['sizelimit']
else:
ra_options['sizelimit'] = self.api.Backend.ldap2.size_limit
result = collections.OrderedDict()
complete = bool(ra_options)
# workaround for RHBZ#1669012 and RHBZ#1695685
# Improve performance for service, host and user case by also
# searching for subject. This limits the amount of certificate
# retrieved from Dogtag. The special case is only used, when
# no ra_options are set and exactly one service, host, or user is
# supplied.
# IPA enforces that subject CN is either a hostname or a username.
# The complete flag is left to False to catch overrides.
if not ra_options:
services = options.get('service', ())
hosts = options.get('host', ())
users = options.get('user', ())
if len(services) == 1 and not hosts and not users:
principal = kerberos.Principal(services[0])
if principal.is_service:
ra_options['subject'] = principal.hostname
elif len(hosts) == 1 and not services and not users:
ra_options['subject'] = hosts[0]
elif len(users) == 1 and not services and not hosts:
ra_options['subject'] = users[0]
if 'status' in options:
ra_options['status'] = options.get('status')
try:
ca_enabled_check(self.api)
except errors.NotFound:
if ra_options:
raise
return result, False, complete
ca_objs = self.api.Command.ca_find(
timelimit=0,
sizelimit=0,
)['result']
ca_objs = {DN(ca['ipacasubjectdn'][0]): ca for ca in ca_objs}
ra = self.api.Backend.ra
for ra_obj in ra.find(ra_options):
issuer = DN(ra_obj['issuer'])
serial_number = ra_obj['serial_number']
try:
ca_obj = ca_objs[issuer]
except KeyError:
continue
if pkey_only:
obj = {'serial_number': serial_number}
else:
obj = ra_obj
if not raw:
obj['issuer'] = issuer
obj['subject'] = DN(ra_obj['subject'])
obj['valid_not_before'] = (
convert_pkidatetime(obj['valid_not_before']))
obj['valid_not_after'] = (
convert_pkidatetime(obj['valid_not_after']))
obj['revoked'] = (
ra_obj['status'] in (u'REVOKED', u'REVOKED_EXPIRED'))
obj['cacn'] = ca_obj['cn'][0]
result[issuer, serial_number] = obj
return result, False, complete
def _ldap_search(self, all, pkey_only, no_members, **options):
ldap = self.api.Backend.ldap2
filters = []
for owner, search_key in self.obj._owners():
for prefix, rule in (('', ldap.MATCH_ALL),
('no_', ldap.MATCH_NONE)):
try:
value = options[prefix + owner.name]
except KeyError:
continue
filter = ldap.make_filter_from_attr(
'objectclass',
owner.object_class,
ldap.MATCH_ALL)
if filter not in filters:
filters.append(filter)
filter = ldap.make_filter_from_attr(
search_key.name,
value,
rule)
filters.append(filter)
result = collections.OrderedDict()
complete = bool(filters)
cert = options.get('certificate')
if cert is not None:
filter = ldap.make_filter_from_attr(
'usercertificate', cert.public_bytes(x509.Encoding.DER))
else:
filter = '(usercertificate=*)'
filters.append(filter)
filter = ldap.combine_filters(filters, ldap.MATCH_ALL)
try:
entries, truncated = ldap.find_entries(
base_dn=self.api.env.basedn,
filter=filter,
attrs_list=['usercertificate'],
time_limit=0,
size_limit=0,
)
except errors.EmptyResult:
entries = []
truncated = False
else:
try:
ldap.handle_truncated_result(truncated)
except errors.LimitsExceeded as e:
self.add_message(messages.SearchResultTruncated(reason=e))
truncated = bool(truncated)
ca_enabled = getattr(context, 'ca_enabled')
for entry in entries:
for attr in ('usercertificate', 'usercertificate;binary'):
for der in entry.raw.get(attr, []):
cert = cryptography.x509.load_der_x509_certificate(der)
cert_key = self._get_cert_key(cert)
try:
obj = result[cert_key]
except KeyError:
obj = {'serial_number': cert.serial_number}
if not pkey_only and (all or not ca_enabled):
# Retrieving certificate details is now deferred
# until after all certificates are collected.
# For the case of CA-less we need to keep
# the certificate because getting it again later
# would require unnecessary LDAP searches.
obj['certificate'] = (
base64.b64encode(
cert.public_bytes(x509.Encoding.DER))
.decode('ascii'))
result[cert_key] = obj
if not pkey_only and (all or not no_members):
owners = obj.setdefault('owner', [])
if entry.dn not in owners:
owners.append(entry.dn)
return result, truncated, complete
def execute(self, criteria=None, all=False, raw=False, pkey_only=False,
no_members=True, timelimit=None, sizelimit=None, **options):
ca_enabled = self.api.Command.ca_is_enabled()['result']
if 'cacn' in options:
ca_obj = api.Command.ca_show(options['cacn'])['result']
ca_sdn = unicode(ca_obj['ipacasubjectdn'][0])
if 'issuer' in options:
if DN(ca_sdn) != DN(options['issuer']):
# client has provided both 'ca' and 'issuer' but
# issuer DNs don't match; result must be empty
return dict(result=[], count=0, truncated=False)
else:
options['issuer'] = ca_sdn
if criteria is not None:
return dict(result=[], count=0, truncated=False)
# respect the configured search limits
if timelimit is None:
timelimit = self.api.Backend.ldap2.time_limit
if sizelimit is None:
sizelimit = self.api.Backend.ldap2.size_limit
options['sizelimit'] = sizelimit
result = collections.OrderedDict()
truncated = False
complete = False
# Do not execute the CA sub-search in CA-less deployment.
# See https://pagure.io/freeipa/issue/8369.
if ca_enabled:
searches = [self._cert_search, self._ca_search, self._ldap_search]
else:
searches = [self._cert_search, self._ldap_search]
for sub_search in searches:
sub_result, sub_truncated, sub_complete = sub_search(
all=all,
raw=raw,
pkey_only=pkey_only,
no_members=no_members,
**options)
if sub_complete:
for key in tuple(result):
if key not in sub_result:
del result[key]
for key, sub_obj in six.iteritems(sub_result):
try:
obj = result[key]
except KeyError:
if complete:
continue
result[key] = sub_obj
else:
obj.update(sub_obj)
truncated = truncated or sub_truncated
complete = complete or sub_complete
if not pkey_only:
ca_objs = {}
if ca_enabled:
ra = self.api.Backend.ra
for key, obj in six.iteritems(result):
if all and 'cacn' in obj:
_issuer, serial_number = key
cacn = obj['cacn']
try:
ca_obj = ca_objs[cacn]
except KeyError:
ca_obj = ca_objs[cacn] = (
self.api.Command.ca_show(cacn, all=True)['result'])
obj.update(
ra.get_certificate(serial_number)
)
if not raw:
obj['certificate'] = (
obj['certificate'].replace('\r\n', ''))
if 'certificate_chain' in ca_obj:
cert_der = base64.b64decode(obj['certificate'])
obj['certificate_chain'] = (
[cert_der] + ca_obj['certificate_chain'])
if not raw:
self.obj._parse(obj, all)
if not ca_enabled and not all:
# For the case of CA-less don't display the full
# certificate unless requested. It is kept in the
# entry from _ldap_search() so its attributes can
# be retrieved.
obj.pop('certificate', None)
self.obj._fill_owners(obj)
result = list(six.itervalues(result))
if (len(result) > sizelimit > 0):
if not truncated:
self.add_message(messages.SearchResultTruncated(
reason=errors.SizeLimitExceeded()))
result = result[:sizelimit]
truncated = True
ret = dict(
result=result
)
ret['count'] = len(ret['result'])
ret['truncated'] = bool(truncated)
return ret
@register()
class ca_is_enabled(Command):
__doc__ = _('Checks if any of the servers has the CA service enabled.')
NO_CLI = True
has_output = output.standard_value
def execute(self, *args, **options):
# Store ca_enabled status in the context to save making the API
# call multiple times.
ca_enabled = getattr(context, 'ca_enabled', None)
if ca_enabled is not None and api.env.context in ('lite', 'server',):
result = ca_enabled
else:
result = is_service_enabled('CA', conn=self.api.Backend.ldap2)
setattr(context, 'ca_enabled', result)
return dict(result=result, value=pkey_to_value(None, options))
| 72,724
|
Python
|
.py
| 1,705
| 30.743695
| 97
| 0.559341
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,868
|
hostgroup.py
|
freeipa_freeipa/ipaserver/plugins/hostgroup.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# 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 ipalib.plugable import Registry
from .baseldap import (LDAPObject, LDAPCreate, LDAPRetrieve,
LDAPDelete, LDAPUpdate, LDAPSearch,
LDAPAddMember, LDAPRemoveMember,
entry_from_entry, wait_for_value)
from ipalib import Str, api, _, ngettext, errors
from .netgroup import NETGROUP_PATTERN, NETGROUP_PATTERN_ERRMSG
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Groups of hosts.
Manage groups of hosts. This is useful for applying access control to a
number of hosts by using Host-based Access Control.
EXAMPLES:
Add a new host group:
ipa hostgroup-add --desc="Baltimore hosts" baltimore
Add another new host group:
ipa hostgroup-add --desc="Maryland hosts" maryland
Add members to the hostgroup (using Bash brace expansion):
ipa hostgroup-add-member --hosts={box1,box2,box3} baltimore
Add a hostgroup as a member of another hostgroup:
ipa hostgroup-add-member --hostgroups=baltimore maryland
Remove a host from the hostgroup:
ipa hostgroup-remove-member --hosts=box2 baltimore
Display a host group:
ipa hostgroup-show baltimore
Add a member manager:
ipa hostgroup-add-member-manager --users=user1 baltimore
Remove a member manager
ipa hostgroup-remove-member-manager --users=user1 baltimore
Delete a hostgroup:
ipa hostgroup-del baltimore
""")
def get_complete_hostgroup_member_list(hostgroup):
result = api.Command['hostgroup_show'](hostgroup)['result']
direct = list(result.get('member_host', []))
indirect = list(result.get('memberindirect_host', []))
return direct + indirect
register = Registry()
PROTECTED_HOSTGROUPS = (u'ipaservers',)
hostgroup_output_params = (
Str(
'membermanager_group',
label='Membership managed by groups',
),
Str(
'membermanager_user',
label='Membership managed by users',
),
Str(
'membermanager',
label=_('Failed member manager'),
),
)
@register()
class hostgroup(LDAPObject):
"""
Hostgroup object.
"""
container_dn = api.env.container_hostgroup
object_name = _('host group')
object_name_plural = _('host groups')
object_class = ['ipaobject', 'ipahostgroup']
permission_filter_objectclasses = ['ipahostgroup']
search_attributes = ['cn', 'description', 'member', 'memberof']
default_attributes = [
'cn', 'description', 'member', 'memberof', 'memberindirect',
'memberofindirect', 'membermanager',
]
uuid_attribute = 'ipauniqueid'
allow_rename = True
attribute_members = {
'member': ['host', 'hostgroup'],
'membermanager': ['user', 'group'],
'memberof': ['hostgroup', 'netgroup', 'hbacrule', 'sudorule'],
'memberindirect': ['host', 'hostgroup'],
'memberofindirect': ['hostgroup', 'hbacrule', 'sudorule'],
}
managed_permissions = {
'System: Read Hostgroups': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'ipauniqueid', 'o',
'objectclass', 'ou', 'owner', 'seealso', 'membermanager',
},
},
'System: Read Hostgroup Membership': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'member', 'memberof', 'memberuser', 'memberhost',
},
},
'System: Add Hostgroups': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=hostgroups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Hostgroups";allow (add) groupdn = "ldap:///cn=Add Hostgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Group Administrators'},
},
'System: Modify Hostgroup Membership': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
'(objectclass=ipahostgroup)',
'(!(cn=ipaservers))',
],
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=hostgroups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Hostgroup membership";allow (write) groupdn = "ldap:///cn=Modify Hostgroup membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Group Administrators'},
},
'System: Modify Hostgroups': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'cn', 'description', 'membermanager'},
'replaces': [
'(targetattr = "cn || description")(target = "ldap:///cn=*,cn=hostgroups,cn=accounts,$SUFFIX")(version 3.0; acl "permission:Modify Hostgroups";allow (write) groupdn = "ldap:///cn=Modify Hostgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Group Administrators'},
},
'System: Remove Hostgroups': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=hostgroups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Hostgroups";allow (delete) groupdn = "ldap:///cn=Remove Hostgroups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Host Group Administrators'},
},
}
label = _('Host Groups')
label_singular = _('Host Group')
takes_params = (
Str('cn',
pattern=NETGROUP_PATTERN,
pattern_errmsg=NETGROUP_PATTERN_ERRMSG,
cli_name='hostgroup_name',
label=_('Host-group'),
doc=_('Name of host-group'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this host-group'),
),
)
def suppress_netgroup_memberof(self, ldap, dn, entry_attrs):
"""
We don't want to show managed netgroups so remove them from the
memberOf list.
"""
hgdn = DN(dn)
for member in list(entry_attrs.get('memberof', [])):
ngdn = DN(member)
if ngdn['cn'] != hgdn['cn']:
continue
filter = ldap.make_filter({'objectclass': 'mepmanagedentry'})
try:
ldap.get_entries(ngdn, ldap.SCOPE_BASE, filter, [''])
except errors.NotFound:
pass
else:
entry_attrs['memberof'].remove(member)
@register()
class hostgroup_add(LDAPCreate):
__doc__ = _('Add a new hostgroup.')
has_output_params = LDAPCreate.has_output_params + hostgroup_output_params
msg_summary = _('Added hostgroup "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
# check duplicity with hostgroups first to provide proper error
api.Object['hostgroup'].get_dn_if_exists(keys[-1])
self.obj.handle_duplicate_entry(*keys)
except errors.NotFound:
pass
try:
# when enabled, a managed netgroup is created for every hostgroup
# make sure that the netgroup can be created
api.Object['netgroup'].get_dn_if_exists(keys[-1])
raise errors.DuplicateEntry(message=unicode(_(
u'netgroup with name "%s" already exists. '
u'Hostgroups and netgroups share a common namespace'
) % keys[-1]))
except errors.NotFound:
pass
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
# Always wait for the associated netgroup to be created so we can
# be sure to ignore it in memberOf
newentry = wait_for_value(ldap, dn, 'objectclass', 'mepOriginEntry')
entry_from_entry(entry_attrs, newentry)
self.obj.suppress_netgroup_memberof(ldap, dn, entry_attrs)
return dn
@register()
class hostgroup_del(LDAPDelete):
__doc__ = _('Delete a hostgroup.')
msg_summary = _('Deleted hostgroup "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
if keys[0] in PROTECTED_HOSTGROUPS:
raise errors.ProtectedEntryError(label=_(u'hostgroup'),
key=keys[0],
reason=_(u'privileged hostgroup'))
return dn
@register()
class hostgroup_mod(LDAPUpdate):
__doc__ = _('Modify a hostgroup.')
has_output_params = LDAPUpdate.has_output_params + hostgroup_output_params
msg_summary = _('Modified hostgroup "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list,
*keys, **options):
assert isinstance(dn, DN)
if keys[0] in PROTECTED_HOSTGROUPS and 'rename' in options:
raise errors.ProtectedEntryError(label=_(u'hostgroup'),
key=keys[0],
reason=_(u'privileged hostgroup'))
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, dn, entry_attrs)
return dn
@register()
class hostgroup_find(LDAPSearch):
__doc__ = _('Search for hostgroups.')
member_attributes = ['member', 'memberof', 'membermanager']
has_output_params = LDAPSearch.has_output_params + hostgroup_output_params
msg_summary = ngettext(
'%(count)d hostgroup matched', '%(count)d hostgroups matched', 0
)
def post_callback(self, ldap, entries, truncated, *args, **options):
if options.get('pkey_only', False):
return truncated
for entry in entries:
self.obj.suppress_netgroup_memberof(ldap, entry.dn, entry)
return truncated
@register()
class hostgroup_show(LDAPRetrieve):
__doc__ = _('Display information about a hostgroup.')
has_output_params = (
LDAPRetrieve.has_output_params + hostgroup_output_params
)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, dn, entry_attrs)
return dn
@register()
class hostgroup_add_member(LDAPAddMember):
__doc__ = _('Add members to a hostgroup.')
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, dn, entry_attrs)
return (completed, dn)
@register()
class hostgroup_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a hostgroup.')
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
if keys[0] in PROTECTED_HOSTGROUPS and 'host' in options:
result = api.Command.hostgroup_show(keys[0])
hosts_left = set(result['result'].get('member_host', []))
hosts_deleted = set(options['host'])
if hosts_left.issubset(hosts_deleted):
raise errors.LastMemberError(key=sorted(hosts_deleted)[0],
label=_(u'hostgroup'),
container=keys[0])
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.suppress_netgroup_memberof(ldap, dn, entry_attrs)
return (completed, dn)
@register()
class hostgroup_add_member_manager(LDAPAddMember):
__doc__ = _('Add users that can manage members of this hostgroup.')
has_output_params = (
LDAPAddMember.has_output_params + hostgroup_output_params
)
member_attributes = ['membermanager']
@register()
class hostgroup_remove_member_manager(LDAPRemoveMember):
__doc__ = _('Remove users that can manage members of this hostgroup.')
has_output_params = (
LDAPRemoveMember.has_output_params + hostgroup_output_params
)
member_attributes = ['membermanager']
| 13,384
|
Python
|
.py
| 308
| 34.613636
| 256
| 0.618744
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,869
|
ca.py
|
freeipa_freeipa/ipaserver/plugins/ca.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
import base64
import six
from ipalib import api, errors, messages, output
from ipalib import Bytes, DNParam, Flag, Str, Int
from ipalib.constants import IPA_CA_CN
from ipalib.plugable import Registry
from ipapython.dn import ATTR_NAME_BY_OID
from ipaserver.plugins.baseldap import (
LDAPObject, LDAPSearch, LDAPCreate, LDAPDelete,
LDAPUpdate, LDAPRetrieve, LDAPQuery, pkey_to_value)
from ipaserver.plugins.cert import ca_enabled_check
from ipalib import _, ngettext, x509
__doc__ = _("""
Manage Certificate Authorities
""") + _("""
Subordinate Certificate Authorities (Sub-CAs) can be added for scoped issuance
of X.509 certificates.
""") + _("""
CAs are enabled on creation, but their use is subject to CA ACLs unless the
operator has permission to bypass CA ACLs.
""") + _("""
All CAs except the 'IPA' CA can be disabled or re-enabled. Disabling a CA
prevents it from issuing certificates but does not affect the validity of its
certificate.
""") + _("""
CAs (all except the 'IPA' CA) can be deleted. Deleting a CA causes its signing
certificate to be revoked and its private key deleted.
""") + _("""
EXAMPLES:
""") + _("""
Create new CA, subordinate to the IPA CA (requires permission
"System: Add CA"):
ipa ca-add puppet --desc "Puppet" \\
--subject "CN=Puppet CA,O=EXAMPLE.COM"
""") + _("""
Disable a CA (requires permission "System: Modify CA"):
ipa ca-disable puppet
""") + _("""
Re-enable a CA (requires permission "System: Modify CA"):
ipa ca-enable puppet
""") + _("""
Delete a CA (requires permission "System: Delete CA"; also requires
CA to be disabled first):
ipa ca-del puppet
""")
register = Registry()
@register()
class ca(LDAPObject):
"""
Lightweight CA Object
"""
container_dn = api.env.container_ca
object_name = _('Certificate Authority')
object_name_plural = _('Certificate Authorities')
object_class = ['ipaca']
permission_filter_objectclasses = ['ipaca']
default_attributes = [
'cn', 'description', 'ipacaid', 'ipacaissuerdn', 'ipacasubjectdn',
'ipacarandomserialnumberversion', 'ipacahsmconfiguration',
]
rdn_attribute = 'cn'
allow_rename = True
label = _('Certificate Authorities')
label_singular = _('Certificate Authority')
takes_params = (
Str('cn',
primary_key=True,
cli_name='name',
label=_('Name'),
doc=_('Name for referencing the CA'),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Description of the purpose of the CA'),
),
Str('ipacaid',
cli_name='id',
label=_('Authority ID'),
doc=_('Dogtag Authority ID'),
flags=['no_create', 'no_update'],
),
DNParam('ipacasubjectdn',
cli_name='subject',
label=_('Subject DN'),
doc=_('Subject Distinguished Name'),
flags=['no_update'],
),
DNParam('ipacaissuerdn',
cli_name='issuer',
label=_('Issuer DN'),
doc=_('Issuer Distinguished Name'),
flags=['no_create', 'no_update'],
),
Bytes(
'certificate',
label=_("Certificate"),
doc=_("Base-64 encoded certificate."),
flags={'no_create', 'no_update', 'no_search'},
),
Bytes(
'certificate_chain*',
label=_("Certificate chain"),
doc=_("X.509 certificate chain"),
flags={'no_create', 'no_update', 'no_search'},
),
Int(
'ipacarandomserialnumberversion',
cli_name='randomserialnumberversion',
label=_('RSN Version'),
doc=_('Random Serial Number Version'),
flags={'no_create', 'no_update'},
),
)
permission_filter_objectclasses = ['ipaca']
managed_permissions = {
'System: Read CAs': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn',
'description',
'ipacaid',
'ipacaissuerdn',
'ipacasubjectdn',
'ipacarandomserialnumberversion',
'ipacahsmconfiguration',
'objectclass',
},
},
'System: Add CA': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=cas,cn=ca,$SUFFIX")(version 3.0;acl "permission:Add CA";allow (add) groupdn = "ldap:///cn=Add CA,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Delete CA': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=cas,cn=ca,$SUFFIX")(version 3.0;acl "permission:Delete CA";allow (delete) groupdn = "ldap:///cn=Delete CA,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
'System: Modify CA': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'cn',
'description',
},
'replaces': [
'(targetattr = "cn || description")(target = "ldap:///cn=*,cn=cas,cn=ca,$SUFFIX")(version 3.0;acl "permission:Modify CA";allow (write) groupdn = "ldap:///cn=Modify CA,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'CA Administrator'},
},
}
def set_certificate_attrs(entry, options, want_cert=True):
"""
Set certificate attributes into the entry. Depending on
options, this may contact Dogtag to retrieve certificate or
chain. If the retrieval fails with 404 (which can occur under
normal operation due to lightweight CA key replication delay),
return a message object that should be set in the response.
"""
try:
ca_id = entry['ipacaid'][0]
except KeyError:
return None
full = options.get('all', False)
want_chain = options.get('chain', False)
want_data = want_cert or want_chain or full
if not want_data:
return None
msg = None
with api.Backend.ra_lightweight_ca as ca_api:
if want_cert or full:
try:
der = ca_api.read_ca_cert(ca_id)
entry['certificate'] = base64.b64encode(der).decode('ascii')
except errors.HTTPRequestError as e:
if e.status == 404: # pylint: disable=no-member
msg = messages.LightweightCACertificateNotAvailable(
ca=entry['cn'][0])
else:
raise e
if want_chain or full:
try:
pkcs7_der = ca_api.read_ca_chain(ca_id)
certs = x509.pkcs7_to_certs(pkcs7_der, x509.DER)
ders = [cert.public_bytes(x509.Encoding.DER) for cert in certs]
entry['certificate_chain'] = ders
except errors.HTTPRequestError as e:
if e.status == 404: # pylint: disable=no-member
msg = messages.LightweightCACertificateNotAvailable(
ca=entry['cn'][0])
else:
raise e
return msg
@register()
class ca_find(LDAPSearch):
__doc__ = _("Search for CAs.")
msg_summary = ngettext(
'%(count)d CA matched', '%(count)d CAs matched', 0
)
def execute(self, *keys, **options):
ca_enabled_check(self.api)
result = super(ca_find, self).execute(*keys, **options)
if not options.get('pkey_only', False):
for entry in result['result']:
msg = set_certificate_attrs(entry, options, want_cert=False)
if msg:
self.add_message(msg)
return result
_chain_flag = Flag(
'chain',
default=False,
doc=_('Include certificate chain in output'),
)
@register()
class ca_show(LDAPRetrieve):
__doc__ = _("Display the properties of a CA.")
takes_options = LDAPRetrieve.takes_options + (
_chain_flag,
)
def execute(self, *keys, **options):
ca_enabled_check(self.api)
result = super(ca_show, self).execute(*keys, **options)
msg = set_certificate_attrs(result['result'], options)
if msg:
self.add_message(msg)
return result
@register()
class ca_add(LDAPCreate):
__doc__ = _("Create a CA.")
msg_summary = _('Created CA "%(value)s"')
takes_options = LDAPCreate.takes_options + (
_chain_flag,
)
def pre_callback(self, ldap, dn, entry, entry_attrs, *keys, **options):
ca_enabled_check(self.api)
if not ldap.can_add(dn[1:], 'ipaca'):
raise errors.ACIError(
info=_("Insufficient 'add' privilege for entry '%s'.") % dn)
# check that DN only includes standard naming attributes
dn_attrs = {
ava.attr.lower()
for rdn in options['ipacasubjectdn']
for ava in rdn
}
x509_attrs = {
attr.lower()
for attr in six.viewvalues(ATTR_NAME_BY_OID)
}
unknown_attrs = dn_attrs - x509_attrs
if len(unknown_attrs) > 0:
raise errors.ValidationError(
name=_("Subject DN"),
error=_("Unrecognized attributes: %(attrs)s")
% dict(attrs=", ".join(unknown_attrs))
)
# check for name collision before creating CA in Dogtag
try:
api.Object.ca.get_dn_if_exists(keys[-1])
self.obj.handle_duplicate_entry(*keys)
except errors.NotFound:
pass
# check for subject collision before creating CA in Dogtag
result = api.Command.ca_find(ipacasubjectdn=options['ipacasubjectdn'])
if result['count'] > 0:
raise errors.DuplicateEntry(message=_(
"Subject DN is already used by CA '%s'"
) % result['result'][0]['cn'][0])
# Create the CA in Dogtag.
with self.api.Backend.ra_lightweight_ca as ca_api:
resp = ca_api.create_ca(options['ipacasubjectdn'])
entry['ipacaid'] = [resp['id']]
entry['ipacaissuerdn'] = [resp['issuerDN']]
# In the event that the issued certificate's subject DN
# differs from what was requested, record the actual DN.
#
entry['ipacasubjectdn'] = [resp['dn']]
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
msg = set_certificate_attrs(entry_attrs, options)
if msg:
self.add_message(msg)
return dn
@register()
class ca_del(LDAPDelete):
__doc__ = _('Delete a CA (must be disabled first).')
msg_summary = _('Deleted CA "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
ca_enabled_check(self.api)
# ensure operator has permission to delete CA
# before contacting Dogtag
if not ldap.can_delete(dn):
raise errors.ACIError(info=_(
"Insufficient privilege to delete a CA."))
if keys[0] == IPA_CA_CN:
raise errors.ProtectedEntryError(
label=_("CA"),
key=keys[0],
reason=_("IPA CA cannot be deleted"))
ca_id = self.api.Command.ca_show(keys[0])['result']['ipacaid'][0]
with self.api.Backend.ra_lightweight_ca as ca_api:
data = ca_api.read_ca(ca_id)
if data['enabled']:
raise errors.ProtectedEntryError(
label=_("CA"),
key=keys[0],
reason=_("Must be disabled first"))
ca_api.delete_ca(ca_id)
return dn
@register()
class ca_mod(LDAPUpdate):
__doc__ = _("Modify CA configuration.")
msg_summary = _('Modified CA "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
ca_enabled_check(self.api)
if 'rename' in options or 'cn' in entry_attrs:
if keys[0] == IPA_CA_CN:
raise errors.ProtectedEntryError(
label=_("CA"),
key=keys[0],
reason=u'IPA CA cannot be renamed')
return dn
class CAQuery(LDAPQuery):
has_output = output.standard_value
def execute(self, cn, **options):
ca_enabled_check(self.api)
ca_obj = self.api.Command.ca_show(cn)['result']
# ensure operator has permission to modify CAs
if not self.api.Backend.ldap2.can_write(ca_obj['dn'], 'description'):
raise errors.ACIError(info=_(
"Insufficient privilege to modify a CA."))
with self.api.Backend.ra_lightweight_ca as ca_api:
self.perform_action(ca_api, ca_obj['ipacaid'][0])
return dict(
result=True,
value=pkey_to_value(cn, options),
)
def perform_action(self, ca_api, ca_id):
raise NotImplementedError
@register()
class ca_disable(CAQuery):
__doc__ = _('Disable a CA.')
msg_summary = _('Disabled CA "%(value)s"')
def execute(self, cn, **options):
if cn == IPA_CA_CN:
raise errors.ProtectedEntryError(
label=_("CA"),
key=cn,
reason=_("IPA CA cannot be disabled"))
return super(ca_disable, self).execute(cn, **options)
def perform_action(self, ca_api, ca_id):
ca_api.disable_ca(ca_id)
@register()
class ca_enable(CAQuery):
__doc__ = _('Enable a CA.')
msg_summary = _('Enabled CA "%(value)s"')
def perform_action(self, ca_api, ca_id):
ca_api.enable_ca(ca_id)
| 14,006
|
Python
|
.py
| 366
| 28.956284
| 218
| 0.572881
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,870
|
virtual.py
|
freeipa_freeipa/ipaserver/plugins/virtual.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
"""
Base classes for non-LDAP backend plugins.
"""
import logging
from ipalib import Command
from ipalib import errors
from ipapython.dn import DN
from ipalib.text import _
logger = logging.getLogger(__name__)
class VirtualCommand(Command):
"""
A command that doesn't use the LDAP backend but wants to use the
LDAP access control system to make authorization decisions.
The class variable operation is the commonName attribute of the
entry to be tested against.
In advance, you need to create an entry of the form:
cn=<operation>, api.env.container_virtual, api.env.basedn
Ex.
cn=request certificate, cn=virtual operations,cn=etc, dc=example, dc=com
"""
operation = None
def check_access(self, operation=None):
"""
Perform an LDAP query to determine authorization.
This should be executed before any actual work is done.
"""
if self.operation is None and operation is None:
raise errors.ACIError(info=_('operation not defined'))
if operation is None:
operation = self.operation
logger.debug("IPA: virtual verify %s", operation)
return check_operation_access(self.api, operation)
def check_operation_access(api, operation):
"""
Check access of bound principal to given operation.
:return: ``True``
:raises: ``ACIError`` on access denied or ``NotFound`` for
unknown virtual operation
"""
operationdn = DN(
('cn', operation), api.env.container_virtual, api.env.basedn)
try:
if not api.Backend.ldap2.can_write(operationdn, "objectclass"):
raise errors.ACIError(
info=_('not allowed to perform operation: %s') % operation)
except errors.NotFound:
raise errors.ACIError(info=_('No such virtual command'))
return True
| 2,650
|
Python
|
.py
| 66
| 35.136364
| 80
| 0.710998
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,871
|
servicedelegation.py
|
freeipa_freeipa/ipaserver/plugins/servicedelegation.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import six
from ipalib import api
from ipalib import Str
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPAddMember,
LDAPRemoveMember,
LDAPCreate,
LDAPDelete,
LDAPSearch,
LDAPRetrieve)
from ipalib import _, ngettext
from ipalib import errors
from ipapython.dn import DN
from ipapython import kerberos
if six.PY3:
unicode = str
__doc__ = _("""
Service Constrained Delegation
Manage rules to allow constrained delegation of credentials so
that a service can impersonate a user when communicating with another
service without requiring the user to actually forward their TGT.
This makes for a much better method of delegating credentials as it
prevents exposure of the short term secret of the user.
The naming convention is to append the word "target" or "targets" to
a matching rule name. This is not mandatory but helps conceptually
to associate rules and targets.
A rule consists of two things:
- A list of targets the rule applies to
- A list of memberPrincipals that are allowed to delegate for
those targets
A target consists of a list of principals that can be delegated.
In English, a rule says that this principal can delegate as this
list of principals, as defined by these targets.
In both a rule and a target Kerberos principals may be specified
by their name or an alias and the realm can be omitted. Additionally,
hosts can be specified by their names. If Kerberos principal specified
has a single component and does not end with '$' sign, it will be treated
as a host name. Kerberos principal names ending with '$' are typically
used as aliases for Active Directory-related services.
EXAMPLES:
Add a new constrained delegation rule:
ipa servicedelegationrule-add ftp-delegation
Add a new constrained delegation target:
ipa servicedelegationtarget-add ftp-delegation-target
Add a principal to the rule:
ipa servicedelegationrule-add-member --principals=ftp/ipa.example.com \
ftp-delegation
Add a host principal of the host 'ipa.example.com' to the rule:
ipa servicedelegationrule-add-member --principals=ipa.example.com \
ftp-delegation
Add our target to the rule:
ipa servicedelegationrule-add-target \
--servicedelegationtargets=ftp-delegation-target ftp-delegation
Add a principal to the target:
ipa servicedelegationtarget-add-member --principals=ldap/ipa.example.com \
ftp-delegation-target
Display information about a named delegation rule and target:
ipa servicedelegationrule_show ftp-delegation
ipa servicedelegationtarget_show ftp-delegation-target
Remove a constrained delegation:
ipa servicedelegationrule-del ftp-delegation-target
ipa servicedelegationtarget-del ftp-delegation
In this example the ftp service can get a TGT for the ldap service on
the bound user's behalf.
It is strongly discouraged to modify the delegations that ship with
IPA, ipa-http-delegation and its targets ipa-cifs-delegation-targets and
ipa-ldap-delegation-targets. Incorrect changes can remove the ability
to delegate, causing the framework to stop functioning.
""")
register = Registry()
PROTECTED_CONSTRAINT_RULES = (
u'ipa-http-delegation',
)
PROTECTED_CONSTRAINT_TARGETS = (
u'ipa-cifs-delegation-targets',
u'ipa-ldap-delegation-targets',
)
class servicedelegation(LDAPObject):
"""
Service Constrained Delegation base object.
This jams a couple of concepts into a single plugin because the
data is all stored in one place. There is a "rule" which has the
objectclass ipakrb5delegationacl. This is the entry that controls
the delegation. Other entries that lack this objectclass are
targets and define what services can be impersonated.
"""
container_dn = api.env.container_s4u2proxy
object_class = ['groupofprincipals', 'top']
managed_permissions = {
'System: Read Service Delegations': {
'ipapermbindruletype': 'permission',
'ipapermright': {'read', 'search', 'compare'},
'ipapermtargetfilter': {'(objectclass=groupofprincipals)'},
'ipapermdefaultattr': {
'cn', 'objectclass', 'memberprincipal',
'ipaallowedtarget',
},
'default_privileges': {'Service Administrators'},
},
'System: Add Service Delegations': {
'ipapermright': {'add'},
'ipapermtargetfilter': {'(objectclass=groupofprincipals)'},
'default_privileges': {'Service Administrators'},
},
'System: Remove Service Delegations': {
'ipapermright': {'delete'},
'ipapermtargetfilter': {'(objectclass=groupofprincipals)'},
'default_privileges': {'Service Administrators'},
},
'System: Modify Service Delegation Membership': {
'ipapermright': {'write'},
'ipapermtargetfilter': {'(objectclass=groupofprincipals)'},
'ipapermdefaultattr': {'memberprincipal', 'ipaallowedtarget'},
'default_privileges': {'Service Administrators'},
},
}
allow_rename = True
takes_params = (
Str(
'cn',
pattern='^[a-zA-Z0-9_.][a-zA-Z0-9_ .-]*[a-zA-Z0-9_.-]?$',
pattern_errmsg='may only include letters, numbers, _, -, ., '
'and a space inside',
maxlength=255,
cli_name='delegation_name',
label=_('Delegation name'),
primary_key=True,
),
Str(
'ipaallowedtarget_servicedelegationtarget',
label=_('Allowed Target'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str(
'ipaallowedtoimpersonate',
label=_('Allowed to Impersonate'),
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'memberprincipal',
label=_('Member principals'),
flags={'no_create', 'no_update', 'no_search'},
),
)
def normalize_principal_name(name, realm):
try:
princ = kerberos.Principal(name, realm=realm)
except ValueError as e:
raise errors.ValidationError(
name='principal',
reason=_("Malformed principal: %(error)s") % dict(error=str(e)))
if len(princ.components) == 1 and not princ.components[0].endswith('$'):
nprinc = 'host/' + unicode(princ)
else:
nprinc = unicode(princ)
return nprinc
class servicedelegation_add_member(LDAPAddMember):
__doc__ = _('Add target to a named service delegation.')
member_attrs = ['memberprincipal']
member_attributes = []
member_names = {}
principal_attr = 'memberprincipal'
principal_failedattr = 'failed_memberprincipal'
def get_options(self):
for option in super(servicedelegation_add_member, self).get_options():
yield option
for attr in self.member_attrs:
name = self.member_names[attr]
doc = self.member_param_doc % name
yield Str('%s*' % name, cli_name='%ss' % name, doc=doc,
label=_('member %s') % name, alwaysask=True)
def get_member_dns(self, **options):
"""
There are no member_dns to return. memberPrincipal needs
special handling since it is just a principal, not a
full dn.
"""
return dict(), dict()
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
"""
Add memberPrincipal values. This is done afterward because it isn't
a DN and the LDAPAddMember method explicitly only handles DNs.
A separate fake attribute name is used for failed members. This is
a reverse of the way this is typically handled in the *Member
routines, where a successful addition will be represented as
member/memberof_<attribute>. In this case, because memberPrincipal
isn't a DN, I'm doing the reverse, and creating a fake failed
attribute instead.
"""
ldap = self.obj.backend
members = []
failed[self.principal_failedattr] = {}
failed[self.principal_failedattr][self.principal_attr] = []
names = options.get(self.member_names[self.principal_attr], [])
basedn = self.api.env.container_accounts + self.api.env.basedn
if names:
for name in names:
if not name:
continue
princ = normalize_principal_name(name, self.api.env.realm)
try:
e_attrs = ldap.find_entry_by_attr(
'krbprincipalname', princ, 'krbprincipalaux',
attrs_list=['krbprincipalname'],
base_dn=basedn)
except errors.NotFound as e:
failed[self.principal_failedattr][
self.principal_attr].append((name, unicode(e)))
continue
try:
# normalize principal as set in krbPrincipalName attribute
mprinc = None
for p in e_attrs.get('krbprincipalname'):
p = unicode(p)
if p.lower() == princ.lower():
mprinc = p
if mprinc not in entry_attrs.get(self.principal_attr, []):
members.append(mprinc)
else:
raise errors.AlreadyGroupMember()
except errors.PublicError as e:
failed[self.principal_failedattr][
self.principal_attr].append((name, unicode(e)))
else:
completed += 1
if members:
value = entry_attrs.setdefault(self.principal_attr, [])
value.extend(members)
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return completed, dn
class servicedelegation_remove_member(LDAPRemoveMember):
__doc__ = _('Remove member from a named service delegation.')
member_attrs = ['memberprincipal']
member_attributes = []
member_names = {}
principal_attr = 'memberprincipal'
principal_failedattr = 'failed_memberprincipal'
def get_options(self):
for option in super(
servicedelegation_remove_member, self).get_options():
yield option
for attr in self.member_attrs:
name = self.member_names[attr]
doc = self.member_param_doc % name
yield Str('%s*' % name, cli_name='%ss' % name, doc=doc,
label=_('member %s') % name, alwaysask=True)
def get_member_dns(self, **options):
"""
Need to ignore memberPrincipal for now and handle the difference
in objectclass between a rule and a target.
"""
dns = {}
failed = {}
for attr in self.member_attrs:
dns[attr] = {}
if attr.lower() == 'memberprincipal':
# This will be handled later. memberprincipal isn't a
# DN so will blow up in assertions in baseldap.
continue
failed[attr] = {}
for ldap_obj_name in self.obj.attribute_members[attr]:
dns[attr][ldap_obj_name] = []
failed[attr][ldap_obj_name] = []
names = options.get(self.member_names[attr], [])
if not names:
continue
for name in names:
if not name:
continue
ldap_obj = self.api.Object[ldap_obj_name]
try:
dns[attr][ldap_obj_name].append(ldap_obj.get_dn(name))
except errors.PublicError as e:
failed[attr][ldap_obj_name].append((name, unicode(e)))
return dns, failed
def post_callback(self, ldap, completed, failed, dn, entry_attrs,
*keys, **options):
"""
Remove memberPrincipal values. This is done afterward because it
isn't a DN and the LDAPAddMember method explicitly only handles DNs.
See servicedelegation_add_member() for an explanation of what
failedattr is.
"""
ldap = self.obj.backend
failed[self.principal_failedattr] = {}
failed[self.principal_failedattr][self.principal_attr] = []
names = options.get(self.member_names[self.principal_attr], [])
if names:
for name in names:
if not name:
continue
princ = normalize_principal_name(name, self.api.env.realm)
try:
if princ in entry_attrs.get(self.principal_attr, []):
entry_attrs[self.principal_attr].remove(princ)
else:
raise errors.NotGroupMember()
except errors.PublicError as e:
failed[self.principal_failedattr][
self.principal_attr].append((name, unicode(e)))
else:
completed += 1
try:
ldap.update_entry(entry_attrs)
except errors.EmptyModlist:
pass
return completed, dn
@register()
class servicedelegationrule(servicedelegation):
"""
A service delegation rule. This is the ACL that controls
what can be delegated to whom.
"""
object_name = _('service delegation rule')
object_name_plural = _('service delegation rules')
object_class = ['ipakrb5delegationacl', 'groupofprincipals', 'top']
default_attributes = [
'cn', 'memberprincipal', 'ipaallowedtarget',
'ipaallowedtoimpersonate',
]
attribute_members = {
# memberprincipal is not listed because it isn't a DN
'ipaallowedtarget': ['servicedelegationtarget'],
}
label = _('Service delegation rules')
label_singular = _('Service delegation rule')
@register()
class servicedelegationrule_add(LDAPCreate):
__doc__ = _('Create a new service delegation rule.')
msg_summary = _('Added service delegation rule "%(value)s"')
@register()
class servicedelegationrule_del(LDAPDelete):
__doc__ = _('Delete service delegation.')
msg_summary = _('Deleted service delegation "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if keys[0] in PROTECTED_CONSTRAINT_RULES:
raise errors.ProtectedEntryError(
label=_(u'service delegation rule'),
key=keys[0],
reason=_(u'privileged service delegation rule')
)
return dn
@register()
class servicedelegationrule_find(LDAPSearch):
__doc__ = _('Search for service delegations rule.')
msg_summary = ngettext(
'%(count)d service delegation rule matched',
'%(count)d service delegation rules matched', 0
)
@register()
class servicedelegationrule_show(LDAPRetrieve):
__doc__ = _('Display information about a named service delegation rule.')
@register()
class servicedelegationrule_add_member(servicedelegation_add_member):
__doc__ = _('Add member to a named service delegation rule.')
member_names = {
'memberprincipal': 'principal',
}
@register()
class servicedelegationrule_remove_member(servicedelegation_remove_member):
__doc__ = _('Remove member from a named service delegation rule.')
member_names = {
'memberprincipal': 'principal',
}
@register()
class servicedelegationrule_add_target(LDAPAddMember):
__doc__ = _('Add target to a named service delegation rule.')
member_attributes = ['ipaallowedtarget']
attribute_members = {
'ipaallowedtarget': ['servicedelegationtarget'],
}
@register()
class servicedelegationrule_remove_target(LDAPRemoveMember):
__doc__ = _('Remove target from a named service delegation rule.')
member_attributes = ['ipaallowedtarget']
attribute_members = {
'ipaallowedtarget': ['servicedelegationtarget'],
}
@register()
class servicedelegationtarget(servicedelegation):
object_name = _('service delegation target')
object_name_plural = _('service delegation targets')
object_class = ['groupofprincipals', 'top']
default_attributes = [
'cn', 'memberprincipal',
]
attribute_members = {}
label = _('Service delegation targets')
label_singular = _('Service delegation target')
@register()
class servicedelegationtarget_add(LDAPCreate):
__doc__ = _('Create a new service delegation target.')
msg_summary = _('Added service delegation target "%(value)s"')
@register()
class servicedelegationtarget_del(LDAPDelete):
__doc__ = _('Delete service delegation target.')
msg_summary = _('Deleted service delegation target "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if keys[0] in PROTECTED_CONSTRAINT_TARGETS:
raise errors.ProtectedEntryError(
label=_(u'service delegation target'),
key=keys[0],
reason=_(u'privileged service delegation target')
)
return dn
@register()
class servicedelegationtarget_find(LDAPSearch):
__doc__ = _('Search for service delegation target.')
msg_summary = ngettext(
'%(count)d service delegation target matched',
'%(count)d service delegation targets matched', 0
)
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope,
term=None, **options):
"""
Exclude rules from the search output. A target contains a subset
of a rule objectclass.
"""
search_kw = self.args_options_2_entry(**options)
search_kw['objectclass'] = self.obj.object_class
attr_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
rule_kw = {'objectclass': 'ipakrb5delegationacl'}
target_filter = ldap.make_filter(rule_kw, rules=ldap.MATCH_NONE)
attr_filter = ldap.combine_filters(
(target_filter, attr_filter), rules=ldap.MATCH_ALL
)
search_kw = {}
for a in self.obj.default_attributes:
search_kw[a] = term
term_filter = ldap.make_filter(search_kw, exact=False)
sfilter = ldap.combine_filters(
(term_filter, attr_filter), rules=ldap.MATCH_ALL
)
return sfilter, base_dn, ldap.SCOPE_ONELEVEL
@register()
class servicedelegationtarget_show(LDAPRetrieve):
__doc__ = _('Display information about a named service delegation target.')
@register()
class servicedelegationtarget_add_member(servicedelegation_add_member):
__doc__ = _('Add member to a named service delegation target.')
member_names = {
'memberprincipal': 'principal',
}
@register()
class servicedelegationtarget_remove_member(servicedelegation_remove_member):
__doc__ = _('Remove member from a named service delegation target.')
member_names = {
'memberprincipal': 'principal',
}
| 19,377
|
Python
|
.py
| 460
| 33.184783
| 79
| 0.634653
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,872
|
aci.py
|
freeipa_freeipa/ipaserver/plugins/aci.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# 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 copy import deepcopy
import logging
import six
from ipalib import api, crud, errors
from ipalib import Object
from ipalib import Flag, Str, StrEnum, DNParam
from ipalib.aci import ACI
from ipalib import output
from ipalib import _, ngettext
from ipalib.plugable import Registry
from .baseldap import gen_pkey_only_option, pkey_to_value
from ipapython.dn import DN
__doc__ = _("""
Directory Server Access Control Instructions (ACIs)
ACIs are used to allow or deny access to information. This module is
currently designed to allow, not deny, access.
The aci commands are designed to grant permissions that allow updating
existing entries or adding or deleting new ones. The goal of the ACIs
that ship with IPA is to provide a set of low-level permissions that
grant access to special groups called taskgroups. These low-level
permissions can be combined into roles that grant broader access. These
roles are another type of group, roles.
For example, if you have taskgroups that allow adding and modifying users you
could create a role, useradmin. You would assign users to the useradmin
role to allow them to do the operations defined by the taskgroups.
You can create ACIs that delegate permission so users in group A can write
attributes on group B.
The type option is a map that applies to all entries in the users, groups or
host location. It is primarily designed to be used when granting add
permissions (to write new entries).
An ACI consists of three parts:
1. target
2. permissions
3. bind rules
The target is a set of rules that define which LDAP objects are being
targeted. This can include a list of attributes, an area of that LDAP
tree or an LDAP filter.
The targets include:
- attrs: list of attributes affected
- type: an object type (user, group, host, service, etc)
- memberof: members of a group
- targetgroup: grant access to modify a specific group. This is primarily
designed to enable users to add or remove members of a specific group.
- filter: A legal LDAP filter used to narrow the scope of the target.
- subtree: Used to apply a rule across an entire set of objects. For example,
to allow adding users you need to grant "add" permission to the subtree
ldap://uid=*,cn=users,cn=accounts,dc=example,dc=com. The subtree option
is a fail-safe for objects that may not be covered by the type option.
The permissions define what the ACI is allowed to do, and are one or
more of:
1. write - write one or more attributes
2. read - read one or more attributes
3. add - add a new entry to the tree
4. delete - delete an existing entry
5. all - all permissions are granted
Note the distinction between attributes and entries. The permissions are
independent, so being able to add a user does not mean that the user will
be editable.
The bind rule defines who this ACI grants permissions to. The LDAP server
allows this to be any valid LDAP entry but we encourage the use of
taskgroups so that the rights can be easily shared through roles.
For a more thorough description of access controls see
http://www.redhat.com/docs/manuals/dir-server/ag/8.0/Managing_Access_Control.html
EXAMPLES:
NOTE: ACIs are now added via the permission plugin. These examples are to
demonstrate how the various options work but this is done via the permission
command-line now (see last example).
Add an ACI so that the group "secretaries" can update the address on any user:
ipa group-add --desc="Office secretaries" secretaries
ipa aci-add --attrs=streetAddress --memberof=ipausers --group=secretaries --permissions=write --prefix=none "Secretaries write addresses"
Show the new ACI:
ipa aci-show --prefix=none "Secretaries write addresses"
Add an ACI that allows members of the "addusers" permission to add new users:
ipa aci-add --type=user --permission=addusers --permissions=add --prefix=none "Add new users"
Add an ACI that allows members of the editors manage members of the admins group:
ipa aci-add --permissions=write --attrs=member --targetgroup=admins --group=editors --prefix=none "Editors manage admins"
Add an ACI that allows members of the admins group to manage the street and zip code of those in the editors group:
ipa aci-add --permissions=write --memberof=editors --group=admins --attrs=street --attrs=postalcode --prefix=none "admins edit the address of editors"
Add an ACI that allows the admins group manage the street and zipcode of those who work for the boss:
ipa aci-add --permissions=write --group=admins --attrs=street --attrs=postalcode --filter="(manager=uid=boss,cn=users,cn=accounts,dc=example,dc=com)" --prefix=none "Edit the address of those who work for the boss"
Add an entirely new kind of record to IPA that isn't covered by any of the --type options, creating a permission:
ipa permission-add --permissions=add --subtree="cn=*,cn=orange,cn=accounts,dc=example,dc=com" --desc="Add Orange Entries" add_orange
The show command shows the raw 389-ds ACI.
IMPORTANT: When modifying the target attributes of an existing ACI you
must include all existing attributes as well. When doing an aci-mod the
targetattr REPLACES the current attributes, it does not add to them.
""")
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
register = Registry()
ACI_NAME_PREFIX_SEP = ":"
_type_map = {
'user': 'ldap:///' + str(DN(('uid', '*'), api.env.container_user, api.env.basedn)),
'group': 'ldap:///' + str(DN(('cn', '*'), api.env.container_group, api.env.basedn)),
'host': 'ldap:///' + str(DN(('fqdn', '*'), api.env.container_host, api.env.basedn)),
'hostgroup': 'ldap:///' + str(DN(('cn', '*'), api.env.container_hostgroup, api.env.basedn)),
'service': 'ldap:///' + str(DN(('krbprincipalname', '*'), api.env.container_service, api.env.basedn)),
'netgroup': 'ldap:///' + str(DN(('ipauniqueid', '*'), api.env.container_netgroup, api.env.basedn)),
'dnsrecord': 'ldap:///' + str(DN(('idnsname', '*'), api.env.container_dns, api.env.basedn)),
}
_valid_permissions_values = [
u'read', u'write', u'add', u'delete', u'all'
]
_valid_prefix_values = (
u'permission', u'delegation', u'selfservice', u'none'
)
class ListOfACI(output.Output):
type = (list, tuple)
doc = _('A list of ACI values')
def validate(self, cmd, entries):
assert isinstance(entries, self.type)
for (i, entry) in enumerate(entries):
if not isinstance(entry, unicode):
raise TypeError(output.emsg %
(cmd.name, self.__class__.__name__,
self.name, i, unicode, type(entry), entry)
)
aci_output = (
output.Output('result', unicode, 'A string representing the ACI'),
output.value,
output.summary,
)
def _make_aci_name(aciprefix, aciname):
"""
Given a name and a prefix construct an ACI name.
"""
if aciprefix == u"none":
return aciname
return aciprefix + ACI_NAME_PREFIX_SEP + aciname
def _parse_aci_name(aciname):
"""
Parse the raw ACI name and return a tuple containing the ACI prefix
and the actual ACI name.
"""
aciparts = aciname.partition(ACI_NAME_PREFIX_SEP)
if not aciparts[2]: # no prefix/name separator found
return (u"none",aciparts[0])
return (aciparts[0], aciparts[2])
def _group_from_memberof(memberof):
"""
Pull the group name out of a memberOf filter
"""
st = memberof.find('memberOf=')
if st == -1:
# We have a raw group name, use that
return api.Object['group'].get_dn(memberof)
en = memberof.find(')', st)
return memberof[st+9:en]
def _make_aci(ldap, current, aciname, kw):
"""
Given a name and a set of keywords construct an ACI.
"""
# Do some quick and dirty validation.
checked_args=['type','filter','subtree','targetgroup','attrs','memberof']
valid={}
for arg in checked_args:
if arg in kw:
valid[arg]=kw[arg] is not None
else:
valid[arg]=False
if valid['type'] + valid['filter'] + valid['subtree'] + valid['targetgroup'] > 1:
raise errors.ValidationError(name='target', error=_('type, filter, subtree and targetgroup are mutually exclusive'))
if 'aciprefix' not in kw:
raise errors.ValidationError(name='aciprefix', error=_('ACI prefix is required'))
if sum(valid.values()) == 0:
raise errors.ValidationError(name='target', error=_('at least one of: type, filter, subtree, targetgroup, attrs or memberof are required'))
if valid['filter'] + valid['memberof'] > 1:
raise errors.ValidationError(name='target', error=_('filter and memberof are mutually exclusive'))
group = 'group' in kw
permission = 'permission' in kw
selfaci = kw.get("selfaci", False)
if group + permission + selfaci > 1:
raise errors.ValidationError(name='target', error=_('group, permission and self are mutually exclusive'))
elif group + permission + selfaci == 0:
raise errors.ValidationError(name='target', error=_('One of group, permission or self is required'))
# Grab the dn of the group we're granting access to. This group may be a
# permission or a user group.
entry_attrs = []
if permission:
# This will raise NotFound if the permission doesn't exist
try:
entry_attrs = api.Command['permission_show'](kw['permission'])['result']
except errors.NotFound as e:
if 'test' in kw and not kw.get('test'):
raise e
else:
entry_attrs = {
'dn': DN(('cn', kw['permission']),
api.env.container_permission, api.env.basedn),
}
elif group:
# Not so friendly with groups. This will raise
try:
group_dn = api.Object['group'].get_dn_if_exists(kw['group'])
entry_attrs = {'dn': group_dn}
except errors.NotFound:
raise errors.NotFound(reason=_("Group '%s' does not exist") % kw['group'])
try:
a = ACI(current)
a.name = _make_aci_name(kw['aciprefix'], aciname)
a.set_permissions(kw['permissions'])
if 'selfaci' in kw and kw['selfaci']:
a.set_bindrule('userdn = "ldap:///self"')
else:
dn = entry_attrs['dn']
a.set_bindrule('groupdn = "ldap:///%s"' % dn)
if valid['attrs']:
a.set_target_attr(kw['attrs'])
if valid['memberof']:
try:
api.Object['group'].get_dn_if_exists(kw['memberof'])
except errors.NotFound:
raise api.Object['group'].handle_not_found(kw['memberof'])
groupdn = _group_from_memberof(kw['memberof'])
a.set_target_filter('memberOf=%s' % groupdn)
if valid['filter']:
# Test the filter by performing a simple search on it. The
# filter is considered valid if either it returns some entries
# or it returns no entries, otherwise we let whatever exception
# happened be raised.
if kw['filter'] in ('', None, u''):
raise errors.BadSearchFilter(info=_('empty filter'))
try:
ldap.find_entries(filter=kw['filter'])
except errors.NotFound:
pass
a.set_target_filter(kw['filter'])
if valid['type']:
target = _type_map[kw['type']]
a.set_target(target)
if valid['targetgroup']:
# Purposely no try here so we'll raise a NotFound
group_dn = api.Object['group'].get_dn_if_exists(kw['targetgroup'])
target = 'ldap:///%s' % group_dn
a.set_target(target)
if valid['subtree']:
# See if the subtree is a full URI
target = kw['subtree']
if not target.startswith('ldap:///'):
target = 'ldap:///%s' % target
a.set_target(target)
except SyntaxError as e:
raise errors.ValidationError(name='target', error=_('Syntax Error: %(error)s') % dict(error=str(e)))
return a
def _aci_to_kw(ldap, a, test=False, pkey_only=False):
"""Convert an ACI into its equivalent keywords.
This is used for the modify operation so we can merge the
incoming kw and existing ACI and pass the result to
_make_aci().
"""
kw = {}
kw['aciprefix'], kw['aciname'] = _parse_aci_name(a.name)
if pkey_only:
return kw
kw['permissions'] = tuple(a.permissions)
if 'targetattr' in a.target:
kw['attrs'] = tuple(unicode(e)
for e in a.target['targetattr']['expression'])
if 'targetfilter' in a.target:
target = a.target['targetfilter']['expression']
if target.startswith('(memberOf=') or target.startswith('memberOf='):
_junk, memberof = target.split('memberOf=', 1)
memberof = DN(memberof)
kw['memberof'] = memberof['cn']
else:
kw['filter'] = unicode(target)
if 'target' in a.target:
target = a.target['target']['expression']
found = False
for k, value in _type_map.items():
if value == target:
kw['type'] = unicode(k)
found = True
break
if not found:
if target.startswith('('):
kw['filter'] = unicode(target)
else:
# See if the target is a group. If so we set the
# targetgroup attr, otherwise we consider it a subtree
try:
targetdn = DN(target.replace('ldap:///',''))
except ValueError as e:
raise errors.ValidationError(
name='subtree', error=_("invalid DN (%s)") % e)
if targetdn.endswith(DN(api.env.container_group, api.env.basedn)):
kw['targetgroup'] = targetdn[0]['cn']
else:
kw['subtree'] = unicode(target)
groupdn = a.bindrule['expression']
groupdn = groupdn.replace('ldap:///','')
if groupdn == 'self':
kw['selfaci'] = True
elif groupdn == 'anyone':
pass
else:
groupdn = DN(groupdn)
if len(groupdn) and groupdn[0].attr == 'cn':
dn = DN()
entry = ldap.make_entry(dn)
try:
entry = ldap.get_entry(groupdn, ['cn'])
except errors.NotFound:
# FIXME, use real name here
if test:
dn = DN(('cn', 'test'), api.env.container_permission,
api.env.basedn)
entry = ldap.make_entry(dn, {'cn': [u'test']})
if api.env.container_permission in entry.dn:
kw['permission'] = entry['cn'][0]
else:
if 'cn' in entry:
kw['group'] = entry['cn'][0]
return kw
def _convert_strings_to_acis(acistrs):
acis = []
for a in acistrs:
try:
acis.append(ACI(a))
except SyntaxError:
logger.warning("Failed to parse: %s", a)
return acis
def _find_aci_by_name(acis, aciprefix, aciname):
name = _make_aci_name(aciprefix, aciname).lower()
for a in acis:
if a.name.lower() == name:
return a
raise errors.NotFound(reason=_('ACI with name "%s" not found') % aciname)
def validate_permissions(ugettext, perm):
perm = perm.strip().lower()
if perm not in _valid_permissions_values:
return '"%s" is not a valid permission' % perm
return None
def _normalize_permissions(perm):
valid_permissions = []
perm = perm.strip().lower()
if perm not in valid_permissions:
valid_permissions.append(perm)
return ','.join(valid_permissions)
_prefix_option = StrEnum('aciprefix',
cli_name='prefix',
label=_('ACI prefix'),
doc=_('Prefix used to distinguish ACI types ' \
'(permission, delegation, selfservice, none)'),
values=_valid_prefix_values,
flags={'no_create', 'no_update', 'no_search'},
)
@register()
class aci(Object):
__doc__ = _('ACI object.')
NO_CLI = True
label = _('ACIs')
takes_params = (
Str('aciname',
cli_name='name',
label=_('ACI name'),
primary_key=True,
flags=('virtual_attribute',),
),
Str('permission?',
cli_name='permission',
label=_('Permission'),
doc=_('Permission ACI grants access to'),
flags=('virtual_attribute',),
),
Str('group?',
cli_name='group',
label=_('User group'),
doc=_('User group ACI grants access to'),
flags=('virtual_attribute',),
),
Str('permissions+', validate_permissions,
cli_name='permissions',
label=_('Permissions'),
doc=_('Permissions to grant' \
'(read, write, add, delete, all)'),
normalizer=_normalize_permissions,
flags=('virtual_attribute',),
),
Str('attrs*',
cli_name='attrs',
label=_('Attributes to which the permission applies'),
doc=_('Attributes'),
flags=('virtual_attribute',),
),
StrEnum('type?',
cli_name='type',
label=_('Type'),
doc=_('type of IPA object (user, group, host, hostgroup, service, netgroup)'),
values=(u'user', u'group', u'host', u'service', u'hostgroup', u'netgroup', u'dnsrecord'),
flags=('virtual_attribute',),
),
Str('memberof?',
cli_name='memberof',
label=_('Member of'), # FIXME: Does this label make sense?
doc=_('Member of a group'),
flags=('virtual_attribute',),
),
Str('filter?',
cli_name='filter',
label=_('Filter'),
doc=_('Legal LDAP filter (e.g. ou=Engineering)'),
flags=('virtual_attribute',),
),
Str('subtree?',
cli_name='subtree',
label=_('Subtree'),
doc=_('Subtree to apply ACI to'),
flags=('virtual_attribute',),
),
Str('targetgroup?',
cli_name='targetgroup',
label=_('Target group'),
doc=_('Group to apply ACI to'),
flags=('virtual_attribute',),
),
Flag('selfaci?',
cli_name='self',
label=_('Target your own entry (self)'),
doc=_('Apply ACI to your own entry (self)'),
flags=('virtual_attribute',),
),
_prefix_option,
Str('aci',
label=_('ACI'),
flags={'no_create', 'no_update', 'no_search'},
),
)
@register()
class aci_add(crud.Create):
__doc__ = _('Create new ACI.')
NO_CLI = True
msg_summary = _('Created ACI "%(value)s"')
takes_options = (
_prefix_option,
Flag('test?',
doc=_('Test the ACI syntax but don\'t write anything'),
default=False,
),
)
def execute(self, aciname, **kw):
"""
Execute the aci-create operation.
Returns the entry as it will be created in LDAP.
:param aciname: The name of the ACI being added.
:param kw: Keyword arguments for the other LDAP attributes.
"""
assert 'aciname' not in kw
ldap = self.api.Backend.ldap2
newaci = _make_aci(ldap, None, aciname, kw)
entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acis = _convert_strings_to_acis(entry.get('aci', []))
for a in acis:
# FIXME: add check for permission_group = permission_group
if a.isequal(newaci) or newaci.name == a.name:
raise errors.DuplicateEntry()
newaci_str = unicode(newaci)
entry.setdefault('aci', []).append(newaci_str)
if not kw.get('test', False):
ldap.update_entry(entry)
if kw.get('raw', False):
result = dict(aci=unicode(newaci_str))
else:
result = _aci_to_kw(ldap, newaci, kw.get('test', False))
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class aci_del(crud.Delete):
__doc__ = _('Delete ACI.')
NO_CLI = True
has_output = output.standard_boolean
msg_summary = _('Deleted ACI "%(value)s"')
takes_options = (_prefix_option,)
def execute(self, aciname, aciprefix, **options):
"""
Execute the aci-delete operation.
:param aciname: The name of the ACI being deleted.
:param aciprefix: The ACI prefix.
"""
ldap = self.api.Backend.ldap2
entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acistrs = entry.get('aci', [])
acis = _convert_strings_to_acis(acistrs)
aci = _find_aci_by_name(acis, aciprefix, aciname)
for a in acistrs:
candidate = ACI(a)
if aci.isequal(candidate):
acistrs.remove(a)
break
entry['aci'] = acistrs
ldap.update_entry(entry)
return dict(
result=True,
value=pkey_to_value(aciname, options),
)
@register()
class aci_mod(crud.Update):
__doc__ = _('Modify ACI.')
NO_CLI = True
takes_options = (_prefix_option,)
internal_options = ['rename']
msg_summary = _('Modified ACI "%(value)s"')
def execute(self, aciname, **kw):
aciprefix = kw['aciprefix']
ldap = self.api.Backend.ldap2
entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acis = _convert_strings_to_acis(entry.get('aci', []))
aci = _find_aci_by_name(acis, aciprefix, aciname)
# The strategy here is to convert the ACI we're updating back into
# a series of keywords. Then we replace any keywords that have been
# updated and convert that back into an ACI and write it out.
oldkw = _aci_to_kw(ldap, aci)
newkw = deepcopy(oldkw)
if newkw.get('selfaci', False):
# selfaci is set in aci_to_kw to True only if the target is self
kw['selfaci'] = True
newkw.update(kw)
for acikw in (oldkw, newkw):
acikw.pop('aciname', None)
# _make_aci is what is run in aci_add and validates the input.
# Do this before we delete the existing ACI.
newaci = _make_aci(ldap, None, aciname, newkw)
if aci.isequal(newaci):
raise errors.EmptyModlist()
self.api.Command['aci_del'](aciname, aciprefix=aciprefix)
try:
result = self.api.Command['aci_add'](aciname, **newkw)['result']
except Exception as e:
# ACI could not be added, try to restore the old deleted ACI and
# report the ADD error back to user
try:
self.api.Command['aci_add'](aciname, **oldkw)
except Exception:
pass
raise e
if kw.get('raw', False):
result = dict(aci=unicode(newaci))
else:
result = _aci_to_kw(ldap, newaci)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class aci_find(crud.Search):
__doc__ = _("""
Search for ACIs.
Returns a list of ACIs
EXAMPLES:
To find all ACIs that apply directly to members of the group ipausers:
ipa aci-find --memberof=ipausers
To find all ACIs that grant add access:
ipa aci-find --permissions=add
Note that the find command only looks for the given text in the set of
ACIs, it does not evaluate the ACIs to see if something would apply.
For example, searching on memberof=ipausers will find all ACIs that
have ipausers as a memberof. There may be other ACIs that apply to
members of that group indirectly.
""")
NO_CLI = True
msg_summary = ngettext('%(count)d ACI matched', '%(count)d ACIs matched', 0)
takes_options = (_prefix_option.clone_rename("aciprefix?", required=False),
gen_pkey_only_option("name"),)
def execute(self, term=None, **kw):
ldap = self.api.Backend.ldap2
entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acis = _convert_strings_to_acis(entry.get('aci', []))
results = []
if term:
term = term.lower()
for a in acis:
if a.name.lower().find(term) != -1 and a not in results:
results.append(a)
acis = list(results)
else:
results = list(acis)
if kw.get('aciname'):
for a in acis:
prefix, name = _parse_aci_name(a.name)
if name != kw['aciname']:
results.remove(a)
acis = list(results)
if kw.get('aciprefix'):
for a in acis:
prefix, name = _parse_aci_name(a.name)
if prefix != kw['aciprefix']:
results.remove(a)
acis = list(results)
if kw.get('attrs'):
for a in acis:
if 'targetattr' not in a.target:
results.remove(a)
continue
alist1 = sorted(
[t.lower() for t in a.target['targetattr']['expression']]
)
alist2 = sorted([t.lower() for t in kw['attrs']])
if len(set(alist1) & set(alist2)) != len(alist2):
results.remove(a)
acis = list(results)
if kw.get('permission'):
try:
self.api.Command['permission_show'](
kw['permission']
)
except errors.NotFound:
pass
else:
for a in acis:
uri = 'ldap:///%s' % entry.dn
if a.bindrule['expression'] != uri:
results.remove(a)
acis = list(results)
if kw.get('permissions'):
for a in acis:
alist1 = sorted(a.permissions)
alist2 = sorted(kw['permissions'])
if len(set(alist1) & set(alist2)) != len(alist2):
results.remove(a)
acis = list(results)
if kw.get('memberof'):
try:
dn = _group_from_memberof(kw['memberof'])
except errors.NotFound:
pass
else:
memberof_filter = '(memberOf=%s)' % dn
for a in acis:
if 'targetfilter' in a.target:
targetfilter = a.target['targetfilter']['expression']
if targetfilter != memberof_filter:
results.remove(a)
else:
results.remove(a)
if kw.get('type'):
for a in acis:
if 'target' in a.target:
target = a.target['target']['expression']
else:
results.remove(a)
continue
found = False
for k, value in _type_map.items():
if value == target and kw['type'] == k:
found = True
break
if not found:
try:
results.remove(a)
except ValueError:
pass
if kw.get('selfaci', False) is True:
for a in acis:
if a.bindrule['expression'] != u'ldap:///self':
try:
results.remove(a)
except ValueError:
pass
if kw.get('group'):
for a in acis:
groupdn = a.bindrule['expression']
groupdn = DN(groupdn.replace('ldap:///',''))
try:
cn = groupdn[0]['cn']
except (IndexError, KeyError):
cn = None
if cn is None or cn != kw['group']:
try:
results.remove(a)
except ValueError:
pass
if kw.get('targetgroup'):
for a in acis:
found = False
if 'target' in a.target:
target = a.target['target']['expression']
targetdn = DN(target.replace('ldap:///',''))
group_container_dn = DN(api.env.container_group, api.env.basedn)
if targetdn.endswith(group_container_dn):
try:
cn = targetdn[0]['cn']
except (IndexError, KeyError):
cn = None
if cn == kw['targetgroup']:
found = True
if not found:
try:
results.remove(a)
except ValueError:
pass
if kw.get('filter'):
if not kw['filter'].startswith('('):
kw['filter'] = unicode('('+kw['filter']+')')
for a in acis:
if 'targetfilter' not in a.target or\
not a.target['targetfilter']['expression'] or\
a.target['targetfilter']['expression'] != kw['filter']:
results.remove(a)
if kw.get('subtree'):
for a in acis:
if 'target' in a.target:
target = a.target['target']['expression']
else:
results.remove(a)
continue
if kw['subtree'].lower() != target.lower():
try:
results.remove(a)
except ValueError:
pass
acis = []
for result in results:
if kw.get('raw', False):
aci = dict(aci=unicode(result))
else:
aci = _aci_to_kw(ldap, result,
pkey_only=kw.get('pkey_only', False))
acis.append(aci)
return dict(
result=acis,
count=len(acis),
truncated=False,
)
@register()
class aci_show(crud.Retrieve):
__doc__ = _('Display a single ACI given an ACI name.')
NO_CLI = True
takes_options = (
_prefix_option,
DNParam('location?',
label=_('Location of the ACI'),
)
)
def execute(self, aciname, **kw):
"""
Execute the aci-show operation.
Returns the entry
:param uid: The login name of the user to retrieve.
:param kw: unused
"""
ldap = self.api.Backend.ldap2
dn = kw.get('location', self.api.env.basedn)
entry = ldap.get_entry(dn, ['aci'])
acis = _convert_strings_to_acis(entry.get('aci', []))
aci = _find_aci_by_name(acis, kw['aciprefix'], aciname)
if kw.get('raw', False):
result = dict(aci=unicode(aci))
else:
result = _aci_to_kw(ldap, aci)
return dict(
result=result,
value=pkey_to_value(aciname, kw),
)
@register()
class aci_rename(crud.Update):
__doc__ = _('Rename an ACI.')
NO_CLI = True
takes_options = (
_prefix_option,
Str('newname',
doc=_('New ACI name'),
),
)
msg_summary = _('Renamed ACI to "%(value)s"')
def execute(self, aciname, **kw):
ldap = self.api.Backend.ldap2
entry = ldap.get_entry(self.api.env.basedn, ['aci'])
acis = _convert_strings_to_acis(entry.get('aci', []))
aci = _find_aci_by_name(acis, kw['aciprefix'], aciname)
for a in acis:
prefix, _name = _parse_aci_name(a.name)
if _make_aci_name(prefix, kw['newname']) == a.name:
raise errors.DuplicateEntry()
# The strategy here is to convert the ACI we're updating back into
# a series of keywords. Then we replace any keywords that have been
# updated and convert that back into an ACI and write it out.
newkw = _aci_to_kw(ldap, aci)
if newkw.get("selfaci"):
# selfaci is set in aci_to_kw to True only if the target is self
kw['selfaci'] = True
if 'aciname' in newkw:
del newkw['aciname']
# _make_aci is what is run in aci_add and validates the input.
# Do this before we delete the existing ACI.
newaci = _make_aci(ldap, None, kw['newname'], newkw)
self.api.Command['aci_del'](aciname, aciprefix=kw['aciprefix'])
result = self.api.Command['aci_add'](kw['newname'], **newkw)['result']
if kw.get('raw', False):
result = dict(aci=unicode(newaci))
else:
result = _aci_to_kw(ldap, newaci)
return dict(
result=result,
value=pkey_to_value(kw['newname'], kw),
)
| 34,153
|
Python
|
.py
| 817
| 31.660955
| 216
| 0.574735
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,873
|
pwpolicy.py
|
freeipa_freeipa/ipaserver/plugins/pwpolicy.py
|
# Authors:
# Pavel Zuna <pzuna@redhat.com>
# Martin Kosek <mkosek@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/>.
import logging
from ipalib import api
from ipalib import Int, Str, DNParam, Bool
from ipalib import errors
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPRetrieve,
LDAPSearch)
from ipalib import _
from ipalib.plugable import Registry
from ipalib.request import context
from ipapython.dn import DN
import six
if six.PY3:
unicode = str
__doc__ = _("""
Password policy
A password policy sets limitations on IPA passwords, including maximum
lifetime, minimum lifetime, the number of passwords to save in
history, the number of character classes required (for stronger passwords)
and the minimum password length.
By default there is a single, global policy for all users. You can also
create a password policy to apply to a group. Each user is only subject
to one password policy, either the group policy or the global policy. A
group policy stands alone; it is not a super-set of the global policy plus
custom settings.
Each group password policy requires a unique priority setting. If a user
is in multiple groups that have password policies, this priority determines
which password policy is applied. A lower value indicates a higher priority
policy.
Group password policies are automatically removed when the groups they
are associated with are removed.
Grace period defines the number of LDAP logins allowed after expiration.
-1 means do not enforce expiration to match previous behavior. 0 allows
no additional logins after expiration.
EXAMPLES:
Modify the global policy:
ipa pwpolicy-mod --minlength=10
Add a new group password policy:
ipa pwpolicy-add --maxlife=90 --minlife=1 --history=10 --minclasses=3 --minlength=8 --priority=10 localadmins
Display the global password policy:
ipa pwpolicy-show
Display a group password policy:
ipa pwpolicy-show localadmins
Display the policy that would be applied to a given user:
ipa pwpolicy-show --user=tuser1
Modify a group password policy:
ipa pwpolicy-mod --minclasses=2 localadmins
""")
logger = logging.getLogger(__name__)
register = Registry()
@register()
class cosentry(LDAPObject):
__doc__ = _('Class of Service object used for linking policies with'
' groups')
NO_CLI = True
container_dn = DN(('cn', 'costemplates'), api.env.container_accounts)
object_class = ['top', 'costemplate', 'extensibleobject', 'krbcontainer']
permission_filter_objectclasses = ['costemplate']
default_attributes = ['cn', 'cospriority', 'krbpwdpolicyreference']
managed_permissions = {
'System: Read Group Password Policy costemplate': {
'replaces_global_anonymous_aci': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'cospriority', 'krbpwdpolicyreference', 'objectclass',
},
'default_privileges': {
'Password Policy Readers',
'Password Policy Administrator',
},
},
'System: Add Group Password Policy costemplate': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=costemplates,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Group Password Policy costemplate";allow (add) groupdn = "ldap:///cn=Add Group Password Policy costemplate,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
'System: Delete Group Password Policy costemplate': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=costemplates,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Delete Group Password Policy costemplate";allow (delete) groupdn = "ldap:///cn=Delete Group Password Policy costemplate,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
'System: Modify Group Password Policy costemplate': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'cospriority'},
'replaces': [
'(targetattr = "cospriority")(target = "ldap:///cn=*,cn=costemplates,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Group Password Policy costemplate";allow (write) groupdn = "ldap:///cn=Modify Group Password Policy costemplate,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
}
takes_params = (
Str('cn', primary_key=True),
DNParam('krbpwdpolicyreference'),
Int('cospriority', minvalue=0),
)
priority_not_unique_msg = _(
'priority must be a unique value (%(prio)d already used by %(gname)s)'
)
def get_dn(self, *keys, **options):
group_dn = self.api.Object.group.get_dn(keys[-1])
return self.backend.make_dn_from_attr(
'cn', group_dn, DN(self.container_dn, api.env.basedn)
)
def check_priority_uniqueness(self, *keys, **options):
if options.get('cospriority') is not None:
entries = self.methods.find(
cospriority=options['cospriority']
)['result']
if len(entries) > 0:
group_name = self.api.Object.group.get_primary_key_from_dn(
DN(entries[0]['cn'][0]))
raise errors.ValidationError(
name='priority',
error=self.priority_not_unique_msg % {
'prio': options['cospriority'],
'gname': group_name,
}
)
@register()
class cosentry_add(LDAPCreate):
__doc__ = _('Add Class of Service entry')
NO_CLI = True
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
# check for existence of the group
group_dn = self.api.Object.group.get_dn(keys[-1])
try:
result = ldap.get_entry(group_dn, ['objectclass'])
except errors.NotFound:
raise self.api.Object.group.handle_not_found(keys[-1])
oc = [x.lower() for x in result['objectclass']]
if 'mepmanagedentry' in oc:
raise errors.ManagedPolicyError()
self.obj.check_priority_uniqueness(*keys, **options)
del entry_attrs['cn']
return dn
@register()
class cosentry_del(LDAPDelete):
__doc__ = _('Delete Class of Service entry')
NO_CLI = True
@register()
class cosentry_mod(LDAPUpdate):
__doc__ = _('Modify Class of Service entry')
NO_CLI = True
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
new_cospriority = options.get('cospriority')
if new_cospriority is not None:
cos_entry = self.api.Command.cosentry_show(keys[-1])['result']
old_cospriority = int(cos_entry['cospriority'][0])
# check uniqueness only when the new priority differs
if old_cospriority != new_cospriority:
self.obj.check_priority_uniqueness(*keys, **options)
return dn
@register()
class cosentry_show(LDAPRetrieve):
__doc__ = _('Display Class of Service entry')
NO_CLI = True
@register()
class cosentry_find(LDAPSearch):
__doc__ = _('Search for Class of Service entry')
NO_CLI = True
global_policy_name = 'global_policy'
global_policy_dn = DN(('cn', global_policy_name), ('cn', api.env.realm), ('cn', 'kerberos'), api.env.basedn)
@register()
class pwpolicy(LDAPObject):
"""
Password Policy object
"""
container_dn = DN(('cn', api.env.realm), ('cn', 'kerberos'))
object_name = _('password policy')
object_name_plural = _('password policies')
object_class = ['top', 'nscontainer', 'krbpwdpolicy', 'ipapwdpolicy']
permission_filter_objectclasses = ['krbpwdpolicy', 'ipapwdpolicy']
default_attributes = [
'cn', 'cospriority', 'krbmaxpwdlife', 'krbminpwdlife',
'krbpwdhistorylength', 'krbpwdmindiffchars', 'krbpwdminlength',
'krbpwdmaxfailure', 'krbpwdfailurecountinterval',
'krbpwdlockoutduration', 'ipapwdmaxrepeat',
'ipapwdmaxsequence', 'ipapwddictcheck',
'ipapwdusercheck', 'passwordgracelimit',
]
managed_permissions = {
'System: Read Group Password Policy': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'permission',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'cospriority', 'krbmaxpwdlife', 'krbminpwdlife',
'krbpwdfailurecountinterval', 'krbpwdhistorylength',
'krbpwdlockoutduration', 'krbpwdmaxfailure',
'krbpwdmindiffchars', 'krbpwdminlength', 'objectclass',
'ipapwdmaxrepeat', 'ipapwdmaxsequence', 'ipapwddictcheck',
'ipapwdusercheck', 'passwordgracelimit',
},
'default_privileges': {
'Password Policy Readers',
'Password Policy Administrator',
},
},
'System: Add Group Password Policy': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=$REALM,cn=kerberos,$SUFFIX")(version 3.0;acl "permission:Add Group Password Policy";allow (add) groupdn = "ldap:///cn=Add Group Password Policy,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
'System: Delete Group Password Policy': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///cn=*,cn=$REALM,cn=kerberos,$SUFFIX")(version 3.0;acl "permission:Delete Group Password Policy";allow (delete) groupdn = "ldap:///cn=Delete Group Password Policy,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
'System: Modify Group Password Policy': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'krbmaxpwdlife', 'krbminpwdlife', 'krbpwdfailurecountinterval',
'krbpwdhistorylength', 'krbpwdlockoutduration',
'krbpwdmaxfailure', 'krbpwdmindiffchars', 'krbpwdminlength',
'ipapwdmaxrepeat', 'ipapwdmaxsequence', 'ipapwddictcheck',
'ipapwdusercheck', 'passwordgracelimit',
},
'replaces': [
'(targetattr = "krbmaxpwdlife || krbminpwdlife || krbpwdhistorylength || krbpwdmindiffchars || krbpwdminlength || krbpwdmaxfailure || krbpwdfailurecountinterval || krbpwdlockoutduration")(target = "ldap:///cn=*,cn=$REALM,cn=kerberos,$SUFFIX")(version 3.0;acl "permission:Modify Group Password Policy";allow (write) groupdn = "ldap:///cn=Modify Group Password Policy,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Password Policy Administrator'},
},
}
label = _('Password Policies')
label_singular = _('Password Policy')
takes_params = (
Str('cn?',
cli_name='group',
label=_('Group'),
doc=_('Manage password policy for specific group'),
primary_key=True,
),
Int('krbmaxpwdlife?',
cli_name='maxlife',
label=_('Max lifetime (days)'),
doc=_('Maximum password lifetime (in days)'),
minvalue=0,
maxvalue=20000, # a little over 54 years
),
Int('krbminpwdlife?',
cli_name='minlife',
label=_('Min lifetime (hours)'),
doc=_('Minimum password lifetime (in hours)'),
minvalue=0,
),
Int('krbpwdhistorylength?',
cli_name='history',
label=_('History size'),
doc=_('Password history size'),
minvalue=0,
),
Int('krbpwdmindiffchars?',
cli_name='minclasses',
label=_('Character classes'),
doc=_('Minimum number of character classes'),
minvalue=0,
maxvalue=5,
),
Int('krbpwdminlength?',
cli_name='minlength',
label=_('Min length'),
doc=_('Minimum length of password'),
minvalue=0,
),
Int('cospriority',
cli_name='priority',
label=_('Priority'),
doc=_('Priority of the policy (higher number means lower priority'),
minvalue=0,
flags=('virtual_attribute',),
),
Int(
'krbpwdmaxfailure?',
cli_name='maxfail',
label=_('Max failures'),
doc=_('Consecutive failures before lockout'),
minvalue=0,
),
Int(
'krbpwdfailurecountinterval?',
cli_name='failinterval',
label=_('Failure reset interval'),
doc=_('Period after which failure count will be reset (seconds)'),
minvalue=0,
),
Int(
'krbpwdlockoutduration?',
cli_name='lockouttime',
label=_('Lockout duration'),
doc=_('Period for which lockout is enforced (seconds)'),
minvalue=0,
),
Int(
'ipapwdmaxrepeat?',
cli_name='maxrepeat',
label=_('Max repeat'),
doc=_('Maximum number of same consecutive characters'),
minvalue=0,
maxvalue=256,
default=0,
),
Int(
'ipapwdmaxsequence?',
cli_name='maxsequence',
label=_('Max sequence'),
doc=_('The max. length of monotonic character sequences (abcd)'),
minvalue=0,
maxvalue=256,
default=0,
),
Bool(
'ipapwddictcheck?',
cli_name='dictcheck',
label=_('Dictionary check'),
doc=_('Check if the password is a dictionary word'),
default=False,
),
Bool(
'ipapwdusercheck?',
cli_name='usercheck',
label=_('User check'),
doc=_('Check if the password contains the username'),
default=False,
),
Int(
'passwordgracelimit?',
cli_name='gracelimit',
label=_('Grace login limit'),
doc=_('Number of LDAP authentications allowed after expiration'),
minvalue=-1,
maxvalue=Int.MAXINT,
default=-1,
autofill=True,
),
)
def get_dn(self, *keys, **options):
if keys[-1] is not None:
return self.backend.make_dn_from_attr(
self.primary_key.name, keys[-1],
DN(self.container_dn, api.env.basedn)
)
return global_policy_dn
def convert_time_for_output(self, entry_attrs, **options):
# Convert seconds to hours and days for displaying to user
if not options.get('raw', False):
if 'krbmaxpwdlife' in entry_attrs:
entry_attrs['krbmaxpwdlife'][0] = unicode(
int(entry_attrs['krbmaxpwdlife'][0]) // 86400
)
if 'krbminpwdlife' in entry_attrs:
entry_attrs['krbminpwdlife'][0] = unicode(
int(entry_attrs['krbminpwdlife'][0]) // 3600
)
def convert_time_on_input(self, entry_attrs):
# Convert hours and days to seconds for writing to LDAP
if 'krbmaxpwdlife' in entry_attrs and entry_attrs['krbmaxpwdlife']:
entry_attrs['krbmaxpwdlife'] = entry_attrs['krbmaxpwdlife'] * 86400
if 'krbminpwdlife' in entry_attrs and entry_attrs['krbminpwdlife']:
entry_attrs['krbminpwdlife'] = entry_attrs['krbminpwdlife'] * 3600
def validate_minlength(self, ldap, entry_attrs, add=False, *keys):
"""
If any of the libpwquality options are used then the minimum
length must be >= 6 which is the built-in default of libpwquality.
Allowing a lower value to be set will result in a failed policy
check and a generic error message.
"""
def get_val(entry, attr):
"""Get a single value from a list or a string"""
val = entry.get(attr, 0)
if isinstance(val, list):
val = val[0]
return val
def has_pwquality_set(entry):
for attr in ['ipapwdmaxrepeat', 'ipapwdmaxsequence',
'ipapwddictcheck', 'ipapwdusercheck']:
val = get_val(entry, attr)
if val not in (False, 'FALSE', '0', 0, None):
return True
return False
has_pwquality_value = False
min_length = 0
if not add:
if len(keys) > 0:
existing_entry = self.api.Command.pwpolicy_show(
keys[-1], all=True,)['result']
else:
existing_entry = self.api.Command.pwpolicy_show(
all=True,)['result']
existing_entry.update(entry_attrs)
if existing_entry.get('krbpwdminlength'):
min_length = int(get_val(existing_entry, 'krbpwdminlength'))
has_pwquality_value = has_pwquality_set(existing_entry)
else:
if entry_attrs.get('krbpwdminlength'):
min_length = int(get_val(entry_attrs, 'krbpwdminlength'))
has_pwquality_value = has_pwquality_set(entry_attrs)
if min_length < 6 and has_pwquality_value:
raise errors.ValidationError(
name='minlength',
error=_('Minimum length must be >= 6 if maxrepeat, '
'maxsequence, dictcheck or usercheck are defined')
)
def validate_lifetime(self, entry_attrs, add=False, *keys):
"""
Ensure that the maximum lifetime is greater than the minimum.
If there is no minimum lifetime set then don't return an error.
"""
maxlife=entry_attrs.get('krbmaxpwdlife', None)
minlife=entry_attrs.get('krbminpwdlife', None)
existing_entry = {}
if not add: # then read existing entry
existing_entry = self.api.Command.pwpolicy_show(keys[-1],
all=True,
)['result']
if minlife is None and 'krbminpwdlife' in existing_entry:
minlife = int(existing_entry['krbminpwdlife'][0]) * 3600
if maxlife is None and 'krbmaxpwdlife' in existing_entry:
maxlife = int(existing_entry['krbmaxpwdlife'][0]) * 86400
if maxlife not in (None, 0) and minlife is not None:
if minlife > maxlife:
raise errors.ValidationError(
name='maxlife',
error=_(
"Maximum password life must be equal to "
"or greater than the minimum."
),
)
def add_cospriority(self, entry, pwpolicy_name, rights=True):
if pwpolicy_name and pwpolicy_name != global_policy_name:
cos_entry = self.api.Command.cosentry_show(
pwpolicy_name,
rights=rights, all=rights
)['result']
if cos_entry.get('cospriority') is not None:
entry['cospriority'] = cos_entry['cospriority']
if rights:
entry['attributelevelrights']['cospriority'] = \
cos_entry['attributelevelrights']['cospriority']
@register()
class pwpolicy_add(LDAPCreate):
__doc__ = _('Add a new group password policy.')
def get_args(self):
yield self.obj.primary_key.clone(attribute=True, required=True)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_time_on_input(entry_attrs)
self.obj.validate_lifetime(entry_attrs, True)
self.obj.validate_minlength(ldap, entry_attrs, True)
self.api.Command.cosentry_add(
keys[-1], krbpwdpolicyreference=dn,
cospriority=options.get('cospriority')
)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
logger.info('%r', entry_attrs)
# attribute rights are not allowed for pwpolicy_add
self.obj.add_cospriority(entry_attrs, keys[-1], rights=False)
self.obj.convert_time_for_output(entry_attrs, **options)
return dn
@register()
class pwpolicy_del(LDAPDelete):
__doc__ = _('Delete a group password policy.')
def get_args(self):
yield self.obj.primary_key.clone(
attribute=True, required=True, multivalue=True
)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
if dn == global_policy_dn:
raise errors.ValidationError(
name='group',
error=_('cannot delete global password policy')
)
return dn
def post_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
try:
self.api.Command.cosentry_del(keys[-1])
except errors.NotFound:
pass
return True
@register()
class pwpolicy_mod(LDAPUpdate):
__doc__ = _('Modify a group password policy.')
def execute(self, cn=None, **options):
return super(pwpolicy_mod, self).execute(cn, **options)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
old_entry_attrs = ldap.get_entry(dn, ['objectclass'])
if not self.obj.has_objectclass(
old_entry_attrs['objectclass'], 'ipapwdpolicy'
):
old_entry_attrs['objectclass'].append('ipapwdpolicy')
entry_attrs['objectclass'] = old_entry_attrs['objectclass']
self.obj.convert_time_on_input(entry_attrs)
self.obj.validate_minlength(ldap, entry_attrs, False, *keys)
self.obj.validate_lifetime(entry_attrs, False, *keys)
setattr(context, 'cosupdate', False)
if options.get('cospriority') is not None:
if keys[-1] is None:
raise errors.ValidationError(
name='priority',
error=_('priority cannot be set on global policy')
)
try:
self.api.Command.cosentry_mod(
keys[-1], cospriority=options['cospriority']
)
except errors.EmptyModlist as e:
if len(entry_attrs) == 1: # cospriority only was passed
raise e
else:
setattr(context, 'cosupdate', True)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
rights = options.get('all', False) and options.get('rights', False)
self.obj.add_cospriority(entry_attrs, keys[-1], rights)
self.obj.convert_time_for_output(entry_attrs, **options)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
if call_func.__name__ == 'update_entry':
if isinstance(exc, errors.EmptyModlist):
entry_attrs = call_args[0]
cosupdate = getattr(context, 'cosupdate')
if not entry_attrs or cosupdate:
return
raise exc
@register()
class pwpolicy_show(LDAPRetrieve):
__doc__ = _('Display information about password policy.')
takes_options = LDAPRetrieve.takes_options + (
Str('user?',
label=_('User'),
doc=_('Display effective policy for a specific user'),
),
)
def execute(self, cn=None, **options):
return super(pwpolicy_show, self).execute(cn, **options)
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if options.get('user') is not None:
user_entry = self.api.Command.user_show(
options['user'], all=True
)['result']
if 'krbpwdpolicyreference' in user_entry:
return user_entry.get('krbpwdpolicyreference', [dn])[0]
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
rights = options.get('all', False) and options.get('rights', False)
self.obj.add_cospriority(entry_attrs, keys[-1], rights)
self.obj.convert_time_for_output(entry_attrs, **options)
return dn
@register()
class pwpolicy_find(LDAPSearch):
__doc__ = _('Search for group password policies.')
# this command does custom sorting in post_callback
sort_result_entries = False
def priority_sort_key(self, entry):
"""Key for sorting password policies
returns a pair: (is_global, priority)
"""
# global policy will be always last in the output
if entry['cn'][0] == global_policy_name:
return True, 0
else:
# policies with higher priority (lower number) will be at the
# beginning of the list
try:
cospriority = int(entry['cospriority'][0])
except KeyError:
# if cospriority is not present in the entry, rather return 0
# than crash
cospriority = 0
return False, cospriority
def post_callback(self, ldap, entries, truncated, *args, **options):
for e in entries:
# When pkey_only flag is on, entries should contain only a cn.
# Add a cospriority attribute that will be used for sorting.
# Attribute rights are not allowed for pwpolicy_find.
self.obj.add_cospriority(e, e['cn'][0], rights=False)
self.obj.convert_time_for_output(e, **options)
# do custom entry sorting by its cospriority
entries.sort(key=self.priority_sort_key)
if options.get('pkey_only', False):
# remove cospriority that was used for sorting
for e in entries:
try:
del e['cospriority']
except KeyError:
pass
return truncated
| 27,345
|
Python
|
.py
| 627
| 33.417863
| 417
| 0.599549
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,874
|
misc.py
|
freeipa_freeipa/ipaserver/plugins/misc.py
|
# Authors:
# Jason Gerard DeRose <jderose@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 ipalib import _
from ipalib.misc import env, plugins
from ipalib.plugable import Registry
__doc__ = _("""
Misc plug-ins
""")
register = Registry()
env = register()(env)
plugins = register()(plugins)
| 987
|
Python
|
.py
| 27
| 35.37037
| 71
| 0.766492
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,875
|
schema.py
|
freeipa_freeipa/ipaserver/plugins/schema.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
import importlib
import itertools
import sys
import six
import hashlib
from .baseldap import LDAPObject
from ipalib import errors
from ipalib.crud import PKQuery, Retrieve, Search
from ipalib.frontend import Command, Local, Method, Object
from ipalib.output import Entry, ListOfEntries, ListOfPrimaryKeys, PrimaryKey
from ipalib.parameters import Bool, Dict, Flag, Str
from ipalib.plugable import Registry
from ipalib.request import context
from ipalib.text import _
from ipapython.version import API_VERSION
__doc__ = _("""
API Schema
""") + _("""
Provides API introspection capabilities.
""") + _("""
EXAMPLES:
""") + _("""
Show user-find details:
ipa command-show user-find
""") + _("""
Find user-find parameters:
ipa param-find user-find
""")
if six.PY3:
unicode = str
register = Registry()
class BaseMetaObject(Object):
takes_params = (
Str(
'name',
label=_("Name"),
normalizer=lambda name: name.replace(u'-', u'_'),
flags={'no_search'},
),
Str(
'doc?',
label=_("Documentation"),
flags={'no_search'},
),
Str(
'exclude*',
label=_("Exclude from"),
flags={'no_search'},
),
Str(
'include*',
label=_("Include in"),
flags={'no_search'},
),
)
def _get_obj(self, obj, **kwargs):
raise NotImplementedError()
def _retrieve(self, *args, **kwargs):
raise NotImplementedError()
def retrieve(self, *args, **kwargs):
obj = self._retrieve(*args, **kwargs)
obj = self._get_obj(obj, **kwargs)
return obj
def _search(self, *args, **kwargs):
raise NotImplementedError()
def _split_search_args(self, criteria=None):
return [], criteria
def search(self, *args, **kwargs):
args, criteria = self._split_search_args(*args)
result = self._search(*args, **kwargs)
if not result:
return tuple()
result = (self._get_obj(r, **kwargs) for r in result)
if criteria:
criteria = criteria.lower()
result = (r for r in result
if (criteria in r['name'].lower() or
criteria in r.get('doc', u'').lower()))
if not kwargs.get('all', False) and kwargs.get('pkey_only', False):
key = self.primary_key.name
result = ({key: r[key]} for r in result)
return result
class BaseMetaRetrieve(Retrieve):
def execute(self, *args, **options):
obj = self.obj.retrieve(*args, **options)
return dict(result=obj, value=args[-1])
class BaseMetaSearch(Search):
def get_options(self):
for option in super(BaseMetaSearch, self).get_options():
yield option
yield Flag(
'pkey_only?',
label=_("Primary key only"),
doc=_("Results should contain primary key attribute only "
"(\"%s\")") % 'name',
)
def execute(self, criteria=None, **options):
result = list(self.obj.search(criteria, **options))
return dict(result=result, count=len(result), truncated=False)
class MetaObject(BaseMetaObject):
takes_params = BaseMetaObject.takes_params + (
Str(
'topic_topic?',
label=_("Help topic"),
flags={'no_search'},
),
)
def get_params(self):
for param in super(MetaObject, self).get_params():
yield param
if param.name == 'name':
yield Str(
'version',
label=_("Version"),
flags={'no_search'},
)
yield Str(
'full_name',
label=_("Full name"),
primary_key=True,
normalizer=lambda name: name.replace(u'-', u'_'),
flags={'no_search'},
)
class MetaRetrieve(BaseMetaRetrieve):
pass
class MetaSearch(BaseMetaSearch):
pass
@register()
class metaobject(MetaObject):
takes_params = MetaObject.takes_params + (
Str(
'params_param*',
label=_("Parameters"),
flags={'no_search'},
),
)
def _iter_params(self, metaobj):
raise NotImplementedError()
def _get_obj(self, metaobj, all=False, **kwargs): # pylint: disable=W0237
obj = dict()
obj['name'] = unicode(metaobj.name)
obj['version'] = unicode(metaobj.version)
obj['full_name'] = unicode(metaobj.full_name)
if all:
params = [unicode(p.name) for p in self._iter_params(metaobj)]
if params:
obj['params_param'] = params
return obj
class metaobject_show(MetaRetrieve):
pass
class metaobject_find(MetaSearch):
pass
@register()
class command(metaobject):
takes_params = metaobject.takes_params + (
Str(
'obj_class?',
label=_("Method of"),
flags={'no_search'},
),
Str(
'attr_name?',
label=_("Method name"),
flags={'no_search'},
),
)
def _iter_params(self, metaobj):
for arg in metaobj.args():
yield arg
for option in metaobj.options():
if option.name == 'version':
continue
yield option
def _get_obj(self, cmd, **kwargs):
obj = super(command, self)._get_obj(cmd, **kwargs)
if cmd.doc:
obj['doc'] = unicode(cmd.doc)
if cmd.topic:
try:
topic = self.api.Object.topic.retrieve(unicode(cmd.topic))
except errors.NotFound:
pass
else:
obj['topic_topic'] = topic['full_name']
if isinstance(cmd, Method):
obj['obj_class'] = unicode(cmd.obj_full_name)
obj['attr_name'] = unicode(cmd.attr_name)
if cmd.NO_CLI:
obj['exclude'] = [u'cli']
return obj
def _retrieve(self, name, **kwargs):
try:
cmd = self.api.Command[name]
if not isinstance(cmd, Local):
return cmd
except KeyError:
pass
raise errors.NotFound(
reason=_("%(pkey)s: %(oname)s not found") % {
'pkey': name, 'oname': self.name,
}
)
def _search(self, **kwargs):
for cmd in self.api.Command():
if not isinstance(cmd, Local):
yield cmd
@register()
class command_show(metaobject_show):
__doc__ = _("Display information about a command.")
@register()
class command_find(metaobject_find):
__doc__ = _("Search for commands.")
@register()
class command_defaults(PKQuery):
__doc__ = _('Return command defaults')
NO_CLI = True
takes_options = (
Str('params*'),
Dict('kw?'),
)
def execute(self, name, **options):
if name not in self.api.Command:
raise errors.NotFound(
reason=_("{oname}: {command_name} not found").format(
oname=self.name, command_name=name
)
)
command = self.api.Command[name]
params = options.get('params') or []
kw = options.get('kw') or {}
result = command.get_default(params, **kw)
return dict(result=result)
@register()
class class_(metaobject):
name = 'class'
def _iter_params(self, metaobj):
for param in metaobj.params():
yield param
if isinstance(metaobj, LDAPObject) and 'show' in metaobj.methods:
members = (
'{}_{}'.format(attr_name, obj_name)
for attr_name, obj_names in metaobj.attribute_members.items()
for obj_name in obj_names)
passwords = (name for _, name in metaobj.password_attributes)
names = set(itertools.chain(members, passwords))
for param in metaobj.methods.show.output_params():
if param.name in names and param.name not in metaobj.params:
yield param
def _retrieve(self, name, **kwargs):
try:
return self.api.Object[name]
except KeyError:
pass
raise errors.NotFound(
reason=_("%(pkey)s: %(oname)s not found") % {
'pkey': name, 'oname': self.name,
}
)
def _search(self, **kwargs):
return self.api.Object()
@register()
class class_show(metaobject_show):
__doc__ = _("Display information about a class.")
@register()
class class_find(metaobject_find):
__doc__ = _("Search for classes.")
@register()
class topic_(MetaObject):
name = 'topic'
def __init__(self, api):
super(topic_, self).__init__(api)
self.__topics = None
self.__topics_by_key = None
def __make_topics(self):
if self.__topics is not None and self.__topics_by_key is not None:
return
object.__setattr__(self, '_topic___topics', [])
topics = self.__topics
object.__setattr__(self, '_topic___topics_by_key', {})
topics_by_key = self.__topics_by_key
for command in self.api.Command():
topic_value = command.topic
if topic_value is None:
continue
topic_name = unicode(topic_value)
while topic_name not in topics_by_key:
topic_version = u'1'
topic_full_name = u'{}/{}'.format(topic_name,
topic_version)
topic = {
'name': topic_name,
'version': topic_version,
'full_name': topic_full_name,
}
topics.append(topic)
# pylint: disable=unsupported-assignment-operation
topics_by_key[topic_name] = topic
topics_by_key[topic_full_name] = topic
# pylint: enable=unsupported-assignment-operation
for package in self.api.packages:
module_name = '.'.join((package.__name__, topic_name))
try:
module = sys.modules[module_name]
except KeyError:
try:
module = importlib.import_module(module_name)
except ImportError:
continue
if module.__doc__ is not None:
topic['doc'] = unicode(module.__doc__).strip()
try:
topic_value = module.topic
except AttributeError:
continue
if topic_value is not None:
topic_name = unicode(topic_value)
topic['topic_topic'] = u'{}/{}'.format(topic_name,
topic_version)
else:
topic.pop('topic_topic', None)
def _get_obj(self, obj, **kwargs):
return obj
def _retrieve(self, full_name, **kwargs):
self.__make_topics()
try:
return self.__topics_by_key[full_name]
except KeyError:
raise errors.NotFound(
reason=_("%(pkey)s: %(oname)s not found") % {
'pkey': full_name, 'oname': self.name,
}
)
def _search(self, **kwargs):
self.__make_topics()
return iter(self.__topics)
@register()
class topic_show(MetaRetrieve):
__doc__ = _("Display information about a help topic.")
@register()
class topic_find(MetaSearch):
__doc__ = _("Search for help topics.")
class BaseParam(BaseMetaObject):
takes_params = BaseMetaObject.takes_params + (
Str(
'type?',
label=_("Type"),
flags={'no_search'},
),
Bool(
'required?',
label=_("Required"),
flags={'no_search'},
),
Bool(
'multivalue?',
label=_("Multi-value"),
flags={'no_search'},
),
)
def get_params(self):
for param in super(BaseParam, self).get_params():
if param.name == 'name':
param = param.clone(primary_key=True)
yield param
@property
def parent(self):
raise AttributeError('parent')
# pylint: disable-next=arguments-renamed
def _split_search_args(self, parent_name, criteria=None):
return [parent_name], criteria
class BaseParamMethod(Method):
def get_args(self):
parent = self.obj.parent
parent_key = parent.primary_key
yield parent_key.clone_rename(
parent.name + parent_key.name,
cli_name=parent.name,
label=parent_key.label,
required=True,
query=True,
)
for arg in super(BaseParamMethod, self).get_args():
yield arg
class BaseParamRetrieve(BaseParamMethod, BaseMetaRetrieve):
pass
class BaseParamSearch(BaseParamMethod, BaseMetaSearch):
# pylint: disable-next=arguments-renamed
def execute(self, command, criteria=None, **options):
result = list(self.obj.search(command, criteria, **options))
return dict(result=result, count=len(result), truncated=False)
@register()
class param(BaseParam):
takes_params = BaseParam.takes_params + (
Bool(
'alwaysask?',
label=_("Always ask"),
flags={'no_search'},
),
Str(
'cli_metavar?',
label=_("CLI metavar"),
flags={'no_search'},
),
Str(
'cli_name?',
label=_("CLI name"),
flags={'no_search'},
),
Bool(
'confirm',
label=_("Confirm (password)"),
flags={'no_search'},
),
Str(
'default*',
label=_("Default"),
flags={'no_search'},
),
Str(
'default_from_param*',
label=_("Default from"),
flags={'no_search'},
),
Str(
'label?',
label=_("Label"),
flags={'no_search'},
),
Bool(
'no_convert?',
label=_("Convert on server"),
flags={'no_search'},
),
Str(
'option_group?',
label=_("Option group"),
flags={'no_search'},
),
Bool(
'sensitive?',
label=_("Sensitive"),
flags={'no_search'},
),
Bool(
'positional?',
label=_("Positional argument"),
flags={'no_search'},
),
)
@property
def parent(self):
return self.api.Object.metaobject
def _get_obj(self, obj, **kwargs):
metaobj, param = obj
obj = dict()
obj['name'] = unicode(param.name)
if param.type is unicode:
obj['type'] = u'str'
elif param.type is bytes:
obj['type'] = u'bytes'
elif param.type is not None:
obj['type'] = unicode(param.type.__name__)
if not param.required:
obj['required'] = False
if param.multivalue:
obj['multivalue'] = True
if param.password:
obj['sensitive'] = True
if isinstance(metaobj, Command):
if param.required and param.name not in metaobj.args:
obj['positional'] = False
elif not param.required and param.name in metaobj.args:
obj['positional'] = True
for key, value in param._Param__clonekw.items():
if key in ('doc',
'label'):
obj[key] = unicode(value)
elif key in ('exclude',
'include'):
obj[key] = sorted(list(unicode(v) for v in value))
if isinstance(metaobj, Command):
if key == 'alwaysask':
obj.setdefault(key, value)
elif key == 'confirm':
obj[key] = value
elif key in ('cli_metavar',
'cli_name',
'option_group'):
obj[key] = unicode(value)
elif key == 'default':
if param.multivalue:
obj[key] = [unicode(v) for v in value]
else:
obj[key] = [unicode(value)]
if not param.autofill:
obj['alwaysask'] = True
elif key == 'default_from':
obj['default_from_param'] = list(unicode(k)
for k in value.keys)
if not param.autofill:
obj['alwaysask'] = True
elif key in ('exponential',
'normalizer',
'only_absolute',
'precision'):
obj['no_convert'] = True
if ((isinstance(metaobj, Command) and 'no_option' in param.flags) or
(isinstance(metaobj, Object) and 'no_output' in param.flags)):
value = obj.setdefault('exclude', [])
if u'cli' not in value:
value.append(u'cli')
if u'webui' not in value:
value.append(u'webui')
return obj
def _retrieve(self, metaobjectfull_name, name, **kwargs):
found = False
try:
metaobj = self.api.Command[metaobjectfull_name]
except KeyError:
raise errors.NotFound(
reason=_("%(metaobject)s: %(oname)s not found") % {
'metaobject': metaobjectfull_name, 'oname': self.name,
}
)
if 'command' in self.api.Object:
plugin = self.api.Object['command']
found = True
elif 'class' in self.api.Object:
plugin = self.api.Object['class']
found = True
if found:
for param in plugin._iter_params(metaobj):
if param.name == name:
return metaobj, param
raise errors.NotFound(
reason=_("%(pkey)s: %(oname)s not found") % {
'pkey': name, 'oname': self.name,
}
)
def _search(self, metaobjectfull_name, **kwargs):
try:
metaobj = self.api.Command[metaobjectfull_name]
plugin = self.api.Object['command']
except KeyError:
try:
metaobj = self.api.Object[metaobjectfull_name]
plugin = self.api.Object['class']
except KeyError:
return tuple()
return ((metaobj, param) for param in plugin._iter_params(metaobj))
@register()
class param_show(BaseParamRetrieve):
__doc__ = _("Display information about a command parameter.")
@register()
class param_find(BaseParamSearch):
__doc__ = _("Search command parameters.")
@register()
class output(BaseParam):
@property
def parent(self):
return self.api.Object.command
def _get_obj(self, obj, **kwargs):
cmd, output = obj
required = True
multivalue = False
if isinstance(output, (Entry, ListOfEntries)):
type_type = dict
multivalue = isinstance(output, ListOfEntries)
elif isinstance(output, (PrimaryKey, ListOfPrimaryKeys)):
if getattr(cmd, 'obj', None) and cmd.obj.primary_key:
type_type = cmd.obj.primary_key.type
else:
type_type = type(None)
multivalue = isinstance(output, ListOfPrimaryKeys)
elif isinstance(output.type, tuple):
if tuple in output.type or list in output.type:
type_type = None
multivalue = True
else:
type_type = output.type[0]
required = type(None) not in output.type
else:
type_type = output.type
obj = dict()
obj['name'] = unicode(output.name)
if type_type is unicode:
obj['type'] = u'str'
elif type_type is bytes:
obj['type'] = u'bytes'
elif type_type is not None:
obj['type'] = unicode(type_type.__name__)
if not required:
obj['required'] = False
if multivalue:
obj['multivalue'] = True
if 'doc' in output.__dict__:
obj['doc'] = unicode(output.doc)
return obj
def _retrieve(self, commandfull_name, name, **kwargs):
if commandfull_name not in self.api.Command:
raise errors.NotFound(
reason=_("%(command_name)s: %(oname)s not found") % {
'command_name': commandfull_name, 'oname': self.name,
}
)
cmd = self.api.Command[commandfull_name]
try:
return (cmd, cmd.output[name])
except KeyError:
raise errors.NotFound(
reason=_("%(pkey)s: %(oname)s not found") % {
'pkey': name, 'oname': self.name,
}
)
def _search(self, commandfull_name, **kwargs):
if commandfull_name not in self.api.Command:
return None
cmd = self.api.Command[commandfull_name]
return ((cmd, output) for output in cmd.output())
@register()
class output_show(BaseParamRetrieve):
__doc__ = _("Display information about a command output.")
@register()
class output_find(BaseParamSearch):
__doc__ = _("Search for command outputs.")
@register()
class schema(Command):
__doc__ = _('Store and provide schema for commands and topics')
NO_CLI = True
takes_options = (
Str(
'known_fingerprints*',
label=_("Fingerprint of schema cached by client")
),
)
@staticmethod
def _calculate_fingerprint(data):
"""
Returns fingerprint for schema
Behavior of this function can be changed at any time
given that it always generates identical fingerprint for
identical data (change in order of items in dict is
irelevant) and the risk of generating identical fingerprint
for different inputs is low.
"""
to_process = [data]
fingerprint = hashlib.sha1()
i = 0
while i < len(to_process):
entry = to_process[i]
if isinstance(entry, (list, tuple)):
for item in entry:
to_process.append(item)
elif isinstance(entry, dict):
for key in sorted(entry.keys()):
to_process.append(key)
to_process.append(entry[key])
else:
fingerprint.update(unicode(entry).encode('utf-8'))
i += 1
return unicode(fingerprint.hexdigest()[:8])
def _generate_schema(self, **kwargs):
commands = list(self.api.Object.command.search(**kwargs))
for command in commands:
name = command['name']
command['params'] = list(
self.api.Object.param.search(name, **kwargs))
command['output'] = list(
self.api.Object.output.search(name, **kwargs))
classes = list(self.api.Object['class'].search(**kwargs))
for cls in classes:
cls['params'] = list(
self.api.Object.param.search(cls['name'], **kwargs))
topics = list(self.api.Object.topic.search(**kwargs))
schema = dict()
schema['version'] = API_VERSION
schema['commands'] = commands
schema['classes'] = classes
schema['topics'] = topics
schema['fingerprint'] = self._calculate_fingerprint(schema)
return schema
def execute(self, *args, **kwargs):
langs = "".join(getattr(context, "languages", []))
if getattr(self.api, "_schema", None) is None:
object.__setattr__(self.api, "_schema", {})
schema = self.api._schema.get(langs)
if schema is None:
schema = self._generate_schema(**kwargs)
self.api._schema[langs] = schema
schema['ttl'] = self.api.env.schema_ttl
if schema['fingerprint'] in kwargs.get('known_fingerprints', []):
raise errors.SchemaUpToDate(
fingerprint=schema['fingerprint'],
ttl=schema['ttl'],
)
return dict(result=schema)
| 24,980
|
Python
|
.py
| 699
| 24.55794
| 78
| 0.526146
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,876
|
sudocmd.py
|
freeipa_freeipa/ipaserver/plugins/sudocmd.py
|
# Authors:
# Jr Aquino <jr.aquino@citrixonline.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 ipalib import api, errors
from ipalib import Str
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve)
from ipalib import _, ngettext
from ipapython.dn import DN
__doc__ = _("""
Sudo Commands
Commands used as building blocks for sudo
EXAMPLES:
Create a new command
ipa sudocmd-add --desc='For reading log files' /usr/bin/less
Remove a command
ipa sudocmd-del /usr/bin/less
""")
register = Registry()
topic = 'sudo'
def command_validator(ugettext, value):
if value.endswith('.'):
return _('must not contain trailing dot: %s') % value
return None
@register()
class sudocmd(LDAPObject):
"""
Sudo Command object.
"""
container_dn = api.env.container_sudocmd
object_name = _('sudo command')
object_name_plural = _('sudo commands')
object_class = ['ipaobject', 'ipasudocmd']
permission_filter_objectclasses = ['ipasudocmd']
# object_class_config = 'ipahostobjectclasses'
search_attributes = [
'sudocmd', 'description',
]
default_attributes = [
'sudocmd', 'description', 'memberof',
]
attribute_members = {
'memberof': ['sudocmdgroup'],
}
uuid_attribute = 'ipauniqueid'
rdn_attribute = 'ipauniqueid'
managed_permissions = {
'System: Read Sudo Commands': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'description', 'ipauniqueid', 'memberof', 'objectclass',
'sudocmd',
},
},
'System: Add Sudo Command': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///sudocmd=*,cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Add Sudo command";allow (add) groupdn = "ldap:///cn=Add Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(objectclass=ipasudocmd)")(target = "ldap:///cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Add Sudo command";allow (add) groupdn = "ldap:///cn=Add Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Delete Sudo Command': {
'ipapermright': {'delete'},
'replaces': [
'(target = "ldap:///sudocmd=*,cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Delete Sudo command";allow (delete) groupdn = "ldap:///cn=Delete Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(objectclass=ipasudocmd)")(target = "ldap:///cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Delete Sudo command";allow (delete) groupdn = "ldap:///cn=Delete Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
'System: Modify Sudo Command': {
'ipapermright': {'write'},
'ipapermdefaultattr': {'description'},
'replaces': [
'(targetattr = "description")(target = "ldap:///sudocmd=*,cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Modify Sudo command";allow (write) groupdn = "ldap:///cn=Modify Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(objectclass=ipasudocmd)")(targetattr = "description")(target = "ldap:///cn=sudocmds,cn=sudo,$SUFFIX")(version 3.0;acl "permission:Modify Sudo command";allow (write) groupdn = "ldap:///cn=Modify Sudo command,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Sudo Administrator'},
},
}
label = _('Sudo Commands')
label_singular = _('Sudo Command')
takes_params = (
Str('sudocmd', command_validator,
cli_name='command',
label=_('Sudo Command'),
primary_key=True,
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('A description of this command'),
),
)
def get_dn(self, *keys, **options):
if keys[-1].endswith('.'):
keys = (keys[:-1] + (keys[-1][:-1], ))
dn = super(sudocmd, self).get_dn(*keys, **options)
try:
self.backend.get_entry(dn, [''])
except errors.NotFound:
try:
entry_attrs = self.backend.find_entry_by_attr(
'sudocmd', keys[-1], self.object_class, [''],
DN(self.container_dn, api.env.basedn))
dn = entry_attrs.dn
except errors.NotFound:
pass
return dn
@register()
class sudocmd_add(LDAPCreate):
__doc__ = _('Create new Sudo Command.')
msg_summary = _('Added Sudo Command "%(value)s"')
@register()
class sudocmd_del(LDAPDelete):
__doc__ = _('Delete Sudo Command.')
msg_summary = _('Deleted Sudo Command "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
filters = [
ldap.make_filter_from_attr(attr, dn)
for attr in ('memberallowcmd', 'memberdenycmd')]
filter = ldap.combine_filters(filters, ldap.MATCH_ANY)
filter = ldap.combine_filters(
(filter, ldap.make_filter_from_attr('objectClass', 'ipasudorule')),
ldap.MATCH_ALL)
dependent_sudorules = []
try:
entries, _truncated = ldap.find_entries(
filter, ['cn'],
base_dn=DN(api.env.container_sudorule, api.env.basedn))
except errors.NotFound:
pass
else:
for entry_attrs in entries:
[cn] = entry_attrs['cn']
dependent_sudorules.append(cn)
if dependent_sudorules:
raise errors.DependentEntry(
key=keys[0], label='sudorule',
dependent=', '.join(dependent_sudorules))
return dn
@register()
class sudocmd_mod(LDAPUpdate):
__doc__ = _('Modify Sudo Command.')
msg_summary = _('Modified Sudo Command "%(value)s"')
@register()
class sudocmd_find(LDAPSearch):
__doc__ = _('Search for Sudo Commands.')
msg_summary = ngettext(
'%(count)d Sudo Command matched', '%(count)d Sudo Commands matched', 0
)
@register()
class sudocmd_show(LDAPRetrieve):
__doc__ = _('Display Sudo Command.')
| 7,264
|
Python
|
.py
| 177
| 33.248588
| 277
| 0.612725
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,877
|
server.py
|
freeipa_freeipa/ipaserver/plugins/server.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import logging
import dbus
import dbus.mainloop.glib
import ldap
import time
from ipalib import api, crud, errors, messages
from ipalib import Int, Flag, Str, StrEnum, DNSNameParam
from ipalib.plugable import Registry
from .baseldap import (
LDAPSearch,
LDAPRetrieve,
LDAPDelete,
LDAPObject,
LDAPUpdate,
)
from ipalib.request import context
from ipalib import _, ngettext
from ipalib import output
from ipaplatform import services
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
from ipaserver import topology
from ipaserver.servroles import ENABLED, HIDDEN
from ipaserver.install import bindinstance, dnskeysyncinstance
from ipaserver.install.service import hide_services, enable_services
from ipaserver.plugins.privilege import principal_has_privilege
__doc__ = _("""
IPA servers
""") + _("""
Get information about installed IPA servers.
""") + _("""
EXAMPLES:
""") + _("""
Find all servers:
ipa server-find
""") + _("""
Show specific server:
ipa server-show ipa.example.com
""")
logger = logging.getLogger(__name__)
register = Registry()
@register()
class server(LDAPObject):
"""
IPA server
"""
container_dn = api.env.container_masters
object_name = _('server')
object_name_plural = _('servers')
object_class = ['top']
possible_objectclasses = ['ipaLocationMember']
search_attributes = ['cn']
default_attributes = [
'cn', 'iparepltopomanagedsuffix', 'ipamindomainlevel',
'ipamaxdomainlevel', 'ipalocation', 'ipaserviceweight'
]
label = _('IPA Servers')
label_singular = _('IPA Server')
attribute_members = {
'iparepltopomanagedsuffix': ['topologysuffix'],
'ipalocation': ['location'],
'role': ['servrole'],
}
relationships = {
'iparepltopomanagedsuffix': ('Managed', '', 'no_'),
'ipalocation': ('IPA', 'in_', 'not_in_'),
'role': ('Enabled', '', 'no_'),
}
permission_filter_objectclasses = ['ipaConfigObject']
managed_permissions = {
'System: Read Locations of IPA Servers': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'ipalocation', 'ipaserviceweight',
},
'default_privileges': {'DNS Administrators'},
},
'System: Read Status of Services on IPA Servers': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {'objectclass', 'cn', 'ipaconfigstring'},
'default_privileges': {'DNS Administrators'},
}
}
takes_params = (
Str(
'cn',
cli_name='name',
primary_key=True,
label=_('Server name'),
doc=_('IPA server hostname'),
),
Str(
'iparepltopomanagedsuffix*',
flags={'no_create', 'no_update', 'no_search'},
),
Str(
'iparepltopomanagedsuffix_topologysuffix*',
label=_('Managed suffixes'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Int(
'ipamindomainlevel',
cli_name='minlevel',
label=_('Min domain level'),
doc=_('Minimum domain level'),
flags={'no_create', 'no_update'},
),
Int(
'ipamaxdomainlevel',
cli_name='maxlevel',
label=_('Max domain level'),
doc=_('Maximum domain level'),
flags={'no_create', 'no_update'},
),
DNSNameParam(
'ipalocation_location?',
cli_name='location',
label=_('Location'),
doc=_('Server DNS location'),
only_relative=True,
flags={'no_search'},
),
Int(
'ipaserviceweight?',
cli_name='service_weight',
label=_('Service weight'),
doc=_('Weight for server services'),
minvalue=0,
maxvalue=65535,
flags={'no_search'},
),
Str(
'service_relative_weight',
label=_('Service relative weight'),
doc=_('Relative weight for server services (counts per location)'),
flags={'virtual_attribute','no_create', 'no_update', 'no_search'},
),
Str(
'enabled_role_servrole*',
label=_('Enabled server roles'),
doc=_('List of enabled roles'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'}
),
)
def _get_suffixes(self):
suffixes = self.api.Command.topologysuffix_find(
all=True, raw=True,
)['result']
suffixes = [(s['iparepltopoconfroot'][0], s['dn']) for s in suffixes]
return suffixes
def _apply_suffixes(self, entry, suffixes):
# change suffix DNs to topologysuffix entry DNs
# this fixes LDAPObject.convert_attribute_members() for suffixes
suffixes = dict(suffixes)
if 'iparepltopomanagedsuffix' in entry:
entry['iparepltopomanagedsuffix'] = [
suffixes.get(m, m) for m in entry['iparepltopomanagedsuffix']
]
def normalize_location(self, kw, **options):
"""
Return the DN of location
"""
if 'ipalocation_location' in kw:
location = kw.pop('ipalocation_location')
kw['ipalocation'] = (
[self.api.Object.location.get_dn(location)]
if location is not None else location
)
def convert_location(self, entry_attrs, **options):
"""
Return a location name from DN
"""
if options.get('raw'):
return
converted_locations = [
DNSName(location_dn['idnsname']) for
location_dn in entry_attrs.pop('ipalocation', [])
]
if converted_locations:
entry_attrs['ipalocation_location'] = converted_locations
def get_enabled_roles(self, entry_attrs, **options):
if not options.get('all', False) and options.get('no_members', False):
return
if options.get('raw', False):
return
enabled_roles = self.api.Command.server_role_find(
server_server=entry_attrs['cn'][0],
status=ENABLED,
include_master=True,
)['result']
enabled_role_names = [r[u'role_servrole'] for r in enabled_roles]
entry_attrs['enabled_role_servrole'] = enabled_role_names
@register()
class server_mod(LDAPUpdate):
__doc__ = _('Modify information about an IPA server.')
msg_summary = _('Modified IPA server "%(value)s"')
def args_options_2_entry(self, *args, **options):
kw = super(server_mod, self).args_options_2_entry(
*args, **options)
self.obj.normalize_location(kw, **options)
return kw
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if entry_attrs.get('ipalocation'):
if not ldap.entry_exists(entry_attrs['ipalocation'][0]):
raise self.api.Object.location.handle_not_found(
options['ipalocation_location'])
if 'ipalocation' in entry_attrs or 'ipaserviceweight' in entry_attrs:
server_entry = ldap.get_entry(dn, ['objectclass'])
# we need to extend object with ipaLocationMember objectclass
entry_attrs['objectclass'] = (
server_entry['objectclass'] + ['ipalocationmember']
)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.get_enabled_roles(entry_attrs)
if 'ipalocation_location' in options:
ipalocation = entry_attrs.get('ipalocation')
if ipalocation:
ipalocation = ipalocation[0]['idnsname']
else:
ipalocation = u''
try:
self.api.Command.dnsserver_mod(
keys[0],
setattr=[
u'idnsSubstitutionVariable;ipalocation={loc}'.format(
loc=ipalocation)
]
)
except errors.EmptyModlist:
pass
except errors.NotFound:
# server is not DNS server
pass
if 'ipalocation_location' in options or 'ipaserviceweight' in options:
self.add_message(messages.ServiceRestartRequired(
service=services.service('named', api).systemd_name,
server=keys[0], ))
result = self.api.Command.dns_update_system_records()
if not result.get('value'):
self.add_message(messages.AutomaticDNSRecordsUpdateFailed())
self.obj.convert_location(entry_attrs, **options)
ipalocation = entry_attrs.get('ipalocation_location', [None])[0]
if ipalocation:
servers_in_loc = self.api.Command.server_find(
in_location=ipalocation, no_members=False)['result']
dns_server_in_loc = False
for server in servers_in_loc:
if 'DNS server' in server.get('enabled_role_servrole', ()):
dns_server_in_loc = True
break
if not dns_server_in_loc:
self.add_message(messages.LocationWithoutDNSServer(
location=ipalocation
))
return dn
@register()
class server_find(LDAPSearch):
__doc__ = _('Search for IPA servers.')
msg_summary = ngettext(
'%(count)d IPA server matched',
'%(count)d IPA servers matched', 0
)
member_attributes = ['iparepltopomanagedsuffix', 'ipalocation', 'role']
def args_options_2_entry(self, *args, **options):
kw = super(server_find, self).args_options_2_entry(
*args, **options)
self.obj.normalize_location(kw, **options)
return kw
def get_options(self):
for option in super(server_find, self).get_options():
if option.name == 'topologysuffix':
option = option.clone(cli_name='topologysuffixes')
elif option.name == 'no_topologysuffix':
option = option.clone(cli_name='no_topologysuffixes')
# we do not want to test negative membership for roles
elif option.name == 'no_servrole':
continue
yield option
def get_member_filter(self, ldap, **options):
options.pop('topologysuffix', None)
options.pop('no_topologysuffix', None)
options.pop('servrole', None)
return super(server_find, self).get_member_filter(
ldap, **options)
def _get_enabled_servrole_filter(self, ldap, servroles):
"""
return a filter matching any master which has all the specified roles
enabled.
"""
def _get_masters_with_enabled_servrole(role):
role_status = self.api.Command.server_role_find(
server_server=None,
role_servrole=role,
status=ENABLED,
include_master=True,
)['result']
return set(
r[u'server_server'] for r in role_status)
enabled_masters = _get_masters_with_enabled_servrole(
servroles[0])
for role in servroles[1:]:
enabled_masters.intersection_update(
_get_masters_with_enabled_servrole(role)
)
if not enabled_masters:
return '(!(objectclass=*))'
return ldap.make_filter_from_attr(
'cn',
list(enabled_masters),
rules=ldap.MATCH_ANY
)
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope,
*args, **options):
included = options.get('topologysuffix')
excluded = options.get('no_topologysuffix')
if included or excluded:
topologysuffix = self.api.Object.topologysuffix
suffixes = self.obj._get_suffixes()
suffixes = {s[1]: s[0] for s in suffixes}
if included:
included = [topologysuffix.get_dn(pk) for pk in included]
try:
included = [suffixes[dn] for dn in included]
except KeyError:
# force empty result
filter = '(!(objectclass=*))'
else:
filter = ldap.make_filter_from_attr(
'iparepltopomanagedsuffix', included, ldap.MATCH_ALL
)
filters = ldap.combine_filters(
(filters, filter), ldap.MATCH_ALL
)
if excluded:
excluded = [topologysuffix.get_dn(pk) for pk in excluded]
excluded = [suffixes[dn] for dn in excluded if dn in suffixes]
filter = ldap.make_filter_from_attr(
'iparepltopomanagedsuffix', excluded, ldap.MATCH_NONE
)
filters = ldap.combine_filters(
(filters, filter), ldap.MATCH_ALL
)
if options.get('servrole', []):
servrole_filter = self._get_enabled_servrole_filter(
ldap, options['servrole'])
filters = ldap.combine_filters(
(filters, servrole_filter), ldap.MATCH_ALL)
return (filters, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
if not options.get('raw', False):
suffixes = self.obj._get_suffixes()
for entry in entries:
self.obj._apply_suffixes(entry, suffixes)
for entry in entries:
self.obj.convert_location(entry, **options)
self.obj.get_enabled_roles(entry, **options)
return truncated
@register()
class server_show(LDAPRetrieve):
__doc__ = _('Show IPA server.')
def post_callback(self, ldap, dn, entry, *keys, **options):
if not options.get('raw', False):
suffixes = self.obj._get_suffixes()
self.obj._apply_suffixes(entry, suffixes)
self.obj.convert_location(entry, **options)
self.obj.get_enabled_roles(entry, **options)
return dn
@register()
class server_del(LDAPDelete):
__doc__ = _('Delete IPA server.')
msg_summary = _('Deleted IPA server "%(value)s"')
takes_options = LDAPDelete.takes_options + (
Flag(
'ignore_topology_disconnect?',
label=_('Ignore topology errors'),
doc=_('Ignore topology connectivity problems after removal'),
default=False,
),
Flag(
'ignore_last_of_role?',
label=_('Ignore check for last remaining CA or DNS server'),
doc=_('Skip a check whether the last CA master or DNS server is '
'removed'),
default=False,
),
Flag(
'force?',
label=_('Force server removal'),
doc=_('Force server removal even if it does not exist'),
default=False,
),
)
def _ensure_last_of_role(self, hostname, ignore_last_of_role=False):
"""
1. When deleting server, check if there will be at least one remaining
DNS and CA server.
2. Pick CA renewal master
"""
def handler(msg, ignore_last_of_role):
if ignore_last_of_role:
self.add_message(
messages.ServerRemovalWarning(
message=msg
)
)
else:
raise errors.ServerRemovalError(reason=msg)
ipa_config = self.api.Command.config_show()['result']
ipa_masters = ipa_config.get('ipa_master_server', [])
# skip these checks if the last master is being removed
if len(ipa_masters) <= 1:
return
if self.api.Command.dns_is_enabled()['result']:
dns_config = self.api.Command.dnsconfig_show()['result']
dns_servers = dns_config.get('dns_server_server', [])
dnssec_keymaster = dns_config.get('dnssec_key_master_server', [])
if dnssec_keymaster == hostname:
handler(
_("Replica is active DNSSEC key master. Uninstall "
"could break your DNS system. Please disable or "
"replace DNSSEC key master first."), ignore_last_of_role)
if dns_servers == [hostname]:
handler(
_("Deleting this server will leave your installation "
"without a DNS."), ignore_last_of_role)
if self.api.Command.ca_is_enabled()['result']:
try:
roles = self.api.Command.server_role_find(
role_servrole='KRA server',
status='enabled',
include_master=True,
)['result']
except errors.NotFound:
roles = ()
if len(roles) == 1 and roles[0]['server_server'] == hostname:
handler(
_("Deleting this server is not allowed as it would "
"leave your installation without a KRA."),
ignore_last_of_role)
ca_servers = ipa_config.get('ca_server_server', [])
ca_renewal_master = ipa_config.get(
'ca_renewal_master_server', [])
if ca_servers == [hostname]:
handler(
_("Deleting this server is not allowed as it would "
"leave your installation without a CA."),
ignore_last_of_role)
# change the renewal master if there is other master with CA
if ca_renewal_master == hostname:
other_cas = [ca for ca in ca_servers if ca != hostname]
if other_cas:
self.api.Command.config_mod(
ca_renewal_master_server=other_cas[0])
if ignore_last_of_role:
self.add_message(
messages.ServerRemovalWarning(
message=_("Ignoring these warnings and proceeding with "
"removal")))
def _check_topology_connectivity(self, topology_connectivity, master_cn):
try:
topology_connectivity.check_current_state()
except ValueError as e:
raise errors.ServerRemovalError(reason=e)
try:
topology_connectivity.check_state_after_removal(master_cn)
except ValueError as e:
raise errors.ServerRemovalError(reason=e)
def _remove_server_principal_references(self, master):
"""
This method removes information about the replica in parts
of the shared tree that expose it, so clients stop trying to
use this replica.
"""
conn = self.Backend.ldap2
env = self.api.env
master_principal = "{}@{}".format(master, env.realm).encode('utf-8')
# remove replica memberPrincipal from s4u2proxy configuration
s4u2proxy_subtree = DN(env.container_s4u2proxy,
env.basedn)
dn1 = DN(('cn', 'ipa-http-delegation'), s4u2proxy_subtree)
member_principal1 = b"HTTP/%s" % master_principal
dn2 = DN(('cn', 'ipa-ldap-delegation-targets'), s4u2proxy_subtree)
member_principal2 = b"ldap/%s" % master_principal
dn3 = DN(('cn', 'ipa-cifs-delegation-targets'), s4u2proxy_subtree)
member_principal3 = b"cifs/%s" % master_principal
for (dn, member_principal) in ((dn1, member_principal1),
(dn2, member_principal2),
(dn3, member_principal3)):
try:
mod = [(ldap.MOD_DELETE, 'memberPrincipal', member_principal)]
conn.conn.modify_s(str(dn), mod)
except (ldap.NO_SUCH_OBJECT, ldap.NO_SUCH_ATTRIBUTE):
logger.debug(
"Replica (%s) memberPrincipal (%s) not found in %s",
master, member_principal.decode('utf-8'), dn)
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_("Failed to clean memberPrincipal "
"%(principal)s from s4u2proxy entry %(dn)s: "
"%(err)s") % dict(
principal=(member_principal
.decode('utf-8')),
dn=dn, err=e)))
try:
etc_basedn = DN(('cn', 'etc'), env.basedn)
filter = '(dnaHostname=%s)' % master
entries = conn.get_entries(
etc_basedn, ldap.SCOPE_SUBTREE, filter=filter)
if len(entries) != 0:
for entry in entries:
conn.delete_entry(entry)
except errors.NotFound:
pass
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_(
"Failed to clean up DNA hostname entries for "
"%(master)s: %(err)s") % dict(master=master, err=e)))
try:
dn = DN(('cn', 'default'), ('ou', 'profile'), env.basedn)
ret = conn.get_entry(dn)
srvlist = ret.single_value.get('defaultServerList', '')
srvlist = srvlist.split()
if master in srvlist:
srvlist.remove(master)
if not srvlist:
del ret['defaultServerList']
else:
ret['defaultServerList'] = ' '.join(srvlist)
conn.update_entry(ret)
except (errors.NotFound, errors.MidairCollision,
errors.EmptyModlist):
pass
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_("Failed to remove server %(master)s from server "
"list: %(err)s") % dict(master=master, err=e)))
def _remove_server_custodia_keys(self, ldap, master):
"""
Delete all Custodia encryption and signing keys
"""
conn = self.Backend.ldap2
env = self.api.env
# search for memberPrincipal=*/fqdn@realm
member_filter = ldap.make_filter_from_attr(
'memberPrincipal', "/{}@{}".format(master, env.realm),
exact=False, leading_wildcard=True, trailing_wildcard=False)
custodia_subtree = DN(env.container_custodia, env.basedn)
try:
entries = conn.get_entries(custodia_subtree,
ldap.SCOPE_SUBTREE,
filter=member_filter)
for entry in entries:
conn.delete_entry(entry)
except errors.NotFound:
pass
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_(
"Failed to clean up Custodia keys for "
"%(master)s: %(err)s") % dict(master=master, err=e)))
def _remove_server_host_services(self, ldap, master):
"""
delete server kerberos key and all its svc principals
"""
try:
# do not delete ldap principal if server-del command
# has been called on a machine which is being deleted
# since this will break replication.
# ldap principal to be cleaned later by topology plugin
# necessary changes to a topology plugin are tracked
# under https://pagure.io/freeipa/issue/7359
if master == self.api.env.host:
filter = (
'(&(krbprincipalname=*/{}@{})'
'(!(krbprincipalname=ldap/*)))'
.format(master, self.api.env.realm)
)
else:
filter = '(krbprincipalname=*/{}@{})'.format(
master, self.api.env.realm
)
entries = ldap.get_entries(
self.api.env.basedn, ldap.SCOPE_SUBTREE, filter=filter
)
if entries:
entries.sort(key=lambda x: len(x.dn), reverse=True)
for entry in entries:
ldap.delete_entry(entry)
except errors.NotFound:
pass
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_("Failed to cleanup server principals/keys: "
"%(err)s") % dict(err=e)))
def _cleanup_server_dns_records(self, hostname, **options):
if not self.api.Command.dns_is_enabled(
**options):
return
try:
bindinstance.remove_master_dns_records(
hostname, self.api.env.realm)
dnskeysyncinstance.remove_replica_public_keys(hostname)
except Exception as e:
self.add_message(
messages.ServerRemovalWarning(
message=_(
"Failed to cleanup %(hostname)s DNS entries: "
"%(err)s") % dict(hostname=hostname, err=e)))
self.add_message(
messages.ServerRemovalWarning(
message=_("You may need to manually remove them from the "
"tree")))
def _cleanup_server_dns_config(self, hostname):
try:
self.api.Command.dnsserver_del(hostname)
except errors.NotFound:
pass
def pre_callback(self, ldap, dn, *keys, **options):
pkey = self.obj.get_primary_key_from_dn(dn)
if options.get('force', False):
self.add_message(
messages.ServerRemovalWarning(
message=_("Forcing removal of %(hostname)s") % dict(
hostname=pkey)))
# check the topology errors before and after removal
self.context.topology_connectivity = topology.TopologyConnectivity(
self.api)
if options.get('ignore_topology_disconnect', False):
self.add_message(
messages.ServerRemovalWarning(
message=_("Ignoring topology connectivity errors.")))
else:
self._check_topology_connectivity(
self.context.topology_connectivity, pkey)
# ensure that we are not removing last CA/DNS server, DNSSec master and
# CA renewal master
self._ensure_last_of_role(
pkey, ignore_last_of_role=options.get('ignore_last_of_role', False)
)
if self.api.Command.ca_is_enabled()['result']:
try:
with self.api.Backend.ra_securitydomain as domain_api:
domain_api.delete_domain(pkey, 'KRA')
domain_api.delete_domain(pkey, 'CA')
except Exception as e:
self.add_message(messages.ServerRemovalWarning(
message=_(
"Failed to remove server from security domain: %s" % e
))
)
# remove the references to master's ldap/http principals
self._remove_server_principal_references(pkey)
# remove Custodia encryption and signing keys
self._remove_server_custodia_keys(ldap, pkey)
# finally destroy all Kerberos principals
self._remove_server_host_services(ldap, pkey)
# try to clean up the leftover DNS entries
self._cleanup_server_dns_records(pkey)
# try to clean up the DNS config from ldap
self._cleanup_server_dns_config(pkey)
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args,
**call_kwargs):
if (options.get('force', False) and isinstance(exc, errors.NotFound)
and call_func.__name__ == 'delete_entry'):
self.add_message(
message=messages.ServerRemovalWarning(
message=_("Server has already been deleted")))
return
raise exc
def _check_deleted_segments(self, hostname, topology_connectivity,
starting_host):
def wait_for_segment_removal(hostname, master_cns, suffix_name,
orig_errors, new_errors):
i = 0
while True:
left = self.api.Command.topologysegment_find(
suffix_name,
iparepltoposegmentleftnode=hostname,
sizelimit=0
)['result']
right = self.api.Command.topologysegment_find(
suffix_name,
iparepltoposegmentrightnode=hostname,
sizelimit=0
)['result']
# Relax check if topology was or is disconnected. Disconnected
# topology can contain segments with already deleted servers
# Check only if segments of servers, which can contact this
# server, and the deleted server were removed.
# This code should handle a case where there was a topology
# with a central node(B): A <-> B <-> C, where A is current
# server. After removal of B, topology will be disconnected and
# removal of segment B <-> C won't be replicated back to server
# A, therefore presence of the segment has to be ignored.
if orig_errors or new_errors:
# use errors after deletion because we don't care if some
# server can't contact the deleted one
cant_contact_me = [e[0] for e in new_errors
if starting_host in e[2]]
can_contact_me = set(master_cns) - set(cant_contact_me)
left = [
s for s in left if s['iparepltoposegmentrightnode'][0]
in can_contact_me
]
right = [
s for s in right if s['iparepltoposegmentleftnode'][0]
in can_contact_me
]
if not left and not right:
self.add_message(
messages.ServerRemovalInfo(
message=_("Agreements deleted")
))
return
time.sleep(2)
if i == 2: # taking too long, something is wrong, report
logger.info(
"Waiting for removal of replication agreements")
if i > 90:
logger.info("Taking too long, skipping")
logger.info("Following segments were not deleted:")
self.add_message(messages.ServerRemovalWarning(
message=_("Following segments were not deleted:")))
for s in left:
self.add_message(messages.ServerRemovalWarning(
message=u" %s" % s['cn'][0]))
for s in right:
self.add_message(messages.ServerRemovalWarning(
message=u" %s" % s['cn'][0]))
return
i += 1
topology_graphs = topology_connectivity.graphs
orig_errors = topology_connectivity.errors
new_errors = topology_connectivity.errors_after_master_removal(
hostname
)
for suffix_name in topology_graphs:
suffix_members = topology_graphs[suffix_name].vertices
if hostname not in suffix_members:
# If the server was already deleted, we can expect that all
# removals had been done in previous run and dangling segments
# were not deleted.
logger.info(
"Skipping replication agreement deletion check for "
"suffix '%s'", suffix_name)
continue
logger.info(
"Checking for deleted segments in suffix '%s",
suffix_name)
wait_for_segment_removal(
hostname,
list(suffix_members),
suffix_name,
orig_errors[suffix_name],
new_errors[suffix_name])
def post_callback(self, ldap, dn, *keys, **options):
# there is no point in checking deleted segment on local host
# we should do this only when removing other masters
if self.api.env.host != keys[-1]:
self._check_deleted_segments(
keys[-1], self.context.topology_connectivity,
self.api.env.host)
return super(server_del, self).post_callback(
ldap, dn, *keys, **options)
@register()
class server_conncheck(crud.PKQuery):
__doc__ = _("Check connection to remote IPA server.")
NO_CLI = True
takes_args = (
Str(
'remote_cn',
cli_name='remote_name',
label=_('Remote server name'),
doc=_('Remote IPA server hostname'),
),
)
has_output = output.standard_value
def execute(self, *keys, **options):
# the server must be the local host
if keys[-2] != api.env.host:
raise errors.ValidationError(
name='cn', error=_("must be \"%s\"") % api.env.host)
# the server entry must exist
try:
self.obj.get_dn_if_exists(*keys[:-1])
except errors.NotFound:
raise self.obj.handle_not_found(keys[-2])
# the user must have the Replication Administrators privilege
privilege = u'Replication Administrators'
op_account = getattr(context, 'principal', None)
if not principal_has_privilege(self.api, op_account, privilege):
raise errors.ACIError(
info=_("not allowed to perform server connection check"))
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
obj = bus.get_object('org.freeipa.server', '/',
follow_name_owner_changes=True)
server = dbus.Interface(obj, 'org.freeipa.server')
ret, stdout, _stderr = server.conncheck(keys[-1])
result = dict(
result=(ret == 0),
value=keys[-2],
)
for line in stdout.splitlines():
messages.add_message(options['version'],
result,
messages.ExternalCommandOutput(line=line))
return result
@register()
class server_state(crud.PKQuery):
__doc__ = _("Set enabled/hidden state of a server.")
takes_options = (
StrEnum(
'state',
values=(u'enabled', u'hidden'),
label=_('State'),
doc=_('Server state'),
flags={'virtual_attribute', 'no_create', 'no_search'},
),
)
msg_summary = _('Changed server state of "%(value)s".')
has_output = output.standard_boolean
def _check_hide_server(self, fqdn):
result = self.api.Command.config_show()['result']
err = []
# single value entries
if result.get("ca_renewal_master_server") == fqdn:
err.append(_("Cannot hide CA renewal master."))
if result.get("dnssec_key_master_server") == fqdn:
err.append(_("Cannot hide DNSSec key master."))
# multi value entries, only fail if we are the last one
checks = [
("ca_server_server", "CA"),
("dns_server_server", "DNS"),
("ipa_master_server", "IPA"),
("kra_server_server", "KRA"),
]
for key, name in checks:
values = result.get(key, [])
if values == [fqdn]: # fqdn is the only entry
err.append(
_("Cannot hide last enabled %(name)s server.") % {
'name': name
}
)
if err:
raise errors.ValidationError(
name=fqdn,
error=' '.join(str(e) for e in err)
)
def execute(self, *keys, **options):
fqdn = keys[0]
if options['state'] == u'enabled':
to_status = ENABLED
from_status = HIDDEN
else:
to_status = HIDDEN
from_status = ENABLED
roles = self.api.Command.server_role_find(
server_server=fqdn,
status=from_status,
include_master=True,
)['result']
from_roles = [r[u'role_servrole'] for r in roles]
if not from_roles:
# no server role is in source status
raise errors.EmptyModlist
if to_status == ENABLED:
enable_services(fqdn)
else:
self._check_hide_server(fqdn)
hide_services(fqdn)
# update system roles
result = self.api.Command.dns_update_system_records()
if not result.get('value'):
self.add_message(messages.AutomaticDNSRecordsUpdateFailed())
return {
'value': fqdn,
'result': True,
}
| 38,021
|
Python
|
.py
| 894
| 29.585011
| 80
| 0.546718
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,878
|
idrange.py
|
freeipa_freeipa/ipaserver/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/>.
import six
from ipalib.plugable import Registry
from .baseldap import (LDAPObject, LDAPCreate, LDAPDelete,
LDAPRetrieve, LDAPSearch, LDAPUpdate)
from ipalib import api, Int, Str, StrEnum, _, ngettext, messages
from ipalib import errors
from ipaplatform import services
from ipapython.dn import DN
if six.PY3:
unicode = str
if api.env.in_server:
try:
import ipaserver.dcerpc
_dcerpc_bindings_installed = True
except ImportError:
_dcerpc_bindings_installed = False
else:
_dcerpc_bindings_installed = False
ID_RANGE_VS_DNA_WARNING = _("""-------
WARNING:
DNA plugin in 389-ds will allocate IDs based on the ranges configured for the
local domain. Currently the DNA plugin *cannot* be reconfigured itself based
on the local ranges set via this family of commands.
Manual configuration change has to be done in the DNA plugin configuration for
the new local range. Specifically, The dnaNextRange attribute of 'cn=Posix
IDs,cn=Distributed Numeric Assignment Plugin,cn=plugins,cn=config' has to be
modified to match the new range.
-------
""")
__doc__ = _("""
ID ranges
Manage ID ranges used to map Posix IDs to SIDs and back.
There are two type of ID ranges which are both handled by this utility:
- the ID ranges of the local domain
- the ID ranges of trusted remote domains
Both types have the following attributes in common:
- base-id: the first ID of the Posix ID range
- range-size: the size of the range
With those two attributes a range object can reserve the Posix IDs starting
with base-id up to but not including base-id+range-size exclusively.
Additionally an ID range of the local domain may set
- rid-base: the first RID(*) of the corresponding RID range
- secondary-rid-base: first RID of the secondary RID range
and an ID range of a trusted domain must set
- rid-base: the first RID of the corresponding RID range
- sid: domain SID of the trusted domain
and an ID range of a trusted domain may set
- auto-private-groups: [true|false|hybrid] automatic creation of private groups
EXAMPLE: Add a new ID range for a trusted domain
Since there might be more than one trusted domain the domain SID must be given
while creating the ID range.
ipa idrange-add --base-id=1200000 --range-size=200000 --rid-base=0 \\
--dom-sid=S-1-5-21-123-456-789 trusted_dom_range
This ID range is then used by the IPA server and the SSSD IPA provider to
assign Posix UIDs to users from the trusted domain.
If e.g. a range for a trusted domain is configured with the following values:
base-id = 1200000
range-size = 200000
rid-base = 0
the RIDs 0 to 199999 are mapped to the Posix ID from 1200000 to 13999999. So
RID 1000 <-> Posix ID 1201000
EXAMPLE: Add a new ID range for the local domain
To create an ID range for the local domain it is not necessary to specify a
domain SID. But since it is possible that a user and a group can have the same
value as Posix ID a second RID interval is needed to handle conflicts.
ipa idrange-add --base-id=1200000 --range-size=200000 --rid-base=1000 \\
--secondary-rid-base=1000000 local_range
The data from the ID ranges of the local domain are used by the IPA server
internally to assign SIDs to IPA users and groups. The SID will then be stored
in the user or group objects.
If e.g. the ID range for the local domain is configured with the values from
the example above then a new user with the UID 1200007 will get the RID 1007.
If this RID is already used by a group the RID will be 1000007. This can only
happen if a user or a group object was created with a fixed ID because the
automatic assignment will not assign the same ID twice. Since there are only
users and groups sharing the same ID namespace it is sufficient to have only
one fallback range to handle conflicts.
To find the Posix ID for a given RID from the local domain it has to be
checked first if the RID falls in the primary or secondary RID range and
the rid-base or the secondary-rid-base has to be subtracted, respectively,
and the base-id has to be added to get the Posix ID.
Typically the creation of ID ranges happens behind the scenes and this CLI
must not be used at all. The ID range for the local domain will be created
during installation or upgrade from an older version. The ID range for a
trusted domain will be created together with the trust by 'ipa trust-add ...'.
USE CASES:
Add an ID range from a transitively trusted domain
If the trusted domain (A) trusts another domain (B) as well and this trust
is transitive 'ipa trust-add domain-A' will only create a range for
domain A. The ID range for domain B must be added manually.
Add an additional ID range for the local domain
If the ID range of the local domain is exhausted, i.e. no new IDs can be
assigned to Posix users or groups by the DNA plugin, a new range has to be
created to allow new users and groups to be added. (Currently there is no
connection between this range CLI and the DNA plugin, but a future version
might be able to modify the configuration of the DNS plugin as well)
In general it is not necessary to modify or delete ID ranges. If there is no
other way to achieve a certain configuration than to modify or delete an ID
range it should be done with great care. Because UIDs are stored in the file
system and are used for access control it might be possible that users are
allowed to access files of other users if an ID range got deleted and reused
for a different domain.
(*) The RID is typically the last integer of a user or group SID which follows
the domain SID. E.g. if the domain SID is S-1-5-21-123-456-789 and a user from
this domain has the SID S-1-5-21-123-456-789-1010 then 1010 is the RID of the
user. RIDs are unique in a domain, 32bit values and are used for users and
groups.
""") + ID_RANGE_VS_DNA_WARNING
register = Registry()
@register()
class idrange(LDAPObject):
"""
Range object.
"""
range_type = ('domain', 'ad', 'ipa')
container_dn = api.env.container_ranges
object_name = ('range')
object_name_plural = ('ranges')
object_class = ['ipaIDrange']
permission_filter_objectclasses = ['ipaidrange']
possible_objectclasses = ['ipadomainidrange', 'ipatrustedaddomainrange']
default_attributes = ['cn', 'ipabaseid', 'ipaidrangesize', 'ipabaserid',
'ipasecondarybaserid', 'ipanttrusteddomainsid',
'iparangetype', 'ipaautoprivategroups']
managed_permissions = {
'System: Read ID Ranges': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass',
'ipabaseid', 'ipaidrangesize', 'iparangetype',
'ipabaserid', 'ipasecondarybaserid', 'ipanttrusteddomainsid',
'ipaautoprivategroups',
},
},
}
label = _('ID Ranges')
label_singular = _('ID Range')
# The commented range types are planned but not yet supported
range_types = {
u'ipa-local': unicode(_('local domain range')),
# u'ipa-local-subid': unicode(_('local domain subid range')),
# u'ipa-ad-winsync': unicode(_('Active Directory winsync range')),
u'ipa-ad-trust': unicode(_('Active Directory domain range')),
u'ipa-ad-trust-posix': unicode(_('Active Directory trust range with '
'POSIX attributes')),
# u'ipa-ipa-trust': unicode(_('IPA trust range')),
}
takes_params = (
Str('cn',
cli_name='name',
label=_('Range name'),
primary_key=True,
),
Int('ipabaseid',
cli_name='base_id',
label=_("First Posix ID of the range"),
minvalue=1,
maxvalue=Int.MAX_UINT32
),
Int('ipaidrangesize',
cli_name='range_size',
label=_("Number of IDs in the range"),
minvalue=1,
maxvalue=Int.MAX_UINT32
),
Int('ipabaserid?',
cli_name='rid_base',
label=_('First RID of the corresponding RID range'),
),
Int('ipasecondarybaserid?',
cli_name='secondary_rid_base',
label=_('First RID of the secondary RID range'),
),
Str('ipanttrusteddomainsid?',
cli_name='dom_sid',
flags=('no_update',),
label=_('Domain SID of the trusted domain'),
),
Str('ipanttrusteddomainname?',
cli_name='dom_name',
flags=('no_search', 'virtual_attribute', 'no_update'),
label=_('Name of the trusted domain'),
),
StrEnum('iparangetype?',
label=_('Range type'),
cli_name='type',
doc=_('ID range type, one of allowed values'),
values=sorted(range_types),
flags=['no_update'],
),
StrEnum('ipaautoprivategroups?',
label=_('Auto private groups'),
cli_name='auto_private_groups',
doc=_('Auto creation of private groups, one of allowed values'),
values=(u'true', u'false', u'hybrid'),
),
)
def handle_iparangetype(self, entry_attrs, options,
keep_objectclass=False):
if not any((options.get('pkey_only', False),
options.get('raw', False))):
range_type = entry_attrs['iparangetype'][0]
entry_attrs['iparangetyperaw'] = [range_type]
entry_attrs['iparangetype'] = [self.range_types.get(range_type, None)]
# Remove the objectclass
if not keep_objectclass:
if not options.get('all', False) or options.get('pkey_only', False):
entry_attrs.pop('objectclass', None)
def handle_ipabaserid(self, entry_attrs, options):
if any((options.get('pkey_only', False), options.get('raw', False))):
return
if entry_attrs['iparangetype'][0] == u'ipa-ad-trust-posix':
entry_attrs.pop('ipabaserid', None)
def check_ids_in_modified_range(self, old_base, old_size, new_base,
new_size):
if new_base is None and new_size is None:
# nothing to check
return
if new_base is None:
new_base = old_base
if new_size is None:
new_size = old_size
old_interval = (old_base, old_base + old_size - 1)
new_interval = (new_base, new_base + new_size - 1)
checked_intervals = []
low_diff = new_interval[0] - old_interval[0]
if low_diff > 0:
checked_intervals.append((old_interval[0],
min(old_interval[1], new_interval[0] - 1)))
high_diff = old_interval[1] - new_interval[1]
if high_diff > 0:
checked_intervals.append((max(old_interval[0], new_interval[1] + 1),
old_interval[1]))
if not checked_intervals:
# range is equal or covers the entire old range, nothing to check
return
ldap = self.backend
id_filter_base = ["(objectclass=posixAccount)",
"(objectclass=posixGroup)",
"(objectclass=ipaIDObject)"]
id_filter_ids = []
for id_low, id_high in checked_intervals:
id_filter_ids.append("(&(uidNumber>=%(low)d)(uidNumber<=%(high)d))"
% dict(low=id_low, high=id_high))
id_filter_ids.append("(&(gidNumber>=%(low)d)(gidNumber<=%(high)d))"
% dict(low=id_low, high=id_high))
id_filter = ldap.combine_filters(
[ldap.combine_filters(id_filter_base, "|"),
ldap.combine_filters(id_filter_ids, "|")],
"&")
try:
ldap.find_entries(filter=id_filter,
attrs_list=['uid', 'cn'],
base_dn=DN(api.env.container_accounts, api.env.basedn))
except errors.NotFound:
# no objects in this range found, allow the command
pass
else:
raise errors.ValidationError(name="ipabaseid,ipaidrangesize",
error=_('range modification leaving objects with ID out '
'of the defined range is not allowed'))
def get_domain_validator(self):
if not _dcerpc_bindings_installed:
raise errors.NotFound(reason=_('Cannot perform SID validation '
'without Samba 4 support installed. Make sure you have '
'installed server-trust-ad sub-package of IPA on the server'))
# pylint: disable=used-before-assignment
domain_validator = ipaserver.dcerpc.DomainValidator(self.api)
# pylint: enable=used-before-assignment
if not domain_validator.is_configured():
raise errors.NotFound(reason=_('Cross-realm trusts are not '
'configured. Make sure you have run ipa-adtrust-install '
'on the IPA server first'))
return domain_validator
def validate_trusted_domain_sid(self, sid):
domain_validator = self.get_domain_validator()
if not domain_validator.is_trusted_domain_sid_valid(sid):
raise errors.ValidationError(name='domain SID',
error=_('SID is not recognized as a valid SID for a '
'trusted domain'))
def get_trusted_domain_sid_from_name(self, name):
""" Returns unicode string representation for given trusted domain name
or None if SID forthe given trusted domain name could not be found."""
domain_validator = self.get_domain_validator()
sid = domain_validator.get_sid_from_domain_name(name)
if sid is not None:
sid = unicode(sid)
return sid
# checks that primary and secondary rid ranges do not overlap
def are_rid_ranges_overlapping(self, rid_base, secondary_rid_base, size):
# if any of these is None, the check does not apply
if any(attr is None for attr in (rid_base, secondary_rid_base, size)):
return False
# sort the bases
if rid_base > secondary_rid_base:
rid_base, secondary_rid_base = secondary_rid_base, rid_base
# rid_base is now <= secondary_rid_base,
# so the following check is sufficient
if rid_base + size <= secondary_rid_base:
return False
else:
return True
@register()
class idrange_add(LDAPCreate):
__doc__ = _("""
Add new ID range.
To add a new ID range you always have to specify
--base-id
--range-size
Additionally
--rid-base
--secondary-rid-base
may be given for a new ID range for the local domain while
--auto-private-groups
may be given for a new ID range for a trusted AD domain and
--rid-base
--dom-sid
must be given to add a new range for a trusted AD domain.
""") + ID_RANGE_VS_DNA_WARNING
msg_summary = _('Added ID range "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
def is_set(x):
return entry_attrs.get(x) is not None
# This needs to stay in options since there is no
# ipanttrusteddomainname attribute in LDAP
if options.get('ipanttrusteddomainname'):
if is_set('ipanttrusteddomainsid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options dom-sid and dom-name '
'cannot be used together'))
sid = self.obj.get_trusted_domain_sid_from_name(
options['ipanttrusteddomainname'])
if sid is not None:
entry_attrs['ipanttrusteddomainsid'] = sid
else:
raise errors.ValidationError(
name='ID Range setup',
error=_('Specified trusted domain name could not be '
'found.'))
# ipaNTTrustedDomainSID attribute set, this is AD Trusted domain range
if is_set('ipanttrusteddomainsid'):
entry_attrs['objectclass'].append('ipatrustedaddomainrange')
# Default to ipa-ad-trust if no type set
if not is_set('iparangetype'):
entry_attrs['iparangetype'] = u'ipa-ad-trust'
if entry_attrs['iparangetype'] == u'ipa-ad-trust':
if not is_set('ipabaserid'):
raise errors.ValidationError(
name='ID Range setup',
error=_('Options dom-sid/dom-name and rid-base must '
'be used together')
)
elif entry_attrs['iparangetype'] == u'ipa-ad-trust-posix':
if is_set('ipabaserid') and entry_attrs['ipabaserid'] != 0:
raise errors.ValidationError(
name='ID Range setup',
error=_('Option rid-base must not be used when IPA '
'range type is ipa-ad-trust-posix')
)
else:
entry_attrs['ipabaserid'] = 0
else:
raise errors.ValidationError(name='ID Range setup',
error=_('IPA Range type must be one of ipa-ad-trust '
'or ipa-ad-trust-posix when SID of the trusted '
'domain is specified'))
if is_set('ipasecondarybaserid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options dom-sid/dom-name and secondary-rid-base '
'cannot be used together'))
# Validate SID as the one of trusted domains
self.obj.validate_trusted_domain_sid(
entry_attrs['ipanttrusteddomainsid'])
# ipaNTTrustedDomainSID attribute not set, this is local domain range
else:
entry_attrs['objectclass'].append('ipadomainidrange')
# Default to ipa-local if no type set
if 'iparangetype' not in entry_attrs:
entry_attrs['iparangetype'] = 'ipa-local'
# TODO: can also be ipa-ad-winsync here?
if entry_attrs['iparangetype'] in (u'ipa-ad-trust',
u'ipa-ad-trust-posix'):
raise errors.ValidationError(name='ID Range setup',
error=_('IPA Range type must not be one of ipa-ad-trust '
'or ipa-ad-trust-posix when SID of the trusted '
'domain is not specified.'))
# auto private group is possible only for ad trusts
if is_set('ipaautoprivategroups') and \
entry_attrs['iparangetype'] not in (u'ipa-ad-trust',
u'ipa-ad-trust-posix'):
raise errors.ValidationError(
name='ID Range setup',
error=_('IPA Range type must be one of ipa-ad-trust '
'or ipa-ad-trust-posix when '
'auto-private-groups is specified'))
# secondary base rid must be set if and only if base rid is set
if is_set('ipasecondarybaserid') != is_set('ipabaserid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options secondary-rid-base and rid-base must '
'be used together'))
# and they must not overlap
if is_set('ipabaserid') and is_set('ipasecondarybaserid'):
if self.obj.are_rid_ranges_overlapping(
entry_attrs['ipabaserid'],
entry_attrs['ipasecondarybaserid'],
entry_attrs['ipaidrangesize']):
raise errors.ValidationError(name='ID Range setup',
error=_("Primary RID range and secondary RID range"
" cannot overlap"))
# rid-base and secondary-rid-base must be set if
# ipa-adtrust-install has been run on the system
adtrust_is_enabled = api.Command['adtrust_is_enabled']()['result']
if adtrust_is_enabled and not (
is_set('ipabaserid') and is_set('ipasecondarybaserid')):
raise errors.ValidationError(
name='ID Range setup',
error=_(
'You must specify both rid-base and '
'secondary-rid-base options, because '
'ipa-adtrust-install has already been run.'
)
)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.handle_ipabaserid(entry_attrs, options)
self.obj.handle_iparangetype(entry_attrs, options,
keep_objectclass=True)
if entry_attrs.single_value.get('iparangetype') in (
'ipa-local', self.obj.range_types.get('ipa-local', None)):
self.add_message(
messages.ServiceRestartRequired(
service=services.knownservices.dirsrv.service_instance(""),
server=_('<all IPA servers>')
)
)
return dn
@register()
class idrange_del(LDAPDelete):
__doc__ = _('Delete an ID range.')
msg_summary = _('Deleted ID range "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
try:
old_attrs = ldap.get_entry(dn, ['ipabaseid',
'ipaidrangesize',
'ipanttrusteddomainsid',
'iparangetype'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
# Check whether we leave any object with id in deleted range
old_base_id = int(old_attrs.get('ipabaseid', [0])[0])
old_range_size = int(old_attrs.get('ipaidrangesize', [0])[0])
self.obj.check_ids_in_modified_range(
old_base_id, old_range_size, 0, 0)
# Check whether the range does not belong to the active trust
range_sid = old_attrs.get('ipanttrusteddomainsid')
if range_sid is not None:
# Search for trusted domain with SID specified in the ID range entry
range_sid = range_sid[0]
domain_filter=('(&(objectclass=ipaNTTrustedDomain)'
'(ipanttrusteddomainsid=%s))' % range_sid)
try:
trust_domains, _truncated = ldap.find_entries(
base_dn=DN(api.env.container_trusts, api.env.basedn),
filter=domain_filter)
except errors.NotFound:
pass
else:
# If there's an entry, it means that there's active domain
# of a trust that this range belongs to, so raise a
# DependentEntry error
raise errors.DependentEntry(
label='Active Trust domain',
key=keys[0],
dependent=trust_domains[0].dn[0].value)
self.add_message(
messages.ServiceRestartRequired(
service=services.knownservices['sssd'].systemd_name,
server=_('<all IPA servers>')
)
)
if old_attrs.single_value.get('iparangetype') == 'ipa-local':
self.add_message(
messages.ServiceRestartRequired(
service=services.knownservices.dirsrv.service_instance(""),
server=_('<all IPA servers>')
)
)
return dn
@register()
class idrange_find(LDAPSearch):
__doc__ = _('Search for ranges.')
msg_summary = ngettext(
'%(count)d range matched', '%(count)d ranges matched', 0
)
# Since all range types are stored within separate containers under
# 'cn=ranges,cn=etc' search can be done on a one-level scope
def pre_callback(self, ldap, filters, attrs_list, base_dn, scope, *args,
**options):
assert isinstance(base_dn, DN)
attrs_list.append('objectclass')
return (filters, base_dn, ldap.SCOPE_ONELEVEL)
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry in entries:
self.obj.handle_ipabaserid(entry, options)
self.obj.handle_iparangetype(entry, options)
return truncated
@register()
class idrange_show(LDAPRetrieve):
__doc__ = _('Display information about a range.')
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
attrs_list.append('objectclass')
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.handle_ipabaserid(entry_attrs, options)
self.obj.handle_iparangetype(entry_attrs, options)
return dn
@register()
class idrange_mod(LDAPUpdate):
__doc__ = _("""Modify ID range.
""") + ID_RANGE_VS_DNA_WARNING
msg_summary = _('Modified ID range "%(value)s"')
takes_options = LDAPUpdate.takes_options + (
Str(
'ipanttrusteddomainsid?',
deprecated=True,
cli_name='dom_sid',
flags=('no_update', 'no_option'),
label=_('Domain SID of the trusted domain'),
autofill=False,
),
Str(
'ipanttrusteddomainname?',
deprecated=True,
cli_name='dom_name',
flags=('no_search', 'virtual_attribute', 'no_update', 'no_option'),
label=_('Name of the trusted domain'),
autofill=False,
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
attrs_list.append('objectclass')
try:
old_attrs = ldap.get_entry(dn, ['*'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if (
old_attrs['iparangetype'][0] in {'ipa-local', 'ipa-local-subid'}
or old_attrs['cn'][0] == f'{self.api.env.realm}_subid_range'
):
raise errors.ExecutionError(
message=_('This command can not be used to change ID '
'allocation for local IPA domain. Run '
'`ipa help idrange` for more information')
)
def is_set(x):
return entry_attrs.get(x) is not None
def in_updated_attrs(x):
return is_set(x) or (
x not in entry_attrs and old_attrs.get(x) is not None
)
# This needs to stay in options since there is no
# ipanttrusteddomainname attribute in LDAP
if 'ipanttrusteddomainname' in options:
if is_set('ipanttrusteddomainsid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options dom-sid and dom-name '
'cannot be used together'))
sid = self.obj.get_trusted_domain_sid_from_name(
options['ipanttrusteddomainname'])
# we translate the name into sid so further validation can rely
# on ipanttrusteddomainsid attribute only
if sid is not None:
entry_attrs['ipanttrusteddomainsid'] = sid
else:
raise errors.ValidationError(name='ID Range setup',
error=_('SID for the specified trusted domain name could '
'not be found. Please specify the SID directly '
'using dom-sid option.'))
if in_updated_attrs('ipanttrusteddomainsid'):
if in_updated_attrs('ipasecondarybaserid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options dom-sid and secondary-rid-base cannot '
'be used together'))
range_type = old_attrs['iparangetype'][0]
if range_type == u'ipa-ad-trust':
if not in_updated_attrs('ipabaserid'):
raise errors.ValidationError(
name='ID Range setup',
error=_('Options dom-sid and rid-base must '
'be used together'))
elif (range_type == u'ipa-ad-trust-posix' and
'ipabaserid' in entry_attrs):
if entry_attrs['ipabaserid'] is None:
entry_attrs['ipabaserid'] = 0
elif entry_attrs['ipabaserid'] != 0:
raise errors.ValidationError(
name='ID Range setup',
error=_('Option rid-base must not be used when IPA '
'range type is ipa-ad-trust-posix')
)
if is_set('ipanttrusteddomainsid'):
# Validate SID as the one of trusted domains
# perform this check only if the attribute was changed
self.obj.validate_trusted_domain_sid(
entry_attrs['ipanttrusteddomainsid'])
# Add trusted AD domain range object class, if it wasn't there
if 'ipatrustedaddomainrange' not in old_attrs['objectclass']:
entry_attrs['objectclass'].append('ipatrustedaddomainrange')
else:
# secondary base rid must be set if and only if base rid is set
if in_updated_attrs('ipasecondarybaserid') !=\
in_updated_attrs('ipabaserid'):
raise errors.ValidationError(name='ID Range setup',
error=_('Options secondary-rid-base and rid-base must '
'be used together'))
# ensure that primary and secondary rid ranges do not overlap
if all(in_updated_attrs(base)
for base in ('ipabaserid', 'ipasecondarybaserid')):
# make sure we are working with updated attributes
rid_range_attributes = ('ipabaserid', 'ipasecondarybaserid',
'ipaidrangesize')
updated_values = dict()
for attr in rid_range_attributes:
if is_set(attr):
updated_values[attr] = entry_attrs[attr]
else:
updated_values[attr] = int(old_attrs[attr][0])
if self.obj.are_rid_ranges_overlapping(
updated_values['ipabaserid'],
updated_values['ipasecondarybaserid'],
updated_values['ipaidrangesize']):
raise errors.ValidationError(name='ID Range setup',
error=_("Primary RID range and secondary RID range"
" cannot overlap"))
# check whether ids are in modified range
old_base_id = int(old_attrs.get('ipabaseid', [0])[0])
old_range_size = int(old_attrs.get('ipaidrangesize', [0])[0])
new_base_id = entry_attrs.get('ipabaseid')
if new_base_id is not None:
new_base_id = int(new_base_id)
new_range_size = entry_attrs.get('ipaidrangesize')
if new_range_size is not None:
new_range_size = int(new_range_size)
self.obj.check_ids_in_modified_range(old_base_id, old_range_size,
new_base_id, new_range_size)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.handle_ipabaserid(entry_attrs, options)
self.obj.handle_iparangetype(entry_attrs, options)
if entry_attrs.single_value.get('iparangetype') in (
'ipa-local', self.obj.range_types.get('ipa-local', None)):
self.add_message(
messages.ServiceRestartRequired(
service=services.knownservices.dirsrv.service_instance(""),
server=_('<all IPA servers>')
)
)
self.add_message(
messages.ServiceRestartRequired(
service=services.knownservices['sssd'].systemd_name,
server=_('<all IPA servers>')
)
)
return dn
| 33,824
|
Python
|
.py
| 690
| 36.824638
| 82
| 0.592001
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,879
|
serverroles.py
|
freeipa_freeipa/ipaserver/plugins/serverroles.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
serverroles backend
=======================================
The `serverroles` backend has access to all roles and attributes stored in
module-level lists exposed in `ipaserver/servroles.py` module. It uses these
lists to populate populate its internal stores with instances of the
roles/attributes. The information contained in them can be accessed by
the following methods:
*api.Backend.serverroles.server_role_search(
server_server=None, role_servrole=None status=None)
search for roles matching the given substrings and return the status of
the matched roles. Optionally filter the result by role status. If
`server_erver` is not None, the search is limited to a single master.
Otherwise, the status is computed for all masters in the topology. If
`role_servrole` is None, the all configured roled are queried
*api.Backend.serverroles.server_role_retrieve(server_server, role_servrole)
retrieve the status of a single role on a given master
*api.Backend.serverroles.config_retrieve(role_servrole)
return a configuration object given role name. This object is a
dictionary containing a list of enabled masters and all attributes
associated with the role along with master(s) on which they are set.
*api.Backend.serverroles.config_update(**attrs_values)
update configuration object. Since server roles are currently
immutable, only attributes can be set
Note that attribute/role names are searched/matched case-insensitively. Also
note that the `serverroles` backend does not create/destroy any LDAP connection
by itself, so make sure `ldap2` backend connections are taken care of
in the calling code
"""
import six
from ipalib import errors, _
from ipalib.backend import Backend
from ipalib.plugable import Registry
from ipaserver.servroles import (
attribute_instances, ENABLED, HIDDEN, role_instances
)
from ipaserver.servroles import SingleValuedServerAttribute
if six.PY3:
unicode = str
register = Registry()
@register()
class serverroles(Backend):
"""
This Backend can be used to query various information about server roles
and attributes configured in the topology.
"""
def __init__(self, api_instance):
super(serverroles, self).__init__(api_instance)
self.role_names = {
obj.name.lower(): obj for obj in role_instances}
self.attributes = {
attr.attr_name: attr for attr in attribute_instances}
def _get_role(self, role_name):
key = role_name.lower()
try:
return self.role_names[key]
except KeyError:
raise errors.NotFound(
reason=_("{role}: role not found").format(role=role_name))
def _get_masters(self, role_name, include_hidden):
result = {}
role = self._get_role(role_name)
role_states = role.status(self.api, server=None)
enabled_masters = [
r[u'server_server'] for r in role_states if
r[u'status'] == ENABLED
]
if enabled_masters:
result.update({role.attr_name: enabled_masters})
if include_hidden and role.attr_name_hidden is not None:
hidden_masters = [
r[u'server_server'] for r in role_states if
r[u'status'] == HIDDEN
]
if hidden_masters:
result.update({role.attr_name_hidden: hidden_masters})
return result
def _get_assoc_attributes(self, role_name):
role = self._get_role(role_name)
assoc_attributes = {
name: attr for name, attr in self.attributes.items() if
attr.associated_role is role}
if not assoc_attributes:
raise NotImplementedError(
"Role {} has no associated attribute to set".format(role.name))
return assoc_attributes
def server_role_search(self, server_server=None, role_servrole=None,
status=None):
if role_servrole is None:
found_roles = self.role_names.values()
else:
try:
found_roles = [self._get_role(role_servrole)]
except errors.NotFound:
found_roles = []
result = []
for found_role in found_roles:
role_status = found_role.status(self.api, server=server_server)
result.extend(role_status)
if status is not None:
return [r for r in result if r[u'status'] == status]
return result
def server_role_retrieve(self, server_server, role_servrole):
return self._get_role(role_servrole).status(
self.api, server=server_server)
def config_retrieve(self, servrole, include_hidden=True):
result = self._get_masters(servrole, include_hidden=include_hidden)
try:
assoc_attributes = self._get_assoc_attributes(servrole)
except NotImplementedError:
return result
for name, attr in assoc_attributes.items():
attr_value = attr.get(self.api)
if attr_value:
# attr can be a SingleValuedServerAttribute
# in this case, the API expects a value, not a list of values
if isinstance(attr, SingleValuedServerAttribute):
attr_value = attr_value[0]
result.update({name: attr_value})
return result
def config_update(self, **attrs_values):
for attr, value in attrs_values.items():
try:
# when the attribute is single valued, it will be stored
# in a SingleValuedServerAttribute. The set method expects
# a list containing a single value.
# We need to convert value to a list containing value
if isinstance(self.attributes[attr],
SingleValuedServerAttribute):
value = [value]
self.attributes[attr].set(self.api, value)
except KeyError:
raise errors.NotFound(
reason=_('{attr}: no such attribute').format(attr=attr))
| 6,281
|
Python
|
.py
| 137
| 36.248175
| 79
| 0.645584
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,880
|
idviews.py
|
freeipa_freeipa/ipaserver/plugins/idviews.py
|
# Authors:
# 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/>.
import re
import six
from .baseldap import (LDAPQuery, LDAPObject, LDAPCreate,
LDAPDelete, LDAPUpdate, LDAPSearch,
LDAPAddAttributeViaOption,
LDAPRemoveAttributeViaOption,
LDAPRetrieve, global_output_params,
host_is_master,
add_missing_object_class, member_validator)
from .hostgroup import get_complete_hostgroup_member_list
from ipalib import (
api, Str, Int, Flag, _, ngettext, errors, output
)
from ipalib.parameters import Certificate
from ipalib.constants import (
IPA_ANCHOR_PREFIX,
SID_ANCHOR_PREFIX,
PATTERN_GROUPUSER_NAME,
ERRMSG_GROUPUSER_NAME
)
from ipalib.plugable import Registry
from ipalib.util import (normalize_sshpubkey, validate_sshpubkey,
convert_sshpubkey_post)
from ipapython.dn import DN
if six.PY3:
unicode = str
_dcerpc_bindings_installed = False
if api.env.in_server:
try:
import ipaserver.dcerpc
_dcerpc_bindings_installed = True
except ImportError:
pass
__doc__ = _("""
ID Views
Manage ID Views
IPA allows to override certain properties of users and groups per each host.
This functionality is primarily used to allow migration from older systems or
other Identity Management solutions.
""")
register = Registry()
protected_default_trust_view_error = errors.ProtectedEntryError(
label=_('ID View'),
key=u"Default Trust View",
reason=_('system ID View')
)
fallback_to_ldap_option = Flag(
'fallback_to_ldap?',
default=False,
label=_('Fallback to AD DC LDAP'),
doc=_("Allow falling back to AD DC LDAP when resolving AD "
"trusted objects. For two-way trusts only."),
)
DEFAULT_TRUST_VIEW_NAME = "default trust view"
ANCHOR_REGEX = re.compile(
r':IPA:.*:[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
r'|'
r':SID:S-[0-9\-]+'
)
def normalize_idview_name(value):
if value in (None, '',):
return DEFAULT_TRUST_VIEW_NAME
return value
def handle_idoverride_memberof(self, ldap, dn, found, not_found,
*keys, **options):
if ('idoverrideuser' in options) and ('member' in found):
for id in found['member'].get('idoverrideuser', []):
try:
e = ldap.get_entry(id, ['*'])
if not self.obj.has_objectclass(e['objectclass'],
'nsmemberof'):
add_missing_object_class(ldap, 'nsmemberof',
id, entry_attrs=e, update=True)
except errors.NotFound:
# We are not adding an object here, only modifying existing
continue
return dn
@register()
class idview(LDAPObject):
"""
ID View object.
"""
container_dn = api.env.container_views
object_name = _('ID View')
object_name_plural = _('ID Views')
object_class = ['ipaIDView', 'top']
possible_objectclasses = ['ipaNameResolutionData']
default_attributes = ['cn', 'description', 'ipadomainresolutionorder']
allow_rename = True
label = _('ID Views')
label_singular = _('ID View')
takes_params = (
Str('cn',
cli_name='name',
label=_('ID View Name'),
primary_key=True,
normalizer=normalize_idview_name,
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
Str('useroverrides',
label=_('User object overrides'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('groupoverrides',
label=_('Group object overrides'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str('appliedtohosts',
label=_('Hosts the view applies to'),
flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'},
),
Str(
'ipadomainresolutionorder?',
cli_name='domain_resolution_order',
label=_('Domain resolution order'),
doc=_('colon-separated list of domains used for short name'
' qualification'),
flags={'no_search'}
)
)
permission_filter_objectclasses = ['nsContainer']
managed_permissions = {
'System: Read ID Views': {
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'description', 'ipadomainresolutionorder', 'objectClass',
},
},
}
def ensure_possible_objectclasses(self, ldap, dn, entry_attrs, *keys):
try:
orig_entry_attrs = ldap.get_entry(dn, ['objectclass'])
except errors.NotFound:
# pylint: disable=raising-bad-type, #4772
raise self.handle_not_found(*keys)
orig_objectclasses = {
o.lower() for o in orig_entry_attrs.get('objectclass', [])}
entry_attrs['objectclass'] = orig_entry_attrs['objectclass']
for obj_class_name in self.possible_objectclasses:
if obj_class_name.lower() not in orig_objectclasses:
entry_attrs['objectclass'].append(obj_class_name)
@register()
class idview_add(LDAPCreate):
__doc__ = _('Add a new ID View.')
msg_summary = _('Added ID View "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
self.api.Object.config.validate_domain_resolution_order(entry_attrs)
# The objectclass ipaNameResolutionData may not be present on
# the id view. We need to add it if we define a new
# value for ipaDomainResolutionOrder
if 'ipadomainresolutionorder' in entry_attrs:
add_missing_object_class(ldap, u'ipanameresolutiondata', dn,
entry_attrs, update=False)
return dn
@register()
class idview_del(LDAPDelete):
__doc__ = _('Delete an ID View.')
msg_summary = _('Deleted ID View "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
for key in keys:
if key.lower() == DEFAULT_TRUST_VIEW_NAME:
raise protected_default_trust_view_error
return dn
@register()
class idview_mod(LDAPUpdate):
__doc__ = _('Modify an ID View.')
msg_summary = _('Modified an ID View "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
for key in keys:
if key.lower() == DEFAULT_TRUST_VIEW_NAME:
raise protected_default_trust_view_error
self.api.Object.config.validate_domain_resolution_order(entry_attrs)
self.obj.ensure_possible_objectclasses(ldap, dn, entry_attrs, *keys)
return dn
@register()
class idview_find(LDAPSearch):
__doc__ = _('Search for an ID View.')
msg_summary = ngettext('%(count)d ID View matched',
'%(count)d ID Views matched', 0)
@register()
class idview_show(LDAPRetrieve):
__doc__ = _('Display information about an ID View.')
takes_options = LDAPRetrieve.takes_options + (
Flag('show_hosts?',
cli_name='show_hosts',
doc=_('Enumerate all the hosts the view applies to.'),
),
)
has_output_params = global_output_params
def show_id_overrides(self, dn, entry_attrs):
ldap = self.obj.backend
for objectclass, obj_type in [('ipaUserOverride', 'user'),
('ipaGroupOverride', 'group')]:
# Attribute to store results is called (user|group)overrides
attr_name = obj_type + 'overrides'
try:
overrides, _truncated = ldap.find_entries(
filter="objectclass=%s" % objectclass,
attrs_list=['ipaanchoruuid', 'ipaoriginaluid'],
base_dn=dn,
scope=ldap.SCOPE_ONELEVEL,
paged_search=True)
resolved_overrides = []
for override in overrides:
if 'ipaoriginaluid' in override:
# No need to resolve the anchor, we already know
# the value
resolved_overrides.append(
override.single_value['ipaoriginaluid'])
continue
anchor = override.single_value['ipaanchoruuid']
try:
name = resolve_anchor_to_object_name(ldap, obj_type,
anchor)
resolved_overrides.append(name)
except (errors.NotFound, errors.ValidationError):
# Anchor could not be resolved, use raw
resolved_overrides.append(anchor)
entry_attrs[attr_name] = resolved_overrides
except errors.NotFound:
# No overrides found, nothing to do
pass
def enumerate_hosts(self, dn, entry_attrs):
ldap = self.obj.backend
filter_params = {
'ipaAssignedIDView': dn,
'objectClass': 'ipaHost',
}
try:
hosts, _truncated = ldap.find_entries(
filter=ldap.make_filter(filter_params, rules=ldap.MATCH_ALL),
attrs_list=['cn'],
base_dn=api.env.container_host + api.env.basedn,
scope=ldap.SCOPE_ONELEVEL,
paged_search=True)
entry_attrs['appliedtohosts'] = [host.single_value['cn']
for host in hosts]
except errors.NotFound:
pass
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.show_id_overrides(dn, entry_attrs)
# Enumerating hosts is a potentially expensive operation (uses paged
# search to list all the hosts the ID view applies to). Show the list
# of the hosts only if explicitly asked for (or asked for --all).
# Do not display with --raw, since this attribute does not exist in
# LDAP.
if ((options.get('show_hosts') or options.get('all'))
and not options.get('raw')):
self.enumerate_hosts(dn, entry_attrs)
return dn
class baseidview_apply(LDAPQuery):
"""
Base class for idview_apply and idview_unapply commands.
"""
has_output_params = global_output_params
def execute(self, *keys, **options):
view = keys[-1] if keys else None
ldap = self.obj.backend
# Test if idview actually exists, if it does not, NotFound is raised
if not options.get('clear_view', False):
view_dn = self.api.Object['idview'].get_dn_if_exists(view)
assert isinstance(view_dn, DN)
# Check that we're not applying the Default Trust View
if view.lower() == DEFAULT_TRUST_VIEW_NAME:
raise errors.ValidationError(
name=_('ID View'),
error=_('Default Trust View cannot be applied on hosts')
)
else:
# In case we are removing assigned view, we modify the host setting
# the ipaAssignedIDView to None
view_dn = None
completed = 0
succeeded = {'host': []}
failed = {
'host': [],
'hostgroup': [],
}
# Make sure we ignore None passed via host or hostgroup, since it does
# not make sense
for key in ('host', 'hostgroup'):
if key in options and options[key] is None:
del options[key]
# Generate a list of all hosts to apply the view to
hosts_to_apply = list(options.get('host', []))
for hostgroup in options.get('hostgroup', ()):
try:
hosts_to_apply += get_complete_hostgroup_member_list(hostgroup)
except errors.NotFound:
failed['hostgroup'].append((hostgroup, unicode(_("not found"))))
except errors.PublicError as e:
failed['hostgroup'].append((hostgroup, "%s : %s" % (
e.__class__.__name__, str(e))))
for host in hosts_to_apply:
try:
# Check that the host is not a master
# IDView must not be applied to masters
try:
host_is_master(ldap, host)
except errors.ValidationError:
failed['host'].append(
(host,
unicode(_("ID View cannot be applied to IPA master")))
)
continue
host_dn = api.Object['host'].get_dn_if_exists(host)
host_entry = ldap.get_entry(host_dn,
attrs_list=['ipaassignedidview'])
host_entry['ipaassignedidview'] = view_dn
ldap.update_entry(host_entry)
# If no exception was raised, view assignment went well
completed = completed + 1
succeeded['host'].append(host)
except errors.EmptyModlist:
# If view was already applied, complain about it
failed['host'].append((host,
unicode(_("ID View already applied"))))
except errors.NotFound:
failed['host'].append((host, unicode(_("not found"))))
except errors.PublicError as e:
failed['host'].append((host, str(e)))
# Wrap dictionary containing failures in another dictionary under key
# 'memberhost', since that is output parameter in global_output_params
# and thus we get nice output in the CLI
failed = {'memberhost': failed}
# Sort the list of affected hosts
succeeded['host'].sort()
# Note that we're returning the list of affected hosts even if they
# were passed via referencing a hostgroup. This is desired, since we
# want to stress the fact that view is applied on all the current
# member hosts of the hostgroup and not tied with the hostgroup itself.
return dict(
summary=unicode(_(self.msg_summary % {'value': view})),
succeeded=succeeded,
completed=completed,
failed=failed,
)
@register()
class idview_apply(baseidview_apply):
__doc__ = _('Applies ID View to specified hosts or current members of '
'specified hostgroups. If any other ID View is applied to '
'the host, it is overridden.')
member_count_out = (_('ID View applied to %i host.'),
_('ID View applied to %i hosts.'))
msg_summary = 'Applied ID View "%(value)s"'
takes_options = (
Str('host*',
cli_name='hosts',
doc=_('Hosts to apply the ID View to'),
label=_('hosts'),
),
Str('hostgroup*',
cli_name='hostgroups',
doc=_('Hostgroups to whose hosts apply the ID View to. Please note '
'that view is not applied automatically to any hosts added '
'to the hostgroup after running the idview-apply command.'),
label=_('hostgroups'),
),
)
has_output = (
output.summary,
output.Output('succeeded',
type=dict,
doc=_('Hosts that this ID View was applied to.'),
),
output.Output('failed',
type=dict,
doc=_('Hosts or hostgroups that this ID View could not be '
'applied to.'),
),
output.Output('completed',
type=int,
doc=_('Number of hosts the ID View was applied to:'),
),
)
@register()
class idview_unapply(baseidview_apply):
__doc__ = _('Clears ID View from specified hosts or current members of '
'specified hostgroups.')
member_count_out = (_('ID View cleared from %i host.'),
_('ID View cleared from %i hosts.'))
msg_summary = 'Cleared ID Views'
takes_options = (
Str('host*',
cli_name='hosts',
doc=_('Hosts to clear (any) ID View from.'),
label=_('hosts'),
),
Str('hostgroup*',
cli_name='hostgroups',
doc=_('Hostgroups whose hosts should have ID Views cleared. Note '
'that view is not cleared automatically from any host added '
'to the hostgroup after running idview-unapply command.'),
label=_('hostgroups'),
),
)
has_output = (
output.summary,
output.Output('succeeded',
type=dict,
doc=_('Hosts that ID View was cleared from.'),
),
output.Output('failed',
type=dict,
doc=_('Hosts or hostgroups that ID View could not be cleared '
'from.'),
),
output.Output('completed',
type=int,
doc=_('Number of hosts that had a ID View was unset:'),
),
)
# Take no arguments, since ID View reference is not needed to clear
# the hosts
def get_args(self):
return ()
def execute(self, *keys, **options):
options['clear_view'] = True
return super(idview_unapply, self).execute(*keys, **options)
# ID overrides helper methods
def verify_trusted_domain_object_type(validator, desired_type, name_or_sid):
object_type = validator.get_trusted_domain_object_type(name_or_sid)
if object_type == desired_type:
# In case SSSD returns the same type as the type being
# searched, no problems here.
return True
elif desired_type == 'user' and object_type == 'both':
# Type both denotes users with magic private groups.
# Overriding attributes for such users is OK.
return True
elif desired_type == 'group' and object_type == 'both':
# However, overriding attributes for magic private groups
# does not make sense. One should override the GID of
# the user itself.
raise errors.ConversionError(
name='identifier',
error=_('You are trying to reference a magic private group '
'which is not allowed to be overridden. '
'Try overriding the GID attribute of the '
'corresponding user instead.')
)
return False
def resolve_object_to_anchor(ldap, obj_type, obj, fallback_to_ldap):
"""
Resolves the user/group name to the anchor uuid:
- first it tries to find the object as user or group in IPA (depending
on the passed obj_type)
- if the IPA lookup failed, lookup object SID in the trusted domains
Takes options:
ldap - the backend
obj_type - either 'user' or 'group'
obj - the name of the object, e.g. 'admin' or 'testuser'
"""
try:
entry = ldap.get_entry(api.Object[obj_type].get_dn(obj),
attrs_list=['ipaUniqueID', 'objectClass'])
# First we check this is a valid object to override
# - for groups, it must have ipaUserGroup objectclass
# - for users, it must have posixAccount objectclass
required_objectclass = {
'user': 'posixaccount',
'group': 'ipausergroup',
}[obj_type]
if not api.Object[obj_type].has_objectclass(entry['objectclass'],
required_objectclass):
raise errors.ValidationError(
name=_('IPA object'),
error=_('system IPA objects (e.g. system groups, user '
'private groups) cannot be overridden')
)
# The domain prefix, this will need to be reworked once we
# introduce IPA-IPA trusts
domain = api.env.domain
uuid = entry.single_value['ipaUniqueID']
return "%s%s:%s" % (IPA_ANCHOR_PREFIX, domain, uuid)
except errors.NotFound:
pass
# If not successful, try looking up the object in the trusted domain
try:
if _dcerpc_bindings_installed:
# pylint: disable=used-before-assignment
domain_validator = ipaserver.dcerpc.DomainValidator(api)
# pylint: enable=used-before-assignment
if domain_validator.is_configured():
sid = domain_validator.get_trusted_domain_object_sid(obj,
fallback_to_ldap=fallback_to_ldap)
# We need to verify that the object type is correct
type_correct = verify_trusted_domain_object_type(
domain_validator, obj_type, sid)
if type_correct:
# There is no domain prefix since SID contains information
# about the domain
return SID_ANCHOR_PREFIX + sid
except errors.ValidationError:
# Domain validator raises Validation Error if object name does not
# contain domain part (either NETBIOS\ prefix or @domain.name suffix)
pass
# No acceptable object was found
raise api.Object[obj_type].handle_not_found(obj)
def resolve_anchor_to_object_name(ldap, obj_type, anchor):
"""
Resolves IPA Anchor UUID to the actual common object name (uid for users,
cn for groups).
Takes options:
ldap - the backend
anchor - the anchor, e.g.
':IPA:ipa.example.com:2cb604ea-39a5-11e4-a37e-001a4a22216f'
"""
if anchor.startswith(IPA_ANCHOR_PREFIX):
# Prepare search parameters
accounts_dn = DN(api.env.container_accounts, api.env.basedn)
# Anchor of the form :IPA:<domain>:<uuid>
# Strip the IPA prefix and the domain prefix
uuid = anchor.rpartition(':')[-1].strip()
# Set the object type-specific search attributes
objectclass, name_attr = {
'user': ('posixaccount', 'uid'),
'group': ('ipausergroup', 'cn'),
}[obj_type]
entry = ldap.find_entry_by_attr(attr='ipaUniqueID',
value=uuid,
object_class=objectclass,
attrs_list=[name_attr],
base_dn=accounts_dn)
# Return the name of the object, which is either cn for
# groups or uid for users
return entry.single_value[name_attr]
elif anchor.startswith(SID_ANCHOR_PREFIX):
# Parse the SID out from the anchor
sid = anchor[len(SID_ANCHOR_PREFIX):].strip()
if _dcerpc_bindings_installed:
domain_validator = ipaserver.dcerpc.DomainValidator(api)
if domain_validator.is_configured():
name = domain_validator.get_trusted_domain_object_from_sid(sid)
# We need to verify that the object type is correct
type_correct = verify_trusted_domain_object_type(
domain_validator, obj_type, name)
if type_correct:
return name
else:
# Without the DCERPC bindings the sid is not resolvable, return
# ipaAnchorUUID
_dn = DN(("cn", api.packages[0].idviews.DEFAULT_TRUST_VIEW_NAME),
api.env.container_views + api.env.basedn)
try:
entry = ldap.find_entry_by_attr(attr="ipaanchoruuid",
value=anchor,
object_class="ipaUserOverride",
attrs_list=["ipaoriginaluid"],
base_dn=_dn)
return entry.single_value("ipaoriginaluid")
except (errors.EmptyResult, errors.NotFound):
pass
# No acceptable object was found
raise errors.NotFound(
reason=_("Anchor '%(anchor)s' could not be resolved.")
% dict(anchor=anchor))
def remove_ipaobject_overrides(ldap, api, dn):
"""
Removes all ID overrides for given object. This method is to be
consumed by -del commands of the given objects (users, groups).
"""
entry = ldap.get_entry(dn, attrs_list=['ipaUniqueID'])
object_uuid = entry.single_value['ipaUniqueID']
override_filter = '(ipaanchoruuid=:IPA:{0}:{1})'.format(api.env.domain,
object_uuid)
try:
entries, _truncated = ldap.find_entries(
override_filter,
base_dn=DN(api.env.container_views, api.env.basedn),
paged_search=True
)
except errors.EmptyResult:
pass
else:
# In case we found something, delete it
for entry in entries:
ldap.delete_entry(entry)
# Extended user validator that allows to resolve users from trusted domains
def validate_external_object(ldap, dn, keys, options, value, object_type):
trusted_objects = options.get('trusted_objects', [])
param = api.Object[object_type].primary_key
if object_type == 'group' and value.startswith('%'):
value = value[1:]
o_id = param(value)
try:
param.validate(o_id)
except errors.ValidationError as e:
membertype = object_type
try:
id = resolve_object_to_anchor(ldap, object_type, o_id, False)
if id.startswith(SID_ANCHOR_PREFIX):
if object_type == 'group':
trusted_objects.append('%' + value)
else:
trusted_objects.append(value)
options['trusted_objects'] = trusted_objects
return
except errors.NotFound:
raise errors.ValidationError(name=membertype, error=e.error)
@member_validator(membertype='user')
def validate_external_user(ldap, dn, keys, options, value):
validate_external_object(ldap, dn, keys, options, value, 'user')
@member_validator(membertype='group')
def validate_external_ipasudorunas(ldap, dn, keys, options, value):
validate_external_object(ldap, dn, keys, options, value, 'group')
# This is not registered on purpose, it's a base class for ID overrides
class baseidoverride(LDAPObject):
"""
Base ID override object.
"""
parent_object = 'idview'
container_dn = api.env.container_views
object_class = ['ipaOverrideAnchor', 'top']
default_attributes = [
'description', 'ipaAnchorUUID',
]
takes_params = (
Str('ipaanchoruuid',
cli_name='anchor',
primary_key=True,
label=_('Anchor to override'),
),
Str('description?',
cli_name='desc',
label=_('Description'),
),
)
override_object = None
def get_dn(self, *keys, **options):
# If user passed raw anchor, do not try
# to translate it.
if ANCHOR_REGEX.match(keys[-1]):
anchor = keys[-1]
# Otherwise, translate object into a
# legitimate object anchor.
else:
anchor = resolve_object_to_anchor(
self.backend,
self.override_object,
keys[-1],
fallback_to_ldap=options.get('fallback_to_ldap', False)
)
if all([len(keys[:-1]) == 0,
self.override_object == 'user',
anchor.startswith(SID_ANCHOR_PREFIX)]):
keys = (DEFAULT_TRUST_VIEW_NAME, ) + keys
keys = keys[:-1] + (anchor, )
return super(baseidoverride, self).get_dn(*keys, **options)
def set_anchoruuid_from_dn(self, dn, entry_attrs):
# TODO: Use entry_attrs.single_value once LDAPUpdate supports
# lists in primary key fields (baseldap.LDAPUpdate.execute)
entry_attrs['ipaanchoruuid'] = dn[0].value
def convert_anchor_to_human_readable_form(self, entry_attrs, **options):
if not options.get('raw'):
if 'ipaoriginaluid' in entry_attrs:
originaluid = entry_attrs.single_value['ipaoriginaluid']
entry_attrs.single_value['ipaanchoruuid'] = originaluid
return
anchor = entry_attrs.single_value['ipaanchoruuid']
if anchor:
try:
object_name = resolve_anchor_to_object_name(
self.backend,
self.override_object,
anchor
)
entry_attrs.single_value['ipaanchoruuid'] = object_name
except errors.NotFound:
# If we were unable to resolve the anchor,
# keep it in the raw form
pass
except errors.ValidationError:
# Same as above, ValidationError may be raised when SIDs
# are attempted to be converted, but the domain is no
# longer trusted
pass
def prohibit_ipa_users_in_default_view(self, dn, entry_attrs):
# Check if parent object is Default Trust View, if so, prohibit
# adding overrides for IPA objects
if dn[1].value.lower() == DEFAULT_TRUST_VIEW_NAME:
if dn[0].value.startswith(IPA_ANCHOR_PREFIX):
raise errors.ValidationError(
name=_('ID View'),
error=_('Default Trust View cannot contain IPA users')
)
def filter_for_anchor(self, ldap, filter, options, obj_type):
"""Modify filter to support user and group names
Allow users to pass in an IPA user/group name and resolve it to an
anchor name.
:param ldap: ldap connection
:param filter: pre_callback filter
:param options: option dict
:param obj_type: 'user' or 'group'
:return: modified or same filter
"""
anchor = options.get('ipaanchoruuid', None)
# return original filter if anchor is absent or correct
if anchor is None or ANCHOR_REGEX.match(anchor):
return filter
try:
resolved_anchor = resolve_object_to_anchor(
ldap, obj_type, anchor,
options.get('fallback_to_ldap', False)
)
except (errors.NotFound, errors.ValidationError):
# anchor cannot be resolved, let it pass through
return filter
else:
return ldap.make_filter(
{
'objectClass': self.object_class,
'ipaanchoruuid': resolved_anchor,
},
rules=ldap.MATCH_ALL
)
def get_primary_key_from_dn(self, dn):
return resolve_anchor_to_object_name(self.backend,
self.override_object,
dn[0].value)
class baseidoverride_add(LDAPCreate):
__doc__ = _('Add a new ID override.')
msg_summary = _('Added ID override "%(value)s"')
takes_options = LDAPCreate.takes_options + (fallback_to_ldap_option,)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
self.obj.set_anchoruuid_from_dn(dn, entry_attrs)
self.obj.prohibit_ipa_users_in_default_view(dn, entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_anchor_to_human_readable_form(entry_attrs, **options)
return dn
class baseidoverride_del(LDAPDelete):
__doc__ = _('Delete an ID override.')
msg_summary = _('Deleted ID override "%(value)s"')
takes_options = LDAPDelete.takes_options + (fallback_to_ldap_option,)
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
# Make sure the entry we're deleting has all the objectclasses
# this object requires
try:
entry = ldap.get_entry(dn, ['objectclass'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
# If not, treat it as a failed search
for required_oc in self.obj.object_class:
if not self.obj.has_objectclass(entry['objectclass'], required_oc):
raise self.obj.handle_not_found(*keys)
return dn
class baseidoverride_mod(LDAPUpdate):
__doc__ = _('Modify an ID override.')
msg_summary = _('Modified an ID override "%(value)s"')
takes_options = LDAPUpdate.takes_options + (fallback_to_ldap_option,)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
if 'rename' in options:
raise errors.ValidationError(
name=_('ID override'),
error=_('ID overrides cannot be renamed')
)
self.obj.prohibit_ipa_users_in_default_view(dn, entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_anchor_to_human_readable_form(entry_attrs, **options)
return dn
class baseidoverride_find(LDAPSearch):
__doc__ = _('Search for an ID override.')
msg_summary = ngettext('%(count)d ID override matched',
'%(count)d ID overrides matched', 0)
takes_options = LDAPSearch.takes_options + (fallback_to_ldap_option,)
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry in entries:
self.obj.convert_anchor_to_human_readable_form(entry, **options)
return truncated
class baseidoverride_show(LDAPRetrieve):
__doc__ = _('Display information about an ID override.')
takes_options = LDAPRetrieve.takes_options + (fallback_to_ldap_option,)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_anchor_to_human_readable_form(entry_attrs, **options)
return dn
@register()
class idoverrideuser(baseidoverride):
object_name = _('User ID override')
object_name_plural = _('User ID overrides')
label = _('User ID overrides')
label_singular = _('User ID override')
allow_rename = True
# ID user overrides are bindable because we map SASL GSSAPI
# authentication of trusted users to ID user overrides in the
# default trust view.
bindable = True
permission_filter_objectclasses = ['ipaUserOverride']
managed_permissions = {
'System: Read User ID Overrides': {
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectClass', 'ipaAnchorUUID', 'uidNumber', 'description',
'homeDirectory', 'uid', 'ipaOriginalUid', 'loginShell', 'gecos',
'gidNumber', 'ipaSshPubkey', 'usercertificate', 'memberof'
},
},
}
object_class = baseidoverride.object_class + ['ipaUserOverride']
possible_objectclasses = ['ipasshuser', 'ipaSshGroupOfPubKeys',
'nsmemberof']
default_attributes = baseidoverride.default_attributes + [
'homeDirectory', 'uidNumber', 'uid', 'ipaOriginalUid', 'loginShell',
'ipaSshPubkey', 'gidNumber', 'gecos', 'usercertificate;binary',
'memberofindirect', 'memberof'
]
search_display_attributes = baseidoverride.default_attributes + [
'homeDirectory', 'uidNumber', 'uid', 'ipaOriginalUid', 'loginShell',
'ipaSshPubkey', 'gidNumber', 'gecos',
]
attribute_members = {
'memberof': ['group', 'role'],
'memberofindirect': ['group', 'role'],
}
takes_params = baseidoverride.takes_params + (
Str('uid?',
pattern=PATTERN_GROUPUSER_NAME,
pattern_errmsg=ERRMSG_GROUPUSER_NAME.format('user'),
maxlength=255,
cli_name='login',
label=_('User login'),
normalizer=lambda value: value.lower(),
),
Int('uidnumber?',
cli_name='uid',
label=_('UID'),
doc=_('User ID Number'),
minvalue=1,
),
Str('gecos?',
label=_('GECOS'),
),
Int('gidnumber?',
label=_('GID'),
doc=_('Group ID Number'),
minvalue=1,
),
Str('homedirectory?',
cli_name='homedir',
label=_('Home directory'),
),
Str('loginshell?',
cli_name='shell',
label=_('Login shell'),
),
Str('ipaoriginaluid?',
flags=['no_option', 'no_output']
),
Str('ipasshpubkey*', validate_sshpubkey,
cli_name='sshpubkey',
label=_('SSH public key'),
normalizer=normalize_sshpubkey,
flags=['no_search'],
),
Certificate('usercertificate*',
cli_name='certificate',
label=_('Certificate'),
doc=_('Base-64 encoded user certificate'),
flags=['no_search',],
),
)
override_object = 'user'
def update_original_uid_reference(self, entry_attrs):
anchor = entry_attrs.single_value['ipaanchoruuid']
try:
original_uid = resolve_anchor_to_object_name(self.backend,
self.override_object,
anchor)
entry_attrs['ipaoriginaluid'] = original_uid
except (errors.NotFound, errors.ValidationError):
# Anchor could not be resolved, this means we had to specify the
# object to manipulate using a raw anchor value already, hence
# we have no way to update the original_uid
pass
def convert_usercertificate_pre(self, entry_attrs):
if 'usercertificate' in entry_attrs:
entry_attrs['usercertificate;binary'] = entry_attrs.pop(
'usercertificate')
def convert_usercertificate_post(self, entry_attrs, **options):
if 'usercertificate;binary' in entry_attrs:
entry_attrs['usercertificate'] = entry_attrs.pop(
'usercertificate;binary')
@register()
class idoverridegroup(baseidoverride):
object_name = _('Group ID override')
object_name_plural = _('Group ID overrides')
label = _('Group ID overrides')
label_singular = _('Group ID override')
allow_rename = True
permission_filter_objectclasses = ['ipaGroupOverride']
managed_permissions = {
'System: Read Group ID Overrides': {
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectClass', 'ipaAnchorUUID', 'gidNumber',
'description', 'cn',
},
},
}
object_class = baseidoverride.object_class + ['ipaGroupOverride']
default_attributes = baseidoverride.default_attributes + [
'gidNumber', 'cn',
]
takes_params = baseidoverride.takes_params + (
Str('cn?',
pattern=PATTERN_GROUPUSER_NAME,
pattern_errmsg=ERRMSG_GROUPUSER_NAME.format('group'),
maxlength=255,
cli_name='group_name',
label=_('Group name'),
normalizer=lambda value: value.lower(),
),
Int('gidnumber?',
cli_name='gid',
label=_('GID'),
doc=_('Group ID Number'),
minvalue=1,
),
)
override_object = 'group'
@register()
class idoverrideuser_add_cert(LDAPAddAttributeViaOption):
__doc__ = _('Add one or more certificates to the idoverrideuser entry')
msg_summary = _('Added certificates to idoverrideuser "%(value)s"')
attribute = 'usercertificate'
takes_options = LDAPAddAttributeViaOption.takes_options + (
fallback_to_ldap_option,)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
dn = self.obj.get_dn(*keys, **options)
self.obj.convert_usercertificate_pre(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_usercertificate_post(entry_attrs, **options)
self.obj.convert_anchor_to_human_readable_form(entry_attrs, **options)
return dn
@register()
class idoverrideuser_remove_cert(LDAPRemoveAttributeViaOption):
__doc__ = _('Remove one or more certificates to the idoverrideuser entry')
msg_summary = _('Removed certificates from idoverrideuser "%(value)s"')
attribute = 'usercertificate'
takes_options = LDAPRemoveAttributeViaOption.takes_options + (
fallback_to_ldap_option,)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys,
**options):
dn = self.obj.get_dn(*keys, **options)
self.obj.convert_usercertificate_pre(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj.convert_usercertificate_post(entry_attrs, **options)
self.obj.convert_anchor_to_human_readable_form(entry_attrs, **options)
return dn
@register()
class idoverrideuser_add(baseidoverride_add):
__doc__ = _('Add a new User ID override.')
msg_summary = _('Added User ID override "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
dn = super(idoverrideuser_add, self).pre_callback(ldap, dn,
entry_attrs, attrs_list, *keys, **options)
entry_attrs['objectclass'].append('ipasshuser')
self.obj.convert_usercertificate_pre(entry_attrs)
# Update the ipaOriginalUid
self.obj.update_original_uid_reference(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
dn = super(idoverrideuser_add, self).post_callback(ldap, dn,
entry_attrs, *keys, **options)
convert_sshpubkey_post(entry_attrs)
self.obj.convert_usercertificate_post(entry_attrs, **options)
return dn
@register()
class idoverrideuser_del(baseidoverride_del):
__doc__ = _('Delete an User ID override.')
msg_summary = _('Deleted User ID override "%(value)s"')
@register()
class idoverrideuser_mod(baseidoverride_mod):
__doc__ = _('Modify an User ID override.')
msg_summary = _('Modified an User ID override "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
dn = super(idoverrideuser_mod, self).pre_callback(ldap, dn,
entry_attrs, attrs_list, *keys, **options)
# Update the ipaOriginalUid
self.obj.set_anchoruuid_from_dn(dn, entry_attrs)
self.obj.update_original_uid_reference(entry_attrs)
if 'objectclass' in entry_attrs:
obj_classes = entry_attrs['objectclass']
else:
_entry_attrs = ldap.get_entry(dn, ['objectclass'])
obj_classes = entry_attrs['objectclass'] = _entry_attrs['objectclass']
if 'ipasshpubkey' in entry_attrs and 'ipasshuser' not in obj_classes:
obj_classes.append('ipasshuser')
self.obj.convert_usercertificate_pre(entry_attrs)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
dn = super(idoverrideuser_mod, self).post_callback(ldap, dn,
entry_attrs, *keys, **options)
convert_sshpubkey_post(entry_attrs)
self.obj.convert_usercertificate_post(entry_attrs, **options)
return dn
@register()
class idoverrideuser_find(baseidoverride_find):
__doc__ = _('Search for an User ID override.')
msg_summary = ngettext('%(count)d User ID override matched',
'%(count)d User ID overrides matched', 0)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args,
**options):
result = super(idoverrideuser_find, self).pre_callback(
ldap, filter, attrs_list, base_dn, scope, *args, **options
)
filter, base_dn, scope = result
filter = self.obj.filter_for_anchor(ldap, filter, options, 'user')
return filter, base_dn, scope
def post_callback(self, ldap, entries, truncated, *args, **options):
truncated = super(idoverrideuser_find, self).post_callback(
ldap, entries, truncated, *args, **options)
for entry in entries:
convert_sshpubkey_post(entry)
self.obj.convert_usercertificate_post(entry, **options)
return truncated
@register()
class idoverrideuser_show(baseidoverride_show):
__doc__ = _('Display information about an User ID override.')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
dn = super(idoverrideuser_show, self).post_callback(ldap, dn,
entry_attrs, *keys, **options)
convert_sshpubkey_post(entry_attrs)
self.obj.convert_usercertificate_post(entry_attrs, **options)
return dn
@register()
class idoverridegroup_add(baseidoverride_add):
__doc__ = _('Add a new Group ID override.')
msg_summary = _('Added Group ID override "%(value)s"')
@register()
class idoverridegroup_del(baseidoverride_del):
__doc__ = _('Delete an Group ID override.')
msg_summary = _('Deleted Group ID override "%(value)s"')
@register()
class idoverridegroup_mod(baseidoverride_mod):
__doc__ = _('Modify an Group ID override.')
msg_summary = _('Modified an Group ID override "%(value)s"')
@register()
class idoverridegroup_find(baseidoverride_find):
__doc__ = _('Search for an Group ID override.')
msg_summary = ngettext('%(count)d Group ID override matched',
'%(count)d Group ID overrides matched', 0)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args,
**options):
result = super(idoverridegroup_find, self).pre_callback(
ldap, filter, attrs_list, base_dn, scope, *args, **options
)
filter, base_dn, scope = result
filter = self.obj.filter_for_anchor(ldap, filter, options, 'group')
return filter, base_dn, scope
@register()
class idoverridegroup_show(baseidoverride_show):
__doc__ = _('Display information about an Group ID override.')
| 47,673
|
Python
|
.py
| 1,085
| 33.051613
| 82
| 0.589419
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,881
|
ldap2.py
|
freeipa_freeipa/ipaserver/plugins/ldap2.py
|
# Authors:
# Pavel Zuna <pzuna@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/>.
"""
Backend plugin for LDAP.
"""
# Entries are represented as (dn, entry_attrs), where entry_attrs is a dict
# mapping attribute names to values. Values can be a single value or list/tuple
# of virtually any type. Each method passing these values to the python-ldap
# binding encodes them into the appropriate representation. This applies to
# everything except the CrudBackend methods, where dn is part of the entry dict.
from __future__ import absolute_import
import logging
import os
import ldap as _ldap
from ipalib import krb_utils
from ipaplatform.paths import paths
from ipapython.dn import DN
from ipapython.ipaldap import (LDAPCache, AUTOBIND_AUTO, AUTOBIND_ENABLED,
AUTOBIND_DISABLED)
from ipalib import Registry, errors, _
from ipalib.crud import CrudBackend
from ipalib.request import context
logger = logging.getLogger(__name__)
register = Registry()
_missing = object()
@register()
class ldap2(CrudBackend, LDAPCache):
"""
LDAP Backend Take 2.
"""
def __init__(self, api):
force_schema_updates = api.env.context in ('installer', 'updates')
CrudBackend.__init__(self, api)
LDAPCache.__init__(
self, None,
force_schema_updates=force_schema_updates,
enable_cache=api.env.ldap_cache and not force_schema_updates,
cache_size=api.env.ldap_cache_size,
debug_cache=api.env.ldap_cache_debug,
)
self._time_limit = float(LDAPCache.time_limit)
self._size_limit = int(LDAPCache.size_limit)
@property
def ldap_uri(self):
return self.api.env.ldap_uri
@property
def time_limit(self):
if self._time_limit is None:
return float(self.get_ipa_config().single_value.get(
'ipasearchtimelimit', 2))
return self._time_limit
@time_limit.setter
def time_limit(self, val):
if val is not None:
val = float(val)
object.__setattr__(self, '_time_limit', val)
@time_limit.deleter
def time_limit(self):
object.__setattr__(self, '_time_limit', int(LDAPCache.size_limit))
@property
def size_limit(self):
if self._size_limit is None:
return int(self.get_ipa_config().single_value.get(
'ipasearchrecordslimit', 0))
return self._size_limit
@size_limit.setter
def size_limit(self, val):
if val is not None:
val = int(val)
object.__setattr__(self, '_size_limit', val)
@size_limit.deleter
def size_limit(self):
object.__setattr__(self, '_size_limit', float(LDAPCache.time_limit))
def _connect(self):
# Connectible.conn is a proxy to thread-local storage;
# do not set it
pass
def close(self):
if self.isconnected():
self.disconnect()
def __str__(self):
return self.ldap_uri
def create_connection(
self, ccache=None, bind_dn=None, bind_pw='', cacert=None,
autobind=AUTOBIND_AUTO, serverctrls=None, clientctrls=None,
time_limit=_missing, size_limit=_missing):
"""
Connect to LDAP server.
Keyword arguments:
ldapuri -- the LDAP server to connect to
ccache -- Kerberos ccache name
bind_dn -- dn used to bind to the server
bind_pw -- password used to bind to the server
debug_level -- LDAP debug level option
cacert -- TLS CA certificate filename
autobind - autobind as the current user
time_limit, size_limit -- maximum time and size limit for LDAP
possible options:
- value - sets the given value
- None - reads value from ipaconfig
- _missing - keeps previously configured settings
(unlimited set by default in constructor)
Extends backend.Connectible.create_connection.
"""
if bind_dn is None:
bind_dn = DN(('cn', 'directory manager'))
assert isinstance(bind_dn, DN)
if cacert is None:
cacert = paths.IPA_CA_CRT
if time_limit is not _missing:
object.__setattr__(self, 'time_limit', time_limit)
if size_limit is not _missing:
object.__setattr__(self, 'size_limit', size_limit)
client = LDAPCache(
self.ldap_uri,
force_schema_updates=self._force_schema_updates,
enable_cache=self._enable_cache,
cacert=cacert)
conn = client._conn
with client.error_handler():
minssf = conn.get_option(_ldap.OPT_X_SASL_SSF_MIN)
maxssf = conn.get_option(_ldap.OPT_X_SASL_SSF_MAX)
# Always connect with at least an SSF of 56, confidentiality
# This also protects us from a broken ldap.conf
if minssf < 56:
minssf = 56
conn.set_option(_ldap.OPT_X_SASL_SSF_MIN, minssf)
if maxssf < minssf:
conn.set_option(_ldap.OPT_X_SASL_SSF_MAX, minssf)
ldapi = self.ldap_uri.startswith('ldapi://')
if bind_pw:
client.simple_bind(bind_dn, bind_pw,
server_controls=serverctrls,
client_controls=clientctrls)
elif autobind != AUTOBIND_DISABLED and os.getegid() == 0 and ldapi:
try:
client.external_bind(server_controls=serverctrls,
client_controls=clientctrls)
except errors.NotFound:
if autobind == AUTOBIND_ENABLED:
# autobind was required and failed, raise
# exception that it failed
raise
else:
if ldapi:
with client.error_handler():
conn.set_option(_ldap.OPT_HOST_NAME, self.api.env.host)
if ccache is None:
os.environ.pop('KRB5CCNAME', None)
else:
os.environ['KRB5CCNAME'] = ccache
principal = krb_utils.get_principal(ccache_name=ccache)
client.gssapi_bind(server_controls=serverctrls,
client_controls=clientctrls)
setattr(context, 'principal', principal)
return conn
def destroy_connection(self):
"""Disconnect from LDAP server."""
try:
if self.conn is not None:
self.unbind()
except errors.PublicError:
# ignore when trying to unbind multiple times
pass
object.__delattr__(self, 'time_limit')
object.__delattr__(self, 'size_limit')
self.clear_cache()
def get_ipa_config(self, attrs_list=None):
"""Returns the IPA configuration entry (dn, entry_attrs)."""
dn = self.api.Object.config.get_dn()
assert isinstance(dn, DN)
try:
config_entry = getattr(context, 'config_entry')
if config_entry.conn.conn is self.conn:
return config_entry
except AttributeError:
# Not in our context yet
pass
try:
# use find_entries here lest we hit an infinite recursion when
# ldap2.get_entries tries to determine default time/size limits
(entries, truncated) = self.find_entries(
None, attrs_list, base_dn=dn, scope=self.SCOPE_BASE,
time_limit=2, size_limit=10
)
self.handle_truncated_result(truncated)
config_entry = entries[0]
except errors.NotFound:
config_entry = self.make_entry(dn)
context.config_entry = config_entry
return config_entry
def has_upg(self):
"""Returns True/False whether User-Private Groups are enabled.
This is determined based on whether the UPG Definition's originfilter
contains "(objectclass=disable)".
If the UPG Definition or its originfilter is not readable,
an ACI error is raised.
"""
try:
return context.has_upg
except AttributeError:
pass
upg_dn = DN(('cn', 'UPG Definition'), ('cn', 'Definitions'), ('cn', 'Managed Entries'),
('cn', 'etc'), self.api.env.basedn)
try:
with self.error_handler():
upg_entries = self.conn.search_s(str(upg_dn), _ldap.SCOPE_BASE,
attrlist=['*'])
upg_entries = self._convert_result(upg_entries)
except errors.NotFound:
upg_entries = None
if not upg_entries or 'originfilter' not in upg_entries[0]:
raise errors.ACIError(info=_(
'Could not read UPG Definition originfilter. '
'Check your permissions.'))
org_filter = upg_entries[0].single_value['originfilter']
has_upg = '(objectclass=disable)' not in org_filter
context.has_upg = has_upg
return has_upg
def get_effective_rights(self, dn, attrs_list):
"""Returns the rights the currently bound user has for the given DN.
Returns 2 attributes, the attributeLevelRights for the given list of
attributes and the entryLevelRights for the entry itself.
"""
assert isinstance(dn, DN)
return self.get_entry(dn, attrs_list, get_effective_rights=True)
def can_write(self, dn, attr):
"""Returns True/False if the currently bound user has write permissions
on the attribute. This only operates on a single attribute at a time.
"""
assert isinstance(dn, DN)
attrs = self.get_effective_rights(dn, [attr])
if 'attributelevelrights' in attrs:
attr_rights = attrs.get('attributelevelrights')[0]
(attr, rights) = attr_rights.split(':')
if 'w' in rights:
return True
return False
def can_read(self, dn, attr):
"""Returns True/False if the currently bound user has read permissions
on the attribute. This only operates on a single attribute at a time.
"""
assert isinstance(dn, DN)
attrs = self.get_effective_rights(dn, [attr])
if 'attributelevelrights' in attrs:
attr_rights = attrs.get('attributelevelrights')[0]
(attr, rights) = attr_rights.split(':')
if 'r' in rights:
return True
return False
#
# Entry-level effective rights
#
# a - Add
# d - Delete
# n - Rename the DN
# v - View the entry
#
def can_delete(self, dn):
"""Returns True/False if the currently bound user has delete permissions
on the entry.
"""
assert isinstance(dn, DN)
attrs = self.get_effective_rights(dn, ["*"])
if 'entrylevelrights' in attrs:
entry_rights = attrs['entrylevelrights'][0]
if 'd' in entry_rights:
return True
return False
def can_add(self, parent_dn, objectclass):
"""
Returns True/False if the currently bound user has
permission to add an entry with the given objectclass
immediately below the entry with the given DN.
For example, to check if an entry with objectclass=ipaca
can be added under cn=cas,cn=ca,{basedn}, you should call
``can_add(DN('cn=cas,...'), 'ipaca')``.
"""
assert isinstance(parent_dn, DN)
# the rules for how to request the template entry, and
# the expectations about how 389 constructs the template
# entry, are described here:
#
# https://pagure.io/389-ds-base/issue/49278#comment-480856
#
try:
entry = self.get_entries(
parent_dn,
_ldap.SCOPE_ONELEVEL,
# rdn value of template entry is: template_<objcls>_objectclass
'(cn=template_{}_objectclass)'.format(objectclass),
# request tempalate entry with given objectclass
['cn@{}'.format(objectclass)],
get_effective_rights=True,
)[0]
return 'a' in entry['entrylevelrights'][0]
except errors.NotFound:
return False
def modify_password(self, dn, new_pass, old_pass='', otp='', skip_bind=False):
"""Set user password."""
assert isinstance(dn, DN)
# The python-ldap passwd command doesn't verify the old password
# so we'll do a simple bind to validate it.
if not skip_bind and old_pass != '':
pw = old_pass
if (otp):
pw = old_pass+otp
with LDAPCache(self.ldap_uri, force_schema_updates=False) as conn:
conn.simple_bind(dn, pw)
conn.unbind()
with self.error_handler():
old_pass = self.encode(old_pass)
new_pass = self.encode(new_pass)
self.conn.passwd_s(str(dn), old_pass, new_pass)
def add_entry_to_group(self, dn, group_dn, member_attr='member', allow_same=False):
"""
Add entry designaed by dn to group group_dn in the member attribute
member_attr.
Adding a group as a member of itself is not allowed unless allow_same
is True.
"""
assert isinstance(dn, DN)
assert isinstance(group_dn, DN)
logger.debug(
"add_entry_to_group: dn=%s group_dn=%s member_attr=%s",
dn, group_dn, member_attr)
# check if the entry exists
entry = self.get_entry(dn, [''])
dn = entry.dn
# check if we're not trying to add group into itself
if dn == group_dn and not allow_same:
raise errors.SameGroupError()
# add dn to group entry's `member_attr` attribute
modlist = [(_ldap.MOD_ADD, member_attr, [dn])]
# update group entry
try:
with self.error_handler():
modlist = [(a, b, self.encode(c))
for a, b, c in modlist]
self.modify_s(str(group_dn), modlist)
except errors.DuplicateEntry:
# TYPE_OR_VALUE_EXISTS
raise errors.AlreadyGroupMember()
def remove_entry_from_group(self, dn, group_dn, member_attr='member'):
"""Remove entry from group."""
assert isinstance(dn, DN)
assert isinstance(group_dn, DN)
logger.debug(
"remove_entry_from_group: dn=%s group_dn=%s member_attr=%s",
dn, group_dn, member_attr)
# remove dn from group entry's `member_attr` attribute
modlist = [(_ldap.MOD_DELETE, member_attr, [dn])]
# update group entry
try:
with self.error_handler():
modlist = [(a, b, self.encode(c))
for a, b, c in modlist]
self.modify_s(str(group_dn), modlist)
except errors.MidairCollision:
raise errors.NotGroupMember()
def set_entry_active(self, dn, active):
"""Mark entry active/inactive."""
assert isinstance(dn, DN)
assert isinstance(active, bool)
# get the entry in question
entry_attrs = self.get_entry(dn, ['nsaccountlock'])
# check nsAccountLock attribute
account_lock_attr = entry_attrs.get('nsaccountlock', ['false'])
account_lock_attr = account_lock_attr[0].lower()
if active:
if account_lock_attr == 'false':
raise errors.AlreadyActive()
else:
if account_lock_attr == 'true':
raise errors.AlreadyInactive()
# LDAP expects string instead of Bool but it also requires it to be TRUE or FALSE,
# not True or False as Python stringification does. Thus, we uppercase it.
account_lock_attr = str(not active).upper()
entry_attrs['nsaccountlock'] = account_lock_attr
self.update_entry(entry_attrs)
def activate_entry(self, dn):
"""Mark entry active."""
assert isinstance(dn, DN)
self.set_entry_active(dn, True)
def deactivate_entry(self, dn):
"""Mark entry inactive."""
assert isinstance(dn, DN)
self.set_entry_active(dn, False)
def remove_principal_key(self, dn):
"""Remove a kerberos principal key."""
assert isinstance(dn, DN)
# We need to do this directly using the LDAP library because we
# don't have read access to krbprincipalkey so we need to delete
# it in the blind.
mod = [(_ldap.MOD_REPLACE, 'krbprincipalkey', None),
(_ldap.MOD_REPLACE, 'krblastpwdchange', None)]
with self.error_handler():
self.modify_s(str(dn), mod)
# CrudBackend methods
def _get_normalized_entry_for_crud(self, dn, attrs_list=None):
assert isinstance(dn, DN)
entry_attrs = self.get_entry(dn, attrs_list)
return entry_attrs
def create(self, **kw):
"""
Create a new entry and return it as one dict (DN included).
Extends CrudBackend.create.
"""
assert 'dn' in kw
dn = kw['dn']
assert isinstance(dn, DN)
del kw['dn']
self.add_entry(self.make_entry(dn, kw))
return self._get_normalized_entry_for_crud(dn)
def retrieve(self, primary_key, attributes):
"""
Get entry by primary_key (DN) as one dict (DN included).
Extends CrudBackend.retrieve.
"""
return self._get_normalized_entry_for_crud(primary_key, attributes)
def update(self, primary_key, **kw):
"""
Update entry's attributes and return it as one dict (DN included).
Extends CrudBackend.update.
"""
self.update_entry(self.make_entry(primary_key, kw))
return self._get_normalized_entry_for_crud(primary_key)
def delete(self, primary_key):
"""
Delete entry by primary_key (DN).
Extends CrudBackend.delete.
"""
self.delete_entry(primary_key)
def search(self, **kw):
"""
Return a list of entries (each entry is one dict, DN included) matching
the specified criteria.
Keyword arguments:
filter -- search filter (default: '')
attrs_list -- list of attributes to return, all if None (default None)
base_dn -- dn of the entry at which to start the search (default '')
scope -- search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE)
Extends CrudBackend.search.
"""
# get keyword arguments
filter = kw.pop('filter', None)
attrs_list = kw.pop('attrs_list', None)
base_dn = kw.pop('base_dn', DN())
assert isinstance(base_dn, DN)
scope = kw.pop('scope', self.SCOPE_SUBTREE)
# generate filter
filter_tmp = self.make_filter(kw)
if filter:
filter = self.combine_filters((filter, filter_tmp), self.MATCH_ALL)
else:
filter = filter_tmp
if not filter:
filter = '(objectClass=*)'
# find entries and normalize the output for CRUD
output = []
(entries, truncated) = self.find_entries(
filter, attrs_list, base_dn, scope
)
for entry_attrs in entries:
output.append(entry_attrs)
if truncated:
return (-1, output)
return (len(output), output)
| 20,358
|
Python
|
.py
| 485
| 31.806186
| 95
| 0.599382
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,882
|
topology.py
|
freeipa_freeipa/ipaserver/plugins/topology.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import six
from ipalib import api, errors
from ipalib import Int, Str, StrEnum, Flag, DNParam
from ipalib.plugable import Registry
from .baseldap import (
LDAPObject, LDAPSearch, LDAPCreate, LDAPDelete, LDAPUpdate, LDAPQuery,
LDAPRetrieve)
from ipalib import _, ngettext
from ipalib import output
from ipalib.constants import MIN_DOMAIN_LEVEL, DOMAIN_LEVEL_1
from ipaserver.topology import (
create_topology_graph, get_topology_connection_errors,
map_masters_to_suffixes)
from ipapython.dn import DN
if six.PY3:
unicode = str
__doc__ = _("""
Topology
Management of a replication topology at domain level 1.
""") + _("""
IPA server's data is stored in LDAP server in two suffixes:
* domain suffix, e.g., 'dc=example,dc=com', contains all domain related data
* ca suffix, 'o=ipaca', is present only on server with CA installed. It
contains data for Certificate Server component
""") + _("""
Data stored on IPA servers is replicated to other IPA servers. The way it is
replicated is defined by replication agreements. Replication agreements needs
to be set for both suffixes separately. On domain level 0 they are managed
using ipa-replica-manage and ipa-csreplica-manage tools. With domain level 1
they are managed centrally using `ipa topology*` commands.
""") + _("""
Agreements are represented by topology segments. By default topology segment
represents 2 replication agreements - one for each direction, e.g., A to B and
B to A. Creation of unidirectional segments is not allowed.
""") + _("""
To verify that no server is disconnected in the topology of the given suffix,
use:
ipa topologysuffix-verify $suffix
""") + _("""
Examples:
Find all IPA servers:
ipa server-find
""") + _("""
Find all suffixes:
ipa topologysuffix-find
""") + _("""
Add topology segment to 'domain' suffix:
ipa topologysegment-add domain --left IPA_SERVER_A --right IPA_SERVER_B
""") + _("""
Add topology segment to 'ca' suffix:
ipa topologysegment-add ca --left IPA_SERVER_A --right IPA_SERVER_B
""") + _("""
List all topology segments in 'domain' suffix:
ipa topologysegment-find domain
""") + _("""
List all topology segments in 'ca' suffix:
ipa topologysegment-find ca
""") + _("""
Delete topology segment in 'domain' suffix:
ipa topologysegment-del domain segment_name
""") + _("""
Delete topology segment in 'ca' suffix:
ipa topologysegment-del ca segment_name
""") + _("""
Verify topology of 'domain' suffix:
ipa topologysuffix-verify domain
""") + _("""
Verify topology of 'ca' suffix:
ipa topologysuffix-verify ca
""")
register = Registry()
def validate_domain_level(api):
try:
current = int(api.Command.domainlevel_get()['result'])
except errors.NotFound:
current = MIN_DOMAIN_LEVEL
if current < DOMAIN_LEVEL_1:
raise errors.InvalidDomainLevelError(
reason=_('Topology management requires minimum domain level {0} '
).format(DOMAIN_LEVEL_1)
)
@register()
class topologysegment(LDAPObject):
"""
Topology segment.
"""
parent_object = 'topologysuffix'
container_dn = api.env.container_topology
object_name = _('segment')
object_name_plural = _('segments')
object_class = ['iparepltoposegment']
permission_filter_objectclasses = ['iparepltoposegment', 'iparepltopoconf']
default_attributes = [
'cn',
'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
'ipaReplTopoSegmentLeftNode', 'nsds5replicastripattrs',
'nsds5replicatedattributelist', 'nsds5replicatedattributelisttotal',
'nsds5replicatimeout', 'nsds5replicaenabled'
]
search_display_attributes = [
'cn', 'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
'ipaReplTopoSegmentLeftNode'
]
managed_permissions = {
'System: Read Topology Segments': {
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'cn', 'objectclass',
'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
'ipaReplTopoSegmentLeftNode', 'ipaReplTopoConfRoot',
'ipaReplTopoSegmentStatus','nsds5replicastripattrs',
'nsds5replicatedattributelist',
'nsds5replicatedattributelisttotal',
},
'default_privileges': {'Replication Administrators'},
},
'System: Add Topology Segments': {
'ipapermright': {'add'},
'default_privileges': {'Replication Administrators'},
},
'System: Remove Topology Segments': {
'ipapermright': {'delete'},
'default_privileges': {'Replication Administrators'},
},
'System: Modify Topology Segments': {
'ipapermright': {'write'},
'ipapermdefaultattr': {
'ipaReplTopoSegmentdirection', 'ipaReplTopoSegmentrightNode',
'ipaReplTopoSegmentLeftNode', 'nsds5replicastripattrs',
'nsds5replicatedattributelist',
'nsds5replicatedattributelisttotal',
},
'default_privileges': {'Replication Administrators'},
},
}
label = _('Topology Segments')
label_singular = _('Topology Segment')
takes_params = (
Str(
'cn',
maxlength=255,
cli_name='name',
primary_key=True,
label=_('Segment name'),
default_from=lambda iparepltoposegmentleftnode, iparepltoposegmentrightnode:
'%s-to-%s' % (iparepltoposegmentleftnode, iparepltoposegmentrightnode),
normalizer=lambda value: value.lower(),
doc=_('Arbitrary string identifying the segment'),
),
Str(
'iparepltoposegmentleftnode',
pattern='^[a-zA-Z0-9.][a-zA-Z0-9.-]*[a-zA-Z0-9.$-]?$',
pattern_errmsg='may only include letters, numbers, -, . and $',
maxlength=255,
cli_name='leftnode',
label=_('Left node'),
normalizer=lambda value: value.lower(),
doc=_('Left replication node - an IPA server'),
flags={'no_update'},
),
Str(
'iparepltoposegmentrightnode',
pattern='^[a-zA-Z0-9.][a-zA-Z0-9.-]*[a-zA-Z0-9.$-]?$',
pattern_errmsg='may only include letters, numbers, -, . and $',
maxlength=255,
cli_name='rightnode',
label=_('Right node'),
normalizer=lambda value: value.lower(),
doc=_('Right replication node - an IPA server'),
flags={'no_update'},
),
StrEnum(
'iparepltoposegmentdirection',
cli_name='direction',
label=_('Connectivity'),
values=(u'both', u'left-right', u'right-left'),
default=u'both',
autofill=True,
doc=_('Direction of replication between left and right replication '
'node'),
flags={'no_option', 'no_update'},
),
Str(
'nsds5replicastripattrs?',
cli_name='stripattrs',
label=_('Attributes to strip'),
normalizer=lambda value: value.lower(),
doc=_('A space separated list of attributes which are removed from '
'replication updates.')
),
Str(
'nsds5replicatedattributelist?',
cli_name='replattrs',
label='Attributes to replicate',
doc=_('Attributes that are not replicated to a consumer server '
'during a fractional update. E.g., `(objectclass=*) '
'$ EXCLUDE accountlockout memberof'),
),
Str(
'nsds5replicatedattributelisttotal?',
cli_name='replattrstotal',
label=_('Attributes for total update'),
doc=_('Attributes that are not replicated to a consumer server '
'during a total update. E.g. (objectclass=*) $ EXCLUDE '
'accountlockout'),
),
Int(
'nsds5replicatimeout?',
cli_name='timeout',
label=_('Session timeout'),
minvalue=0,
doc=_('Number of seconds outbound LDAP operations waits for a '
'response from the remote replica before timing out and '
'failing'),
),
StrEnum(
'nsds5replicaenabled?',
cli_name='enabled',
label=_('Replication agreement enabled'),
doc=_('Whether a replication agreement is active, meaning whether '
'replication is occurring per that agreement'),
values=(u'on', u'off'),
flags={'no_option'},
),
)
def validate_nodes(self, ldap, dn, entry_attrs, suffix):
leftnode = entry_attrs.get('iparepltoposegmentleftnode')
rightnode = entry_attrs.get('iparepltoposegmentrightnode')
if not leftnode and not rightnode:
return # nothing to check
# check if nodes are IPA servers
masters = self.api.Command.server_find(
'', sizelimit=0, no_members=False)['result']
m_hostnames = [master['cn'][0].lower() for master in masters]
if leftnode and leftnode not in m_hostnames:
raise errors.ValidationError(
name='leftnode',
error=_('left node is not a topology node: %(leftnode)s') %
dict(leftnode=leftnode)
)
if rightnode and rightnode not in m_hostnames:
raise errors.ValidationError(
name='rightnode',
error=_('right node is not a topology node: %(rightnode)s') %
dict(rightnode=rightnode)
)
# prevent creation of reflexive relation
key = 'leftnode'
if not leftnode or not rightnode: # get missing end
_entry_attrs = ldap.get_entry(dn, ['*'])
if not leftnode:
key = 'rightnode'
leftnode = _entry_attrs['iparepltoposegmentleftnode'][0]
else:
rightnode = _entry_attrs['iparepltoposegmentrightnode'][0]
if leftnode == rightnode:
raise errors.ValidationError(
name=key,
error=_('left node and right node must not be the same')
)
# don't allow segment between nodes where both don't have the suffix
masters_to_suffix = map_masters_to_suffixes(masters)
suffix_masters = masters_to_suffix.get(suffix, [])
suffix_m_hostnames = [m['cn'][0].lower() for m in suffix_masters]
if leftnode not in suffix_m_hostnames:
raise errors.ValidationError(
name='leftnode',
error=_("left node ({host}) does not support "
"suffix '{suff}'"
).format(host=leftnode, suff=suffix)
)
if rightnode not in suffix_m_hostnames:
raise errors.ValidationError(
name='rightnode',
error=_("right node ({host}) does not support "
"suffix '{suff}'"
).format(host=rightnode, suff=suffix)
)
@register()
class topologysegment_find(LDAPSearch):
__doc__ = _('Search for topology segments.')
msg_summary = ngettext(
'%(count)d segment matched',
'%(count)d segments matched', 0
)
@register()
class topologysegment_add(LDAPCreate):
__doc__ = _('Add a new segment.')
msg_summary = _('Added segment "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
self.obj.validate_nodes(ldap, dn, entry_attrs, keys[0])
return dn
@register()
class topologysegment_del(LDAPDelete):
__doc__ = _('Delete a segment.')
msg_summary = _('Deleted segment "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
return dn
@register()
class topologysegment_mod(LDAPUpdate):
__doc__ = _('Modify a segment.')
msg_summary = _('Modified segment "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
self.obj.validate_nodes(ldap, dn, entry_attrs, keys[0])
return dn
@register()
class topologysegment_reinitialize(LDAPQuery):
__doc__ = _('Request a full re-initialization of the node '
'retrieving data from the other node.')
has_output = output.standard_value
msg_summary = _('%(value)s')
takes_options = (
Flag(
'left?',
doc=_('Initialize left node'),
default=False,
),
Flag(
'right?',
doc=_('Initialize right node'),
default=False,
),
Flag(
'stop?',
doc=_('Stop already started refresh of chosen node(s)'),
default=False,
),
)
def execute(self, *keys, **options):
dn = self.obj.get_dn(*keys, **options)
validate_domain_level(self.api)
entry = self.obj.backend.get_entry(
dn, [
'nsds5beginreplicarefresh;left',
'nsds5beginreplicarefresh;right'
])
left = options.get('left')
right = options.get('right')
stop = options.get('stop')
if not left and not right:
raise errors.OptionError(
_('left or right node has to be specified')
)
if left and right:
raise errors.OptionError(
_('only one node can be specified')
)
action = u'start'
msg = _('Replication refresh for segment: "%(pkey)s" requested.')
if stop:
action = u'stop'
msg = _('Stopping of replication refresh for segment: "'
'%(pkey)s" requested.')
# left and right are swapped because internally it's a push not
# pull operation
if right:
entry['nsds5beginreplicarefresh;left'] = [action]
if left:
entry['nsds5beginreplicarefresh;right'] = [action]
self.obj.backend.update_entry(entry)
msg = msg % {'pkey': keys[-1]}
return dict(
result=True,
value=msg,
)
@register()
class topologysegment_show(LDAPRetrieve):
__doc__ = _('Display a segment.')
@register()
class topologysuffix(LDAPObject):
"""
Suffix managed by the topology plugin.
"""
container_dn = api.env.container_topology
object_name = _('suffix')
object_name_plural = _('suffixes')
object_class = ['iparepltopoconf']
default_attributes = ['cn', 'ipaReplTopoConfRoot']
search_display_attributes = ['cn', 'ipaReplTopoConfRoot']
label = _('Topology suffixes')
label_singular = _('Topology suffix')
takes_params = (
Str(
'cn',
cli_name='name',
primary_key=True,
label=_('Suffix name'),
),
DNParam(
'iparepltopoconfroot',
cli_name='suffix_dn',
label=_('Managed LDAP suffix DN'),
),
)
@register()
class topologysuffix_find(LDAPSearch):
__doc__ = _('Search for topology suffixes.')
msg_summary = ngettext(
'%(count)d topology suffix matched',
'%(count)d topology suffixes matched', 0
)
@register()
class topologysuffix_del(LDAPDelete):
__doc__ = _('Delete a topology suffix.')
NO_CLI = True
msg_summary = _('Deleted topology suffix "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
return dn
@register()
class topologysuffix_add(LDAPCreate):
__doc__ = _('Add a new topology suffix to be managed.')
NO_CLI = True
msg_summary = _('Added topology suffix "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
return dn
@register()
class topologysuffix_mod(LDAPUpdate):
__doc__ = _('Modify a topology suffix.')
NO_CLI = True
msg_summary = _('Modified topology suffix "%(value)s"')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
validate_domain_level(self.api)
return dn
@register()
class topologysuffix_show(LDAPRetrieve):
__doc__ = _('Show managed suffix.')
@register()
class topologysuffix_verify(LDAPQuery):
__doc__ = _('''
Verify replication topology for suffix.
Checks done:
1. check if a topology is not disconnected. In other words if there are
replication paths between all servers.
2. check if servers don't have more than the recommended number of
replication agreements
''')
def execute(self, *keys, **options):
validate_domain_level(self.api)
masters = self.api.Command.server_find(
'', sizelimit=0, no_members=False)['result']
masters = map_masters_to_suffixes(masters).get(keys[0], [])
segments = self.api.Command.topologysegment_find(
keys[0], sizelimit=0)['result']
graph = create_topology_graph(masters, segments)
master_cns = [m['cn'][0] for m in masters]
master_cns.sort()
# check if each master can contact others
connect_errors = get_topology_connection_errors(graph)
# check if suggested maximum number of agreements per replica
max_agmts_errors = []
for m in master_cns:
# chosen direction doesn't matter much given that 'both' is the
# only allowed direction
suppliers = graph.get_tails(m)
if len(suppliers) > self.api.env.recommended_max_agmts:
max_agmts_errors.append((m, suppliers))
return dict(
result={
'in_order': not connect_errors and not max_agmts_errors,
'connect_errors': connect_errors,
'max_agmts_errors': max_agmts_errors,
'max_agmts': self.api.env.recommended_max_agmts
},
)
| 18,631
|
Python
|
.py
| 478
| 30.006276
| 96
| 0.603089
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,883
|
session.py
|
freeipa_freeipa/ipaserver/plugins/session.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import logging
from ipalib import Command
from ipalib.request import context
from ipalib.plugable import Registry
from ipalib.text import _
__doc__ = _("""
Session Support for IPA
""")
logger = logging.getLogger(__name__)
register = Registry()
@register()
class session_logout(Command):
__doc__ = _('RPC command used to log the current user out of their'
' session.')
NO_CLI = True
def execute(self, *args, **options):
ccache_name = getattr(context, 'ccache_name', None)
if ccache_name is None:
logger.debug('session logout command: no ccache_name found')
else:
delattr(context, 'ccache_name')
setattr(context, 'logout_cookie', 'MagBearerToken=')
return dict(result=None)
| 845
|
Python
|
.py
| 26
| 27.576923
| 72
| 0.677379
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,884
|
subid.py
|
freeipa_freeipa/ipaserver/plugins/subid.py
|
#
# Copyright (C) 2021 FreeIPA Contributors see COPYING for license
#
import uuid
from ipalib import api
from ipalib import constants
from ipalib import errors
from ipalib import output
from ipalib.plugable import Registry
from ipalib.parameters import Int, Str
from ipalib.request import context
from ipalib.text import _, ngettext
from ipapython.dn import DN
from .baseldap import (
LDAPObject,
LDAPCreate,
LDAPDelete,
LDAPUpdate,
LDAPSearch,
LDAPRetrieve,
LDAPQuery,
DNA_MAGIC,
)
__doc__ = _(
"""
Subordinate ids
Manage subordinate user and group ids for users
EXAMPLES:
Auto-assign a subordinate id range to current user
ipa subid-generate
Auto-assign a subordinate id range to user alice:
ipa subid-generate --owner=alice
Find subordinate ids for user alice:
ipa subid-find --owner=alice
Match entry by any subordinate uid in range:
ipa subid-match --subuid=2147483649
"""
)
register = Registry()
@register()
class subid(LDAPObject):
"""Subordinate id object."""
container_dn = api.env.container_subids
object_name = _("Subordinate id")
object_name_plural = _("Subordinate ids")
label = _("Subordinate ids")
label_singular = _("Subordinate id")
object_class = ["ipasubordinateidentry"]
possible_objectclasses = [
"ipasubordinategid",
"ipasubordinateuid",
"ipasubordinateid",
]
default_attributes = [
"ipauniqueid",
"ipaowner",
"ipasubuidnumber",
"ipasubuidcount",
"ipasubgidnumber",
"ipasubgidcount",
]
allow_rename = False
permission_filter_objectclasses_string = (
"(objectclass=ipasubordinateidentry)"
)
managed_permissions = {
# all authenticated principals can read subordinate id information
"System: Read Subordinate Id Attributes": {
"ipapermbindruletype": "all",
"ipapermright": {"read", "search", "compare"},
"ipapermtargetfilter": [
permission_filter_objectclasses_string,
],
"ipapermdefaultattr": {
"objectclass",
"ipauniqueid",
"description",
"ipaowner",
"ipasubuidnumber",
"ipasubuidcount",
"ipasubgidnumber",
"ipasubgidcount",
},
},
"System: Read Subordinate Id Count": {
"ipapermbindruletype": "all",
"ipapermright": {"read", "search", "compare"},
"ipapermtargetfilter": [],
"ipapermtarget": DN(container_dn, api.env.basedn),
"ipapermdefaultattr": {"numSubordinates"},
},
# user administrators can remove subordinate ids or update the
# ipaowner attribute. This enables user admins to remove users
# with assigned subids or move them to staging area (--preserve).
"System: Manage Subordinate Ids": {
"ipapermright": {"write"},
"ipapermtargetfilter": [
permission_filter_objectclasses_string,
],
"ipapermdefaultattr": {
"description",
"ipaowner", # allow user admins to preserve users
},
"default_privileges": {"User Administrators"},
},
"System: Remove Subordinate Ids": {
"ipapermright": {"delete"},
"ipapermtargetfilter": [
permission_filter_objectclasses_string,
],
"default_privileges": {"User Administrators"},
},
}
takes_params = (
Str(
"ipauniqueid",
cli_name="id",
label=_("Unique ID"),
primary_key=True,
flags={"optional_create"},
),
Str(
"description?",
cli_name="desc",
label=_("Description"),
doc=_("Subordinate id description"),
),
Str(
"ipaowner",
cli_name="owner",
label=_("Owner"),
doc=_("Owning user of subordinate id entry"),
flags={"no_update"},
),
Int(
"ipasubuidnumber?",
label=_("SubUID range start"),
cli_name="subuid",
doc=_("Start value for subordinate user ID (subuid) range"),
flags={"no_update"},
minvalue=constants.SUBID_RANGE_START,
maxvalue=constants.SUBID_RANGE_MAX,
),
Int(
"ipasubuidcount?",
label=_("SubUID range size"),
cli_name="subuidcount",
doc=_("Subordinate user ID count"),
flags={"no_create", "no_update", "no_search"}, # auto-assigned
minvalue=constants.SUBID_COUNT,
maxvalue=constants.SUBID_COUNT,
),
Int(
"ipasubgidnumber?",
label=_("SubGID range start"),
cli_name="subgid",
doc=_("Start value for subordinate group ID (subgid) range"),
flags={"no_create", "no_update"}, # auto-assigned
minvalue=constants.SUBID_RANGE_START,
maxvalue=constants.SUBID_RANGE_MAX,
),
Int(
"ipasubgidcount?",
label=_("SubGID range size"),
cli_name="subgidcount",
doc=_("Subordinate group ID count"),
flags={"no_create", "no_update", "no_search"}, # auto-assigned
minvalue=constants.SUBID_COUNT,
maxvalue=constants.SUBID_COUNT,
),
)
def fixup_objectclass(self, entry_attrs):
"""Add missing object classes to entry"""
has_subuid = "ipasubuidnumber" in entry_attrs
has_subgid = "ipasubgidnumber" in entry_attrs
candicates = set(self.object_class)
if has_subgid:
candicates.add("ipasubordinategid")
if has_subuid:
candicates.add("ipasubordinateuid")
if has_subgid and has_subuid:
candicates.add("ipasubordinateid")
entry_oc = entry_attrs.setdefault("objectclass", [])
current_oc = {x.lower() for x in entry_oc}
for oc in candicates.difference(current_oc):
entry_oc.append(oc)
def handle_duplicate_entry(self, *keys):
if hasattr(context, "subid_owner_dn"):
uid = context.subid_owner_dn[0].value
msg = _(
'%(oname)s with with name "%(pkey)s" or for user "%(uid)s" '
"already exists."
) % {
"uid": uid,
"pkey": keys[-1] if keys else "",
"oname": self.object_name,
}
raise errors.DuplicateEntry(message=msg) from None
else:
super().handle_duplicate_entry(*keys)
def convert_owner(self, entry_attrs, options):
"""Change owner from DN to uid string"""
if not options.get("raw", False) and "ipaowner" in entry_attrs:
userobj = self.api.Object.user
entry_attrs["ipaowner"] = [
userobj.get_primary_key_from_dn(entry_attrs["ipaowner"][0])
]
def get_owner_dn(self, *keys, **options):
"""Get owning user entry entry (username or DN)"""
owner = keys[-1]
userobj = self.api.Object.user
if isinstance(owner, DN):
# it's already a DN, validate it's either an active or preserved
# user. Ref integrity plugin checks that it's not a dangling DN.
user_dns = (
DN(userobj.active_container_dn, self.api.env.basedn),
DN(userobj.delete_container_dn, self.api.env.basedn),
)
if not owner.endswith(user_dns):
raise errors.ValidationError(
name="ipaowner",
error=_("'%(dn)s is not a valid user") % {"dn": owner},
)
return owner
# similar to user.get_either_dn() but with error reporting and
# returns an entry
ldap = self.backend
try:
active_dn = userobj.get_dn(owner, **options)
entry = ldap.get_entry(active_dn, attrs_list=[])
return entry.dn
except errors.NotFound:
# fall back to deleted user
try:
delete_dn = userobj.get_delete_dn(owner, **options)
entry = ldap.get_entry(delete_dn, attrs_list=[])
return entry.dn
except errors.NotFound:
raise userobj.handle_not_found(owner)
def handle_subordinate_ids(self, ldap, dn, entry_attrs):
"""Handle ipaSubordinateId object class"""
new_subuid = entry_attrs.single_value.get("ipasubuidnumber")
new_subgid = entry_attrs.single_value.get("ipasubgidnumber")
if new_subuid is None:
new_subuid = DNA_MAGIC
# enforce subuid == subgid
if new_subgid is not None and new_subgid != new_subuid:
raise errors.ValidationError(
name="ipasubgidnumber",
error=_("subgidnumber must be equal to subuidnumber"),
)
self.set_subordinate_ids(ldap, dn, entry_attrs, new_subuid)
return True
def set_subordinate_ids(self, ldap, dn, entry_attrs, subuid):
"""Set subuid value of an entry
Takes care of objectclass and sibbling attributes
"""
if "objectclass" not in entry_attrs:
_entry_attrs = ldap.get_entry(dn, ["objectclass"])
entry_attrs["objectclass"] = _entry_attrs["objectclass"]
entry_attrs["ipasubuidnumber"] = subuid
# enforce subuid == subgid for now
entry_attrs["ipasubgidnumber"] = subuid
# hard-coded constants
entry_attrs["ipasubuidcount"] = constants.SUBID_COUNT
entry_attrs["ipasubgidcount"] = constants.SUBID_COUNT
self.fixup_objectclass(entry_attrs)
def get_subid_match_candidate_filter(
self,
ldap,
*,
subuid,
subgid,
extra_filters=(),
offset=None,
):
"""Create LDAP filter to locate matching/overlapping subids"""
if subuid is None and subgid is None:
raise ValueError("subuid and subgid are both None")
if offset is None:
# assumes that no subordinate count is larger than SUBID_COUNT
offset = constants.SUBID_COUNT - 1
class_filters = "(objectclass=ipasubordinateid)"
subid_filters = []
if subuid is not None:
subid_filters.append(
ldap.combine_filters(
[
f"(ipasubuidnumber>={subuid - offset})",
f"(ipasubuidnumber<={subuid + offset})",
],
rules=ldap.MATCH_ALL,
)
)
if subgid is not None:
subid_filters.append(
ldap.combine_filters(
[
f"(ipasubgidnumber>={subgid - offset})",
f"(ipasubgidnumber<={subgid + offset})",
],
rules=ldap.MATCH_ALL,
)
)
subid_filters = ldap.combine_filters(
subid_filters, rules=ldap.MATCH_ANY
)
filters = [class_filters, subid_filters]
filters.extend(extra_filters)
return ldap.combine_filters(filters, rules=ldap.MATCH_ALL)
@register()
class subid_add(LDAPCreate):
__doc__ = _("Add a new subordinate id.")
msg_summary = _('Added subordinate id "%(value)s"')
# internal command, use subid-auto to auto-assign subids
NO_CLI = True
def pre_callback(
self, ldap, dn, entry_attrs, attrs_list, *keys, **options
):
# XXX let ref integrity plugin validate DN?
owner_dn = self.obj.get_owner_dn(entry_attrs["ipaowner"], **options)
context.subid_owner_dn = owner_dn
entry_attrs["ipaowner"] = owner_dn
self.obj.handle_subordinate_ids(ldap, dn, entry_attrs)
attrs_list.append("objectclass")
return dn
def execute(self, ipauniqueid=None, **options):
if ipauniqueid is None:
ipauniqueid = str(uuid.uuid4())
return super().execute(ipauniqueid, **options)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_owner(entry_attrs, options)
return super(subid_add, self).post_callback(
ldap, dn, entry_attrs, *keys, **options
)
@register()
class subid_del(LDAPDelete):
__doc__ = _("Delete a subordinate id.")
msg_summary = _('Deleted subordinate id "%(value)s"')
# internal command, subids cannot be removed
NO_CLI = True
@register()
class subid_mod(LDAPUpdate):
__doc__ = _("Modify a subordinate id.")
msg_summary = _('Modified subordinate id "%(value)s"')
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_owner(entry_attrs, options)
return super(subid_mod, self).post_callback(
ldap, dn, entry_attrs, *keys, **options
)
@register()
class subid_find(LDAPSearch):
__doc__ = _("Search for subordinate id.")
msg_summary = ngettext(
"%(count)d subordinate id matched",
"%(count)d subordinate ids matched",
0,
)
def pre_callback(
self, ldap, filters, attrs_list, base_dn, scope, *args, **options
):
attrs_list.append("objectclass")
return super(subid_find, self).pre_callback(
ldap, filters, attrs_list, base_dn, scope, *args, **options
)
def args_options_2_entry(self, *args, **options):
entry_attrs = super(subid_find, self).args_options_2_entry(
*args, **options
)
owner = entry_attrs.get("ipaowner")
if owner is not None:
owner_dn = self.obj.get_owner_dn(owner, **options)
entry_attrs["ipaowner"] = owner_dn
return entry_attrs
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry in entries:
self.obj.convert_owner(entry, options)
return super(subid_find, self).post_callback(
ldap, entries, truncated, *args, **options
)
@register()
class subid_show(LDAPRetrieve):
__doc__ = _("Display information about a subordinate id.")
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
attrs_list.append("objectclass")
return super(subid_show, self).pre_callback(
ldap, dn, attrs_list, *keys, **options
)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.obj.convert_owner(entry_attrs, options)
return super(subid_show, self).post_callback(
ldap, dn, entry_attrs, *keys, **options
)
@register()
class subid_generate(LDAPQuery):
__doc__ = _(
"Generate and auto-assign subuid and subgid range to user entry"
)
has_output = output.standard_entry
takes_options = LDAPQuery.takes_options + (
Str(
"ipaowner?",
cli_name="owner",
label=_("Owner"),
doc=_("Owning user of subordinate id entry"),
),
)
def get_args(self):
return []
def execute(self, *keys, **options):
owner_uid = options.get("ipaowner")
# default to current user
if owner_uid is None:
owner_dn = DN(self.api.Backend.ldap2.conn.whoami_s()[4:])
# validate it's a user and not a service or host
owner_dn = self.obj.get_owner_dn(owner_dn)
owner_uid = owner_dn[0].value
return self.api.Command.subid_add(
description="auto-assigned subid",
ipaowner=owner_uid,
version=options["version"],
)
@register()
class subid_match(subid_find):
__doc__ = _("Match users by any subordinate uid in their range")
def get_options(self):
base_options = {p.name for p in self.obj.takes_params}
for option in super().get_options():
if option.name == "ipasubuidnumber":
yield option.clone(
label=_("SubUID match"),
doc=_("Match value for subordinate user ID"),
required=True,
)
elif option.name not in base_options:
# raw, version
yield option.clone()
def pre_callback(
self, ldap, filters, attrs_list, base_dn, scope, *args, **options
):
# search for candidates in range
# Code assumes that no subordinate count is larger than SUBID_COUNT
filters = self.obj.get_subid_match_candidate_filter(
ldap,
subuid=options["ipasubuidnumber"],
subgid=None,
)
attrs_list.extend(self.obj.default_attributes)
return filters, base_dn, scope
def post_callback(self, ldap, entries, truncated, *args, **options):
# filter out mismatches manually
osubuid = options["ipasubuidnumber"]
new_entries = []
for entry in entries:
self.obj.convert_owner(entry, options)
esubuid = int(entry.single_value["ipasubuidnumber"])
esubcount = int(entry.single_value["ipasubuidcount"])
minsubuid = esubuid
maxsubuid = esubuid + esubcount - 1
if minsubuid <= osubuid <= maxsubuid:
new_entries.append(entry)
entries[:] = new_entries
return truncated
@register()
class subid_stats(LDAPQuery):
__doc__ = _("Subordinate id statistics")
takes_options = ()
has_output = (
output.summary,
output.Entry("result"),
)
def get_args(self):
return ()
def get_remaining_dna(self, ldap, **options):
base_dn = DN(
self.api.env.container_dna_subordinate_ids, self.api.env.basedn
)
entries, _truncated = ldap.find_entries(
"(objectClass=dnaSharedConfig)",
attrs_list=["dnaRemainingValues"],
base_dn=base_dn,
scope=ldap.SCOPE_ONELEVEL,
)
return sum(
int(entry.single_value["dnaRemainingValues"]) for entry in entries
)
def get_idrange(self, ldap, **options):
cn = f"{self.api.env.realm}_subid_range"
result = self.api.Command.idrange_show(cn, version=options["version"])
baseid = int(result["result"]["ipabaseid"][0])
rangesize = int(result["result"]["ipaidrangesize"][0])
return baseid, rangesize
def get_subid_assigned(self, ldap, **options):
dn = DN(self.api.env.container_subids, self.api.env.basedn)
entry = ldap.get_entry(dn=dn, attrs_list=["numSubordinates"])
return int(entry.single_value["numSubordinates"])
def execute(self, *keys, **options):
ldap = self.obj.backend
dna_remaining = self.get_remaining_dna(ldap, **options)
baseid, rangesize = self.get_idrange(ldap, **options)
assigned_subids = self.get_subid_assigned(ldap, **options)
remaining_subids = dna_remaining // constants.SUBID_COUNT
return dict(
summary=_("%(remaining)i remaining subordinate id ranges")
% {
"remaining": remaining_subids,
},
result=dict(
baseid=baseid,
rangesize=rangesize,
dna_remaining=dna_remaining,
assigned_subids=assigned_subids,
remaining_subids=remaining_subids,
),
)
| 19,669
|
Python
|
.py
| 515
| 28.186408
| 78
| 0.580327
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,885
|
group.py
|
freeipa_freeipa/ipaserver/plugins/group.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# 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
import logging
import re
from ipalib import api
from ipalib import Int, Str, Flag
from ipalib.constants import PATTERN_GROUPUSER_NAME, ERRMSG_GROUPUSER_NAME
from ipalib.plugable import Registry
from .baseldap import (
add_external_post_callback,
pkey_to_value,
remove_external_post_callback,
LDAPObject,
LDAPCreate,
LDAPUpdate,
LDAPDelete,
LDAPSearch,
LDAPRetrieve,
LDAPAddMember,
LDAPRemoveMember,
LDAPQuery,
)
from .idviews import remove_ipaobject_overrides, handle_idoverride_memberof
from . import baseldap
from ipalib import _, ngettext
from ipalib import errors
from ipalib import output
from ipapython.dn import DN
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
if api.env.in_server:
try:
import ipaserver.dcerpc
_dcerpc_bindings_installed = True
except ImportError:
_dcerpc_bindings_installed = False
__doc__ = _("""
Groups of users
Manage groups of users, groups, or services. By default, new groups are POSIX
groups. You can add the --nonposix option to the group-add command to mark a
new group as non-POSIX. You can use the --posix argument with the group-mod
command to convert a non-POSIX group into a POSIX group. POSIX groups cannot be
converted to non-POSIX groups.
Every group must have a description.
The group name must follow these rules:
- cannot contain only numbers
- must start with a letter, a number, _ or .
- may contain letters, numbers, _, ., or -
- may end with a letter, a number, _, ., - or $
POSIX groups must have a Group ID (GID) number. Changing a GID is
supported but can have an impact on your file permissions. It is not necessary
to supply a GID when creating a group. IPA will generate one automatically
if it is not provided.
Groups members can be users, other groups, and Kerberos services. In POSIX
environments only users will be visible as group members, but nested groups and
groups of services can be used for IPA management purposes.
EXAMPLES:
Add a new group:
ipa group-add --desc='local administrators' localadmins
Add a new non-POSIX group:
ipa group-add --nonposix --desc='remote administrators' remoteadmins
Convert a non-POSIX group to posix:
ipa group-mod --posix remoteadmins
Add a new POSIX group with a specific Group ID number:
ipa group-add --gid=500 --desc='unix admins' unixadmins
Add a new POSIX group and let IPA assign a Group ID number:
ipa group-add --desc='printer admins' printeradmins
Remove a group:
ipa group-del unixadmins
To add the "remoteadmins" group to the "localadmins" group:
ipa group-add-member --groups=remoteadmins localadmins
Add multiple users to the "localadmins" group:
ipa group-add-member --users=test1 --users=test2 localadmins
To add Kerberos services to the "printer admins" group:
ipa group-add-member --services=CUPS/some.host printeradmins
Remove a user from the "localadmins" group:
ipa group-remove-member --users=test2 localadmins
Display information about a named group.
ipa group-show localadmins
Group membership managers are users or groups that can add members to a
group or remove members from a group.
Allow user "test2" to add or remove members from group "localadmins":
ipa group-add-member-manager --users=test2 localadmins
Revoke membership management rights for user "test2" from "localadmins":
ipa group-remove-member-manager --users=test2 localadmins
External group membership is designed to allow users from trusted domains
to be mapped to local POSIX groups in order to actually use IPA resources.
External members should be added to groups that specifically created as
external and non-POSIX. Such group later should be included into one of POSIX
groups.
An external group member is currently a Security Identifier (SID) as defined by
the trusted domain. When adding external group members, it is possible to
specify them in either SID, or DOM\\name, or name@domain format. IPA will attempt
to resolve passed name to SID with the use of Global Catalog of the trusted domain.
Example:
1. Create group for the trusted domain admins' mapping and their local POSIX group:
ipa group-add --desc='<ad.domain> admins external map' ad_admins_external --external
ipa group-add --desc='<ad.domain> admins' ad_admins
2. Add security identifier of Domain Admins of the <ad.domain> to the ad_admins_external
group:
ipa group-add-member ad_admins_external --external 'AD\\Domain Admins'
3. Allow members of ad_admins_external group to be associated with ad_admins POSIX group:
ipa group-add-member ad_admins --groups ad_admins_external
4. List members of external members of ad_admins_external group to see their SIDs:
ipa group-show ad_admins_external
""")
register = Registry()
# also see "System: Remove Groups"
PROTECTED_GROUPS = (u'admins', u'trust admins', u'default smb group')
ipaexternalmember_param = Str('ipaexternalmember*',
cli_name='external',
label=_('External member'),
doc=_('Members of a trusted domain in DOM\\name or name@domain form'),
flags=['no_create', 'no_update', 'no_search'],
)
group_output_params = (
Str(
'membermanager_group',
label='Membership managed by groups',
),
Str(
'membermanager_user',
label='Membership managed by users',
),
Str(
'membermanager',
label=_('Failed member manager'),
),
)
@register()
class group(LDAPObject):
"""
Group object.
"""
container_dn = api.env.container_group
object_name = _('group')
object_name_plural = _('groups')
object_class = ['ipausergroup']
object_class_config = 'ipagroupobjectclasses'
possible_objectclasses = ['posixGroup', 'mepManagedEntry', 'ipaExternalGroup']
permission_filter_objectclasses = ['posixgroup', 'ipausergroup']
permission_filter_objectclasses_string = (
'(|(objectclass=ipausergroup)(objectclass=posixgroup))'
)
search_attributes_config = 'ipagroupsearchfields'
default_attributes = [
'cn', 'description', 'gidnumber', 'member', 'memberof',
'memberindirect', 'memberofindirect', 'ipaexternalmember',
'membermanager',
]
uuid_attribute = 'ipauniqueid'
attribute_members = {
'member': ['user', 'group', 'service', 'idoverrideuser'],
'membermanager': ['user', 'group'],
'memberof': ['group', 'netgroup', 'role', 'hbacrule', 'sudorule'],
'memberindirect': ['user', 'group', 'service', 'idoverrideuser'],
'memberofindirect': ['group', 'netgroup', 'role', 'hbacrule',
'sudorule'],
}
allow_rename = True
managed_permissions = {
'System: Read Groups': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'anonymous',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'businesscategory', 'cn', 'description', 'gidnumber',
'ipaexternalmember', 'ipauniqueid', 'mepmanagedby', 'o',
'objectclass', 'ou', 'owner', 'seealso',
'ipantsecurityidentifier', 'membermanager',
},
},
'System: Read Group Membership': {
'replaces_global_anonymous_aci': True,
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'member', 'memberof', 'memberuid', 'memberuser', 'memberhost',
},
},
'System: Read External Group Membership': {
'ipapermbindruletype': 'all',
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'ipaexternalmember',
},
},
'System: Add Groups': {
'ipapermright': {'add'},
'replaces': [
'(target = "ldap:///cn=*,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Add Groups";allow (add) groupdn = "ldap:///cn=Add Groups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Group Administrators'},
},
'System: Modify Group Membership': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
'(objectclass=ipausergroup)', # only ipausergroups
'(!(cn=admins))',
],
'ipapermdefaultattr': {'member'},
'replaces': [
'(targetattr = "member")(target = "ldap:///cn=*,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Group membership";allow (write) groupdn = "ldap:///cn=Modify Group membership,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetfilter = "(!(cn=admins))")(targetattr = "member")(target = "ldap:///cn=*,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Group membership";allow (write) groupdn = "ldap:///cn=Modify Group membership,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {
'Group Administrators', 'Modify Group membership'
},
},
'System: Modify External Group Membership': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
'(objectclass=ipaexternalgroup)',
],
'ipapermdefaultattr': {'ipaexternalmember'},
'default_privileges': {
'Group Administrators', 'Modify Group membership'
},
},
'System: Modify Groups': {
'ipapermright': {'write'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
'(!(cn=admins))',
],
'ipapermdefaultattr': {
'cn', 'description', 'gidnumber', 'ipauniqueid',
'mepmanagedby', 'objectclass', 'membermanager',
},
'replaces': [
'(targetattr = "cn || description || gidnumber || objectclass || mepmanagedby || ipauniqueid")(target = "ldap:///cn=*,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Modify Groups";allow (write) groupdn = "ldap:///cn=Modify Groups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Group Administrators'},
},
'System: Remove Groups': {
'ipapermright': {'delete'},
'ipapermtargetfilter': [
permission_filter_objectclasses_string,
# prevent removal of PROTECTED_GROUPS
'(!(|(cn=admins)(cn=trust admins)(cn=default smb group)))',
],
'replaces': [
'(target = "ldap:///cn=*,cn=groups,cn=accounts,$SUFFIX")(version 3.0;acl "permission:Remove Groups";allow (delete) groupdn = "ldap:///cn=Remove Groups,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'Group Administrators'},
},
'System: Read Group Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=groups', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'memberuid', 'gidnumber',
},
},
'System: Read Group Views Compat Tree': {
'non_object': True,
'ipapermbindruletype': 'anonymous',
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=groups', 'cn=*', 'cn=views', 'cn=compat', api.env.basedn),
'ipapermright': {'read', 'search', 'compare'},
'ipapermdefaultattr': {
'objectclass', 'cn', 'memberuid', 'gidnumber',
},
},
}
label = _('User Groups')
label_singular = _('User Group')
takes_params = (
Str('cn',
pattern=PATTERN_GROUPUSER_NAME,
pattern_errmsg=ERRMSG_GROUPUSER_NAME.format('group'),
maxlength=255,
cli_name='group_name',
label=_('Group name'),
primary_key=True,
normalizer=lambda value: value.lower(),
),
Str('description?',
cli_name='desc',
label=_('Description'),
doc=_('Group description'),
),
Int('gidnumber?',
cli_name='gid',
label=_('GID'),
doc=_('GID (use this option to set it manually)'),
minvalue=1,
),
ipaexternalmember_param,
)
@register()
class group_add(LDAPCreate):
__doc__ = _('Create a new group.')
has_output_params = LDAPCreate.has_output_params + group_output_params
msg_summary = _('Added group "%(value)s"')
takes_options = LDAPCreate.takes_options + (
Flag('nonposix',
cli_name='nonposix',
doc=_('Create as a non-POSIX group'),
default=False,
),
Flag('external',
cli_name='external',
doc=_('Allow adding external non-IPA members from trusted domains'),
default=False,
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
# As both 'external' and 'nonposix' options have default= set for
# them, they will always be present in options dict, thus we can
# safely reference the values
assert isinstance(dn, DN)
if options['external']:
entry_attrs['objectclass'].append('ipaexternalgroup')
if 'gidnumber' in options:
raise errors.MutuallyExclusiveError(reason=_('gid cannot be set for external group'))
elif not options['nonposix']:
entry_attrs['objectclass'].append('posixgroup')
if 'gidnumber' not in options:
entry_attrs['gidnumber'] = baseldap.DNA_MAGIC
return dn
def exc_callback(self, keys, options, exc, call_func,
*call_args, **call_kwargs):
if isinstance(exc, errors.ObjectclassViolation):
if options['nonposix'] and 'gidnumber' in options:
raise errors.ObjectclassViolation(
info=_('attribute "gidNumber" not allowed with --nonposix')
)
raise exc
@register()
class group_del(LDAPDelete):
__doc__ = _('Delete group.')
msg_summary = _('Deleted group "%(value)s"')
def pre_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
config = ldap.get_ipa_config()
def_primary_group = config.get('ipadefaultprimarygroup', '')
def_primary_group_dn = self.obj.get_dn(def_primary_group)
if dn == def_primary_group_dn:
raise errors.DefaultGroupError()
group_attrs = self.obj.methods.show(
self.obj.get_primary_key_from_dn(dn), all=True
)['result']
if keys[0] in PROTECTED_GROUPS:
raise errors.ProtectedEntryError(label=_(u'group'), key=keys[0],
reason=_(u'privileged group'))
if 'mepmanagedby' in group_attrs:
raise errors.ManagedGroupError()
# Remove any ID overrides tied with this group
remove_ipaobject_overrides(ldap, self.obj.api, dn)
return dn
def post_callback(self, ldap, dn, *keys, **options):
assert isinstance(dn, DN)
try:
# A user removing a group may have no rights to remove
# an associated policy. Make sure we log an explanation
# in the Apache logs for this.
api.Command['pwpolicy_del'](keys[-1])
except errors.ACIError:
logger.warning(
"While removing group %s, user lacked permissions "
"to remove corresponding password policy. This is "
"not an issue and can be ignored.", keys[-1]
)
except errors.NotFound:
pass
return True
@register()
class group_mod(LDAPUpdate):
__doc__ = _('Modify a group.')
has_output_params = LDAPUpdate.has_output_params + group_output_params
msg_summary = _('Modified group "%(value)s"')
takes_options = LDAPUpdate.takes_options + (
Flag('posix',
cli_name='posix',
doc=_('change to a POSIX group'),
),
Flag('external',
cli_name='external',
doc=_('change to support external non-IPA members from trusted domains'),
default=False,
),
)
NAME_PATTERN = re.compile(PATTERN_GROUPUSER_NAME)
def pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
is_protected_group = keys[-1] in PROTECTED_GROUPS
if 'rename' in options or 'cn' in entry_attrs:
if is_protected_group:
raise errors.ProtectedEntryError(label=u'group', key=keys[-1],
reason=u'Cannot be renamed')
if 'cn' in entry_attrs:
# Check the pattern if the group is renamed
if self.NAME_PATTERN.match(entry_attrs.single_value['cn']) is None:
raise errors.ValidationError(
name='cn',
error=ERRMSG_GROUPUSER_NAME.format('group'))
if ('posix' in options and options['posix']) or 'gidnumber' in options:
old_entry_attrs = ldap.get_entry(dn, ['objectclass'])
dn = old_entry_attrs.dn
if 'ipaexternalgroup' in old_entry_attrs['objectclass']:
raise errors.ExternalGroupViolation()
if 'posixgroup' in old_entry_attrs['objectclass']:
if options['posix']:
raise errors.AlreadyPosixGroup()
else:
old_entry_attrs['objectclass'].append('posixgroup')
entry_attrs['objectclass'] = old_entry_attrs['objectclass']
if 'gidnumber' not in options:
entry_attrs['gidnumber'] = baseldap.DNA_MAGIC
if options['external']:
if is_protected_group:
raise errors.ProtectedEntryError(label=u'group', key=keys[-1],
reason=u'Cannot support external non-IPA members')
old_entry_attrs = ldap.get_entry(dn, ['objectclass'])
dn = old_entry_attrs.dn
if 'posixgroup' in old_entry_attrs['objectclass']:
raise errors.PosixGroupViolation()
if 'ipaexternalgroup' in old_entry_attrs['objectclass']:
raise errors.AlreadyExternalGroup()
else:
old_entry_attrs['objectclass'].append('ipaexternalgroup')
entry_attrs['objectclass'] = old_entry_attrs['objectclass']
if 'gidnumber' in entry_attrs:
raise errors.MutuallyExclusiveError(reason=_(
'An external group cannot be POSIX'))
# Can't check for this in a validator because we lack context
if 'gidnumber' in options and options['gidnumber'] is None:
raise errors.RequirementError(name='gidnumber')
return dn
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
# Check again for GID requirement in case someone tried to clear it
# using --setattr.
if call_func.__name__ == 'update_entry':
if isinstance(exc, errors.ObjectclassViolation):
if 'gidNumber' in str(exc) and 'posixGroup' in str(exc):
raise errors.RequirementError(name='gidnumber')
raise exc
@register()
class group_find(LDAPSearch):
__doc__ = _('Search for groups.')
member_attributes = ['member', 'memberof', 'membermanager']
has_output_params = LDAPSearch.has_output_params + group_output_params
msg_summary = ngettext(
'%(count)d group matched', '%(count)d groups matched', 0
)
takes_options = LDAPSearch.takes_options + (
Flag('private',
cli_name='private',
doc=_('search for private groups'),
),
Flag('posix',
cli_name='posix',
doc=_('search for POSIX groups'),
),
Flag('external',
cli_name='external',
doc=_('search for groups with support of external non-IPA members from trusted domains'),
),
Flag('nonposix',
cli_name='nonposix',
doc=_('search for non-POSIX groups'),
),
)
# pylint: disable-next=arguments-renamed
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope,
criteria=None, **options):
assert isinstance(base_dn, DN)
# filter groups by pseudo type
filters = []
if options['posix']:
search_kw = {'objectclass': ['posixGroup']}
filters.append(ldap.make_filter(search_kw, rules=ldap.MATCH_ALL))
if options['external']:
search_kw = {'objectclass': ['ipaExternalGroup']}
filters.append(ldap.make_filter(search_kw, rules=ldap.MATCH_ALL))
if options['nonposix']:
search_kw = {'objectclass': ['posixGroup' , 'ipaExternalGroup']}
filters.append(ldap.make_filter(search_kw, rules=ldap.MATCH_NONE))
# if looking for private groups, we need to create a new search filter,
# because private groups have different object classes
if options['private']:
# filter based on options, oflt
search_kw = self.args_options_2_entry(**options)
search_kw['objectclass'] = ['posixGroup', 'mepManagedEntry']
oflt = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
# filter based on 'criteria' argument
search_kw = {}
config = ldap.get_ipa_config()
attrs = config.get(self.obj.search_attributes_config, [])
if len(attrs) == 1 and isinstance(attrs[0], str):
search_attrs = attrs[0].split(',')
for a in search_attrs:
search_kw[a] = criteria
cflt = ldap.make_filter(search_kw, exact=False)
filter = ldap.combine_filters((oflt, cflt), rules=ldap.MATCH_ALL)
elif filters:
filters.append(filter)
filter = ldap.combine_filters(filters, rules=ldap.MATCH_ALL)
return (filter, base_dn, scope)
@register()
class group_show(LDAPRetrieve):
__doc__ = _('Display information about a named group.')
has_output_params = LDAPRetrieve.has_output_params + group_output_params
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if ('ipaexternalmember' in entry_attrs and
len(entry_attrs['ipaexternalmember']) > 0 and
'trust_resolve' in self.Command and
not options.get('raw', False)):
sids = entry_attrs['ipaexternalmember']
result = self.Command.trust_resolve(sids=sids)
for entry in result['result']:
try:
idx = sids.index(entry['sid'][0])
sids[idx] = entry['name'][0]
except ValueError:
pass
return dn
@register()
class group_add_member(LDAPAddMember):
__doc__ = _('Add members to a group.')
takes_options = (ipaexternalmember_param,)
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
handle_idoverride_memberof(self, ldap, dn, found, not_found,
*keys, **options)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
result = (completed, dn)
if 'ipaexternalmember' in options:
if not _dcerpc_bindings_installed:
raise errors.NotFound(reason=_('Cannot perform external member validation without '
'Samba 4 support installed. Make sure you have installed '
'server-trust-ad sub-package of IPA on the server'))
# pylint: disable=used-before-assignment
domain_validator = ipaserver.dcerpc.DomainValidator(self.api)
# pylint: enable=used-before-assignment
if not domain_validator.is_configured():
raise errors.NotFound(reason=_('Cannot perform join operation without own domain configured. '
'Make sure you have run ipa-adtrust-install on the IPA server first'))
sids = []
failed_sids = []
for sid in options['ipaexternalmember']:
if domain_validator.is_trusted_sid_valid(sid):
sids.append(sid)
else:
try:
actual_sid = domain_validator.get_trusted_domain_object_sid(sid)
except errors.PublicError as e:
failed_sids.append((sid, e.strerror))
else:
sids.append(actual_sid)
restore = []
if 'member' in failed and 'group' in failed['member']:
restore = failed['member']['group']
failed['member']['group'] = list((id, id) for id in sids)
result = add_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='member',
membertype='group',
externalattr='ipaexternalmember',
normalize=False)
failed['member']['group'] += restore + failed_sids
return result
@register()
class group_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a group.')
takes_options = (ipaexternalmember_param,)
def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
assert isinstance(dn, DN)
if keys[0] in PROTECTED_GROUPS and 'user' in options:
protected_group_name = keys[0]
result = api.Command.group_show(protected_group_name)
users_left = set(result['result'].get('member_user', []))
users_deleted = set(options['user'])
if users_left.issubset(users_deleted):
raise errors.LastMemberError(key=sorted(users_deleted)[0],
label=_(u'group'), container=protected_group_name)
return dn
def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
result = (completed, dn)
if 'ipaexternalmember' in options:
if not _dcerpc_bindings_installed:
raise errors.NotFound(reason=_('Cannot perform external member validation without '
'Samba 4 support installed. Make sure you have installed '
'server-trust-ad sub-package of IPA on the server'))
domain_validator = ipaserver.dcerpc.DomainValidator(self.api)
if not domain_validator.is_configured():
raise errors.NotFound(reason=_('Cannot perform join operation without own domain configured. '
'Make sure you have run ipa-adtrust-install on the IPA server first'))
sids = []
failed_sids = []
for sid in options['ipaexternalmember']:
if domain_validator.is_trusted_sid_valid(sid):
sids.append(sid)
else:
try:
actual_sid = domain_validator.get_trusted_domain_object_sid(sid)
except errors.PublicError as e:
failed_sids.append((sid, unicode(e)))
else:
sids.append(actual_sid)
restore = []
if 'member' in failed and 'group' in failed['member']:
restore = failed['member']['group']
failed['member']['group'] = list((id, id) for id in sids)
result = remove_external_post_callback(ldap, dn, entry_attrs,
failed=failed,
completed=completed,
memberattr='member',
membertype='group',
externalattr='ipaexternalmember',
)
failed['member']['group'] += restore + failed_sids
return result
@register()
class group_detach(LDAPQuery):
__doc__ = _('Detach a managed group from a user.')
has_output = output.standard_value
msg_summary = _('Detached group "%(value)s" from user "%(value)s"')
def execute(self, *keys, **options):
"""
This requires updating both the user and the group. We first need to
verify that both the user and group can be updated, then we go
about our work. We don't want a situation where only the user or
group can be modified and we're left in a bad state.
"""
ldap = self.obj.backend
group_dn = self.obj.get_dn(*keys, **options)
user_dn = self.api.Object['user'].get_dn(*keys)
try:
user_attrs = ldap.get_entry(user_dn)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
is_managed = self.obj.has_objectclass(
user_attrs['objectclass'], 'mepmanagedentry'
)
if (not ldap.can_write(user_dn, "objectclass") or
not ldap.can_write(user_dn, "mepManagedEntry")
and is_managed):
raise errors.ACIError(
info=_('not allowed to modify user entries')
)
group_attrs = ldap.get_entry(group_dn)
is_managed = self.obj.has_objectclass(
group_attrs['objectclass'], 'mepmanagedby'
)
if (not ldap.can_write(group_dn, "objectclass") or
not ldap.can_write(group_dn, "mepManagedBy")
and is_managed):
raise errors.ACIError(
info=_('not allowed to modify group entries')
)
objectclasses = user_attrs['objectclass']
try:
i = objectclasses.index('mepOriginEntry')
del objectclasses[i]
user_attrs['mepManagedEntry'] = None
ldap.update_entry(user_attrs)
except ValueError:
# Somehow the user isn't managed, let it pass for now. We'll
# let the group throw "Not managed".
pass
group_attrs = ldap.get_entry(group_dn)
objectclasses = group_attrs['objectclass']
try:
i = objectclasses.index('mepManagedEntry')
except ValueError:
# this should never happen
raise errors.NotFound(reason=_('Not a managed group'))
del objectclasses[i]
# Make sure the resulting group has the default group objectclasses
config = ldap.get_ipa_config()
def_objectclass = config.get(
self.obj.object_class_config, objectclasses
)
objectclasses = list(set(def_objectclass + objectclasses))
group_attrs['mepManagedBy'] = None
group_attrs['objectclass'] = objectclasses
ldap.update_entry(group_attrs)
return dict(
result=True,
value=pkey_to_value(keys[0], options),
)
@register()
class group_add_member_manager(LDAPAddMember):
__doc__ = _('Add users that can manage members of this group.')
has_output_params = LDAPAddMember.has_output_params + group_output_params
member_attributes = ['membermanager']
@register()
class group_remove_member_manager(LDAPRemoveMember):
__doc__ = _('Remove users that can manage members of this group.')
has_output_params = (
LDAPRemoveMember.has_output_params + group_output_params
)
member_attributes = ['membermanager']
| 33,235
|
Python
|
.py
| 721
| 35.425798
| 294
| 0.601475
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,886
|
whoami.py
|
freeipa_freeipa/ipaserver/plugins/whoami.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
import six
from ipalib import api, Command, errors, output, Str
from ipalib import _
from ipapython.dn import DN
from ipalib.plugable import Registry
from .idviews import DEFAULT_TRUST_VIEW_NAME
if six.PY3:
unicode = str
__doc__ = _("""
Return information about currently authenticated identity
Who am I command returns information on how to get
more details about the identity authenticated for this
request. The information includes:
* type of object
* command to retrieve details of the object
* arguments and options to pass to the command
The information is returned as a dictionary. Examples below use
'key: value' output for illustrative purposes.
EXAMPLES:
Look up as IPA user:
kinit admin
ipa console
>> api.Command.whoami()
------------------------------------------
object: user
command: user_show/1
arguments: admin
------------------------------------------
Look up as a user from a trusted domain:
kinit user@AD.DOMAIN
ipa console
>> api.Command.whoami()
------------------------------------------
object: idoverrideuser
command: idoverrideuser_show/1
arguments: ('default trust view', 'user@ad.domain')
------------------------------------------
Look up as a host:
kinit -k
ipa console
>> api.Command.whoami()
------------------------------------------
object: host
command: host_show/1
arguments: ipa.example.com
------------------------------------------
Look up as a Kerberos service:
kinit -k -t /path/to/keytab HTTP/ipa.example.com
ipa console
>> api.Command.whoami()
------------------------------------------
object: service
command: service_show/1
arguments: HTTP/ipa.example.com
------------------------------------------
""")
register = Registry()
@register()
class whoami(Command):
__doc__ = _('Describe currently authenticated identity.')
NO_CLI = True
output_params = (
Str('object', label=_('Object class name')),
Str('command', label= _('Function to get details')),
Str('arguments*', label=_('Arguments to details function')),
)
has_output = (
output.Output('object', unicode, _('Object class name')),
output.Output('command', unicode, _('Function to get details')),
output.Output('arguments', (list, tuple),
_('Arguments to details function')),
)
def execute(self, **options):
"""
Retrieve the DN we are authenticated as to LDAP and find bindable IPA
object that handles the container where this DN belongs to. Then report
details about this object.
"""
exceptions = {
'idoverrideuser': (DN("cn={0}".format(DEFAULT_TRUST_VIEW_NAME)),
DEFAULT_TRUST_VIEW_NAME, 'ipaOriginalUid'),
}
ldap = api.Backend.ldap2
# whoami_s() call returns a string 'dn: <actual DN value>'
# We also reject ldapi-as-root connections as DM is a virtual object
dn = DN(ldap.conn.whoami_s()[4:])
if dn == DN('cn=Directory Manager'):
raise errors.NotFound(
reason=_('Cannot query Directory Manager with API'))
entry = ldap.get_entry(dn)
o_name = None
o_func = None
o_args = []
for o in api.Object():
if not getattr(o, 'bindable', None):
continue
container = getattr(o, 'container_dn', None)
if container is None:
continue
# Adjust container for exception two-level objects
if o.name in exceptions:
container = exceptions[o.name][0] + container
if dn.find(container + api.env.basedn) == 1:
# We found exact container this DN belongs to
o_name = unicode(o.name)
o_args = [unicode(entry.single_value.get(o.primary_key.name))]
o_func = unicode(o.methods.show.full_name)
if o.name in exceptions:
o_args = [unicode(exceptions[o.name][1]),
unicode(entry.single_value.get(
exceptions[o.name][2]))]
break
return {'object': o_name, 'command': o_func, 'arguments': o_args}
| 4,391
|
Python
|
.py
| 116
| 30.327586
| 80
| 0.572167
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,887
|
dns.py
|
freeipa_freeipa/ipaserver/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 absolute_import
import logging
import netaddr
import time
import re
import binascii
import encodings.idna
import dns.name
import dns.exception
import dns.rdatatype
import dns.resolver
import six
from ipalib.dns import (extra_name_format,
get_extra_rrtype,
get_part_rrtype,
get_record_rrtype,
get_rrparam_from_part,
has_cli_options,
iterate_rrparams_by_parts,
part_name_format,
record_name_format)
from ipalib.frontend import Method, Object
from ipalib.request import context
from ipalib import api, errors, output
from ipalib import Command
from ipalib.capabilities import (
VERSION_WITHOUT_CAPABILITIES,
client_has_capability)
from ipalib.parameters import (Flag, Bool, Int, Decimal, Str, StrEnum, Any,
DNSNameParam)
from ipalib.plugable import Registry
from .baseldap import (
pkey_to_value,
LDAPObject,
LDAPCreate,
LDAPUpdate,
LDAPSearch,
LDAPQuery,
LDAPDelete,
LDAPRetrieve)
from ipalib import _
from ipalib import messages
from ipalib.util import (normalize_zonemgr,
get_dns_forward_zone_update_policy,
get_dns_reverse_zone_update_policy,
get_reverse_zone_default, REVERSE_DNS_ZONES,
normalize_zone, validate_dnssec_global_forwarder,
DNSSECSignatureMissingError, UnresolvableRecordError,
EDNS0UnsupportedError, DNSSECValidationError,
validate_dnssec_zone_forwarder_step1,
validate_dnssec_zone_forwarder_step2,
verify_host_resolvable,
validate_bind_forwarder,
ipaddr_validator)
from ipaplatform import services
from ipapython.dn import DN
from ipapython.ipautil import CheckedIPAddress
from ipapython.dnsutil import (
check_zone_overlap,
DNSName,
DNSResolver,
DNSZoneAlreadyExists,
related_to_auto_empty_zone,
resolve,
zone_for_name,
)
from ipaserver.dns_data_management import (
IPASystemRecords,
IPADomainIsNotManagedByIPAError,
)
from ipaserver.masters import find_providing_servers, is_service_enabled
if six.PY3:
unicode = str
__doc__ = _("""
Domain Name System (DNS)
""") + _("""
Manage DNS zone and resource records.
""") + _("""
SUPPORTED ZONE TYPES
* Master zone (dnszone-*), contains authoritative data.
* Forward zone (dnsforwardzone-*), forwards queries to configured forwarders
(a set of DNS servers).
""") + _("""
USING STRUCTURED PER-TYPE OPTIONS
""") + _("""
There are many structured DNS RR types where DNS data stored in LDAP server
is not just a scalar value, for example an IP address or a domain name, but
a data structure which may be often complex. A good example is a LOC record
[RFC1876] which consists of many mandatory and optional parts (degrees,
minutes, seconds of latitude and longitude, altitude or precision).
""") + _("""
It may be difficult to manipulate such DNS records without making a mistake
and entering an invalid value. DNS module provides an abstraction over these
raw records and allows to manipulate each RR type with specific options. For
each supported RR type, DNS module provides a standard option to manipulate
a raw records with format --<rrtype>-rec, e.g. --mx-rec, and special options
for every part of the RR structure with format --<rrtype>-<partname>, e.g.
--mx-preference and --mx-exchanger.
""") + _("""
When adding a record, either RR specific options or standard option for a raw
value can be used, they just should not be combined in one add operation. When
modifying an existing entry, new RR specific options can be used to change
one part of a DNS record, where the standard option for raw value is used
to specify the modified value. The following example demonstrates
a modification of MX record preference from 0 to 1 in a record without
modifying the exchanger:
ipa dnsrecord-mod --mx-rec="0 mx.example.com." --mx-preference=1
""") + _("""
EXAMPLES:
""") + _("""
Add new zone:
ipa dnszone-add example.com --admin-email=admin@example.com
""") + _("""
Add system permission that can be used for per-zone privilege delegation:
ipa dnszone-add-permission example.com
""") + _("""
Modify the zone to allow dynamic updates for hosts own records in realm EXAMPLE.COM:
ipa dnszone-mod example.com --dynamic-update=TRUE
""") + _("""
This is the equivalent of:
ipa dnszone-mod example.com --dynamic-update=TRUE \\
--update-policy="grant EXAMPLE.COM krb5-self * A; grant EXAMPLE.COM krb5-self * AAAA; grant EXAMPLE.COM krb5-self * SSHFP;"
""") + _("""
Modify the zone to allow zone transfers for local network only:
ipa dnszone-mod example.com --allow-transfer=192.0.2.0/24
""") + _("""
Add new reverse zone specified by network IP address:
ipa dnszone-add --name-from-ip=192.0.2.0/24
""") + _("""
Add second nameserver for example.com:
ipa dnsrecord-add example.com @ --ns-rec=nameserver2.example.com
""") + _("""
Add a mail server for example.com:
ipa dnsrecord-add example.com @ --mx-rec="10 mail1"
""") + _("""
Add another record using MX record specific options:
ipa dnsrecord-add example.com @ --mx-preference=20 --mx-exchanger=mail2
""") + _("""
Add another record using interactive mode (started when dnsrecord-add, dnsrecord-mod,
or dnsrecord-del are executed with no options):
ipa dnsrecord-add example.com @
Please choose a type of DNS resource record to be added
The most common types for this type of zone are: NS, MX, LOC
DNS resource record type: MX
MX Preference: 30
MX Exchanger: mail3
Record name: example.com
MX record: 10 mail1, 20 mail2, 30 mail3
NS record: nameserver.example.com., nameserver2.example.com.
""") + _("""
Delete previously added nameserver from example.com:
ipa dnsrecord-del example.com @ --ns-rec=nameserver2.example.com.
""") + _("""
Add LOC record for example.com:
ipa dnsrecord-add example.com @ --loc-rec="49 11 42.4 N 16 36 29.6 E 227.64m"
""") + _("""
Add new A record for www.example.com. Create a reverse record in appropriate
reverse zone as well. In this case a PTR record "2" pointing to www.example.com
will be created in zone 2.0.192.in-addr.arpa.
ipa dnsrecord-add example.com www --a-rec=192.0.2.2 --a-create-reverse
""") + _("""
Add new PTR record for www.example.com
ipa dnsrecord-add 2.0.192.in-addr.arpa. 2 --ptr-rec=www.example.com.
""") + _("""
Add new SRV records for LDAP servers. Three quarters of the requests
should go to fast.example.com, one quarter to slow.example.com. If neither
is available, switch to backup.example.com.
ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 3 389 fast.example.com"
ipa dnsrecord-add example.com _ldap._tcp --srv-rec="0 1 389 slow.example.com"
ipa dnsrecord-add example.com _ldap._tcp --srv-rec="1 1 389 backup.example.com"
""") + _("""
The interactive mode can be used for easy modification:
ipa dnsrecord-mod example.com _ldap._tcp
No option to modify specific record provided.
Current DNS record contents:
SRV record: 0 3 389 fast.example.com, 0 1 389 slow.example.com, 1 1 389 backup.example.com
Modify SRV record '0 3 389 fast.example.com'? Yes/No (default No):
Modify SRV record '0 1 389 slow.example.com'? Yes/No (default No): y
SRV Priority [0]: (keep the default value)
SRV Weight [1]: 2 (modified value)
SRV Port [389]: (keep the default value)
SRV Target [slow.example.com]: (keep the default value)
1 SRV record skipped. Only one value per DNS record type can be modified at one time.
Record name: _ldap._tcp
SRV record: 0 3 389 fast.example.com, 1 1 389 backup.example.com, 0 2 389 slow.example.com
""") + _("""
After this modification, three fifths of the requests should go to
fast.example.com and two fifths to slow.example.com.
""") + _("""
An example of the interactive mode for dnsrecord-del command:
ipa dnsrecord-del example.com www
No option to delete specific record provided.
Delete all? Yes/No (default No): (do not delete all records)
Current DNS record contents:
A record: 192.0.2.2, 192.0.2.3
Delete A record '192.0.2.2'? Yes/No (default No):
Delete A record '192.0.2.3'? Yes/No (default No): y
Record name: www
A record: 192.0.2.2 (A record 192.0.2.3 has been deleted)
""") + _("""
Show zone example.com:
ipa dnszone-show example.com
""") + _("""
Find zone with "example" in its domain name:
ipa dnszone-find example
""") + _("""
Find records for resources with "www" in their name in zone example.com:
ipa dnsrecord-find example.com www
""") + _("""
Find A records with value 192.0.2.2 in zone example.com
ipa dnsrecord-find example.com --a-rec=192.0.2.2
""") + _("""
Show records for resource www in zone example.com
ipa dnsrecord-show example.com www
""") + _("""
Delegate zone sub.example to another nameserver:
ipa dnsrecord-add example.com ns.sub --a-rec=203.0.113.1
ipa dnsrecord-add example.com sub --ns-rec=ns.sub.example.com.
""") + _("""
Delete zone example.com with all resource records:
ipa dnszone-del example.com
""") + _("""
If a global forwarder is configured, all queries for which this server is not
authoritative (e.g. sub.example.com) will be routed to the global forwarder.
Global forwarding configuration can be overridden per-zone.
""") + _("""
Semantics of forwarding in IPA matches BIND semantics and depends on the type
of zone:
* Master zone: local BIND replies authoritatively to queries for data in
the given zone (including authoritative NXDOMAIN answers) and forwarding
affects only queries for names below zone cuts (NS records) of locally
served zones.
* Forward zone: forward zone contains no authoritative data. BIND forwards
queries, which cannot be answered from its local cache, to configured
forwarders.
""") + _("""
Semantics of the --forward-policy option:
* none - disable forwarding for the given zone.
* first - forward all queries to configured forwarders. If they fail,
do resolution using DNS root servers.
* only - forward all queries to configured forwarders and if they fail,
return failure.
""") + _("""
Disable global forwarding for given sub-tree:
ipa dnszone-mod example.com --forward-policy=none
""") + _("""
This configuration forwards all queries for names outside the example.com
sub-tree to global forwarders. Normal recursive resolution process is used
for names inside the example.com sub-tree (i.e. NS records are followed etc.).
""") + _("""
Forward all requests for the zone external.example.com to another forwarder
using a "first" policy (it will send the queries to the selected forwarder
and if not answered it will use global root servers):
ipa dnsforwardzone-add external.example.com --forward-policy=first \\
--forwarder=203.0.113.1
""") + _("""
Change forward-policy for external.example.com:
ipa dnsforwardzone-mod external.example.com --forward-policy=only
""") + _("""
Show forward zone external.example.com:
ipa dnsforwardzone-show external.example.com
""") + _("""
List all forward zones:
ipa dnsforwardzone-find
""") + _("""
Delete forward zone external.example.com:
ipa dnsforwardzone-del external.example.com
""") + _("""
Resolve a host name to see if it exists (will add default IPA domain
if one is not included):
ipa dns-resolve www.example.com
ipa dns-resolve www
""") + _("""
GLOBAL DNS CONFIGURATION
""") + _("""
DNS configuration passed to command line install script is stored in a local
configuration file on each IPA server where DNS service is configured. These
local settings can be overridden with a common configuration stored in LDAP
server:
""") + _("""
Show global DNS configuration:
ipa dnsconfig-show
""") + _("""
Modify global DNS configuration and set a list of global forwarders:
ipa dnsconfig-mod --forwarder=203.0.113.113
""")
logger = logging.getLogger(__name__)
register = Registry()
# supported resource record types
_record_types = (
u'A', u'AAAA', u'A6', u'AFSDB', u'APL', u'CERT', u'CNAME', u'DHCID', u'DLV',
u'DNAME', u'DS', u'HIP', u'HINFO', u'IPSECKEY', u'KEY', u'KX', u'LOC',
u'MD', u'MINFO', u'MX', u'NAPTR', u'NS', u'NSEC', u'NXT', u'PTR', u'RRSIG',
u'RP', u'SIG', u'SPF', u'SRV', u'SSHFP', u'TLSA', u'TXT', u"URI"
)
# DNS zone record identificator
_dns_zone_record = DNSName.empty
# attributes derived from record types
_record_attributes = [str(record_name_format % t.lower())
for t in _record_types]
# Deprecated
# supported DNS classes, IN = internet, rest is almost never used
_record_classes = (u'IN', u'CS', u'CH', u'HS')
# IN record class
_IN = dns.rdataclass.IN
# NS record type
_NS = dns.rdatatype.from_text('NS')
_output_permissions = (
output.summary,
output.Output('result', bool, _('True means the operation was successful')),
output.Output('value', unicode, _('Permission value')),
)
def _rname_validator(ugettext, zonemgr):
try:
DNSName(zonemgr) # test only if it is valid domain name
except (ValueError, dns.exception.SyntaxError) as e:
return unicode(e)
return None
def _create_zone_serial():
"""
Generate serial number for zones. bind-dyndb-ldap expects unix time in
to be used for SOA serial.
SOA serial in a date format would also work, but it may be set to far
future when many DNS updates are done per day (more than 100). Unix
timestamp is more resilient to this issue.
"""
return int(time.time())
def _reverse_zone_name(netstr):
try:
netaddr.IPAddress(str(netstr))
except (netaddr.AddrFormatError, ValueError):
pass
else:
# use more sensible default prefix than netaddr default
return unicode(get_reverse_zone_default(netstr))
net = netaddr.IPNetwork(netstr)
items = net.ip.reverse_dns.split('.')
if net.version == 4:
return u'.'.join(items[4 - net.prefixlen // 8:])
elif net.version == 6:
return u'.'.join(items[32 - net.prefixlen // 4:])
else:
return None
def _validate_ip4addr(ugettext, ipaddr):
return ipaddr_validator(ugettext, ipaddr, 4)
def _validate_ip6addr(ugettext, ipaddr):
return ipaddr_validator(ugettext, ipaddr, 6)
def _validate_ipnet(ugettext, ipnet):
try:
netaddr.IPNetwork(ipnet)
except (netaddr.AddrFormatError, ValueError, UnboundLocalError):
return _('invalid IP network format')
return None
def _validate_bind_aci(ugettext, bind_acis):
if not bind_acis:
return None
bind_acis = bind_acis.split(';')
if bind_acis[-1]:
return _('each ACL element must be terminated with a semicolon')
else:
bind_acis.pop(-1)
for bind_aci in bind_acis:
if bind_aci in ("any", "none", "localhost", "localnets"):
continue
if bind_aci.startswith('!'):
bind_aci = bind_aci[1:]
try:
CheckedIPAddress(bind_aci, parse_netmask=True, allow_loopback=True)
except (netaddr.AddrFormatError, ValueError) as e:
return unicode(e)
except UnboundLocalError:
return _(u"invalid address format")
return None
def _normalize_bind_aci(bind_acis):
if not bind_acis:
return None
bind_acis = bind_acis.split(';')
normalized = []
for bind_aci in bind_acis:
if not bind_aci:
continue
if bind_aci in ("any", "none", "localhost", "localnets"):
normalized.append(bind_aci)
continue
prefix = ""
if bind_aci.startswith('!'):
bind_aci = bind_aci[1:]
prefix = "!"
try:
ip = CheckedIPAddress(bind_aci, parse_netmask=True,
allow_loopback=True)
if '/' in bind_aci: # addr with netmask
netmask = "/%s" % ip.prefixlen
else:
netmask = ""
normalized.append(u"%s%s%s" % (prefix, str(ip), netmask))
continue
except Exception:
normalized.append(bind_aci)
continue
acis = u';'.join(normalized)
acis += u';'
return acis
def _validate_nsec3param_record(ugettext, value):
_nsec3param_pattern = (r'^(?P<alg>\d+) (?P<flags>\d+) (?P<iter>\d+) '
r'(?P<salt>([0-9a-fA-F]{2})+|-)$')
rec = re.compile(_nsec3param_pattern, flags=re.U)
result = rec.match(value)
if result is None:
return _(u'expected format: <0-255> <0-255> <0-65535> '
'even-length_hexadecimal_digits_or_hyphen')
alg = int(result.group('alg'))
flags = int(result.group('flags'))
iterations = int(result.group('iter'))
salt = result.group('salt')
if alg > 255:
return _('algorithm value: allowed interval 0-255')
if flags > 255:
return _('flags value: allowed interval 0-255')
if iterations > 65535:
return _('iterations value: allowed interval 0-65535')
if salt == u'-':
return None
try:
binascii.a2b_hex(salt)
except TypeError as e:
return _('salt value: %(err)s') % {'err': e}
return None
def _hostname_validator(ugettext, value):
assert isinstance(value, DNSName)
if len(value.make_absolute().labels) < 3:
return _('invalid domain-name: not fully qualified')
return None
def _no_wildcard_validator(ugettext, value):
"""Disallow usage of wildcards as RFC 4592 section 4 recommends
"""
assert isinstance(value, DNSName)
if value.is_wild():
return _('should not be a wildcard domain name (RFC 4592 section 4)')
return None
def is_forward_record(zone, str_address):
addr = netaddr.IPAddress(str_address)
if addr.version == 4:
result = api.Command['dnsrecord_find'](zone, arecord=str_address)
elif addr.version == 6:
result = api.Command['dnsrecord_find'](zone, aaaarecord=str_address)
else:
raise ValueError('Invalid address family')
return result['count'] > 0
def add_forward_record(zone, name, str_address):
addr = netaddr.IPAddress(str_address)
try:
if addr.version == 4:
api.Command['dnsrecord_add'](zone, name, arecord=str_address)
elif addr.version == 6:
api.Command['dnsrecord_add'](zone, name, aaaarecord=str_address)
else:
raise ValueError('Invalid address family')
except errors.EmptyModlist:
pass # the entry already exists and matches
def get_reverse_zone(ipaddr):
"""
resolve the reverse zone for IP address and see if it is managed by IPA
server
:param ipaddr: host IP address
:return: tuple containing name of the reverse zone and the name of the
record
"""
ip = netaddr.IPAddress(str(ipaddr))
revdns = DNSName(unicode(ip.reverse_dns))
try:
revzone = DNSName(zone_for_name(revdns))
except dns.resolver.NoNameservers:
raise errors.NotFound(
reason=_(
'All nameservers failed to answer the query '
'for DNS reverse zone %(revdns)s') % dict(revdns=revdns)
)
except dns.resolver.Timeout:
raise errors.NotFound(
reason=_(
"No answers could be found in the specified lifetime "
"for DNS reverse zone %(revdns)s"
) % dict(revdns=revdns)
)
try:
api.Command['dnszone_show'](revzone)
except errors.NotFound:
raise errors.NotFound(
reason=_(
'DNS reverse zone %(revzone)s for IP address '
'%(addr)s is not managed by this server') % dict(
addr=ipaddr, revzone=revzone)
)
revname = revdns.relativize(revzone)
return revzone, revname
def add_records_for_host_validation(option_name, host, domain, ip_addresses, check_forward=True, check_reverse=True):
assert isinstance(host, DNSName)
assert isinstance(domain, DNSName)
try:
api.Command['dnszone_show'](domain)['result']
except errors.NotFound:
raise errors.NotFound(
reason=_('DNS zone %(zone)s not found') % dict(zone=domain)
)
if not isinstance(ip_addresses, (tuple, list)):
ip_addresses = [ip_addresses]
for ip_address in ip_addresses:
try:
ip = CheckedIPAddress(
ip_address, allow_multicast=True)
except Exception as e:
raise errors.ValidationError(name=option_name, error=unicode(e))
if check_forward:
if is_forward_record(domain, unicode(ip)):
raise errors.DuplicateEntry(
message=_(u'IP address %(ip)s is already assigned in domain %(domain)s.')\
% dict(ip=str(ip), domain=domain))
if check_reverse:
try:
# we prefer lookup of the IP through the reverse zone
revzone, revname = get_reverse_zone(ip)
reverse = api.Command['dnsrecord_find'](revzone, idnsname=revname)
if reverse['count'] > 0:
raise errors.DuplicateEntry(
message=_(u'Reverse record for IP address %(ip)s already exists in reverse zone %(zone)s.')\
% dict(ip=str(ip), zone=revzone))
except errors.NotFound:
pass
def add_records_for_host(host, domain, ip_addresses, add_forward=True, add_reverse=True):
assert isinstance(host, DNSName)
assert isinstance(domain, DNSName)
if not isinstance(ip_addresses, (tuple, list)):
ip_addresses = [ip_addresses]
for ip_address in ip_addresses:
ip = CheckedIPAddress(
ip_address, allow_multicast=True)
if add_forward:
add_forward_record(domain, host, unicode(ip))
if add_reverse:
try:
revzone, revname = get_reverse_zone(ip)
addkw = {'ptrrecord': host.derelativize(domain).ToASCII()}
api.Command['dnsrecord_add'](revzone, revname, **addkw)
except errors.EmptyModlist:
# the entry already exists and matches
pass
def _dns_name_to_string(value, raw=False):
if isinstance(value, unicode):
try:
value = DNSName(value)
except Exception:
return value
assert isinstance(value, DNSName)
if raw:
return value.ToASCII()
else:
return unicode(value)
def _check_entry_objectclass(entry, objectclasses):
"""
Check if entry contains all objectclasses
"""
if not isinstance(objectclasses, (list, tuple)):
objectclasses = [objectclasses, ]
if not entry.get('objectclass'):
return False
entry_objectclasses = [o.lower() for o in entry['objectclass']]
for o in objectclasses:
if o not in entry_objectclasses:
return False
return True
def _check_DN_objectclass(ldap, dn, objectclasses):
try:
entry = ldap.get_entry(dn, [u'objectclass', ])
except Exception:
return False
else:
return _check_entry_objectclass(entry, objectclasses)
class DNSRecord(Str):
# a list of parts that create the actual raw DNS record
parts = None
# an optional list of parameters used in record-specific operations
extra = None
supported = True
# supported RR types: https://fedorahosted.org/bind-dyndb-ldap/browser/doc/schema
label_format = _("%s record")
part_label_format = "%s %s"
doc_format = _('Raw %s records')
option_group_format = _('%s Record')
see_rfc_msg = _("(see RFC %s for details)")
cli_name_format = "%s_%s"
format_error_msg = None
kwargs = Str.kwargs + (
('validatedns', bool, True),
('normalizedns', bool, True),
)
# should be replaced in subclasses
rrtype = None
rfc = None
def __init__(self, name=None, *rules, **kw):
if self.rrtype not in _record_types:
raise ValueError("Unknown RR type: %s. Must be one of %s" % \
(str(self.rrtype), ", ".join(_record_types)))
if not name:
name = "%s*" % (record_name_format % self.rrtype.lower())
kw.setdefault('cli_name', '%s_rec' % self.rrtype.lower())
kw.setdefault('label', self.label_format % self.rrtype)
kw.setdefault('doc', self.doc_format % self.rrtype)
kw.setdefault('option_group', self.option_group_format % self.rrtype)
if not self.supported:
kw['flags'] = ('no_option',)
super(DNSRecord, self).__init__(name, *rules, **kw)
def _get_part_values(self, value):
values = value.split()
if len(values) != len(self.parts):
return None
return tuple(values)
def _part_values_to_string(self, values, idna=True):
self._validate_parts(values)
parts = []
for v in values:
if v is None:
continue
if isinstance(v, DNSName) and idna:
v = v.ToASCII()
elif not isinstance(v, unicode):
v = unicode(v)
parts.append(v)
return u" ".join(parts)
def get_parts_from_kw(self, kw, raise_on_none=True):
part_names = tuple(part_name_format % (self.rrtype.lower(), part.name)
for part in self.parts)
vals = tuple(kw.get(part_name) for part_name in part_names)
if all(val is None for val in vals):
return None
if raise_on_none:
for val_id,val in enumerate(vals):
if val is None and self.parts[val_id].required:
cli_name = self.cli_name_format % (self.rrtype.lower(), self.parts[val_id].name)
raise errors.ConversionError(name=self.name,
error=_("'%s' is a required part of DNS record") % cli_name)
return vals
def _validate_parts(self, parts):
if len(parts) != len(self.parts):
raise errors.ValidationError(name=self.name,
error=_("Invalid number of parts!"))
def _convert_scalar(self, value, index=None):
if isinstance(value, (tuple, list)):
return self._part_values_to_string(value)
return super(DNSRecord, self)._convert_scalar(value)
def normalize(self, value):
if self.normalizedns: # pylint: disable=using-constant-test
if isinstance(value, (tuple, list)):
value = tuple(
self._normalize_parts(v) for v in value \
if v is not None
)
elif value is not None:
value = (self._normalize_parts(value),)
return super(DNSRecord, self).normalize(value)
def _normalize_parts(self, value):
"""
Normalize a DNS record value using normalizers for its parts.
"""
if self.parts is None:
return value
try:
values = self._get_part_values(value)
if not values:
return value
converted_values = [ part._convert_scalar(values[part_id]) \
if values[part_id] is not None else None
for part_id, part in enumerate(self.parts)
]
new_values = [ part.normalize(converted_values[part_id]) \
for part_id, part in enumerate(self.parts) ]
value = self._convert_scalar(new_values)
except Exception:
# cannot normalize, rather return original value than fail
pass
return value
def _rule_validatedns(self, _, value):
if not self.validatedns:
return None
if value is None:
return None
if not self.supported:
return _('DNS RR type "%s" is not supported by bind-dyndb-ldap plugin') \
% self.rrtype
if self.parts is None:
return None
# validate record format
values = self._get_part_values(value)
if not values:
if not self.format_error_msg:
part_names = [part.name.upper() for part in self.parts]
if self.rfc:
see_rfc_msg = " " + self.see_rfc_msg % self.rfc
else:
see_rfc_msg = ""
return _('format must be specified as "%(format)s" %(rfcs)s') \
% dict(format=" ".join(part_names), rfcs=see_rfc_msg)
else:
return self.format_error_msg
# validate every part
for part_id, part in enumerate(self.parts):
val = part.normalize(values[part_id])
val = part.convert(val)
part.validate(val)
return None
def _convert_dnsrecord_part(self, part):
"""
All parts of DNSRecord need to be processed and modified before they
can be added to global DNS API. For example a prefix need to be added
before part name so that the name is unique in the global namespace.
"""
name = part_name_format % (self.rrtype.lower(), part.name)
cli_name = self.cli_name_format % (self.rrtype.lower(), part.name)
label = self.part_label_format % (self.rrtype, unicode(part.label))
option_group = self.option_group_format % self.rrtype
flags = list(part.flags) + ['virtual_attribute']
if not part.required:
flags.append('dnsrecord_optional')
if not self.supported:
flags.append("no_option")
return part.clone_rename(name,
cli_name=cli_name,
label=label,
required=False,
option_group=option_group,
flags=flags)
def _convert_dnsrecord_extra(self, extra):
"""
Parameters for special per-type behavior need to be processed in the
same way as record parts in _convert_dnsrecord_part().
"""
name = extra_name_format % (self.rrtype.lower(), extra.name)
cli_name = self.cli_name_format % (self.rrtype.lower(), extra.name)
label = self.part_label_format % (self.rrtype, unicode(extra.label))
option_group = self.option_group_format % self.rrtype
flags = list(extra.flags) + ['virtual_attribute']
return extra.clone_rename(name,
cli_name=cli_name,
label=label,
required=False,
option_group=option_group,
flags=flags)
def get_parts(self):
if self.parts is None:
return tuple()
return tuple(self._convert_dnsrecord_part(part) for part in self.parts)
def get_extra(self):
if self.extra is None:
return tuple()
return tuple(self._convert_dnsrecord_extra(extra) for extra in self.extra)
# callbacks for per-type special record behavior
def dnsrecord_add_pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
def dnsrecord_add_post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
class ForwardRecord(DNSRecord):
extra = (
Flag('create_reverse?',
label=_('Create reverse'),
doc=_('Create reverse record for this IP Address'),
flags=['no_update']
),
)
def dnsrecord_add_pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
reverse_option = self._convert_dnsrecord_extra(self.extra[0])
if options.get(reverse_option.name):
records = entry_attrs.get(self.name, [])
if not records:
# --<rrtype>-create-reverse is set, but there are not records
raise errors.RequirementError(name=self.name)
for record in records:
add_records_for_host_validation(self.name, keys[-1], keys[-2], record,
check_forward=False,
check_reverse=True)
setattr(context, '%s_reverse' % self.name, entry_attrs.get(self.name))
def dnsrecord_add_post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
rev_records = getattr(context, '%s_reverse' % self.name, [])
if rev_records:
# make sure we don't run this post callback action again in nested
# commands, line adding PTR record in add_records_for_host
delattr(context, '%s_reverse' % self.name)
for record in rev_records:
try:
add_records_for_host(keys[-1], keys[-2], record,
add_forward=False, add_reverse=True)
except Exception as e:
raise errors.NonFatalError(
reason=_('Cannot create reverse record for "%(value)s": %(exc)s') \
% dict(value=record, exc=unicode(e)))
class UnsupportedDNSRecord(DNSRecord):
"""
Records which are not supported by IPA CLI, but we allow to show them if
LDAP contains these records.
"""
supported = False
def _get_part_values(self, value):
return tuple()
class ARecord(ForwardRecord):
rrtype = 'A'
rfc = 1035
parts = (
Str('ip_address',
_validate_ip4addr,
label=_('IP Address'),
),
)
class A6Record(DNSRecord):
rrtype = 'A6'
rfc = 3226
parts = (
Str('data',
label=_('Record data'),
),
)
def _get_part_values(self, value):
# A6 RR type is obsolete and only a raw interface is provided
return (value,)
class AAAARecord(ForwardRecord):
rrtype = 'AAAA'
rfc = 3596
parts = (
Str('ip_address',
_validate_ip6addr,
label=_('IP Address'),
),
)
class AFSDBRecord(DNSRecord):
rrtype = 'AFSDB'
rfc = 1183
parts = (
Int('subtype?',
label=_('Subtype'),
minvalue=0,
maxvalue=65535,
),
DNSNameParam('hostname',
label=_('Hostname'),
),
)
class APLRecord(UnsupportedDNSRecord):
rrtype = 'APL'
rfc = 3123
class CERTRecord(DNSRecord):
rrtype = 'CERT'
rfc = 4398
parts = (
Int('type',
label=_('Certificate Type'),
minvalue=0,
maxvalue=65535,
),
Int('key_tag',
label=_('Key Tag'),
minvalue=0,
maxvalue=65535,
),
Int('algorithm',
label=_('Algorithm'),
minvalue=0,
maxvalue=255,
),
Str('certificate_or_crl',
label=_('Certificate/CRL'),
),
)
class CNAMERecord(DNSRecord):
rrtype = 'CNAME'
rfc = 1035
parts = (
DNSNameParam('hostname',
label=_('Hostname'),
doc=_('A hostname which this alias hostname points to'),
),
)
class DHCIDRecord(UnsupportedDNSRecord):
rrtype = 'DHCID'
rfc = 4701
class DNAMERecord(DNSRecord):
rrtype = 'DNAME'
rfc = 2672
parts = (
DNSNameParam('target',
label=_('Target'),
),
)
class DSRecord(DNSRecord):
rrtype = 'DS'
rfc = 4034
parts = (
Int('key_tag',
label=_('Key Tag'),
minvalue=0,
maxvalue=65535,
),
Int('algorithm',
label=_('Algorithm'),
minvalue=0,
maxvalue=255,
),
Int('digest_type',
label=_('Digest Type'),
minvalue=0,
maxvalue=255,
),
Str('digest',
label=_('Digest'),
pattern=r'^[0-9a-fA-F]+$',
pattern_errmsg=u'only hexadecimal digits are allowed'
),
)
class DLVRecord(DSRecord):
# must use same attributes as DSRecord
rrtype = 'DLV'
rfc = 4431
class HINFORecord(UnsupportedDNSRecord):
rrtype = 'HINFO'
rfc = 1035
class HIPRecord(UnsupportedDNSRecord):
rrtype = 'HIP'
rfc = 5205
class KEYRecord(UnsupportedDNSRecord):
# managed by BIND itself
rrtype = 'KEY'
rfc = 2535
class IPSECKEYRecord(UnsupportedDNSRecord):
rrtype = 'IPSECKEY'
rfc = 4025
class KXRecord(DNSRecord):
rrtype = 'KX'
rfc = 2230
parts = (
Int('preference',
label=_('Preference'),
doc=_('Preference given to this exchanger. Lower values are more preferred'),
minvalue=0,
maxvalue=65535,
),
DNSNameParam('exchanger',
label=_('Exchanger'),
doc=_('A host willing to act as a key exchanger'),
),
)
class LOCRecord(DNSRecord):
rrtype = 'LOC'
rfc = 1876
parts = (
Int('lat_deg',
label=_('Degrees Latitude'),
minvalue=0,
maxvalue=90,
),
Int('lat_min?',
label=_('Minutes Latitude'),
minvalue=0,
maxvalue=59,
),
Decimal('lat_sec?',
label=_('Seconds Latitude'),
minvalue='0.0',
maxvalue='59.999',
precision=3,
),
StrEnum('lat_dir',
label=_('Direction Latitude'),
values=(u'N', u'S',),
),
Int('lon_deg',
label=_('Degrees Longitude'),
minvalue=0,
maxvalue=180,
),
Int('lon_min?',
label=_('Minutes Longitude'),
minvalue=0,
maxvalue=59,
),
Decimal('lon_sec?',
label=_('Seconds Longitude'),
minvalue='0.0',
maxvalue='59.999',
precision=3,
),
StrEnum('lon_dir',
label=_('Direction Longitude'),
values=(u'E', u'W',),
),
Decimal('altitude',
label=_('Altitude'),
minvalue='-100000.00',
maxvalue='42849672.95',
precision=2,
),
Decimal('size?',
label=_('Size'),
minvalue='0.0',
maxvalue='90000000.00',
precision=2,
),
Decimal('h_precision?',
label=_('Horizontal Precision'),
minvalue='0.0',
maxvalue='90000000.00',
precision=2,
),
Decimal('v_precision?',
label=_('Vertical Precision'),
minvalue='0.0',
maxvalue='90000000.00',
precision=2,
),
)
format_error_msg = _("""format must be specified as
"d1 [m1 [s1]] {"N"|"S"} d2 [m2 [s2]] {"E"|"W"} alt["m"] [siz["m"] [hp["m"] [vp["m"]]]]"
where:
d1: [0 .. 90] (degrees latitude)
d2: [0 .. 180] (degrees longitude)
m1, m2: [0 .. 59] (minutes latitude/longitude)
s1, s2: [0 .. 59.999] (seconds latitude/longitude)
alt: [-100000.00 .. 42849672.95] BY .01 (altitude in meters)
siz, hp, vp: [0 .. 90000000.00] (size/precision in meters)
See RFC 1876 for details""")
def _get_part_values(self, value):
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 None:
return None
return tuple(x.strip() if x is not None else x for x in m.groups())
def _validate_parts(self, parts):
super(LOCRecord, self)._validate_parts(parts)
# create part_name -> part_id map first
part_name_map = dict((part.name, part_id) \
for part_id,part in enumerate(self.parts))
requirements = ( ('lat_sec', 'lat_min'),
('lon_sec', 'lon_min'),
('h_precision', 'size'),
('v_precision', 'h_precision', 'size') )
for req in requirements:
target_part = req[0]
if parts[part_name_map[target_part]] is not None:
required_parts = req[1:]
if any(parts[part_name_map[part]] is None for part in required_parts):
target_cli_name = self.cli_name_format % (self.rrtype.lower(), req[0])
required_cli_names = [ self.cli_name_format % (self.rrtype.lower(), part)
for part in req[1:] ]
error = _("'%(required)s' must not be empty when '%(name)s' is set") % \
dict(required=', '.join(required_cli_names),
name=target_cli_name)
raise errors.ValidationError(name=self.name, error=error)
class MDRecord(UnsupportedDNSRecord):
# obsoleted, use MX instead
rrtype = 'MD'
rfc = 1035
class MINFORecord(UnsupportedDNSRecord):
rrtype = 'MINFO'
rfc = 1035
class MXRecord(DNSRecord):
rrtype = 'MX'
rfc = 1035
parts = (
Int('preference',
label=_('Preference'),
doc=_('Preference given to this exchanger. Lower values are more preferred'),
minvalue=0,
maxvalue=65535,
),
DNSNameParam('exchanger',
label=_('Exchanger'),
doc=_('A host willing to act as a mail exchanger'),
),
)
class NSRecord(DNSRecord):
rrtype = 'NS'
rfc = 1035
parts = (
DNSNameParam('hostname',
label=_('Hostname'),
),
)
class NSECRecord(UnsupportedDNSRecord):
# managed by BIND itself
rrtype = 'NSEC'
rfc = 4034
def _validate_naptr_flags(ugettext, flags):
allowed_flags = u'SAUP'
flags = flags.replace('"','').replace('\'','')
for flag in flags:
if flag not in allowed_flags:
return _('flags must be one of "S", "A", "U", or "P"')
return None
class NAPTRRecord(DNSRecord):
rrtype = 'NAPTR'
rfc = 2915
parts = (
Int('order',
label=_('Order'),
minvalue=0,
maxvalue=65535,
),
Int('preference',
label=_('Preference'),
minvalue=0,
maxvalue=65535,
),
Str('flags',
_validate_naptr_flags,
label=_('Flags'),
normalizer=lambda x:x.upper()
),
Str('service',
label=_('Service'),
),
Str('regexp',
label=_('Regular Expression'),
),
Str('replacement',
label=_('Replacement'),
),
)
class NXTRecord(UnsupportedDNSRecord):
rrtype = 'NXT'
rfc = 2535
class PTRRecord(DNSRecord):
rrtype = 'PTR'
rfc = 1035
parts = (
DNSNameParam('hostname',
#RFC 2317 section 5.2 -- can be relative
label=_('Hostname'),
doc=_('The hostname this reverse record points to'),
),
)
class RPRecord(UnsupportedDNSRecord):
rrtype = 'RP'
rfc = 1183
class SRVRecord(DNSRecord):
rrtype = 'SRV'
rfc = 2782
parts = (
Int('priority',
label=_('Priority (order)'),
doc=_('Lower number means higher priority. Clients will attempt '
'to contact the server with the lowest-numbered priority '
'they can reach.'),
minvalue=0,
maxvalue=65535,
),
Int('weight',
label=_('Weight'),
doc=_('Relative weight for entries with the same priority.'),
minvalue=0,
maxvalue=65535,
),
Int('port',
label=_('Port'),
minvalue=0,
maxvalue=65535,
),
DNSNameParam('target',
label=_('Target'),
doc=_('The domain name of the target host or \'.\' if the service is decidedly not available at this domain'),
),
)
def _sig_time_validator(ugettext, value):
time_format = "%Y%m%d%H%M%S"
try:
time.strptime(value, time_format)
except ValueError:
return _('the value does not follow "YYYYMMDDHHMMSS" time format')
return None
class SIGRecord(UnsupportedDNSRecord):
# managed by BIND itself
rrtype = 'SIG'
rfc = 2535
class SPFRecord(UnsupportedDNSRecord):
rrtype = 'SPF'
rfc = 4408
class RRSIGRecord(UnsupportedDNSRecord):
# managed by BIND itself
rrtype = 'RRSIG'
rfc = 4034
class SSHFPRecord(DNSRecord):
rrtype = 'SSHFP'
rfc = 4255
parts = (
Int('algorithm',
label=_('Algorithm'),
minvalue=0,
maxvalue=255,
),
Int('fp_type',
label=_('Fingerprint Type'),
minvalue=0,
maxvalue=255,
),
Str('fingerprint',
label=_('Fingerprint'),
),
)
def _get_part_values(self, value):
# fingerprint part can contain space in LDAP, return it as one part
values = value.split(None, 2)
if len(values) != len(self.parts):
return None
return tuple(values)
class TLSARecord(DNSRecord):
rrtype = 'TLSA'
rfc = 6698
parts = (
Int('cert_usage',
label=_('Certificate Usage'),
minvalue=0,
maxvalue=255,
),
Int('selector',
label=_('Selector'),
minvalue=0,
maxvalue=255,
),
Int('matching_type',
label=_('Matching Type'),
minvalue=0,
maxvalue=255,
),
Str('cert_association_data',
label=_('Certificate Association Data'),
),
)
class TXTRecord(DNSRecord):
rrtype = 'TXT'
rfc = 1035
parts = (
Str('data',
label=_('Text Data'),
),
)
def _get_part_values(self, value):
# ignore any space in TXT record
return (value,)
def _normalize_uri_target(uri_target):
r"""DNS-escape "\ characters and double-quote target."""
# is user-provided string is already quoted?
if uri_target[0:1] == uri_target[-1:] == '"':
uri_target = uri_target[1:-1]
# RFC 7553 section 4.4: The Target MUST NOT be an empty URI ("").
# minlength in param will detect this
if not uri_target:
return None
return u'"{0}"'.format(uri_target)
class URIRecord(DNSRecord):
rrtype = 'URI'
rfc = 7553
parts = (
Int('priority',
label=_('Priority (order)'),
doc=_('Lower number means higher priority. Clients will attempt '
'to contact the URI with the lowest-numbered priority '
'they can reach.'),
minvalue=0,
maxvalue=65535,
),
Int('weight',
label=_('Weight'),
doc=_('Relative weight for entries with the same priority.'),
minvalue=0,
maxvalue=65535,
),
Str('target',
label=_('Target Uniform Resource Identifier'),
doc=_('Target Uniform Resource Identifier according to RFC 3986'),
minlength=1,
# This field holds the URI of the target, enclosed in double-quote
# characters (e.g. "uri:").
normalizer=_normalize_uri_target,
),
)
_dns_records = (
ARecord(),
AAAARecord(),
A6Record(),
AFSDBRecord(),
APLRecord(),
CERTRecord(),
CNAMERecord(),
DHCIDRecord(),
DLVRecord(),
DNAMERecord(),
DSRecord(),
HIPRecord(),
IPSECKEYRecord(),
KEYRecord(),
KXRecord(),
LOCRecord(),
MXRecord(),
NAPTRRecord(),
NSRecord(),
NSECRecord(),
PTRRecord(),
RRSIGRecord(),
RPRecord(),
SIGRecord(),
SPFRecord(),
SRVRecord(),
SSHFPRecord(),
TLSARecord(),
TXTRecord(),
URIRecord(),
)
def __dns_record_options_iter():
for opt in (Any('dnsrecords?',
label=_('Records'),
flags=['no_create', 'no_search', 'no_update'],),
Str('dnstype?',
label=_('Record type'),
flags=['no_create', 'no_search', 'no_update'],),
Str('dnsdata?',
label=_('Record data'),
flags=['no_create', 'no_search', 'no_update'],)):
# These 3 options are used in --structured format. They are defined
# rather in takes_params than has_output_params because of their
# order - they should be printed to CLI before any DNS part param
yield opt
for option in _dns_records:
yield option
for part in option.get_parts():
yield part
for extra in option.get_extra():
yield extra
_dns_record_options = tuple(__dns_record_options_iter())
def check_ns_rec_resolvable(zone, name):
assert isinstance(zone, DNSName)
assert isinstance(name, DNSName)
if name.is_empty():
name = zone.make_absolute()
elif not name.is_absolute():
# this is a DNS name relative to the zone
name = name.derelativize(zone.make_absolute())
try:
verify_host_resolvable(name)
except errors.DNSNotARecordError:
raise errors.NotFound(
reason=_('Nameserver \'%(host)s\' does not have a corresponding '
'A/AAAA record') % {'host': name}
)
def dns_container_exists(ldap):
try:
ldap.get_entry(DN(api.env.container_dns, api.env.basedn), [])
except errors.NotFound:
return False
return True
def dnssec_installed(ldap):
"""
* Method opendnssecinstance.get_dnssec_key_masters() CANNOT be used in the
dns plugin, or any plugin accessible for common users! *
Why?: The content of service container is not readable for common users.
This method only try to find if a DNSSEC service container exists on any
replica. What means that DNSSEC key master is installed.
:param ldap: ldap connection
:return: True if DNSSEC was installed, otherwise False
"""
return is_service_enabled('DNSSEC', conn=ldap)
def default_zone_update_policy(zone):
if zone.is_reverse():
return get_dns_reverse_zone_update_policy(api.env.realm, zone.ToASCII())
else:
return get_dns_forward_zone_update_policy(api.env.realm)
def _convert_to_idna(value):
"""
Function converts a unicode value to idna, without extra validation.
If conversion fails, None is returned
"""
assert isinstance(value, unicode)
try:
idna_val = value
start_dot = u''
end_dot = u''
if idna_val.startswith(u'.'):
idna_val = idna_val[1:]
start_dot = u'.'
if idna_val.endswith(u'.'):
idna_val = idna_val[:-1]
end_dot = u'.'
idna_val = encodings.idna.nameprep(idna_val)
idna_val = re.split(r'(?<!\\)\.', idna_val)
idna_val = u'%s%s%s' % (start_dot,
u'.'.join(
encodings.idna.ToASCII(x).decode('ascii')
for x in idna_val),
end_dot)
return idna_val
except Exception:
pass
return None
def _create_idn_filter(cmd, ldap, term=None, **options):
if term:
#include idna values to search
term_idna = _convert_to_idna(term)
if term_idna and term != term_idna:
term = (term, term_idna)
search_kw = {}
attr_extra_filters = []
for attr, value in cmd.args_options_2_entry(**options).items():
if not isinstance(value, list):
value = [value]
for i, v in enumerate(value):
if isinstance(v, DNSName):
value[i] = v.ToASCII()
elif attr in map_names_to_records:
record = map_names_to_records[attr]
parts = record._get_part_values(v)
if parts is None:
value[i] = v
continue
try:
value[i] = record._part_values_to_string(parts)
except errors.ValidationError:
value[i] = v
#create MATCH_ANY filter for multivalue
if len(value) > 1:
f = ldap.make_filter({attr: value}, rules=ldap.MATCH_ANY)
attr_extra_filters.append(f)
else:
search_kw[attr] = value
if cmd.obj.search_attributes:
search_attrs = cmd.obj.search_attributes
else:
search_attrs = cmd.obj.default_attributes
if cmd.obj.search_attributes_config:
config = ldap.get_ipa_config()
config_attrs = config.get(cmd.obj.search_attributes_config, [])
if len(config_attrs) == 1 and (isinstance(config_attrs[0],
str)):
search_attrs = config_attrs[0].split(',')
search_kw['objectclass'] = cmd.obj.object_class
attr_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
if attr_extra_filters:
#combine filter if there is any idna value
attr_extra_filters.append(attr_filter)
attr_filter = ldap.combine_filters(attr_extra_filters,
rules=ldap.MATCH_ALL)
search_kw = {}
for a in search_attrs:
search_kw[a] = term
term_filter = ldap.make_filter(search_kw, exact=False)
member_filter = cmd.get_member_filter(ldap, **options)
filter = ldap.combine_filters(
(term_filter, attr_filter, member_filter), rules=ldap.MATCH_ALL
)
return filter
map_names_to_records = {record_name_format % record.rrtype.lower(): record
for record in _dns_records if record.supported}
def _records_idn_postprocess(record, **options):
for attr in record.keys():
attr = attr.lower()
try:
param = map_names_to_records[attr]
except KeyError:
continue
if not isinstance(param, DNSRecord):
continue
part_params = param.get_parts()
rrs = []
for dnsvalue in record[attr]:
parts = param._get_part_values(dnsvalue)
if parts is None:
continue
parts = list(parts)
try:
for (i, p) in enumerate(parts):
if isinstance(part_params[i], DNSNameParam):
parts[i] = DNSName(p)
rrs.append(param._part_values_to_string(parts,
idna=options.get('raw', False)))
except (errors.ValidationError, errors.ConversionError):
rrs.append(dnsvalue)
record[attr] = rrs
def _normalize_zone(zone):
if isinstance(zone, unicode):
# normalize only non-IDNA zones
try:
zone.encode('ascii')
except UnicodeError:
pass
else:
return zone.lower()
return zone
def _get_auth_zone_ldap(api, name):
"""
Find authoritative zone in LDAP for name. Only active zones are considered.
:param name:
:return: (zone, truncated)
zone: authoritative zone, or None if authoritative zone is not in LDAP
"""
assert isinstance(name, DNSName)
ldap = api.Backend.ldap2
# Create all possible parent zone names
search_name = name.make_absolute()
zone_names = []
for i, name in enumerate(search_name):
zone_name_abs = DNSName(search_name[i:]).ToASCII()
zone_names.append(zone_name_abs)
# compatibility with IPA < 4.0, zone name can be relative
zone_names.append(zone_name_abs[:-1])
# Create filters
objectclass_filter = ldap.make_filter({'objectclass':'idnszone'})
zonenames_filter = ldap.make_filter({'idnsname': zone_names})
zoneactive_filter = ldap.make_filter({'idnsZoneActive': 'true'})
complete_filter = ldap.combine_filters(
[objectclass_filter, zonenames_filter, zoneactive_filter],
rules=ldap.MATCH_ALL
)
try:
entries, truncated = ldap.find_entries(
filter=complete_filter,
attrs_list=['idnsname'],
base_dn=DN(api.env.container_dns, api.env.basedn),
scope=ldap.SCOPE_ONELEVEL
)
except errors.NotFound:
return None, False
# always use absolute zones
matched_auth_zones = [entry.single_value['idnsname'].make_absolute()
for entry in entries]
# return longest match
return max(matched_auth_zones, key=len), truncated
def _get_longest_match_ns_delegation_ldap(api, zone, name):
"""
Searches for deepest delegation for name in LDAP zone.
NOTE: NS record in zone apex is not considered as delegation.
It returns None if there is no delegation outside of zone apex.
Example:
zone: example.com.
name: ns.sub.example.com.
records:
extra.ns.sub.example.com.
sub.example.com.
example.com
result: sub.example.com.
:param zone: zone name
:param name:
:return: (match, truncated);
match: delegation name if success, or None if no delegation record exists
"""
assert isinstance(zone, DNSName)
assert isinstance(name, DNSName)
ldap = api.Backend.ldap2
# get zone DN
zone_dn = api.Object.dnszone.get_dn(zone)
if name.is_absolute():
relative_record_name = name.relativize(zone.make_absolute())
else:
relative_record_name = name
# Name is zone apex
if relative_record_name.is_empty():
return None, False
# create list of possible record names
possible_record_names = [DNSName(relative_record_name[i:]).ToASCII()
for i in range(len(relative_record_name))]
# search filters
name_filter = ldap.make_filter({'idnsname': [possible_record_names]})
objectclass_filter = ldap.make_filter({'objectclass': 'idnsrecord'})
complete_filter = ldap.combine_filters(
[name_filter, objectclass_filter],
rules=ldap.MATCH_ALL
)
try:
entries, truncated = ldap.find_entries(
filter=complete_filter,
attrs_list=['idnsname', 'nsrecord'],
base_dn=zone_dn,
scope=ldap.SCOPE_ONELEVEL
)
except errors.NotFound:
return None, False
matched_records = []
# test if entry contains NS records
for entry in entries:
if entry.get('nsrecord'):
matched_records.append(entry.single_value['idnsname'])
if not matched_records:
return None, truncated
# return longest match
return max(matched_records, key=len), truncated
def _find_subtree_forward_zones_ldap(api, name, child_zones_only=False):
"""
Search for forwardzone <name> and all child forwardzones
Filter: (|(*.<name>.)(<name>.))
:param name:
:param child_zones_only: search only for child zones
:return: (list of zonenames, truncated), list is empty if no zone found
"""
assert isinstance(name, DNSName)
ldap = api.Backend.ldap2
# prepare for filter "*.<name>."
search_name = u".%s" % name.make_absolute().ToASCII()
# we need to search zone with and without last dot, due compatibility
# with IPA < 4.0
search_names = [search_name, search_name[:-1]]
# Create filters
objectclass_filter = ldap.make_filter({'objectclass':'idnsforwardzone'})
zonenames_filter = ldap.make_filter({'idnsname': search_names}, exact=False,
trailing_wildcard=False)
if not child_zones_only:
# find also zone with exact name
exact_name = name.make_absolute().ToASCII()
# we need to search zone with and without last dot, due compatibility
# with IPA < 4.0
exact_names = [exact_name, exact_name[-1]]
exact_name_filter = ldap.make_filter({'idnsname': exact_names})
zonenames_filter = ldap.combine_filters([zonenames_filter,
exact_name_filter])
zoneactive_filter = ldap.make_filter({'idnsZoneActive': 'true'})
complete_filter = ldap.combine_filters(
[objectclass_filter, zonenames_filter, zoneactive_filter],
rules=ldap.MATCH_ALL
)
try:
entries, truncated = ldap.find_entries(
filter=complete_filter,
attrs_list=['idnsname'],
base_dn=DN(api.env.container_dns, api.env.basedn),
scope=ldap.SCOPE_ONELEVEL
)
except errors.NotFound:
return [], False
result = [entry.single_value['idnsname'].make_absolute()
for entry in entries]
return result, truncated
def _get_zone_which_makes_fw_zone_ineffective(api, fwzonename):
"""
Check if forward zone is effective.
If parent zone exists as authoritative zone, the forward zone will not
forward queries by default. It is necessary to delegate authority
to forward zone with a NS record.
Example:
Forward zone: sub.example.com
Zone: example.com
Forwarding will not work, because the server thinks it is authoritative
for zone and will return NXDOMAIN
Adding record: sub.example.com NS ns.sub.example.com.
will delegate authority, and IPA DNS server will forward DNS queries.
:param fwzonename: forwardzone
:return: (zone, truncated)
zone: None if effective, name of authoritative zone otherwise
"""
assert isinstance(fwzonename, DNSName)
auth_zone, truncated_zone = _get_auth_zone_ldap(api, fwzonename)
if not auth_zone:
return None, truncated_zone
delegation_record_name, truncated_ns =\
_get_longest_match_ns_delegation_ldap(api, auth_zone, fwzonename)
truncated = truncated_ns or truncated_zone
if delegation_record_name:
return None, truncated
return auth_zone, truncated
def _add_warning_fw_zone_is_not_effective(api, result, fwzone, version):
"""
Adds warning message to result, if required
"""
(
authoritative_zone, _truncated
) = _get_zone_which_makes_fw_zone_ineffective(api, fwzone)
if authoritative_zone:
# forward zone is not effective and forwarding will not work
messages.add_message(
version, result,
messages.ForwardzoneIsNotEffectiveWarning(
fwzone=fwzone, authzone=authoritative_zone,
ns_rec=fwzone.relativize(authoritative_zone)
)
)
def _add_warning_fw_policy_conflict_aez(result, fwzone, **options):
"""Warn if forwarding policy conflicts with an automatic empty zone."""
fwd_policy = result['result'].get(u'idnsforwardpolicy',
dnsforwardzone.default_forward_policy)
if (
fwd_policy != [u'only']
and related_to_auto_empty_zone(DNSName(fwzone))
):
messages.add_message(
options['version'], result,
messages.DNSForwardPolicyConflictWithEmptyZone()
)
class DNSZoneBase(LDAPObject):
"""
Base class for DNS Zone
"""
container_dn = api.env.container_dns
object_class = ['top']
possible_objectclasses = ['ipadnszone']
default_attributes = [
'idnsname', 'idnszoneactive', 'idnsforwarders', 'idnsforwardpolicy'
]
takes_params = (
DNSNameParam('idnsname',
_no_wildcard_validator, # RFC 4592 section 4
only_absolute=True,
cli_name='name',
label=_('Zone name'),
doc=_('Zone name (FQDN)'),
default_from=lambda name_from_ip: _reverse_zone_name(name_from_ip),
normalizer=_normalize_zone,
primary_key=True,
),
Str('name_from_ip?', _validate_ipnet,
label=_('Reverse zone IP network'),
doc=_('IP network to create reverse zone name from'),
flags=('virtual_attribute',),
),
Bool('idnszoneactive?',
cli_name='zone_active',
label=_('Active zone'),
doc=_('Is zone active?'),
flags=['no_create', 'no_update'],
attribute=True,
),
Str('idnsforwarders*',
validate_bind_forwarder,
cli_name='forwarder',
label=_('Zone forwarders'),
doc=_('Per-zone forwarders. A custom port can be specified '
'for each forwarder using a standard format "IP_ADDRESS port PORT"'),
),
StrEnum('idnsforwardpolicy?',
cli_name='forward_policy',
label=_('Forward policy'),
doc=_('Per-zone conditional forwarding policy. Set to "none" to '
'disable forwarding to global forwarder for this zone. In '
'that case, conditional zone forwarders are disregarded.'),
values=(u'only', u'first', u'none'),
),
Str('managedby',
label=_('Managedby permission'),
flags={'virtual_attribute', 'no_create', 'no_search', 'no_update'},
),
)
def get_dn(self, *keys, **options):
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('DNS is not configured'))
zone = keys[-1]
assert isinstance(zone, DNSName)
assert zone.is_absolute()
zone_a = zone.ToASCII()
# special case when zone is the root zone ('.')
if zone == DNSName.root:
return super(DNSZoneBase, self).get_dn(zone_a, **options)
# try first relative name, a new zone has to be added as absolute
# otherwise ObjectViolation is raised
zone_a = zone_a[:-1]
dn = super(DNSZoneBase, self).get_dn(zone_a, **options)
try:
self.backend.get_entry(dn, [''])
except errors.NotFound:
zone_a = u"%s." % zone_a
dn = super(DNSZoneBase, self).get_dn(zone_a, **options)
return dn
def permission_name(self, zone):
assert isinstance(zone, DNSName)
return u"Manage DNS zone %s" % zone.ToASCII()
def get_name_in_zone(self, zone, hostname):
"""
Get name of a record that is to be added to a new zone. I.e. when
we want to add record "ipa.lab.example.com" in a zone "example.com",
this function should return "ipa.lab". Returns None when record cannot
be added to a zone. Returns '@' when the hostname is the zone record.
"""
assert isinstance(zone, DNSName)
assert zone.is_absolute()
assert isinstance(hostname, DNSName)
if not hostname.is_absolute():
return hostname
if hostname.is_subdomain(zone):
return hostname.relativize(zone)
return None
def _remove_permission(self, zone):
permission_name = self.permission_name(zone)
try:
self.api.Command['permission_del'](permission_name, force=True)
except errors.NotFound as e:
if zone == DNSName.root: # special case root zone
raise
# compatibility, older IPA versions which allows to create zone
# without absolute zone name
permission_name_rel = self.permission_name(
zone.relativize(DNSName.root)
)
try:
self.api.Command['permission_del'](permission_name_rel,
force=True)
except errors.NotFound:
raise e # re-raise original exception
def _make_zonename_absolute(self, entry_attrs, **options):
"""
Zone names can be relative in IPA < 4.0, make sure we always return
absolute zone name from ldap
"""
if options.get('raw'):
return
if "idnsname" in entry_attrs:
entry_attrs.single_value['idnsname'] = (
entry_attrs.single_value['idnsname'].make_absolute())
class DNSZoneBase_add(LDAPCreate):
takes_options = LDAPCreate.takes_options + (
Flag('skip_overlap_check',
doc=_('Force DNS zone creation even if it will overlap with '
'an existing zone.')
),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if options.get('name_from_ip'):
zone = _reverse_zone_name(options.get('name_from_ip'))
if keys[-1] != DNSName(zone):
raise errors.ValidationError(
name='name-from-ip',
error=_("cannot be used when a zone is specified")
)
try:
entry = ldap.get_entry(dn)
except errors.NotFound:
pass
else:
if _check_entry_objectclass(entry, self.obj.object_class):
self.obj.handle_duplicate_entry(*keys)
else:
raise errors.DuplicateEntry(
message=_(u'Only one zone type is allowed per zone name')
)
entry_attrs['idnszoneactive'] = True
if not options['skip_overlap_check']:
try:
check_zone_overlap(keys[-1], raise_on_error=False)
except DNSZoneAlreadyExists as e:
raise errors.InvocationError(str(e))
return dn
class DNSZoneBase_del(LDAPDelete):
def pre_callback(self, ldap, dn, *nkeys, **options):
assert isinstance(dn, DN)
if not _check_DN_objectclass(ldap, dn, self.obj.object_class):
raise self.obj.handle_not_found(*nkeys)
return dn
def post_callback(self, ldap, dn, *keys, **options):
try:
self.obj._remove_permission(keys[-1])
except errors.NotFound:
pass
return True
class DNSZoneBase_mod(LDAPUpdate):
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._make_zonename_absolute(entry_attrs, **options)
return dn
class DNSZoneBase_find(LDAPSearch):
__doc__ = _('Search for DNS zones (SOA records).')
def args_options_2_params(self, *args, **options):
# FIXME: Check that name_from_ip is valid. This is necessary because
# custom validation rules, including _validate_ipnet, are not
# used when doing a search. Once we have a parameter type for
# IP network objects, this will no longer be necessary, as the
# parameter type will handle the validation itself (see
# <https://fedorahosted.org/freeipa/ticket/2266>).
if 'name_from_ip' in options:
self.obj.params['name_from_ip'](unicode(options['name_from_ip']))
return super(DNSZoneBase_find, self).args_options_2_params(*args, **options)
def args_options_2_entry(self, *args, **options):
if 'name_from_ip' in options:
if 'idnsname' not in options:
options['idnsname'] = self.obj.params['idnsname'].get_default(**options)
del options['name_from_ip']
search_kw = super(DNSZoneBase_find, self).args_options_2_entry(*args,
**options)
name = search_kw.get('idnsname')
if name:
search_kw['idnsname'] = [name, name.relativize(DNSName.root)]
return search_kw
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
# Check if DNS container exists must be here for find methods
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('DNS is not configured'))
filter = _create_idn_filter(self, ldap, *args, **options)
return (filter, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
for entry_attrs in entries:
self.obj._make_zonename_absolute(entry_attrs, **options)
return truncated
class DNSZoneBase_show(LDAPRetrieve):
def pre_callback(self, ldap, dn, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if not _check_DN_objectclass(ldap, dn, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
return dn
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
self.obj._make_zonename_absolute(entry_attrs, **options)
return dn
class DNSZoneBase_disable(LDAPQuery):
has_output = output.standard_value
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
try:
entry = ldap.get_entry(dn, ['idnszoneactive', 'objectclass'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if not _check_entry_objectclass(entry, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
entry['idnszoneactive'] = [False]
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
return dict(result=True, value=pkey_to_value(keys[-1], options))
class DNSZoneBase_enable(LDAPQuery):
has_output = output.standard_value
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
try:
entry = ldap.get_entry(dn, ['idnszoneactive', 'objectclass'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if not _check_entry_objectclass(entry, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
entry['idnszoneactive'] = [True]
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
pass
return dict(result=True, value=pkey_to_value(keys[-1], options))
class DNSZoneBase_add_permission(LDAPQuery):
has_output = _output_permissions
msg_summary = _('Added system permission "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
try:
entry_attrs = ldap.get_entry(dn, ['objectclass'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
else:
if not _check_entry_objectclass(
entry_attrs, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
permission_name = self.obj.permission_name(keys[-1])
# compatibility with older IPA versions which allows relative zonenames
if keys[-1] != DNSName.root: # special case root zone
permission_name_rel = self.obj.permission_name(
keys[-1].relativize(DNSName.root)
)
try:
self.api.Object['permission'].get_dn_if_exists(
permission_name_rel)
except errors.NotFound:
pass
else:
# permission exists without absolute domain name
raise errors.DuplicateEntry(
message=_('permission "%(value)s" already exists') % {
'value': permission_name
}
)
permission = self.api.Command['permission_add_noaci'](permission_name,
ipapermissiontype=u'SYSTEM'
)['result']
dnszone_ocs = entry_attrs.get('objectclass')
if dnszone_ocs:
for oc in dnszone_ocs:
if oc.lower() == 'ipadnszone':
break
else:
dnszone_ocs.append('ipadnszone')
entry_attrs['managedby'] = [permission['dn']]
ldap.update_entry(entry_attrs)
return dict(
result=True,
value=pkey_to_value(permission_name, options),
)
class DNSZoneBase_remove_permission(LDAPQuery):
has_output = _output_permissions
msg_summary = _('Removed system permission "%(value)s"')
def execute(self, *keys, **options):
ldap = self.obj.backend
dn = self.obj.get_dn(*keys, **options)
try:
entry = ldap.get_entry(dn, ['managedby', 'objectclass'])
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
else:
if not _check_entry_objectclass(entry, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
entry['managedby'] = None
try:
ldap.update_entry(entry)
except errors.EmptyModlist:
# managedBy attribute is clean, lets make sure there is also no
# dangling DNS zone permission
pass
permission_name = self.obj.permission_name(keys[-1])
self.obj._remove_permission(keys[-1])
return dict(
result=True,
value=pkey_to_value(permission_name, options),
)
@register()
class dnszone(DNSZoneBase):
"""
DNS Zone, container for resource records.
"""
object_name = _('DNS zone')
object_name_plural = _('DNS zones')
object_class = DNSZoneBase.object_class + ['idnsrecord', 'idnszone']
default_attributes = DNSZoneBase.default_attributes + [
'idnssoamname', 'idnssoarname', 'idnssoaserial', 'idnssoarefresh',
'idnssoaretry', 'idnssoaexpire', 'idnssoaminimum', 'idnsallowquery',
'idnsallowtransfer', 'idnssecinlinesigning', 'idnsallowdynupdate',
'idnsupdatepolicy'
] + _record_attributes
label = _('DNS Zones')
label_singular = _('DNS Zone')
takes_params = DNSZoneBase.takes_params + (
DNSNameParam('idnssoamname?',
cli_name='name_server',
label=_('Authoritative nameserver'),
doc=_('Authoritative nameserver domain name'),
default=None, # value will be added in precallback from ldap
),
DNSNameParam('idnssoarname',
_rname_validator,
cli_name='admin_email',
label=_('Administrator e-mail address'),
doc=_('Administrator e-mail address'),
default=DNSName(u'hostmaster'),
normalizer=normalize_zonemgr,
autofill=True,
),
Int('idnssoaserial?',
# Deprecated
cli_name='serial',
label=_('SOA serial'),
doc=_('SOA record serial number'),
minvalue=1,
maxvalue=4294967295,
deprecated=True,
flags=['no_option'],
),
Int('idnssoarefresh',
cli_name='refresh',
label=_('SOA refresh'),
doc=_('SOA record refresh time'),
minvalue=0,
maxvalue=2147483647,
default=3600,
autofill=True,
),
Int('idnssoaretry',
cli_name='retry',
label=_('SOA retry'),
doc=_('SOA record retry time'),
minvalue=0,
maxvalue=2147483647,
default=900,
autofill=True,
),
Int('idnssoaexpire',
cli_name='expire',
label=_('SOA expire'),
doc=_('SOA record expire time'),
default=1209600,
minvalue=0,
maxvalue=2147483647,
autofill=True,
),
Int('idnssoaminimum',
cli_name='minimum',
label=_('SOA minimum'),
doc=_('How long should negative responses be cached'),
default=3600,
minvalue=0,
maxvalue=2147483647,
autofill=True,
),
Int('dnsttl?',
cli_name='ttl',
label=_('Time to live'),
doc=_('Time to live for records at zone apex'),
minvalue=0,
maxvalue=2147483647, # see RFC 2181
),
Int('dnsdefaultttl?',
cli_name='default_ttl',
label=_('Default time to live'),
doc=_('Time to live for records without explicit TTL definition'),
minvalue=0,
maxvalue=2147483647, # see RFC 2181
),
StrEnum('dnsclass?',
# Deprecated
cli_name='class',
flags=['no_option'],
values=_record_classes,
),
Str('idnsupdatepolicy?',
cli_name='update_policy',
label=_('BIND update policy'),
doc=_('BIND update policy'),
default_from=lambda idnsname: default_zone_update_policy(idnsname),
autofill=True
),
Bool('idnsallowdynupdate?',
cli_name='dynamic_update',
label=_('Dynamic update'),
doc=_('Allow dynamic updates.'),
attribute=True,
default=False,
autofill=True
),
Str('idnsallowquery?',
_validate_bind_aci,
normalizer=_normalize_bind_aci,
cli_name='allow_query',
label=_('Allow query'),
doc=_('Semicolon separated list of IP addresses or networks which are allowed to issue queries'),
default=u'any;', # anyone can issue queries by default
autofill=True,
),
Str('idnsallowtransfer?',
_validate_bind_aci,
normalizer=_normalize_bind_aci,
cli_name='allow_transfer',
label=_('Allow transfer'),
doc=_('Semicolon separated list of IP addresses or networks which are allowed to transfer the zone'),
default=u'none;', # no one can issue queries by default
autofill=True,
),
Bool('idnsallowsyncptr?',
cli_name='allow_sync_ptr',
label=_('Allow PTR sync'),
doc=_('Allow synchronization of forward (A, AAAA) and reverse (PTR) records in the zone'),
),
Bool('idnssecinlinesigning?',
cli_name='dnssec',
default=False,
label=_('Allow in-line DNSSEC signing'),
doc=_('Allow inline DNSSEC signing of records in the zone'),
),
Str('nsec3paramrecord?',
_validate_nsec3param_record,
cli_name='nsec3param_rec',
label=_('NSEC3PARAM record'),
doc=_('NSEC3PARAM record for zone in format: hash_algorithm flags iterations salt'),
pattern=r'^\d+ \d+ \d+ (([0-9a-fA-F]{2})+|-)$',
pattern_errmsg=(u'expected format: <0-255> <0-255> <0-65535> '
'even-length_hexadecimal_digits_or_hyphen'),
),
)
# Permissions will be apllied for forwardzones too
# Store permissions into api.env.basedn, dns container could not exists
managed_permissions = {
'System: Add DNS Entries': {
'non_object': True,
'ipapermright': {'add'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('idnsname=*', 'cn=dns', api.env.basedn),
'replaces': [
'(target = "ldap:///idnsname=*,cn=dns,$SUFFIX")(version 3.0;acl "permission:add dns entries";allow (add) groupdn = "ldap:///cn=add dns entries,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
'System: Read DNS Entries': {
'non_object': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('idnsname=*', 'cn=dns', api.env.basedn),
'ipapermdefaultattr': {
'objectclass',
'a6record', 'aaaarecord', 'afsdbrecord', 'aplrecord', 'arecord',
'certrecord', 'cn', 'cnamerecord', 'dhcidrecord', 'dlvrecord',
'dnamerecord', 'dnsclass', 'dnsdefaultttl', 'dnsttl',
'dsrecord', 'hinforecord', 'hiprecord', 'idnsallowdynupdate',
'idnsallowquery', 'idnsallowsyncptr', 'idnsallowtransfer',
'idnsforwarders', 'idnsforwardpolicy', 'idnsname',
'idnssecinlinesigning', 'idnssoaexpire', 'idnssoaminimum',
'idnssoamname', 'idnssoarefresh', 'idnssoaretry',
'idnssoarname', 'idnssoaserial', 'idnsTemplateAttribute',
'idnsupdatepolicy',
'idnszoneactive', 'ipseckeyrecord','keyrecord', 'kxrecord',
'locrecord', 'managedby', 'mdrecord', 'minforecord',
'mxrecord', 'naptrrecord', 'nsecrecord', 'nsec3paramrecord',
'nsrecord', 'nxtrecord', 'ptrrecord', 'rprecord', 'rrsigrecord',
'sigrecord', 'spfrecord', 'srvrecord', 'sshfprecord',
'tlsarecord', 'txtrecord', 'urirecord', 'unknownrecord',
},
'replaces_system': ['Read DNS Entries'],
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
'System: Remove DNS Entries': {
'non_object': True,
'ipapermright': {'delete'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('idnsname=*', 'cn=dns', api.env.basedn),
'replaces': [
'(target = "ldap:///idnsname=*,cn=dns,$SUFFIX")(version 3.0;acl "permission:remove dns entries";allow (delete) groupdn = "ldap:///cn=remove dns entries,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
'System: Update DNS Entries': {
'non_object': True,
'ipapermright': {'write'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('idnsname=*', 'cn=dns', api.env.basedn),
'ipapermdefaultattr': {
'objectclass', # needed for record templates
'a6record', 'aaaarecord', 'afsdbrecord', 'aplrecord', 'arecord',
'certrecord', 'cn', 'cnamerecord', 'dhcidrecord', 'dlvrecord',
'dnamerecord', 'dnsclass', 'dnsdefaultttl', 'dnsttl',
'dsrecord', 'hinforecord', 'hiprecord', 'idnsallowdynupdate',
'idnsallowquery', 'idnsallowsyncptr', 'idnsallowtransfer',
'idnsforwarders', 'idnsforwardpolicy', 'idnsname',
'idnssecinlinesigning', 'idnssoaexpire', 'idnssoaminimum',
'idnssoamname', 'idnssoarefresh', 'idnssoaretry',
'idnssoarname', 'idnssoaserial', 'idnsTemplateAttribute',
'idnsupdatepolicy',
'idnszoneactive', 'ipseckeyrecord','keyrecord', 'kxrecord',
'locrecord', 'managedby', 'mdrecord', 'minforecord',
'mxrecord', 'naptrrecord', 'nsecrecord', 'nsec3paramrecord',
'nsrecord', 'nxtrecord', 'ptrrecord', 'rprecord', 'rrsigrecord',
'sigrecord', 'spfrecord', 'srvrecord', 'sshfprecord',
'tlsarecord', 'txtrecord', 'urirecord', 'unknownrecord',
},
'replaces': [
'(targetattr = "idnsname || cn || idnsallowdynupdate || dnsttl || dnsclass || arecord || aaaarecord || a6record || nsrecord || cnamerecord || ptrrecord || srvrecord || txtrecord || mxrecord || mdrecord || hinforecord || minforecord || afsdbrecord || sigrecord || keyrecord || locrecord || nxtrecord || naptrrecord || kxrecord || certrecord || dnamerecord || dsrecord || sshfprecord || rrsigrecord || nsecrecord || idnsname || idnszoneactive || idnssoamname || idnssoarname || idnssoaserial || idnssoarefresh || idnssoaretry || idnssoaexpire || idnssoaminimum || idnsupdatepolicy")(target = "ldap:///idnsname=*,cn=dns,$SUFFIX")(version 3.0;acl "permission:update dns entries";allow (write) groupdn = "ldap:///cn=update dns entries,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetattr = "idnsname || cn || idnsallowdynupdate || dnsttl || dnsclass || arecord || aaaarecord || a6record || nsrecord || cnamerecord || ptrrecord || srvrecord || txtrecord || mxrecord || mdrecord || hinforecord || minforecord || afsdbrecord || sigrecord || keyrecord || locrecord || nxtrecord || naptrrecord || kxrecord || certrecord || dnamerecord || dsrecord || sshfprecord || rrsigrecord || nsecrecord || idnsname || idnszoneactive || idnssoamname || idnssoarname || idnssoaserial || idnssoarefresh || idnssoaretry || idnssoaexpire || idnssoaminimum || idnsupdatepolicy || idnsallowquery || idnsallowtransfer || idnsallowsyncptr || idnsforwardpolicy || idnsforwarders")(target = "ldap:///idnsname=*,cn=dns,$SUFFIX")(version 3.0;acl "permission:update dns entries";allow (write) groupdn = "ldap:///cn=update dns entries,cn=permissions,cn=pbac,$SUFFIX";)',
'(targetattr = "idnsname || cn || idnsallowdynupdate || dnsttl || dnsclass || arecord || aaaarecord || a6record || nsrecord || cnamerecord || ptrrecord || srvrecord || txtrecord || mxrecord || mdrecord || hinforecord || minforecord || afsdbrecord || sigrecord || keyrecord || locrecord || nxtrecord || naptrrecord || kxrecord || certrecord || dnamerecord || dsrecord || sshfprecord || rrsigrecord || nsecrecord || idnsname || idnszoneactive || idnssoamname || idnssoarname || idnssoaserial || idnssoarefresh || idnssoaretry || idnssoaexpire || idnssoaminimum || idnsupdatepolicy || idnsallowquery || idnsallowtransfer || idnsallowsyncptr || idnsforwardpolicy || idnsforwarders || managedby")(target = "ldap:///idnsname=*,cn=dns,$SUFFIX")(version 3.0;acl "permission:update dns entries";allow (write) groupdn = "ldap:///cn=update dns entries,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
'System: Read DNSSEC metadata': {
'non_object': True,
'ipapermright': {'read', 'search', 'compare'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=dns', api.env.basedn),
'ipapermtargetfilter': ['(objectclass=idnsSecKey)'],
'ipapermdefaultattr': {
'idnsSecAlgorithm', 'idnsSecKeyCreated', 'idnsSecKeyPublish',
'idnsSecKeyActivate', 'idnsSecKeyInactive', 'idnsSecKeyDelete',
'idnsSecKeyZone', 'idnsSecKeyRevoke', 'idnsSecKeySep',
'idnsSecKeyRef', 'cn', 'objectclass',
},
'default_privileges': {'DNS Administrators'},
},
'System: Manage DNSSEC metadata': {
'non_object': True,
'ipapermright': {'all'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=dns', api.env.basedn),
'ipapermtargetfilter': ['(objectclass=idnsSecKey)'],
'ipapermdefaultattr': {
'idnsSecAlgorithm', 'idnsSecKeyCreated', 'idnsSecKeyPublish',
'idnsSecKeyActivate', 'idnsSecKeyInactive', 'idnsSecKeyDelete',
'idnsSecKeyZone', 'idnsSecKeyRevoke', 'idnsSecKeySep',
'idnsSecKeyRef', 'cn', 'objectclass',
},
'default_privileges': {'DNS Servers'},
},
'System: Manage DNSSEC keys': {
'non_object': True,
'ipapermright': {'all'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=keys', 'cn=sec', 'cn=dns', api.env.basedn),
'ipapermdefaultattr': {
'ipaPublicKey', 'ipaPrivateKey', 'ipaSecretKey',
'ipaWrappingMech','ipaWrappingKey',
'ipaSecretKeyRef', 'ipk11Private', 'ipk11Modifiable', 'ipk11Label',
'ipk11Copyable', 'ipk11Destroyable', 'ipk11Trusted',
'ipk11CheckValue', 'ipk11StartDate', 'ipk11EndDate',
'ipk11UniqueId', 'ipk11PublicKeyInfo', 'ipk11Distrusted',
'ipk11Subject', 'ipk11Id', 'ipk11Local', 'ipk11KeyType',
'ipk11Derive', 'ipk11KeyGenMechanism', 'ipk11AllowedMechanisms',
'ipk11Encrypt', 'ipk11Verify', 'ipk11VerifyRecover', 'ipk11Wrap',
'ipk11WrapTemplate', 'ipk11Sensitive', 'ipk11Decrypt',
'ipk11Sign', 'ipk11SignRecover', 'ipk11Unwrap',
'ipk11Extractable', 'ipk11AlwaysSensitive',
'ipk11NeverExtractable', 'ipk11WrapWithTrusted',
'ipk11UnwrapTemplate', 'ipk11AlwaysAuthenticate',
'objectclass',
},
'default_privileges': {'DNS Servers'},
},
}
def _rr_zone_postprocess(self, record, **options):
#Decode IDN ACE form to Unicode, raw records are passed directly from LDAP
if options.get('raw', False):
return
_records_idn_postprocess(record, **options)
def _warning_forwarding(self, result, **options):
if ('idnsforwarders' in result['result']):
messages.add_message(options.get('version', VERSION_WITHOUT_CAPABILITIES),
result, messages.ForwardersWarning())
def _warning_name_server_option(self, result, context, **options):
if getattr(context, 'show_warning_nameserver_option', False):
messages.add_message(
options['version'],
result, messages.OptionSemanticChangedWarning(
label=_(u"setting Authoritative nameserver"),
current_behavior=_(u"It is used only for setting the "
u"SOA MNAME attribute."),
hint=_(u"NS record(s) can be edited in zone apex - '@'. ")
)
)
def _warning_fw_zone_is_not_effective(self, result, *keys, **options):
"""
Warning if any operation with zone causes, a child forward zone is
not effective
"""
zone = keys[-1]
affected_fw_zones, _truncated = _find_subtree_forward_zones_ldap(
self.api, zone, child_zones_only=True)
if not affected_fw_zones:
return
for fwzone in affected_fw_zones:
_add_warning_fw_zone_is_not_effective(self.api, result, fwzone,
options['version'])
def _warning_dnssec_master_is_not_installed(self, result, **options):
dnssec_enabled = result['result'].get("idnssecinlinesigning", False)
if dnssec_enabled and not dnssec_installed(self.api.Backend.ldap2):
messages.add_message(
options['version'],
result,
messages.DNSSECMasterNotInstalled()
)
def _warning_ttl_changed_reload_needed(self, result, **options):
if 'dnsdefaultttl' in options:
messages.add_message(
options['version'],
result,
messages.ServiceRestartRequired(
service=services.service('named', api).systemd_name,
server=_('<all IPA DNS servers>'), )
)
@register()
class dnszone_add(DNSZoneBase_add):
__doc__ = _('Create new DNS zone (SOA record).')
takes_options = DNSZoneBase_add.takes_options + (
Flag('force',
doc=_('Force DNS zone creation even if nameserver is not '
'resolvable. (Deprecated)'),
),
Flag('skip_nameserver_check',
doc=_('Force DNS zone creation even if nameserver is not '
'resolvable.'),
),
# Deprecated
# ip-address option is not used anymore, we have to keep it
# due to compability with clients older than 4.1
Str('ip_address?',
flags=['no_option', ]
),
)
def _warning_deprecated_option(self, result, **options):
if 'ip_address' in options:
messages.add_message(
options['version'],
result,
messages.OptionDeprecatedWarning(
option='ip-address',
additional_info=u"Value will be ignored.")
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if options.get('force'):
options['skip_nameserver_check'] = True
dn = super(dnszone_add, self).pre_callback(
ldap, dn, entry_attrs, attrs_list, *keys, **options)
nameservers = [normalize_zone(x) for x in
self.api.Object.dnsrecord.get_dns_masters()]
server = normalize_zone(api.env.host)
zone = keys[-1]
if entry_attrs.get('idnssoamname'):
if zone.is_reverse() and not entry_attrs['idnssoamname'].is_absolute():
raise errors.ValidationError(
name='name-server',
error=_("Nameserver for reverse zone cannot be a relative DNS name"))
# verify if user specified server is resolvable
if not options['skip_nameserver_check']:
check_ns_rec_resolvable(keys[0], entry_attrs['idnssoamname'])
# show warning about --name-server option
context.show_warning_nameserver_option = True
else:
# user didn't specify SOA mname
if server in nameservers:
# current ipa server is authoritative nameserver in SOA record
entry_attrs['idnssoamname'] = [server]
else:
# a first DNS capable server is authoritative nameserver in SOA record
entry_attrs['idnssoamname'] = [nameservers[0]]
# all ipa DNS servers should be in NS zone record (as absolute domain name)
entry_attrs['nsrecord'] = nameservers
return dn
def execute(self, *keys, **options):
options['idnssoaserial'] = _create_zone_serial()
result = super(dnszone_add, self).execute(*keys, **options)
self._warning_deprecated_option(result, **options)
self.obj._warning_forwarding(result, **options)
self.obj._warning_name_server_option(result, context, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
self.obj._warning_dnssec_master_is_not_installed(result, **options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
# Add entry to realmdomains
# except for our own domain, reverse zones and root zone
zone = keys[0]
if (zone != DNSName(api.env.domain).make_absolute() and
not zone.is_reverse() and
zone != DNSName.root):
try:
self.api.Command['realmdomains_mod'](add_domain=unicode(zone),
force=True)
except (errors.EmptyModlist, errors.ValidationError):
pass
self.obj._rr_zone_postprocess(entry_attrs, **options)
return dn
@register()
class dnszone_del(DNSZoneBase_del):
__doc__ = _('Delete DNS zone (SOA record).')
msg_summary = _('Deleted DNS zone "%(value)s"')
def execute(self, *keys, **options):
result = super(dnszone_del, self).execute(*keys, **options)
nkeys = keys[-1] # we can delete more zones
for key in nkeys:
self.obj._warning_fw_zone_is_not_effective(result, key, **options)
return result
def post_callback(self, ldap, dn, *keys, **options):
super(dnszone_del, self).post_callback(ldap, dn, *keys, **options)
# Delete entry from realmdomains
# except for our own domain, reverse zone, and root zone
zone = keys[0].make_absolute()
if (zone != DNSName(api.env.domain).make_absolute() and
not zone.is_reverse() and zone != DNSName.root
):
try:
self.api.Command['realmdomains_mod'](
del_domain=unicode(zone), force=True)
except (errors.AttrValueNotFound, errors.ValidationError):
pass
return True
@register()
class dnszone_mod(DNSZoneBase_mod):
__doc__ = _('Modify DNS zone (SOA record).')
takes_options = DNSZoneBase_mod.takes_options + (
Flag('force',
label=_('Force'),
doc=_('Force nameserver change even if nameserver not in DNS')),
)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list,
*keys, **options):
if not _check_DN_objectclass(ldap, dn, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
if 'idnssoamname' in entry_attrs:
nameserver = entry_attrs['idnssoamname']
if nameserver:
if not nameserver.is_empty() and not options['force']:
check_ns_rec_resolvable(keys[0], nameserver)
context.show_warning_nameserver_option = True
else:
# empty value, this option is required by ldap
raise errors.ValidationError(
name='name_server',
error=_(u"is required"))
return dn
def execute(self, *keys, **options):
result = super(dnszone_mod, self).execute(*keys, **options)
self.obj._warning_forwarding(result, **options)
self.obj._warning_name_server_option(result, context, **options)
self.obj._warning_dnssec_master_is_not_installed(result, **options)
self.obj._warning_ttl_changed_reload_needed(result, **options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
dn = super(dnszone_mod, self).post_callback(ldap, dn, entry_attrs,
*keys, **options)
self.obj._rr_zone_postprocess(entry_attrs, **options)
return dn
@register()
class dnszone_find(DNSZoneBase_find):
__doc__ = _('Search for DNS zones (SOA records).')
takes_options = DNSZoneBase_find.takes_options + (
Flag('forward_only',
label=_('Forward zones only'),
cli_name='forward_only',
doc=_('Search for forward zones only'),
),
)
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
assert isinstance(base_dn, DN)
filter, _base, _scope = super(dnszone_find, self).pre_callback(
ldap, filter, attrs_list, base_dn, scope, *args, **options)
if options.get('forward_only', False):
search_kw = {}
search_kw['idnsname'] = [revzone.ToASCII() for revzone in
REVERSE_DNS_ZONES]
rev_zone_filter = ldap.make_filter(search_kw,
rules=ldap.MATCH_NONE,
exact=False,
trailing_wildcard=False)
filter = ldap.combine_filters((rev_zone_filter, filter),
rules=ldap.MATCH_ALL)
return (filter, base_dn, scope)
def post_callback(self, ldap, entries, truncated, *args, **options):
truncated = super(dnszone_find, self).post_callback(ldap, entries,
truncated, *args,
**options)
for entry_attrs in entries:
self.obj._rr_zone_postprocess(entry_attrs, **options)
return truncated
@register()
class dnszone_show(DNSZoneBase_show):
__doc__ = _('Display information about a DNS zone (SOA record).')
def execute(self, *keys, **options):
result = super(dnszone_show, self).execute(*keys, **options)
self.obj._warning_forwarding(result, **options)
self.obj._warning_dnssec_master_is_not_installed(result, **options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
dn = super(dnszone_show, self).post_callback(ldap, dn, entry_attrs,
*keys, **options)
self.obj._rr_zone_postprocess(entry_attrs, **options)
return dn
@register()
class dnszone_disable(DNSZoneBase_disable):
__doc__ = _('Disable DNS Zone.')
msg_summary = _('Disabled DNS zone "%(value)s"')
def execute(self, *keys, **options):
result = super(dnszone_disable, self).execute(*keys, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
return result
@register()
class dnszone_enable(DNSZoneBase_enable):
__doc__ = _('Enable DNS Zone.')
msg_summary = _('Enabled DNS zone "%(value)s"')
def execute(self, *keys, **options):
result = super(dnszone_enable, self).execute(*keys, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
return result
@register()
class dnszone_add_permission(DNSZoneBase_add_permission):
__doc__ = _('Add a permission for per-zone access delegation.')
@register()
class dnszone_remove_permission(DNSZoneBase_remove_permission):
__doc__ = _('Remove a permission for per-zone access delegation.')
@register()
class dnsrecord(LDAPObject):
"""
DNS record.
"""
parent_object = 'dnszone'
container_dn = api.env.container_dns
object_name = _('DNS resource record')
object_name_plural = _('DNS resource records')
object_class = ['top', 'idnsrecord']
possible_objectclasses = ['idnsTemplateObject']
permission_filter_objectclasses = ['idnsrecord']
default_attributes = ['idnsname'] + _record_attributes
allow_rename = True
label = _('DNS Resource Records')
label_singular = _('DNS Resource Record')
takes_params = (
DNSNameParam('idnsname',
cli_name='name',
label=_('Record name'),
doc=_('Record name'),
primary_key=True,
),
Int('dnsttl?',
cli_name='ttl',
label=_('Time to live'),
doc=_('Time to live'),
minvalue=0,
maxvalue=2147483647, # see RFC 2181,
),
StrEnum('dnsclass?',
# Deprecated
cli_name='class',
flags=['no_option'],
values=_record_classes,
),
) + _dns_record_options
structured_flag = Flag('structured',
label=_('Structured'),
doc=_('Parse all raw DNS records and return them in a structured way'),
)
def _dsrecord_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
dsrecords = entry_attrs.get('dsrecord')
if dsrecords and self.is_pkey_zone_record(*keys):
raise errors.ValidationError(
name='dsrecord',
error=unicode(_('DS record must not be in zone apex (RFC 4035 section 2.4)')))
def _nsrecord_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
nsrecords = entry_attrs.get('nsrecord')
if options.get('force', False) or nsrecords is None:
return
for nsrecord in nsrecords:
check_ns_rec_resolvable(keys[0], DNSName(nsrecord))
def _idnsname_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if keys[-1].is_absolute():
if keys[-1].is_subdomain(keys[-2]):
entry_attrs['idnsname'] = [keys[-1].relativize(keys[-2])]
elif not self.is_pkey_zone_record(*keys):
raise errors.ValidationError(name='idnsname',
error=unicode(_('out-of-zone data: record name must '
'be a subdomain of the zone or a '
'relative name')))
# dissallowed wildcard (RFC 4592 section 4)
no_wildcard_rtypes = ['DNAME', 'DS', 'NS']
if (keys[-1].is_wild() and
any(entry_attrs.get(record_name_format % r.lower())
for r in no_wildcard_rtypes)
):
raise errors.ValidationError(
name='idnsname',
error=(_('owner of %(types)s records '
'should not be a wildcard domain name (RFC 4592 section 4)') %
{'types': ', '.join(no_wildcard_rtypes)}
)
)
def _ptrrecord_pre_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
ptrrecords = entry_attrs.get('ptrrecord')
if ptrrecords is None:
return
zone = keys[-2]
if self.is_pkey_zone_record(*keys):
addr = _dns_zone_record
else:
addr = keys[-1]
zone_len = 0
for valid_zone, zone_num_components in REVERSE_DNS_ZONES.items():
if zone.is_subdomain(valid_zone):
zone = zone.relativize(valid_zone)
zone_name = valid_zone
zone_len = zone_num_components
if not zone_len:
# PTR records in zones other than in-addr.arpa and ip6.arpa are
# legal, e.g. DNS-SD [RFC6763] uses such records. If we have
# such a record there's nothing more to do. Otherwise continue
# with the ip4/ip6 reverse zone checks below.
return
addr_len = len(addr.labels)
# Classless zones (0/25.0.0.10.in-addr.arpa.) -> skip check
# zone has to be checked without reverse domain suffix (in-addr.arpa.)
for sign in (b'/', b'-'):
for name in (zone, addr):
for label in name.labels:
if sign in label:
return
ip_addr_comp_count = addr_len + len(zone.labels)
if ip_addr_comp_count != zone_len:
raise errors.ValidationError(name='ptrrecord',
error=unicode(_('Reverse zone %(name)s requires exactly '
'%(count)d IP address components, '
'%(user_count)d given')
% dict(name=zone_name,
count=zone_len,
user_count=ip_addr_comp_count)))
def run_precallback_validators(self, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
ldap = self.api.Backend.ldap2
for rtype in entry_attrs.keys():
rtype_cb = getattr(self, '_%s_pre_callback' % rtype, None)
if rtype_cb:
rtype_cb(ldap, dn, entry_attrs, *keys, **options)
def is_pkey_zone_record(self, *keys):
assert isinstance(keys[-1], DNSName)
assert isinstance(keys[-2], DNSName)
idnsname = keys[-1]
zonename = keys[-2]
if idnsname.is_empty() or idnsname == zonename:
return True
return False
def check_zone(self, zone, **options):
"""
Check if zone exists and if is master zone
"""
parent_object = self.api.Object[self.parent_object]
dn = parent_object.get_dn(zone, **options)
ldap = self.api.Backend.ldap2
try:
entry = ldap.get_entry(dn, ['objectclass'])
except errors.NotFound:
raise parent_object.handle_not_found(zone)
else:
# only master zones can contain records
if 'idnszone' not in [x.lower()
for x in entry.get('objectclass', [])]:
raise errors.ValidationError(
name='dnszoneidnsname',
error=_(u'only master zones can contain records')
)
return dn
def get_dn(self, *keys, **options):
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('DNS is not configured'))
dn = self.check_zone(keys[-2], **options)
if self.is_pkey_zone_record(*keys):
return dn
#Make RR name relative if possible
relative_name = keys[-1].relativize(keys[-2]).ToASCII()
keys = keys[:-1] + (relative_name,)
return super(dnsrecord, self).get_dn(*keys, **options)
def attr_to_cli(self, attr):
cliname = get_record_rrtype(attr)
if not cliname:
cliname = attr
return cliname
def get_dns_masters(self):
return find_providing_servers(
'DNS', self.api.Backend.ldap2, preferred_hosts=[api.env.host]
)
def get_record_entry_attrs(self, entry_attrs):
entry_attrs = entry_attrs.copy()
for attr in tuple(entry_attrs.keys()):
if attr not in self.params or self.params[attr].primary_key:
del entry_attrs[attr]
return entry_attrs
def postprocess_record(self, record, **options):
if options.get('structured', False):
for attr in tuple(record.keys()):
# attributes in LDAPEntry may not be normalized
attr = attr.lower()
try:
param = self.params[attr]
except KeyError:
continue
if not isinstance(param, DNSRecord):
continue
parts_params = param.get_parts()
for dnsvalue in record[attr]:
dnsentry = {
u'dnstype' : unicode(param.rrtype),
u'dnsdata' : dnsvalue
}
values = param._get_part_values(dnsvalue)
if values is None:
continue
for val_id, val in enumerate(values):
if val is not None:
#decode IDN
if isinstance(parts_params[val_id], DNSNameParam):
dnsentry[parts_params[val_id].name] = \
_dns_name_to_string(val,
options.get('raw', False))
else:
dnsentry[parts_params[val_id].name] = val
record.setdefault('dnsrecords', []).append(dnsentry)
del record[attr]
elif not options.get('raw', False):
#Decode IDN ACE form to Unicode, raw records are passed directly from LDAP
_records_idn_postprocess(record, **options)
def updated_rrattrs(self, old_entry, entry_attrs):
"""Returns updated RR attributes
"""
rrattrs = {}
if old_entry is not None:
old_rrattrs = dict((key, value) for key, value in old_entry.items()
if key in self.params and
isinstance(self.params[key], DNSRecord))
rrattrs.update(old_rrattrs)
new_rrattrs = dict((key, value) for key, value in entry_attrs.items()
if key in self.params and
isinstance(self.params[key], DNSRecord))
rrattrs.update(new_rrattrs)
return rrattrs
def check_record_type_collisions(self, keys, rrattrs):
# Test that only allowed combination of record types was created
# CNAME record validation
cnames = rrattrs.get('cnamerecord')
if cnames is not None:
if len(cnames) > 1:
raise errors.ValidationError(name='cnamerecord',
error=_('only one CNAME record is allowed per name '
'(RFC 2136, section 1.1.5)'))
if any(rrvalue is not None
and rrattr != 'cnamerecord'
for rrattr, rrvalue in rrattrs.items()):
raise errors.ValidationError(name='cnamerecord',
error=_('CNAME record is not allowed to coexist '
'with any other record (RFC 1034, section 3.6.2)'))
# DNAME record validation
dnames = rrattrs.get('dnamerecord')
if dnames is not None:
if len(dnames) > 1:
raise errors.ValidationError(name='dnamerecord',
error=_('only one DNAME record is allowed per name '
'(RFC 6672, section 2.4)'))
# DNAME must not coexist with CNAME, but this is already checked earlier
# NS record validation
# NS record can coexist only with A, AAAA, DS, and other NS records (except zone apex)
# RFC 2181 section 6.1,
allowed_records = ['AAAA', 'A', 'DS', 'NS']
nsrecords = rrattrs.get('nsrecord')
if nsrecords and not self.is_pkey_zone_record(*keys):
for r_type in _record_types:
if (r_type not in allowed_records
and rrattrs.get(record_name_format % r_type.lower())
):
raise errors.ValidationError(
name='nsrecord',
error=_('NS record is not allowed to coexist with an '
'%(type)s record except when located in a '
'zone root record (RFC 2181, section 6.1)') %
{'type': r_type})
def check_record_type_dependencies(self, keys, rrattrs):
# Test that all record type dependencies are satisfied
# DS record validation
# DS record requires to coexists with NS record
dsrecords = rrattrs.get('dsrecord')
nsrecords = rrattrs.get('nsrecord')
# DS record cannot be in zone apex, checked in pre-callback validators
if dsrecords and not nsrecords:
raise errors.ValidationError(
name='dsrecord',
error=_('DS record requires to coexist with an '
'NS record (RFC 4592 section 4.6, RFC 4035 section 2.4)'))
def _entry2rrsets(self, entry_attrs, dns_name, dns_domain):
'''Convert entry_attrs to a dictionary {rdtype: rrset}.
:returns:
None if entry_attrs is None
{rdtype: None} if RRset of given type is empty
{rdtype: RRset} if RRset of given type is non-empty
'''
ldap_rrsets = {}
if not entry_attrs:
# all records were deleted => name should not exist in DNS
return None
for attr, value in entry_attrs.items():
rrtype = get_record_rrtype(attr)
if not rrtype:
continue
rdtype = dns.rdatatype.from_text(rrtype)
if not value:
ldap_rrsets[rdtype] = None # RRset is empty
continue
try:
# TTL here can be arbitrary value because it is ignored
# during comparison
ldap_rrset = dns.rrset.from_text(
dns_name, 86400, dns.rdataclass.IN, rdtype,
*[str(v) for v in value])
# make sure that all names are absolute so RRset
# comparison will work
for ldap_rr in ldap_rrset:
ldap_rr.choose_relativity(origin=dns_domain,
relativize=False)
ldap_rrsets[rdtype] = ldap_rrset
except dns.exception.SyntaxError as e:
logger.error('DNS syntax error: %s %s %s: %s', dns_name,
dns.rdatatype.to_text(rdtype), value, e)
raise
return ldap_rrsets
def wait_for_modified_attr(self, ldap_rrset, rdtype, dns_name):
'''Wait until DNS resolver returns up-to-date answer for given RRset
or until the maximum number of attempts is reached.
Number of attempts is controlled by self.api.env['wait_for_dns'].
:param ldap_rrset:
None if given rdtype should not exist or
dns.rrset.RRset to match against data in DNS.
:param dns_name: FQDN to query
:type dns_name: dns.name.Name
:return: None if data in DNS and LDAP match
:raises errors.DNSDataMismatch: if data in DNS and LDAP doesn't match
:raises dns.exception.DNSException: if DNS resolution failed
'''
resolver = DNSResolver()
resolver.set_flags(0) # disable recursion (for NS RR checks)
max_attempts = int(self.api.env['wait_for_dns'])
warn_attempts = max_attempts // 2
period = 1 # second
attempt = 0
log_fn = logger.debug
log_fn('querying DNS server: expecting answer {%s}', ldap_rrset)
wait_template = 'waiting for DNS answer {%s}: got {%s} (attempt %s); '\
'waiting %s seconds before next try'
while attempt < max_attempts:
if attempt >= warn_attempts:
log_fn = logger.warning
attempt += 1
try:
dns_answer = resolver.resolve(dns_name, rdtype,
dns.rdataclass.IN,
raise_on_no_answer=False)
dns_rrset = None
if rdtype == _NS:
# NS records can be in Authority section (sometimes)
dns_rrset = dns_answer.response.get_rrset(
dns_answer.response.authority, dns_name, _IN, rdtype)
if not dns_rrset:
# Look for NS and other data in Answer section
dns_rrset = dns_answer.rrset
if dns_rrset == ldap_rrset:
log_fn('DNS answer matches expectations (attempt %s)',
attempt)
return
log_msg = wait_template % (ldap_rrset, dns_answer.response,
attempt, period)
except (dns.resolver.NXDOMAIN,
dns.resolver.YXDOMAIN,
dns.resolver.NoNameservers,
dns.resolver.Timeout) as e:
if attempt >= max_attempts:
raise
else:
log_msg = wait_template % (ldap_rrset, type(e), attempt,
period)
log_fn(log_msg)
time.sleep(period)
# Maximum number of attempts was reached
raise errors.DNSDataMismatch(expected=ldap_rrset, got=dns_rrset)
def wait_for_modified_attrs(self, entry_attrs, dns_name, dns_domain):
'''Wait until DNS resolver returns up-to-date answer for given entry
or until the maximum number of attempts is reached.
:param entry_attrs:
None if the entry was deleted from LDAP or
LDAPEntry instance containing at least all modified attributes.
:param dns_name: FQDN
:type dns_name: dns.name.Name
:raises errors.DNSDataMismatch: if data in DNS and LDAP doesn't match
'''
# represent data in LDAP as dictionary rdtype => rrset
ldap_rrsets = self._entry2rrsets(entry_attrs, dns_name, dns_domain)
nxdomain = ldap_rrsets is None
if nxdomain:
# name should not exist => ask for A record and check result
ldap_rrsets = {dns.rdatatype.from_text('A'): None}
for rdtype, ldap_rrset in ldap_rrsets.items():
try:
self.wait_for_modified_attr(ldap_rrset, rdtype, dns_name)
except dns.resolver.NXDOMAIN as e:
if nxdomain:
continue
e = errors.DNSDataMismatch(expected=ldap_rrset,
got="NXDOMAIN")
logger.error('%s', e)
raise e
except dns.resolver.NoNameservers as e:
# Do not raise exception if we have got SERVFAILs.
# Maybe the user has created an invalid zone intentionally.
logger.warning('waiting for DNS answer {%s}: got {%s}; '
'ignoring', ldap_rrset, type(e))
continue
except dns.exception.DNSException as e:
err_desc = str(type(e))
err_str = str(e)
if err_str:
err_desc += ": %s" % err_str
e = errors.DNSDataMismatch(expected=ldap_rrset, got=err_desc)
logger.error('%s', e)
raise e
def wait_for_modified_entries(self, entries):
'''Call wait_for_modified_attrs for all entries in given dict.
:param entries:
Dict {(dns_domain, dns_name): entry_for_wait_for_modified_attrs}
'''
for entry_name, entry in entries.items():
dns_domain = entry_name[0]
dns_name = entry_name[1].derelativize(dns_domain)
self.wait_for_modified_attrs(entry, dns_name, dns_domain)
def warning_if_ns_change_cause_fwzone_ineffective(self, result, *keys,
**options):
"""Detect if NS record change can make forward zones ineffective due
missing delegation. Run after parent's execute method.
"""
record_name_absolute = keys[-1]
zone = keys[-2]
if not record_name_absolute.is_absolute():
record_name_absolute = record_name_absolute.derelativize(zone)
affected_fw_zones, _truncated = _find_subtree_forward_zones_ldap(
self.api, record_name_absolute)
if not affected_fw_zones:
return
for fwzone in affected_fw_zones:
_add_warning_fw_zone_is_not_effective(self.api, result, fwzone,
options['version'])
def warning_suspicious_relative_name(self, result, *keys, **options):
"""Detect if zone name is suffix of relative record name and warn.
Zone name: test.zone.
Relative name: record.test.zone
"""
record_name = keys[-1]
zone = keys[-2]
if not record_name.is_absolute() and record_name.is_subdomain(
zone.relativize(DNSName.root)):
messages.add_message(
options['version'],
result,
messages.DNSSuspiciousRelativeName(record=record_name,
zone=zone,
fqdn=record_name + zone)
)
# Make DNS record types available as objects in the API.
# This is used by the CLI to get otherwise unavailable attributes of record
# parts.
for param in _dns_records:
register()(
type(
'dns{}record'.format(param.rrtype.lower()),
(Object,),
dict(
takes_params=param.parts or (),
)
)
)
@register()
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):
result = self.api.Object.dnsrecord.params[name]._get_part_values(value)
return dict(result=result)
@register()
class dnsrecord_add(LDAPCreate):
__doc__ = _('Add new DNS resource record.')
no_option_msg = 'No options to add a specific record provided.\n' \
"Command help may be consulted for all supported record types."
takes_options = LDAPCreate.takes_options + (
Flag('force',
label=_('Force'),
doc=_('force NS record creation even if its hostname is not in DNS'),
),
dnsrecord.structured_flag,
)
def args_options_2_entry(self, *keys, **options):
has_cli_options(self, options, self.no_option_msg)
return super(dnsrecord_add, self).args_options_2_entry(*keys, **options)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
precallback_attrs = []
processed_attrs = []
for option, option_val in options.items():
try:
param = self.params[option]
except KeyError:
continue
rrparam = get_rrparam_from_part(self, option)
if rrparam is None:
continue
if get_part_rrtype(param.name):
if rrparam.name in processed_attrs:
# this record was already entered
continue
if rrparam.name in entry_attrs:
# this record is entered both via parts and raw records
raise errors.ValidationError(name=param.cli_name or param.name,
error=_('Raw value of a DNS record was already set by "%(name)s" option') \
% dict(name=rrparam.cli_name or rrparam.name))
parts = rrparam.get_parts_from_kw(options)
dnsvalue = [rrparam._convert_scalar(parts)]
entry_attrs[rrparam.name] = dnsvalue
processed_attrs.append(rrparam.name)
continue
if get_extra_rrtype(param.name):
# do not run precallback for unset flags
if isinstance(param, Flag) and not option_val:
continue
# extra option is passed, run per-type pre_callback for given RR type
precallback_attrs.append(rrparam.name)
# Run pre_callback validators
self.obj.run_precallback_validators(dn, entry_attrs, *keys, **options)
# run precallback also for all new RR type attributes in entry_attrs
for attr in entry_attrs.keys():
try:
param = self.params[attr]
except KeyError:
continue
if not isinstance(param, DNSRecord):
continue
precallback_attrs.append(attr)
precallback_attrs = list(set(precallback_attrs))
for attr in precallback_attrs:
# run per-type
try:
param = self.params[attr]
except KeyError:
continue
param.dnsrecord_add_pre_callback(ldap, dn, entry_attrs, attrs_list, *keys, **options)
# Store all new attrs so that DNSRecord post callback is called for
# new attributes only and not for all attributes in the LDAP entry
setattr(context, 'dnsrecord_precallback_attrs', precallback_attrs)
# We always want to retrieve all DNS record attributes to test for
# record type collisions (#2601)
try:
old_entry = ldap.get_entry(dn, _record_attributes)
except errors.NotFound:
old_entry = None
else:
for attr in entry_attrs.keys():
if attr not in _record_attributes:
continue
if entry_attrs[attr] is None:
vals = []
elif not isinstance(entry_attrs[attr], (tuple, list)):
vals = [entry_attrs[attr]]
else:
vals = list(entry_attrs[attr])
entry_attrs[attr] = list(set(old_entry.get(attr, []) + vals))
rrattrs = self.obj.updated_rrattrs(old_entry, entry_attrs)
self.obj.check_record_type_dependencies(keys, rrattrs)
self.obj.check_record_type_collisions(keys, rrattrs)
context.dnsrecord_entry_mods = getattr(context, 'dnsrecord_entry_mods',
{})
context.dnsrecord_entry_mods[(keys[0], keys[1])] = entry_attrs.copy()
return dn
def execute(self, *keys, **options):
result = super(dnsrecord_add, self).execute(*keys, **options)
self.obj.warning_suspicious_relative_name(result, *keys, **options)
return result
def exc_callback(self, keys, options, exc, call_func, *call_args, **call_kwargs):
if call_func.__name__ == 'add_entry':
if isinstance(exc, errors.DuplicateEntry):
# A new record is being added to existing LDAP DNS object
# Update can be safely run as old record values has been
# already merged in pre_callback
ldap = self.obj.backend
entry_attrs = self.obj.get_record_entry_attrs(call_args[0])
update = ldap.get_entry(entry_attrs.dn, list(entry_attrs))
update.update(entry_attrs)
ldap.update_entry(update, **call_kwargs)
return
raise exc
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
for attr in getattr(context, 'dnsrecord_precallback_attrs', []):
param = self.params[attr]
param.dnsrecord_add_post_callback(ldap, dn, entry_attrs, *keys, **options)
if self.obj.is_pkey_zone_record(*keys):
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
self.obj.postprocess_record(entry_attrs, **options)
if self.api.env['wait_for_dns']:
self.obj.wait_for_modified_entries(context.dnsrecord_entry_mods)
return dn
@register()
class dnsrecord_mod(LDAPUpdate):
__doc__ = _('Modify a DNS resource record.')
no_option_msg = 'No options to modify a specific record provided.'
takes_options = LDAPUpdate.takes_options + (
dnsrecord.structured_flag,
)
def args_options_2_entry(self, *keys, **options):
has_cli_options(self, options, self.no_option_msg, True)
return super(dnsrecord_mod, self).args_options_2_entry(*keys, **options)
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
if options.get('rename') and self.obj.is_pkey_zone_record(*keys):
# zone rename is not allowed
raise errors.ValidationError(name='rename',
error=_('DNS zone root record cannot be renamed'))
# check if any attr should be updated using structured instead of replaced
# format is recordname : (old_value, new_parts)
updated_attrs = {}
for param in iterate_rrparams_by_parts(self, options, skip_extra=True):
parts = param.get_parts_from_kw(options, raise_on_none=False)
if parts is None:
# old-style modification
continue
old_value = entry_attrs.get(param.name)
if not old_value:
raise errors.RequirementError(name=param.name)
if isinstance(old_value, (tuple, list)):
if len(old_value) > 1:
raise errors.ValidationError(name=param.name,
error=_('DNS records can be only updated one at a time'))
old_value = old_value[0]
updated_attrs[param.name] = (old_value, parts)
# Run pre_callback validators
self.obj.run_precallback_validators(dn, entry_attrs, *keys, **options)
# current entry is needed in case of per-dns-record-part updates and
# for record type collision check
try:
old_entry = ldap.get_entry(dn, _record_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if updated_attrs:
for attr, attr_vals in updated_attrs.items():
param = self.params[attr]
old_dnsvalue, new_parts = attr_vals
if old_dnsvalue not in old_entry.get(attr, []):
attr_name = unicode(param.label or param.name)
raise errors.AttrValueNotFound(attr=attr_name,
value=old_dnsvalue)
old_entry[attr].remove(old_dnsvalue)
old_parts = param._get_part_values(old_dnsvalue)
modified_parts = tuple(part if part is not None else old_parts[part_id] \
for part_id,part in enumerate(new_parts))
new_dnsvalue = [param._convert_scalar(modified_parts)]
entry_attrs[attr] = list(set(old_entry[attr] + new_dnsvalue))
rrattrs = self.obj.updated_rrattrs(old_entry, entry_attrs)
self.obj.check_record_type_dependencies(keys, rrattrs)
self.obj.check_record_type_collisions(keys, rrattrs)
context.dnsrecord_entry_mods = getattr(context, 'dnsrecord_entry_mods',
{})
context.dnsrecord_entry_mods[(keys[0], keys[1])] = entry_attrs.copy()
return dn
def execute(self, *keys, **options):
result = super(dnsrecord_mod, self).execute(*keys, **options)
# remove if empty
if not self.obj.is_pkey_zone_record(*keys):
rename = options.get('rename')
if rename is not None:
keys = keys[:-1] + (rename,)
dn = self.obj.get_dn(*keys, **options)
ldap = self.obj.backend
old_entry = ldap.get_entry(dn, _record_attributes)
del_all = True
for attr in old_entry.keys():
if old_entry[attr]:
del_all = False
break
if del_all:
result = self.obj.methods.delentry(*keys,
version=options['version'])
# we need to modify delete result to match mod output type
# only one value is expected, not a list
if client_has_capability(options['version'], 'primary_key_types'):
assert len(result['value']) == 1
result['value'] = result['value'][0]
# indicate that entry was deleted
context.dnsrecord_entry_mods[(keys[0], keys[1])] = None
if self.api.env['wait_for_dns']:
self.obj.wait_for_modified_entries(context.dnsrecord_entry_mods)
if 'nsrecord' in options:
self.obj.warning_if_ns_change_cause_fwzone_ineffective(result,
*keys,
**options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if self.obj.is_pkey_zone_record(*keys):
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
self.obj.postprocess_record(entry_attrs, **options)
return dn
@register()
class dnsrecord_delentry(LDAPDelete):
__doc__ = _('Delete DNS record entry.')
msg_summary = _('Deleted record "%(value)s"')
NO_CLI = True
@register()
class dnsrecord_del(LDAPUpdate):
__doc__ = _('Delete DNS resource record.')
has_output = output.standard_multi_delete
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.")
takes_options = (
Flag('del_all',
default=False,
label=_('Delete all associated records'),
),
dnsrecord.structured_flag,
Flag(
'raw',
exclude=('cli', 'webui'),
),
)
def get_options(self):
for option in super(dnsrecord_del, self).get_options():
if get_part_rrtype(option.name) or get_extra_rrtype(option.name):
continue
if option.name in ('rename', ):
# options only valid for dnsrecord-mod
continue
if isinstance(option, DNSRecord):
yield option.clone(option_group=None)
continue
yield option
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
try:
old_entry = ldap.get_entry(dn, _record_attributes)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
for attr in entry_attrs.keys():
if attr not in _record_attributes:
continue
vals = entry_attrs[attr]
if vals is None:
continue
if not isinstance(vals, (tuple, list)):
vals = [vals]
for val in vals:
try:
old_entry[attr].remove(val)
except (KeyError, ValueError):
try:
param = self.params[attr]
attr_name = unicode(param.label or param.name)
except Exception:
attr_name = attr
raise errors.AttrValueNotFound(attr=attr_name, value=val)
entry_attrs[attr] = list(set(old_entry[attr]))
rrattrs = self.obj.updated_rrattrs(old_entry, entry_attrs)
self.obj.check_record_type_dependencies(keys, rrattrs)
del_all = False
if not self.obj.is_pkey_zone_record(*keys):
record_found = False
for attr in old_entry.keys():
if old_entry[attr]:
record_found = True
break
del_all = not record_found
# set del_all flag in context
# when the flag is enabled, the entire DNS record object is deleted
# in a post callback
context.del_all = del_all
context.dnsrecord_entry_mods = getattr(context, 'dnsrecord_entry_mods',
{})
context.dnsrecord_entry_mods[(keys[0], keys[1])] = entry_attrs.copy()
return dn
def execute(self, *keys, **options):
if options.get('del_all', False):
if self.obj.is_pkey_zone_record(*keys):
raise errors.ValidationError(
name='del_all',
error=_('Zone record \'%s\' cannot be deleted') \
% _dns_zone_record
)
result = self.obj.methods.delentry(*keys,
version=options['version'])
if self.api.env['wait_for_dns']:
entries = {(keys[0], keys[1]): None}
self.obj.wait_for_modified_entries(entries)
else:
result = super(dnsrecord_del, self).execute(*keys, **options)
result['value'] = pkey_to_value([keys[-1]], options)
if getattr(context, 'del_all', False) and not \
self.obj.is_pkey_zone_record(*keys):
result = self.obj.methods.delentry(*keys,
version=options['version'])
context.dnsrecord_entry_mods[(keys[0], keys[1])] = None
if self.api.env['wait_for_dns']:
self.obj.wait_for_modified_entries(context.dnsrecord_entry_mods)
if 'nsrecord' in options or options.get('del_all', False):
self.obj.warning_if_ns_change_cause_fwzone_ineffective(result,
*keys,
**options)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if self.obj.is_pkey_zone_record(*keys):
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
self.obj.postprocess_record(entry_attrs, **options)
return dn
def args_options_2_entry(self, *keys, **options):
has_cli_options(self, options, self.no_option_msg)
return super(dnsrecord_del, self).args_options_2_entry(*keys, **options)
@register()
class dnsrecord_show(LDAPRetrieve):
__doc__ = _('Display DNS resource.')
takes_options = LDAPRetrieve.takes_options + (
dnsrecord.structured_flag,
)
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
assert isinstance(dn, DN)
if self.obj.is_pkey_zone_record(*keys):
entry_attrs[self.obj.primary_key.name] = [_dns_zone_record]
self.obj.postprocess_record(entry_attrs, **options)
return dn
@register()
class dnsrecord_find(LDAPSearch):
__doc__ = _('Search for DNS resources.')
takes_options = LDAPSearch.takes_options + (
dnsrecord.structured_flag,
)
def get_options(self):
for option in super(dnsrecord_find, self).get_options():
if get_part_rrtype(option.name) or get_extra_rrtype(option.name):
continue
if isinstance(option, DNSRecord):
yield option.clone(option_group=None)
continue
yield option
def pre_callback(self, ldap, filter, attrs_list, base_dn, scope,
dnszoneidnsname, *args, **options):
assert isinstance(base_dn, DN)
# validate if zone is master zone
self.obj.check_zone(dnszoneidnsname, **options)
filter = _create_idn_filter(self, ldap, *args, **options)
return (filter, base_dn, ldap.SCOPE_SUBTREE)
def post_callback(self, ldap, entries, truncated, *args, **options):
if entries:
zone_obj = self.api.Object[self.obj.parent_object]
zone_dn = zone_obj.get_dn(args[0])
if entries[0].dn == zone_dn:
entries[0][zone_obj.primary_key.name] = [_dns_zone_record]
for entry in entries:
self.obj.postprocess_record(entry, **options)
return truncated
@register()
class dns_resolve(Command):
__doc__ = _('Resolve a host name in DNS. (Deprecated)')
NO_CLI = True
has_output = output.simple_value
msg_summary = _('Found \'%(value)s\'')
takes_args = (
Str('hostname',
label=_('Hostname (FQDN)'),
),
)
def execute(self, *args, **options):
query=args[0]
try:
verify_host_resolvable(query)
except errors.DNSNotARecordError:
raise errors.NotFound(
reason=_('Host \'%(host)s\' not found') % {'host': query}
)
result = dict(result=True, value=query)
messages.add_message(
options['version'], result,
messages.CommandDeprecatedWarning(
command='dns-resolve',
additional_info='The command may return an unexpected result, '
'the resolution of the DNS domain is done on '
'a randomly chosen IPA server.'
)
)
return result
@register()
class dns_is_enabled(Command):
__doc__ = _('Checks if any of the servers has the DNS service enabled.')
NO_CLI = True
has_output = output.standard_value
def execute(self, *args, **options):
dns_enabled = is_service_enabled('DNS', conn=self.api.Backend.ldap2)
return dict(result=dns_enabled, value=pkey_to_value(None, options))
@register()
class dnsconfig(LDAPObject):
"""
DNS global configuration object
"""
object_name = _('DNS configuration options')
default_attributes = [
'idnsforwardpolicy', 'idnsforwarders', 'idnsallowsyncptr'
]
label = _('DNS Global Configuration')
label_singular = _('DNS Global Configuration')
takes_params = (
Str('idnsforwarders*',
validate_bind_forwarder,
cli_name='forwarder',
label=_('Global forwarders'),
doc=_('Global forwarders. A custom port can be specified for each '
'forwarder using a standard format "IP_ADDRESS port PORT"'),
),
StrEnum('idnsforwardpolicy?',
cli_name='forward_policy',
label=_('Forward policy'),
doc=_('Global forwarding policy. Set to "none" to disable '
'any configured global forwarders.'),
values=(u'only', u'first', u'none'),
),
Bool('idnsallowsyncptr?',
cli_name='allow_sync_ptr',
label=_('Allow PTR sync'),
doc=_('Allow synchronization of forward (A, AAAA) and reverse (PTR) records'),
),
Int('idnszonerefresh?',
deprecated=True,
cli_name='zone_refresh',
label=_('Zone refresh interval'),
doc=_('An interval between regular polls of the name server for new DNS zones'),
minvalue=0,
flags={'no_option'},
),
Int('ipadnsversion?', # available only in installer/upgrade
label=_('IPA DNS version'),
),
Str(
'dns_server_server*',
label=_('IPA DNS servers'),
doc=_('List of IPA masters configured as DNS servers'),
flags={'virtual_attribute', 'no_create', 'no_update'}
),
Str(
'dnssec_key_master_server?',
label=_('IPA DNSSec key master'),
doc=_('IPA server configured as DNSSec key master'),
flags={'virtual_attribute', 'no_create', 'no_update'}
)
)
managed_permissions = {
'System: Write DNS Configuration': {
'non_object': True,
'ipapermright': {'write'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=dns', api.env.basedn),
'ipapermtargetfilter': ['(objectclass=idnsConfigObject)'],
'ipapermdefaultattr': {
'idnsallowsyncptr', 'idnsforwarders', 'idnsforwardpolicy',
'idnspersistentsearch', 'idnszonerefresh'
},
'replaces': [
'(targetattr = "idnsforwardpolicy || idnsforwarders || idnsallowsyncptr || idnszonerefresh || idnspersistentsearch")(target = "ldap:///cn=dns,$SUFFIX")(version 3.0;acl "permission:Write DNS Configuration";allow (write) groupdn = "ldap:///cn=Write DNS Configuration,cn=permissions,cn=pbac,$SUFFIX";)',
],
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
'System: Read DNS Configuration': {
'non_object': True,
'ipapermright': {'read'},
'ipapermlocation': api.env.basedn,
'ipapermtarget': DN('cn=dns', api.env.basedn),
'ipapermtargetfilter': ['(objectclass=idnsConfigObject)'],
'ipapermdefaultattr': {
'objectclass',
'idnsallowsyncptr', 'idnsforwarders', 'idnsforwardpolicy',
'idnspersistentsearch', 'idnszonerefresh', 'ipadnsversion'
},
'default_privileges': {'DNS Administrators', 'DNS Servers'},
},
}
def get_dn(self, *keys, **kwargs):
if not dns_container_exists(self.api.Backend.ldap2):
raise errors.NotFound(reason=_('DNS is not configured'))
return DN(api.env.container_dns, api.env.basedn)
def get_dnsconfig(self, ldap):
entry = ldap.get_entry(self.get_dn(), None)
return entry
def postprocess_result(self, result):
is_config_empty = not any(
param.name in result['result'] for param in self.params() if
u'virtual_attribute' not in param.flags
)
if is_config_empty:
result['summary'] = unicode(_('Global DNS configuration is empty'))
@register()
class dnsconfig_mod(LDAPUpdate):
__doc__ = _('Modify global DNS configuration.')
def get_options(self):
"""hide ipadnsversion outside of installer/upgrade"""
for option in super(dnsconfig_mod, self).get_options():
if option.name == 'ipadnsversion':
option = option.clone(include=('installer', 'updates'))
yield option
def execute(self, *keys, **options):
# test dnssec forwarders
forwarders = options.get('idnsforwarders')
result = super(dnsconfig_mod, self).execute(*keys, **options)
self.obj.postprocess_result(result)
# this check makes sense only when resulting forwarders are non-empty
if result['result'].get('idnsforwarders'):
fwzone = DNSName('.')
_add_warning_fw_policy_conflict_aez(result, fwzone, **options)
if forwarders:
# forwarders were changed
for forwarder in forwarders:
try:
validate_dnssec_global_forwarder(forwarder)
except DNSSECSignatureMissingError as e:
messages.add_message(
options['version'],
result, messages.DNSServerDoesNotSupportDNSSECWarning(
server=forwarder, error=e,
)
)
except EDNS0UnsupportedError as e:
messages.add_message(
options['version'],
result, messages.DNSServerDoesNotSupportEDNS0Warning(
server=forwarder, error=e,
)
)
except UnresolvableRecordError as e:
messages.add_message(
options['version'],
result, messages.DNSServerValidationWarning(
server=forwarder, error=e
)
)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.api.Object.config.show_servroles_attributes(
entry_attrs, "DNS server", **options)
return dn
@register()
class dnsconfig_show(LDAPRetrieve):
__doc__ = _('Show the current global DNS configuration.')
def execute(self, *keys, **options):
result = super(dnsconfig_show, self).execute(*keys, **options)
self.obj.postprocess_result(result)
return result
def post_callback(self, ldap, dn, entry_attrs, *keys, **options):
self.api.Object.config.show_servroles_attributes(
entry_attrs, "DNS server", **options)
return dn
@register()
class dnsforwardzone(DNSZoneBase):
"""
DNS Forward zone, container for resource records.
"""
object_name = _('DNS forward zone')
object_name_plural = _('DNS forward zones')
object_class = DNSZoneBase.object_class + ['idnsforwardzone']
label = _('DNS Forward Zones')
label_singular = _('DNS Forward Zone')
default_forward_policy = u'first'
# managed_permissions: permissions was apllied in dnszone class, do NOT
# add them here, they should not be applied twice.
def _warning_fw_zone_is_not_effective(self, result, *keys, **options):
fwzone = keys[-1]
_add_warning_fw_zone_is_not_effective(self.api, result, fwzone,
options['version'])
def _warning_if_forwarders_do_not_work(self, result, new_zone,
*keys, **options):
fwzone = keys[-1]
forwarders = options.get('idnsforwarders', [])
any_forwarder_work = False
for forwarder in forwarders:
try:
validate_dnssec_zone_forwarder_step1(forwarder, fwzone)
except UnresolvableRecordError as e:
messages.add_message(
options['version'],
result, messages.DNSServerValidationWarning(
server=forwarder, error=e
)
)
except EDNS0UnsupportedError as e:
messages.add_message(
options['version'],
result, messages.DNSServerDoesNotSupportEDNS0Warning(
server=forwarder, error=e
)
)
else:
any_forwarder_work = True
if not any_forwarder_work:
# do not test DNSSEC validation if there is no valid forwarder
return
# resolve IP address of any DNS replica
# FIXME: https://fedorahosted.org/bind-dyndb-ldap/ticket/143
# we currenly should to test all IPA DNS replica, because DNSSEC
# validation is configured just in named.conf per replica
ipa_dns_masters = [normalize_zone(x) for x in
self.api.Object.dnsrecord.get_dns_masters()]
if not ipa_dns_masters:
# something very bad happened, DNS is installed, but no IPA DNS
# servers available
logger.error("No IPA DNS server can be found, but integrated DNS "
"is installed")
return
ipa_dns_ip = None
for rdtype in (dns.rdatatype.A, dns.rdatatype.AAAA):
try:
ans = resolve(ipa_dns_masters[0], rdtype)
except dns.exception.DNSException:
continue
else:
ipa_dns_ip = str(next(iter(ans.rrset.items)))
break
if not ipa_dns_ip:
logger.error("Cannot resolve %s hostname", ipa_dns_masters[0])
return
# sleep a bit, adding new zone to BIND from LDAP may take a while
if new_zone:
time.sleep(5)
# Test if IPA is able to receive replies from forwarders
try:
validate_dnssec_zone_forwarder_step2(ipa_dns_ip, fwzone)
except DNSSECValidationError as e:
messages.add_message(
options['version'],
result, messages.DNSSECValidationFailingWarning(error=e)
)
except UnresolvableRecordError as e:
messages.add_message(
options['version'],
result, messages.DNSServerValidationWarning(
server=ipa_dns_ip, error=e
)
)
@register()
class dnsforwardzone_add(DNSZoneBase_add):
__doc__ = _('Create new DNS forward zone.')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
assert isinstance(dn, DN)
dn = super(dnsforwardzone_add, self).pre_callback(ldap, dn,
entry_attrs, attrs_list, *keys, **options)
if 'idnsforwardpolicy' not in entry_attrs:
entry_attrs['idnsforwardpolicy'] = self.obj.default_forward_policy
if (not entry_attrs.get('idnsforwarders') and
entry_attrs['idnsforwardpolicy'] != u'none'):
raise errors.ValidationError(name=u'idnsforwarders',
error=_('Please specify forwarders.'))
return dn
def execute(self, *keys, **options):
fwzone = keys[-1]
result = super(dnsforwardzone_add, self).execute(*keys, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
_add_warning_fw_policy_conflict_aez(result, fwzone, **options)
if options.get('idnsforwarders'):
self.obj._warning_if_forwarders_do_not_work(
result, True, *keys, **options)
return result
@register()
class dnsforwardzone_del(DNSZoneBase_del):
__doc__ = _('Delete DNS forward zone.')
msg_summary = _('Deleted DNS forward zone "%(value)s"')
@register()
class dnsforwardzone_mod(DNSZoneBase_mod):
__doc__ = _('Modify DNS forward zone.')
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
try:
entry = ldap.get_entry(dn)
except errors.NotFound:
raise self.obj.handle_not_found(*keys)
if not _check_entry_objectclass(entry, self.obj.object_class):
raise self.obj.handle_not_found(*keys)
policy = self.obj.default_forward_policy
forwarders = []
if 'idnsforwarders' in entry_attrs:
forwarders = entry_attrs['idnsforwarders']
elif 'idnsforwarders' in entry:
forwarders = entry['idnsforwarders']
if 'idnsforwardpolicy' in entry_attrs:
policy = entry_attrs['idnsforwardpolicy']
elif 'idnsforwardpolicy' in entry:
policy = entry['idnsforwardpolicy']
if not forwarders and policy != u'none':
raise errors.ValidationError(name=u'idnsforwarders',
error=_('Please specify forwarders.'))
return dn
def execute(self, *keys, **options):
fwzone = keys[-1]
result = super(dnsforwardzone_mod, self).execute(*keys, **options)
_add_warning_fw_policy_conflict_aez(result, fwzone, **options)
if options.get('idnsforwarders'):
self.obj._warning_if_forwarders_do_not_work(result, False, *keys,
**options)
return result
@register()
class dnsforwardzone_find(DNSZoneBase_find):
__doc__ = _('Search for DNS forward zones.')
@register()
class dnsforwardzone_show(DNSZoneBase_show):
__doc__ = _('Display information about a DNS forward zone.')
@register()
class dnsforwardzone_disable(DNSZoneBase_disable):
__doc__ = _('Disable DNS Forward Zone.')
msg_summary = _('Disabled DNS forward zone "%(value)s"')
@register()
class dnsforwardzone_enable(DNSZoneBase_enable):
__doc__ = _('Enable DNS Forward Zone.')
msg_summary = _('Enabled DNS forward zone "%(value)s"')
def execute(self, *keys, **options):
result = super(dnsforwardzone_enable, self).execute(*keys, **options)
self.obj._warning_fw_zone_is_not_effective(result, *keys, **options)
return result
@register()
class dnsforwardzone_add_permission(DNSZoneBase_add_permission):
__doc__ = _('Add a permission for per-forward zone access delegation.')
@register()
class dnsforwardzone_remove_permission(DNSZoneBase_remove_permission):
__doc__ = _('Remove a permission for per-forward zone access delegation.')
@register()
class dns_system_records(Object):
takes_params = (
Str(
'ipa_records*',
label=_('IPA DNS records')
),
Str(
'location_records*',
label=_('IPA location records')
)
)
@register()
class dns_update_system_records(Method):
__doc__ = _('Update location and IPA server DNS records')
obj_name = 'dns_system_records'
attr_name = 'update'
has_output = (
output.Entry(
'result',
),
output.Output(
'value', bool,
_('Result of the command'), ['no_display']
)
)
takes_options = (
Flag(
'dry_run',
label=_('Dry run'),
doc=_('Do not update records only return expected records')
)
)
def execute(self, *args, **options):
def output_to_list(iterable):
rec_list = []
for name, node in iterable:
rec_list.extend(IPASystemRecords.records_list_from_node(
name, node))
return rec_list
def output_to_list_with_failed(iterable):
err_rec_list = []
for name, node, error in iterable:
err_rec_list.extend([
(v, unicode(error)) for v in
IPASystemRecords.records_list_from_node(name, node)
])
return err_rec_list
result = {
'result': {},
'value': True,
}
system_records = IPASystemRecords(self.api)
if options.get('dry_run'):
result['result']['ipa_records'] = output_to_list(
system_records.get_base_records().items())
result['result']['location_records'] = output_to_list(
system_records.get_locations_records().items())
else:
try:
(
(success_base, failed_base),
(success_loc, failed_loc),
) = system_records.update_dns_records()
except IPADomainIsNotManagedByIPAError:
result['value'] = False
self.add_message(
messages.DNSUpdateNotIPAManagedZone(
zone=self.api.env.domain)
)
result['result']['ipa_records'] = output_to_list(
system_records.get_base_records().items())
else:
if success_base:
result['result']['ipa_records'] = output_to_list(
success_base)
if success_loc:
result['result']['location_records'] = output_to_list(
success_loc)
for failed in (failed_base, failed_loc):
for record, error in output_to_list_with_failed(failed):
self.add_message(
messages.DNSUpdateOfSystemRecordFailed(
record=record,
error=error
)
)
if failed_base or failed_loc:
result['value'] = False
return result
| 167,003
|
Python
|
.py
| 3,894
| 31.969183
| 892
| 0.580081
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,888
|
conf.py
|
freeipa_freeipa/doc/conf.py
|
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
# insert parent directory with ipalib and ipasphinx
sys.path.insert(0, os.path.abspath('..'))
# -- Project information -----------------------------------------------------
project = 'FreeIPA'
copyright = '2022, FreeIPA Contributors'
author = 'FreeIPA Contributors'
# The short X.Y version
version = '4.11-dev'
# The full version, including alpha/beta/rc tags
release = '4.11-dev'
master_doc = 'index'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'ipasphinx.ipabase',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinxcontrib.plantuml',
'm2r2',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = [
'_build', 'Thumbs.db', '.DS_Store', 'workshop/README.rst', '.venv/*',
'designs/template.md'
]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_book_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = [
'css/ipa.css',
]
# -- Options for sources -----------------------------------------------------
source_suffix = {
'.rst': 'restructuredtext',
'.md': 'markdown',
}
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
# intersphinx_mapping = {'https://docs.python.org/': None}
| 3,031
|
Python
|
.py
| 71
| 40.746479
| 79
| 0.658495
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,889
|
examples.py
|
freeipa_freeipa/doc/examples/examples.py
|
# Authors:
# 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/>.
"""
Example plugins
"""
# Hey guys, so you're interested in writing plugins for IPA? Great!
# We compiled this small file with examples on how to extend IPA to suit
# your needs. We'll be going from very simple to pretty complex plugins
# hopefully covering most of what our framework has to offer.
# First, let's import some stuff.
# errors is a module containing all IPA specific exceptions.
from ipalib import errors
# Command is the base class for command plugin.
from ipalib import Command
# Str is a subclass of Param, it is used to define string parameters for
# command. We'll go through all other subclasses of Param supported by IPA
# later in this file
from ipalib import Str
# output is a module containing the most common output patterns.
# Command plugin do output validation based on these patterns.
# You can define your own as we're going to show you later.
from ipalib import output
# To make the example ready for Python 3, we alias "unicode" to strings.
import six
if six.PY3:
unicode = str
# We're going to create an example command plugin, that takes a name as its
# only argument. Commands in IPA support input validation by defining
# functions we're going to call 'validators'. This is an example of such
# function:
def validate_name(ugettext, name):
"""
Validate names for the exhelloworld command. Names starting with 'Y'
(picked at random) are considered invalid.
"""
if name.startswith('Y'):
raise errors.ValidationError(
name='name',
error='Names starting with \'Y\' are invalid!'
)
# If the validator doesn't return anything (i.e. it returns None),
# the parameter passes validation.
class exhelloworld(Command):
"""
Example command: Hello world!
"""
# takes_args is an attribute of Command. It's a tuple containing
# instances of Param (or its subclasses such as Str) that define
# what position arguments are accepted by the command.
takes_args = (
# The first argument of Param constructor is the name that will be
# used to identify this parameter. It can be followed by validator
# functions. The constructor can also take a bunch of keyword
# arguments. Here we use default, to set the parameters default value
# and autofill, that fills the default value if the parameter isn't
# present.
# Note the ? at the end of the parameter name. It makes the parameter
# optional.
Str('name?', validate_name,
default=u'anonymous coward',
autofill=True,
),
)
# has_output is an attribute of Command, it is a tuple containing
# output.Output instances that define its output pattern.
# Commands in IPA return dicts with keys corresponding to items
# in the has_output tuple.
has_output = (
# output.summary is one of the basic patterns.
# It's a string that should be filled with a user-friendly
# decription of the action performed by the command.
output.summary,
)
# Every command needs to override the execute method.
# This is where the command functionality should go.
# It is always executed on the server-side, so don't rely
# on client-side stuff in here!
def execute(self, name, **options):
return dict(summary='Hello world, %s!' % name)
# register the command, uncomment this line if you want to try it out
#api.register(exhelloworld)
# Anyway, that was a pretty bad example of a command or, to be more precise,
# a bad example of resource use. When a client executes a command locally, its
# name and parameters are transfered to the server over XML-RPC. The command
# execute method is then executed on the server and results are transfered
# back to the client. The command does nothing, but create a string - a task
# that could be easily done locally. This can be done by overriding the Command
# forward method. It has the same signature as execute and is normally
# responsible for transferring stuff to the server.
# Most commands will, however, need to perfom tasks on the server. I didn't
# want to start with forward and confuse the hell out of you. :)
# Okey, time to look at something a little more advance. A command that
# actually communicates with the LDAP backend.
# Let's import a new parameter type: Flag.
# Parameters of type Flag do not have values per say. They are either enabled
# or disabled (True or False), so there's no need to make then optional, ever.
from ipalib import Flag
class exshowuser(Command):
"""
Example command: retrieve an user entry from LDAP
"""
takes_args = (
Str('username'),
)
# takes_options is another attribute of Command. It works the same
# way as takes_args, but instead of positional arguments, it enables
# us to define what options the commmand takes.
# Note that an options can be both required and optional.
takes_options = (
Flag('all',
# the doc keyword argument is what you see when you go
# `ipa COMMAND --help` or `ipa help COMMAND`
doc='retrieve and print all attributes from the server. Affects command output.',
flags=['no_output'],
),
)
has_output = (
# Here, you can see a custom output pattern. The pattern constructor
# takes the output name (key in the dictionary returned by execute),
# the allowed type(s) (can be a tuple with several types), a
# simple description and a list of flags. Currently, only
# the 'no_display' flag is supported by the Command.output_for_cli
# method, but you can always use your own if you plan
# to override it - I'll show you how later.
output.Output('result', dict, 'user entry without DN'),
output.Output('dn', unicode, 'DN of the user entry', ['no_display']),
)
# Notice the ** argument notation for options. It is not required, but
# we strongly recommend you to use it. In some cases, special options
# are added automatically to commands and not listing them or using **
# may lead to exception flying around... and nobody likes exceptions
# flying around.
def execute(self, username, **options):
# OK, I said earlier that this command is going to communicate
# with the LDAP backend, You could always use python-ldap to do
# that, but there's also this nice class we have... it's called
# ldap2 and this is how you get a handle to it:
ldap = self.api.Backend.ldap2
# ldap2 enables you to do a lot of crazy stuff with LDAP and it's
# specially crafted to suit IPA plugin needs. I recommend you either
# look at ipaserver/plugins/ldap2 or checkout some of the generated
# HTML docs on www.freeipa.org as I won't be able to cover everything
# it offers in this file.
# We want to retrieve an user entry from LDAP. We need to know its
# DN first. There's a bunch of method in ldap2 to build DNs. For our
# purpose, this will do:
dn = ldap.make_dn_from_attr(
'uid', username, self.api.env.container_user
)
# Note that api.env contains a lot of useful constant. We recommend
# you to check them out and use them whenever possible.
# Let's check if the --all option is enabled. If it is, let's
# retrieve all of the entry attributes. If not, only retrieve some
# basic stuff like the username, first and last names.
if options.get('all', False):
attrs_list = ['*']
else:
attrs_list = ['uid', 'givenname', 'sn']
# Give us the entry, LDAP!
(dn, entry_attrs) = ldap.get_entry(dn, attrs_list)
return dict(result=entry_attrs, dn=dn)
# register the command, uncomment this line if you want to try it out
#api.register(exshowuser)
# Now let's a take a look on how you can modify the command output if you don't
# like the default.
class exshowuser2(exshowuser):
"""
Example command: exusershow with custom output
"""
# Just some values we're going to use for textui.print_entry
attr_order = ['uid', 'givenname', 'sn']
attr_labels = {
'uid': 'User login', 'givenname': 'First name', 'sn': 'Last name'
}
def output_for_cli(self, textui, output, *args, **options):
# Now we've done it! We have overridden the default output_for_cli.
# textui is a class that implements a lot of useful outputting methods,
# please use it when you can
# output contains the dict returned by execute
# args, options contain the command parameters
textui.print_dashed('User entry:')
textui.print_indented('DN: %s' % output['dn'])
textui.print_entry(output['result'], self.attr_order, self.attr_labels)
# register the command, uncomment this line if you want to try it out
#api.register(exshowuser2)
# Alright, so now you'll always want to define your own output_for_cli...
# No, you won't! Because the default output_for_cli isn't as stupid as it looks.
# It can take information from the command parameters and output patterns
# to produce nice output like all real IPA commands have.
class exshowuser3(exshowuser):
"""
Example command: exusershow that takes full advantage of the default output
"""
takes_args = (
# We're going to rename the username argument to uid to match
# the attribute name it represent. The cli_name kwarg is what
# users will see in the CLI and label is what the default
# output_for_cli is going to use when printing the attribute value.
Str('uid',
cli_name='username',
label='User login',
),
)
# has_output_params works the same way as takes_args and takes_options,
# but is only used to define output attributes. These won't show up
# as parameters for the command.
has_output_params = (
Str('givenname',
label='First name',
),
Str('sn',
label='Last name',
),
)
# standard_entry includes an entry 'result' (dict), a summary 'summary'
# and the entry primary key 'value'
# It also makes the command automatically add two special options:
# --all and --raw. Look at the description of nearly any real IPA command
# to see what they're about.
has_output = output.standard_entry
# Since --all and --raw are added automatically thanks to standard_entry,
# we need to clear takes_options from the base class otherwise we would
# get a parameter conflict.
takes_options = tuple()
def execute(self, *args, **options):
# Let's just call execute of the base class, extract it's output
# and fit it into the standard_entry output pattern.
output = super(exshowuser3, self).execute(*args, **options)
output['result']['dn'] = output['dn']
return dict(result=output['result'], value=args[0])
# register the command, uncomment this line if you want to try it out
#api.register(exshowuser3)
# Pretty cool, right? But you will probably want to implement a set of commands
# to manage a certain type of entries (like users in the above examples).
# To save you the massive PITA of parameter copy&paste, we introduced
# the Object and Method plugin classes. Let's see how they work.
from ipalib import Object, Method
# First, we're going to create an object that represent the user entry.
class exuser(Object):
"""
Example plugin: user object
"""
# takes_params is an attribute of Object. It is used to define output
# parameters for associated Methods. Methods can also use them to
# to generate their own parameters as you'll see in a while.
takes_params = (
Str('uid',
cli_name='username',
label='User login',
# The primary_key kwarg is used to, well, specify the object's
# primary key.
primary_key=True,
),
Str('givenname?',
cli_name='first',
label='First name',
),
Str('sn?',
cli_name='last',
label='Last name',
),
)
# register the object, uncomment this line if you want to try it out
#api.register(exuser)
# Next, we're going to create a set of methods to manage this type of object
# i.e. to manage user entries. We're only going to do "read" commands, because
# we don't want to damage your user entries - adding, deleting, modifying is a
# bit more complicated and will be covered later in this file.
# Methods are automatically associated with a parent Object based on class
# names. They can then access their parent Object using self.obj.
# Simply said, Methods are just Commands associated with an Object.
class exuser_show(Method):
has_output = output.standard_entry
# get_args is a method of Command used to generate positional arguments
# we're going to use it to extract parameters from the parent
# Object
def get_args(self):
# self.obj.primary_key contains a reference the parameter with
# primary_key kwarg set to True.
# Parameters can be cloned to create new instance with additional
# kwargs. Here we add the attribute kwargs, that tells the framework
# the parameters corresponds to an LDAP attribute. The query kwargs
# tells the framework to skip parameter validation (i.e. do NOT call
# validators).
yield self.obj.primary_key.clone(attribute=True, query=True)
def execute(self, *args, **options):
ldap = self.api.Backend.ldap2
dn = ldap.make_dn_from_attr(
'uid', args[0], self.api.env.container_user
)
if options.get('all', False):
attrs_list = ['*']
else:
attrs_list = [p.name for p in self.output_params()]
(dn, entry_attrs) = ldap.get_entry(dn, attrs_list)
entry_attrs['dn'] = dn
return dict(result=entry_attrs, value=args[0])
# register the command, uncomment this line if you want to try it out
#api.register(exuser_show)
class exuser_find(Method):
# standard_list_of_entries is an output pattern that
# define a dict with a list of entries, their count
# and a truncated flag. The truncated flag is used to mark
# truncated (incomplete) search results - for example due to
# timeouts.
has_output = output.standard_list_of_entries
# get_options is similar to get_args, but is used to generate
# options instead of positional arguments
def get_options(self):
for option in self.obj.params():
yield option.clone(
attribute=True, query=True, required=False
)
def execute(self, *args, **options):
ldap = self.api.Backend.ldap2
# args_options_2_entry is a helper method of Command used
# to create a dictionary from the command parameters that
# have the attribute kwargs set to True.
search_kw = self.args_options_2_entry(*args, **options)
# make_filter will create an LDAP filter from attribute values
# exact=False means the values are surrounded with * when constructing
# the filter and rules=ldap.MATCH_ALL means the filter is going
# to use the & operators. More complex filters can be constructed
# by joining simpler filters using ldap2.combine_filters.
attr_filter = ldap.make_filter(
search_kw, exact=False, rules=ldap.MATCH_ALL
)
if options.get('all', False):
attrs_list = ['*']
else:
attrs_list = [p.name for p in self.output_params()]
# perform the search
(entries, truncated) = ldap.find_entries(
attr_filter, attrs_list, self.api.env.container_user,
scope=ldap.SCOPE_ONELEVEL
)
# find_entries returns DNs and attributes separately, but the output
# patter expects them in one dict. We need to arrange that.
for e in entries:
e[1]['dn'] = e[0]
entries = [e for (_dn, e) in entries]
return dict(result=entries, count=len(entries), truncated=truncated)
# register the command, uncomment this line if you want to try it out
#api.register(exuser_find)
# As most commands associated with objects are used to manage entries in LDAP,
# we defined a basic set of base classes for your plugins implementing CRUD
# operations. This is maily to save you from defining your own has_output,
# get_args, get_options and to have a standardized way of doing things for the
# sake of consistency. We won't cover them here, because you probably won't
# need to use them. So why did we botter? Well, you're going to see in
# a while. If interested anyway, check them out in ipalib/crud.py.
# At this point, if you've already seen some of the real plugins, you might
# be going like "WTH is this !@#^&? The user_show plugin is only like 4 lines
# of code and does much more than the exshowuser crap. Well yes, that's because
# it is based on one of the awesome plugin base classes we created to save
# authors from doing all the dirty work. Let's take a look at them.
# COMING SOON: baseldap.py classes, extending existing plugins, etc.
| 18,136
|
Python
|
.py
| 373
| 42.573727
| 93
| 0.690099
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,890
|
python-api.py
|
freeipa_freeipa/doc/examples/python-api.py
|
#!/usr/bin/python3
# Authors:
# Jason Gerard DeRose <jderose@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 __future__ import print_function
from ipalib import api
def example():
# 1. Initialize ipalib
#
# Run ./python-api.py --help to see the global options. Some useful
# options:
#
# -v Produce more verbose output
# -d Produce full debugging output
# -e in_server=True Force running in server mode
# -e xmlrpc_uri=https://foo.com/ipa/xml # Connect to a specific server
api.bootstrap_with_global_options(context='example')
api.finalize()
# You will need to create a connection. If you're in_server, call
# Backend.ldap.connect(), otherwise Backend.rpcclient.connect().
if api.env.in_server:
api.Backend.ldap2.connect()
else:
api.Backend.rpcclient.connect()
# Now that you're connected, you can make calls to api.Command.whatever():
print('The admin user:')
print(api.Command.user_show(u'admin'))
if __name__ == '__main__':
example()
| 1,747
|
Python
|
.py
| 45
| 35.577778
| 78
| 0.715889
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,891
|
wsgi.py.txt
|
freeipa_freeipa/doc/guide/wsgi.py.txt
|
import logging
import os
from ipaplatform.paths import paths
from ipalib import api
logger = logging.getLogger(os.path.basename(__file__))
api.bootstrap(context='server', confdir=paths.ETC_IPA, log=None) (ref:wsgi-app-bootstrap)
try:
api.finalize() (ref:wsgi-app-finalize)
except Exception as e:
logger.error('Failed to start IPA: %s', e)
else:
logger.info('*** PROCESS START ***')
# This is the WSGI callable:
def application(environ, start_response): (ref:wsgi-app-start)
if not environ['wsgi.multithread']:
return api.Backend.session(environ, start_response)
else:
logger.error("IPA does not work with the threaded MPM, "
"use the pre-fork MPM") (ref:wsgi-app-end)
| 757
|
Python
|
.py
| 19
| 34.157895
| 89
| 0.682561
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,892
|
role.py.txt
|
freeipa_freeipa/doc/guide/role.py.txt
|
from ipalib.plugins.baseldap import *
from ipalib import api, Str, _, ngettext
from ipalib import Command
from ipalib.plugins import privilege
class role(LDAPObject):
"""
Role object.
"""
container_dn = api.env.container_rolegroup
object_name = _('role')
object_name_plural = _('roles')
object_class = ['groupofnames', 'nestedgroup']
default_attributes = ['cn', 'description', 'member', 'memberof',
'memberindirect', 'memberofindirect',
]
attribute_members = {
'member': ['user', 'group', 'host', 'hostgroup'],
'memberof': ['privilege'],
}
reverse_members = {
'member': ['privilege'],
}
rdnattr='cn'
label = _('Roles')
label_singular = _('Role')
takes_params = (
Str('cn',
cli_name='name',
label=_('Role name'),
primary_key=True,
),
Str('description',
cli_name='desc',
label=_('Description'),
doc=_('A description of this role-group'),
),
)
api.register(role)
class role_add(LDAPCreate):
__doc__ = _('Add a new role.')
msg_summary = _('Added role "%(value)s"')
api.register(role_add)
class role_del(LDAPDelete):
__doc__ = _('Delete a role.')
msg_summary = _('Deleted role "%(value)s"')
api.register(role_del)
class role_mod(LDAPUpdate):
__doc__ = _('Modify a role.')
msg_summary = _('Modified role "%(value)s"')
api.register(role_mod)
class role_find(LDAPSearch):
__doc__ = _('Search for roles.')
msg_summary = ngettext(
'%(count)d role matched', '%(count)d roles matched', 0
)
api.register(role_find)
class role_show(LDAPRetrieve):
__doc__ = _('Display information about a role.')
api.register(role_show)
class role_add_member(LDAPAddMember):
__doc__ = _('Add members to a role.')
api.register(role_add_member)
class role_remove_member(LDAPRemoveMember):
__doc__ = _('Remove members from a role.')
api.register(role_remove_member)
class role_add_privilege(LDAPAddReverseMember):
__doc__ = _('Add privileges to a role.')
show_command = 'role_show'
member_command = 'privilege_add_member'
reverse_attr = 'privilege'
member_attr = 'role'
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of privileges added'),
),
)
api.register(role_add_privilege)
class role_remove_privilege(LDAPRemoveReverseMember):
__doc__ = _('Remove privileges from a role.')
show_command = 'role_show'
member_command = 'privilege_remove_member'
reverse_attr = 'privilege'
member_attr = 'role'
has_output = (
output.Entry('result'),
output.Output('failed',
type=dict,
doc=_('Members that could not be added'),
),
output.Output('completed',
type=int,
doc=_('Number of privileges removed'),
),
)
api.register(role_remove_privilege)
| 3,156
|
Python
|
.py
| 101
| 24.950495
| 68
| 0.604111
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,893
|
__main__.py
|
freeipa_freeipa/ipaclient/__main__.py
|
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
"""
Command Line Interface for IPA administration.
The CLI functionality is implemented in ipalib/cli.py
"""
from ipalib import api, cli
def main():
cli.run(api)
if __name__ == '__main__':
main()
| 276
|
Python
|
.py
| 10
| 25.3
| 66
| 0.727969
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,894
|
setup.py
|
freeipa_freeipa/ipaclient/setup.py
|
# Copyright (C) 2007 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 client library
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="ipaclient",
doc=__doc__,
package_dir={'ipaclient': ''},
packages=[
"ipaclient",
"ipaclient.install",
"ipaclient.plugins",
"ipaclient.remote_plugins",
"ipaclient.remote_plugins.2_49",
"ipaclient.remote_plugins.2_114",
"ipaclient.remote_plugins.2_156",
"ipaclient.remote_plugins.2_164",
],
install_requires=[
"cryptography",
"ipalib",
"ipapython",
"qrcode",
"six",
],
entry_points={
'console_scripts': [
'ipa = ipaclient.__main__:main'
]
},
extras_require={
"install": ["ipaplatform"],
"otptoken_yubikey": ["python-yubico", "pyusb"],
"ldap": ["python-ldap"], # ipapython.ipaldap
},
zip_safe=False,
)
| 1,974
|
Python
|
.py
| 58
| 26.965517
| 71
| 0.612448
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,895
|
__init__.py
|
freeipa_freeipa/ipaclient/__init__.py
|
# Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2007 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/>.
#
| 766
|
Python
|
.py
| 18
| 41.555556
| 71
| 0.774064
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,896
|
frontend.py
|
freeipa_freeipa/ipaclient/frontend.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from ipalib import api
from ipalib.frontend import Command, Method
from ipalib.parameters import Str
from ipalib.text import _
from ipalib.util import classproperty
class ClientCommand(Command):
def get_options(self):
skip = set()
for option in super(ClientCommand, self).get_options():
if option.name in skip:
continue
if option.name in ('all', 'raw'):
skip.add(option.name)
yield option
class ClientMethod(ClientCommand, Method):
_failed_member_output_params = (
# baseldap
Str(
'member',
label=_("Failed members"),
),
Str(
'sourcehost',
label=_("Failed source hosts/hostgroups"),
),
Str(
'memberhost',
label=_("Failed hosts/hostgroups"),
),
Str(
'memberuser',
label=_("Failed users/groups"),
),
Str(
'memberservice',
label=_("Failed service/service groups"),
),
Str(
'failed',
label=_("Failed to remove"),
flags=['suppress_empty'],
),
Str(
'ipasudorunas',
label=_("Failed RunAs"),
),
Str(
'ipasudorunasgroup',
label=_("Failed RunAsGroup"),
),
# caacl
Str(
'ipamembercertprofile',
label=_("Failed profiles"),
),
Str(
'ipamemberca',
label=_("Failed CAs"),
),
# group, hostgroup
Str(
'membermanager',
label=_("Failed member manager"),
),
# host
Str(
'managedby',
label=_("Failed managedby"),
),
# service
Str(
'ipaallowedtoperform_read_keys',
label=_("Failed allowed to retrieve keytab"),
),
Str(
'ipaallowedtoperform_write_keys',
label=_("Failed allowed to create keytab"),
),
# servicedelegation
Str(
'failed_memberprincipal',
label=_("Failed members"),
),
Str(
'ipaallowedtarget',
label=_("Failed targets"),
),
# vault
Str(
'owner?',
label=_("Failed owners"),
),
)
def get_output_params(self):
seen = set()
for param in self.params():
if param.name not in self.obj.params:
seen.add(param.name)
yield param
for output_param in super(ClientMethod, self).get_output_params():
seen.add(output_param.name)
yield output_param
for output_param in self._failed_member_output_params:
if output_param.name not in seen:
yield output_param
class CommandOverride(Command):
def __init__(self, api):
super(CommandOverride, self).__init__(api)
next_class = self.__get_next()
self.next = next_class(api)
@classmethod
def __get_next(cls):
return api.get_plugin_next(cls)
@classmethod
def __doc_getter(cls):
return cls.__get_next().doc
doc = classproperty(__doc_getter)
@classmethod
def __summary_getter(cls):
return cls.__get_next().summary
summary = classproperty(__summary_getter)
@classmethod
def __NO_CLI_getter(cls):
return cls.__get_next().NO_CLI
NO_CLI = classproperty(__NO_CLI_getter)
@classmethod
def __topic_getter(cls):
return cls.__get_next().topic
topic = classproperty(__topic_getter)
@property
def forwarded_name(self):
return self.next.forwarded_name
@property
def api_version(self):
return self.next.api_version
def _on_finalize(self):
self.next.finalize()
super(CommandOverride, self)._on_finalize()
def get_args(self):
for arg in self.next.args():
yield arg
for arg in super(CommandOverride, self).get_args():
yield arg
def get_options(self):
for option in self.next.options():
yield option
for option in super(CommandOverride, self).get_options():
if option.name not in ('all', 'raw', 'version'):
yield option
def get_output_params(self):
for output_param in self.next.output_params():
yield output_param
for output_param in super(CommandOverride, self).get_output_params():
yield output_param
def _iter_output(self):
return self.next.output()
class MethodOverride(CommandOverride, Method):
@property
def obj_name(self):
try:
return self.next.obj_name
except AttributeError:
return None
@property
def attr_name(self):
try:
return self.next.attr_name
except AttributeError:
return None
@property
def obj(self):
return self.next.obj
def get_output_params(self):
seen = set()
for output_param in super(MethodOverride, self).get_output_params():
if output_param.name in seen:
continue
seen.add(output_param.name)
yield output_param
| 5,431
|
Python
|
.py
| 182
| 20.450549
| 77
| 0.551361
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,897
|
discovery.py
|
freeipa_freeipa/ipaclient/discovery.py
|
# Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2007 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 absolute_import
import logging
import six
from dns import rdatatype
from dns.exception import DNSException
from ipalib import errors
from ipalib.constants import FQDN
from ipalib.util import validate_domain_name
from ipapython.dnsutil import query_srv, resolve
from ipaplatform.paths import paths
from ipapython.ipautil import valid_ip, realm_to_suffix
from ipapython.dn import DN
try:
import ldap # pylint: disable=unused-import
except ImportError:
ipaldap = None
else:
from ipapython import ipaldap
logger = logging.getLogger(__name__)
SUCCESS = 0
NOT_FQDN = -1
NO_LDAP_SERVER = -2
REALM_NOT_FOUND = -3
NOT_IPA_SERVER = -4
NO_ACCESS_TO_LDAP = -5
NO_TLS_LDAP = -6
PYTHON_LDAP_NOT_INSTALLED = -7
BAD_HOST_CONFIG = -10
UNKNOWN_ERROR = -15
IPA_BASEDN_INFO = 'ipa v2.0'
error_names = {
SUCCESS: 'Success',
NOT_FQDN: 'NOT_FQDN',
NO_LDAP_SERVER: 'NO_LDAP_SERVER',
REALM_NOT_FOUND: 'REALM_NOT_FOUND',
NOT_IPA_SERVER: 'NOT_IPA_SERVER',
NO_ACCESS_TO_LDAP: 'NO_ACCESS_TO_LDAP',
NO_TLS_LDAP: 'NO_TLS_LDAP',
PYTHON_LDAP_NOT_INSTALLED: 'PYTHON_LDAP_NOT_INSTALLED',
BAD_HOST_CONFIG: 'BAD_HOST_CONFIG',
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
}
def get_ipa_basedn(conn):
"""
Get base DN of IPA suffix in given LDAP server.
None is returned if the suffix is not found
:param conn: Bound LDAPClient that will be used for searching
"""
entry = conn.get_entry(
DN(), attrs_list=['defaultnamingcontext', 'namingcontexts'])
contexts = [c.decode('utf-8') for c in entry.raw['namingcontexts']]
if 'defaultnamingcontext' in entry:
# If there is a defaultNamingContext examine that one first
[default] = entry.raw['defaultnamingcontext']
default = default.decode('utf-8')
if default in contexts:
contexts.remove(default)
contexts.insert(0, default)
for context in contexts:
logger.debug("Check if naming context '%s' is for IPA", context)
try:
[entry] = conn.get_entries(
DN(context), conn.SCOPE_BASE, "(info=IPA*)")
except errors.NotFound:
logger.debug("LDAP server did not return info attribute to "
"check for IPA version")
continue
[info] = entry.raw['info']
info = info.decode('utf-8').lower()
if info != IPA_BASEDN_INFO:
logger.debug(
"Detected IPA server version (%s) did not match the "
"client (%s)", info, IPA_BASEDN_INFO)
continue
logger.debug("Naming context '%s' is a valid IPA context", context)
return DN(context)
return None
class IPADiscovery:
def __init__(self):
self.realm = None
self.domain = None
self.server = None
self.servers = []
self.basedn = None
self.realm_source = None
self.domain_source = None
self.server_source = None
self.basedn_source = None
def __get_resolver_domains(self):
"""Read /etc/resolv.conf and return all domains
Returns a list of (domain, info) pairs. The info contains a reason
why the domain is returned.
"""
domains = []
domain = None
try:
with open(paths.RESOLV_CONF, 'r') as f:
lines = f.readlines()
for line in lines:
if line.lower().startswith('domain'):
domain = (line.split()[-1],
'local domain from /etc/resolv.conf')
elif line.lower().startswith('search'):
domains.extend(
(d, 'search domain from /etc/resolv.conf')
for d in line.split()[1:]
)
except Exception:
pass
if domain:
domains = [domain] + domains
return domains
def getServerName(self):
return self.server
def getDomainName(self):
return self.domain
def getRealmName(self):
return self.realm
def getKDCName(self):
return self.kdc
def getBaseDN(self):
return self.basedn
def check_domain(self, domain, tried, reason):
"""
Given a domain search it for SRV records, breaking it down to search
all subdomains too.
Returns a tuple (servers, domain) or (None,None) if a SRV record
isn't found. servers is a list of servers found. domain is a string.
:param tried: A set of domains that were tried already
:param reason: Reason this domain is searched (included in the log)
"""
servers = None
logger.debug('Start searching for LDAP SRV record in "%s" (%s) '
'and its sub-domains', domain, reason)
while not servers:
if domain in tried:
logger.debug("Already searched %s; skipping", domain)
break
tried.add(domain)
servers = self.ipadns_search_srv(domain, '_ldap._tcp', 389,
break_on_first=False)
if servers:
return (servers, domain)
else:
p = domain.find(".")
if p == -1:
# no ldap server found and last component of the domain
# already tested
return None, None
domain = domain[p + 1:]
return None, None
def search(self, domain="", servers="", realm=None, hostname=None,
ca_cert_path=None):
"""
Use DNS discovery to identify valid IPA servers.
servers may contain an optional list of servers which will be used
instead of discovering available LDAP SRV records.
Returns a constant representing the overall search result.
"""
logger.debug("[IPA Discovery]")
logger.debug(
'Starting IPA discovery with domain=%s, servers=%s, hostname=%s',
domain, servers, hostname)
self.server = None
autodiscovered = False
if not servers:
if not domain: # domain not provided do full DNS discovery
# get the local host name
if not hostname:
hostname = FQDN
logger.debug('Hostname: %s', hostname)
if not hostname:
return BAD_HOST_CONFIG
if valid_ip(hostname):
return NOT_FQDN
# first, check for an LDAP server for the local domain
p = hostname.find(".")
if p == -1: # no domain name
return NOT_FQDN
domain = hostname[p + 1:]
# Get the list of domains from /etc/resolv.conf, we'll search
# them all. We search the domain of our hostname first though.
# This is to avoid the situation where domain isn't set in
# /etc/resolv.conf and the search list has the hostname domain
# not first. We could end up with the wrong SRV record.
domains = self.__get_resolver_domains()
domains = [(domain, 'domain of the hostname')] + domains
tried = set()
for domain, reason in domains:
# Domain name should not be single-label
try:
validate_domain_name(domain)
except ValueError as e:
logger.debug("Skipping invalid domain '%s' (%s)",
domain, e)
continue
servers, domain = self.check_domain(domain, tried, reason)
if servers:
autodiscovered = True
self.domain = domain
self.server_source = self.domain_source = (
'Discovered LDAP SRV records from %s (%s)' %
(domain, reason))
break
if not self.domain: # no ldap server found
logger.debug('No LDAP server found')
return NO_LDAP_SERVER
else:
logger.debug("Search for LDAP SRV record in %s", domain)
servers = self.ipadns_search_srv(domain, '_ldap._tcp', 389,
break_on_first=False)
if servers:
autodiscovered = True
self.domain = domain
self.server_source = self.domain_source = (
'Discovered LDAP SRV records from %s' % domain)
else:
self.server = None
logger.debug('No LDAP server found')
return NO_LDAP_SERVER
else:
logger.debug("Server and domain forced")
self.domain = domain
self.domain_source = self.server_source = 'Forced'
# search for kerberos
logger.debug("[Kerberos realm search]")
if realm:
logger.debug("Kerberos realm forced")
self.realm = realm
self.realm_source = 'Forced'
else:
realm = self.ipadnssearchkrbrealm()
self.realm = realm
self.realm_source = (
'Discovered Kerberos DNS records from %s' % self.domain)
if not servers and not realm:
return REALM_NOT_FOUND
if autodiscovered:
self.kdc = self.ipadnssearchkrbkdc()
self.kdc_source = (
'Discovered Kerberos DNS records from %s' % self.domain)
else:
self.kdc = ', '.join(servers)
self.kdc_source = "Kerberos DNS record discovery bypassed"
# We may have received multiple servers corresponding to the domain
# Iterate through all of those to check if it is IPA LDAP server
ldapret = [NOT_IPA_SERVER]
ldapaccess = True
logger.debug("[LDAP server check]")
valid_servers = []
for server in servers:
logger.debug('Verifying that %s (realm %s) is an IPA server',
server, self.realm)
# check ldap now
ldapret = self.ipacheckldap(
server, self.realm, ca_cert_path=ca_cert_path
)
if ldapret[0] == SUCCESS:
# Make sure that realm is not single-label
try:
validate_domain_name(ldapret[2], entity='realm')
except ValueError as e:
logger.debug("Skipping invalid realm '%s' (%s)",
ldapret[2], e)
ldapret = [NOT_IPA_SERVER]
else:
self.server = ldapret[1]
self.realm = ldapret[2]
self.server_source = self.realm_source = (
'Discovered from LDAP DNS records in %s' % self.server)
valid_servers.append(server)
# verified, we actually talked to the remote server and it
# is definetely an IPA server
if autodiscovered:
# No need to keep verifying servers if we discovered
# them via DNS
break
elif ldapret[0] in (NO_ACCESS_TO_LDAP, NO_TLS_LDAP,
PYTHON_LDAP_NOT_INSTALLED):
ldapaccess = False
valid_servers.append(server)
# we may set verified_servers below, we don't have it yet
if autodiscovered:
# No need to keep verifying servers if we discovered them
# via DNS
break
elif ldapret[0] == NOT_IPA_SERVER:
logger.warning(
'Skip %s: not an IPA server', server)
elif ldapret[0] == NO_LDAP_SERVER:
logger.warning(
'Skip %s: LDAP server is not responding, unable to '
'verify if this is an IPA server', server)
else:
logger.warning(
'Skip %s: cannot verify if this is an IPA server', server)
# If one of LDAP servers checked rejects access (maybe anonymous
# bind is disabled), assume realm and basedn generated off domain.
# Note that in case ldapret[0] == 0 and ldapaccess == False (one of
# servers didn't provide access but another one succeeded), self.realm
# will be set already to a proper value above, self.basdn will be
# initialized during the LDAP check itself and we'll skip these two
# checks.
if not ldapaccess and self.realm is None:
# Assume realm is the same as domain.upper()
self.realm = self.domain.upper()
self.realm_source = 'Assumed same as domain'
logger.debug(
"Assuming realm is the same as domain: %s", self.realm)
if not ldapaccess and self.basedn is None:
# Generate suffix from realm
self.basedn = realm_to_suffix(self.realm)
self.basedn_source = 'Generated from Kerberos realm'
logger.debug("Generated basedn from realm: %s", self.basedn)
logger.debug(
"Discovery result: %s; server=%s, domain=%s, kdc=%s, basedn=%s",
error_names.get(ldapret[0], ldapret[0]),
self.server, self.domain, self.kdc, self.basedn)
logger.debug("Validated servers: %s", ','.join(valid_servers))
self.servers = valid_servers
# If we have any servers left then override the last return value
# to indicate success.
if valid_servers:
self.server = servers[0]
ldapret[0] = SUCCESS
return ldapret[0]
def ipacheckldap(self, thost, trealm, ca_cert_path=None):
"""
Given a host and kerberos realm verify that it is an IPA LDAP
server hosting the realm.
Returns a list [errno, host, realm] or an empty list on error.
Errno is an error number:
0 means all ok
negative number means something went wrong
"""
if ipaldap is None:
return [PYTHON_LDAP_NOT_INSTALLED]
lrealms = []
# now verify the server is really an IPA server
try:
ldap_uri = ipaldap.get_ldap_uri(thost)
start_tls = False
if ca_cert_path:
start_tls = True
logger.debug("Init LDAP connection to: %s", ldap_uri)
lh = ipaldap.LDAPClient(
ldap_uri, cacert=ca_cert_path, start_tls=start_tls,
no_schema=True, decode_attrs=False)
try:
lh.simple_bind(DN(), '')
# get IPA base DN
logger.debug("Search LDAP server for IPA base DN")
basedn = get_ipa_basedn(lh)
except errors.ACIError:
logger.debug("LDAP Error: Anonymous access not allowed")
return [NO_ACCESS_TO_LDAP]
except errors.DatabaseError as err:
logger.error("Error checking LDAP: %s", err.strerror)
# We should only get UNWILLING_TO_PERFORM if the remote LDAP
# server has minssf > 0 and we have attempted a non-TLS conn.
if ca_cert_path is None:
logger.debug(
"Cannot connect to LDAP server. Check that minssf is "
"not enabled")
return [NO_TLS_LDAP]
else:
return [UNKNOWN_ERROR]
if basedn is None:
logger.debug("The server is not an IPA server")
return [NOT_IPA_SERVER]
self.basedn = basedn
self.basedn_source = 'From IPA server %s' % lh.ldap_uri
# search and return known realms
logger.debug(
"Search for (objectClass=krbRealmContainer) in %s (sub)",
self.basedn)
try:
lret = lh.get_entries(
DN(('cn', 'kerberos'), self.basedn),
lh.SCOPE_SUBTREE, "(objectClass=krbRealmContainer)")
except errors.NotFound:
# something very wrong
return [REALM_NOT_FOUND]
for lres in lret:
logger.debug("Found: %s", lres.dn)
[cn] = lres.raw['cn']
if six.PY3:
cn = cn.decode('utf-8')
lrealms.append(cn)
if trealm:
for r in lrealms:
if trealm == r:
return [SUCCESS, thost, trealm]
# must match or something is very wrong
logger.debug("Realm %s does not match any realm in LDAP "
"database", trealm)
return [REALM_NOT_FOUND]
else:
if len(lrealms) != 1:
# which one? we can't attach to a multi-realm server
# without DNS working
logger.debug(
"Multiple realms found, cannot decide which realm "
"is the correct realm without working DNS")
return [REALM_NOT_FOUND]
else:
return [SUCCESS, thost, lrealms[0]]
# we shouldn't get here
assert False, "Unknown error in ipadiscovery"
except errors.DatabaseTimeout:
logger.debug("LDAP Error: timeout")
return [NO_LDAP_SERVER]
except errors.NetworkError as err:
logger.debug("LDAP Error: %s", err.strerror)
return [NO_LDAP_SERVER]
except errors.ACIError:
logger.debug("LDAP Error: Anonymous access not allowed")
return [NO_ACCESS_TO_LDAP]
except errors.DatabaseError as err:
logger.debug("Error checking LDAP: %s", err.strerror)
return [UNKNOWN_ERROR]
except Exception as err:
logger.debug("Error checking LDAP: %s", err)
return [UNKNOWN_ERROR]
def ipadns_search_srv(self, domain, srv_record_name, default_port,
break_on_first=True):
"""
Search for SRV records in given domain. When no record is found,
en empty list is returned
:param domain: Search domain name
:param srv_record_name: SRV record name, e.g. "_ldap._tcp"
:param default_port: When default_port is not None, it is being
checked with the port in SRV record and if they don't
match, the port from SRV record is appended to
found hostname in this format: "hostname:port"
:param break_on_first: break on the first find and return just one
entry
"""
servers = []
qname = '%s.%s' % (srv_record_name, domain)
logger.debug("Search DNS for SRV record of %s", qname)
try:
answers = query_srv(qname)
except DNSException as e:
logger.debug("DNS record not found: %s", e.__class__.__name__)
answers = []
for answer in answers:
logger.debug("DNS record found: %s", answer)
server = str(answer.target).rstrip(".")
if not server:
logger.debug("Cannot parse the hostname from SRV record: %s",
answer)
continue
if default_port is not None and answer.port != default_port:
server = "%s:%s" % (server, str(answer.port))
servers.append(server)
if break_on_first:
break
return servers
def ipadnssearchkrbrealm(self, domain=None):
"""
:param domain: Domain to be searched in
:returns: string of a realm found in a TXT record
None if no realm was found
"""
if not domain:
domain = self.domain
# now, check for a Kerberos realm the local host or domain is in
qname = "_kerberos." + domain
logger.debug("Search DNS for TXT record of %s", qname)
try:
answers = resolve(qname, rdatatype.TXT)
except DNSException as e:
logger.debug("DNS record not found: %s", e.__class__.__name__)
answers = []
realm = None
for answer in answers:
logger.debug("DNS record found: %s", answer)
if answer.strings:
try:
realm = answer.strings[0].decode('utf-8')
except UnicodeDecodeError as e:
logger.debug(
'A TXT record cannot be decoded as UTF-8: %s', e)
continue
if realm:
# Make sure that the realm is not single-label
try:
validate_domain_name(realm, entity='realm')
except ValueError as e:
logger.debug("Skipping invalid realm '%s' (%s)",
realm, e)
continue
return realm
return None
def ipadnssearchkrbkdc(self, domain=None):
if not domain:
domain = self.domain
kdc = self.ipadns_search_srv(domain, '_kerberos._udp', 88,
break_on_first=False)
if kdc:
kdc = ','.join(kdc)
else:
logger.debug("SRV record for KDC not found! Domain: %s", domain)
kdc = None
return kdc
def main():
import argparse
import os
from ipapython.ipa_log_manager import standard_logging_setup
parser = argparse.ArgumentParser(__name__)
if os.path.isfile(paths.IPA_CA_CRT):
default_ca = paths.IPA_CA_CRT
else:
default_ca = None
parser.add_argument('--ca-cert', default=default_ca)
parser.add_argument('--debug', action='store_true')
parser.add_argument('domain')
args = parser.parse_args()
standard_logging_setup(debug=args.debug)
discover = IPADiscovery()
result = discover.search(args.domain, ca_cert_path=args.ca_cert)
for key in ['realm', 'domain', 'basedn', 'server', 'servers']:
value = str(getattr(discover, key))
source_key = "{}_source".format(key)
source = getattr(discover, source_key, None)
if source is not None:
print("{:<8} {:<32}\t({})".format(key, value, source))
else:
print("{:<8} {:<32}".format(key, value))
parser.exit(
abs(result),
"{}\n".format(error_names.get(result, result))
)
if __name__ == '__main__':
main()
| 23,867
|
Python
|
.py
| 554
| 30.218412
| 79
| 0.551503
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,898
|
__init__.py
|
freeipa_freeipa/ipaclient/remote_plugins/__init__.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from collections.abc import MutableMapping
import errno
import json
import locale
import logging
import os
import time
from . import compat
from . import schema
from ipaclient.plugins.rpcclient import rpcclient
from ipapython.dnsutil import DNSName
logger = logging.getLogger(__name__)
class ServerInfo(MutableMapping):
def __init__(self, api):
self._dir = os.path.join(api.env.cache_dir, "servers")
hostname = DNSName(api.env.server).ToASCII()
self._filename = os.path.join(self._dir, hostname)
self._force_check = api.env.force_schema_check
self._now = time.time()
self._dict = {}
# copy-paste from ipalib/rpc.py
try:
self._language = locale.setlocale(
locale.LC_MESSAGES, ''
).split('.', maxsplit=1)[0].lower()
except locale.Error:
self._language = 'en_us'
self._read()
def _read(self):
try:
with open(self._filename, 'r') as sc:
self._dict = json.load(sc)
except Exception as e:
if (isinstance(e, EnvironmentError) and
e.errno == errno.ENOENT): # pylint: disable=no-member
# ignore non-existent file, this happens when the cache was
# erased or the server is contacted for the first time
pass
else:
# warn that the file is unreadable, probably corrupted
logger.warning('Failed to read server info: %s', e)
def _write(self):
try:
try:
os.makedirs(self._dir)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
with open(self._filename, 'w') as sc:
json.dump(self._dict, sc)
except EnvironmentError as e:
logger.warning('Failed to write server info: %s', e)
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
def __delitem__(self, key):
del self._dict[key]
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
def update_validity(self, ttl):
if not self.is_valid():
self['expiration'] = self._now + ttl
self['language'] = self._language
self._write()
def is_valid(self):
if self._force_check:
return False
try:
expiration = self._dict['expiration']
language = self._dict['language']
except KeyError:
# if any of these is missing consider the entry expired
return False
if expiration < self._now:
return False
if language != self._language:
# language changed since last check
return False
return True
def get_package(api):
if api.env.in_tree:
# server packages are not published on pypi.org
# pylint: disable=useless-suppression
# pylint: disable=import-error,ipa-forbidden-import
from ipaserver import plugins
# pylint: enable=import-error,ipa-forbidden-import
# pylint: enable=useless-suppression
else:
try:
plugins = api._remote_plugins
except AttributeError:
server_info = ServerInfo(api)
client = rpcclient(api)
client.finalize()
try:
plugins = schema.get_package(server_info, client)
except schema.NotAvailable:
plugins = compat.get_package(server_info, client)
finally:
if client.isconnected():
client.disconnect()
object.__setattr__(api, '_remote_plugins', plugins)
return plugins
| 3,933
|
Python
|
.py
| 109
| 26.220183
| 75
| 0.581359
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,899
|
compat.py
|
freeipa_freeipa/ipaclient/remote_plugins/compat.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import unicode_literals
import importlib
import os
import re
import sys
import six
from ipaclient.frontend import ClientCommand, ClientMethod
from ipalib.frontend import Object
from ipapython.ipautil import APIVersion
if six.PY3:
unicode = str
class CompatCommand(ClientCommand):
@property
def forwarded_name(self):
return self.name
class CompatMethod(ClientMethod, CompatCommand):
pass
class CompatObject(Object):
pass
def get_package(server_info, client):
try:
server_version = server_info['version']
except KeyError:
is_valid = False
else:
is_valid = server_info.is_valid()
if not is_valid:
if not client.isconnected():
client.connect(verbose=False)
env = client.forward('env', 'api_version', version='2.0')
try:
server_version = env['result']['api_version']
except KeyError:
ping = client.forward('ping', version='2.0')
try:
match = re.search(r'API version (2\.[0-9]+)', ping['summary'])
except KeyError:
match = None
if match is not None:
server_version = match.group(1)
else:
server_version = '2.0'
server_info['version'] = server_version
# in compat mode we don't get the schema TTL from the server
# so use the client context value.
server_info.update_validity(client.api.env.schema_ttl)
server_version = APIVersion(server_version)
package_names = {}
base_name = __name__.rpartition('.')[0]
base_dir = os.path.dirname(__file__)
for name in os.listdir(base_dir):
package_dir = os.path.join(base_dir, name)
if name.startswith('2_') and os.path.isdir(package_dir):
package_version = APIVersion(name.replace('_', '.'))
package_names[package_version] = '{}.{}'.format(base_name, name)
package_version = None
for version in sorted(package_names):
if package_version is None or package_version < version:
package_version = version
if version >= server_version:
break
package_name = package_names[package_version]
try:
package = sys.modules[package_name]
except KeyError:
package = importlib.import_module(package_name)
return package
| 2,462
|
Python
|
.py
| 70
| 27.885714
| 78
| 0.642074
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|