diff options
-rw-r--r-- | ipa_server/ipaldap.py | 7 | ||||
-rw-r--r-- | ipa_server/servercore.py | 183 | ||||
-rw-r--r-- | ipalib/errors.py | 42 | ||||
-rw-r--r-- | ipalib/plugins/f_delegation.py | 2 | ||||
-rw-r--r-- | ipalib/plugins/f_pwpolicy.py | 100 | ||||
-rw-r--r-- | ipalib/plugins/f_user.py | 38 | ||||
-rwxr-xr-x | test_server | 4 |
7 files changed, 350 insertions, 26 deletions
diff --git a/ipa_server/ipaldap.py b/ipa_server/ipaldap.py index b791e18e..6a7e6644 100644 --- a/ipa_server/ipaldap.py +++ b/ipa_server/ipaldap.py @@ -396,8 +396,7 @@ class IPAdmin(SimpleLDAPObject): modlist = self.generateModList(oldentry, newentry) if len(modlist) == 0: - # FIXME: better error - raise SyntaxError("empty modlist") + raise errors.EmptyModlist try: if sctrl is not None: @@ -407,9 +406,9 @@ class IPAdmin(SimpleLDAPObject): # it indicates the previous attribute was removed by another # update, making the oldentry stale. except ldap.NO_SUCH_ATTRIBUTE: - raise ipaldap.MidairCollision + raise errors.MidairCollision except ldap.LDAPError, e: - raise ipaldap.DatabaseError, e + raise errors.DatabaseError, e return True def generateModList(self, old_entry, new_entry): diff --git a/ipa_server/servercore.py b/ipa_server/servercore.py index 29a8afbd..3e98e6f6 100644 --- a/ipa_server/servercore.py +++ b/ipa_server/servercore.py @@ -21,6 +21,7 @@ import ldap import string import re from ipa_server.context import context +from ipa_server import ipaldap import ipautil from ipalib import errors @@ -123,6 +124,37 @@ def get_list (base, searchfilter, sattrs=None): return map(convert_entry, entries) +def has_nsaccountlock(dn): + """Check to see if an entry has the nsaccountlock attribute. + This attribute is provided by the Class of Service plugin so + doing a search isn't enough. It is provided by the two + entries cn=inactivated and cn=activated. So if the entry has + the attribute and isn't in either cn=activated or cn=inactivated + then the attribute must be in the entry itself. + + Returns True or False + """ + # First get the entry. If it doesn't have nsaccountlock at all we + # can exit early. + entry = get_entry_by_dn(dn, ['dn', 'nsaccountlock', 'memberof']) + if not entry.get('nsaccountlock'): + return False + + # Now look to see if they are in activated or inactivated + # entry is a member + memberof = entry.get('memberof') + if isinstance(memberof, basestring): + memberof = [memberof] + for m in memberof: + inactivated = m.find("cn=inactivated") + activated = m.find("cn=activated") + # if they are in either group that means that the nsaccountlock + # value comes from there, otherwise it must be in this entry. + if inactivated >= 0 or activated >= 0: + return False + + return True + # General searches def get_entry_by_dn (dn, sattrs=None): @@ -142,6 +174,14 @@ def get_entry_by_cn (cn, sattrs): searchfilter = "(cn=%s)" % cn return get_sub_entry("cn=accounts," + basedn, searchfilter, sattrs) +def get_user_by_uid(uid, sattrs): + """Get a specific user's entry.""" + # FIXME: should accept a container to look in +# uid = self.__safe_filter(uid) + searchfilter = "(&(uid=%s)(objectclass=posixAccount))" % uid + + return get_sub_entry("cn=accounts," + basedn, searchfilter, sattrs) + # User support def user_exists(uid): @@ -152,10 +192,9 @@ def user_exists(uid): searchfilter = "(&(uid=%s)(objectclass=posixAccount))" % uid try: - entry = get_sub_entry("cn=accounts," + basedn, searchfilter, ['dn','uid']) - return False -# except ipaerror.exception_for(ipaerror.LDAP_NOT_FOUND): - except Exception: + get_sub_entry("cn=accounts," + basedn, searchfilter, ['dn','uid']) + return True + except errors.NotFound: return True def get_user_by_uid (uid, sattrs): @@ -348,3 +387,139 @@ def get_ipa_config(): raise errors.NotFound return config + +def mark_entry_active (dn): + """Mark an entry as active in LDAP.""" + + # This can be tricky. The entry itself can be marked inactive + # by being in the inactivated group. It can also be inactivated by + # being the member of an inactive group. + # + # First we try to remove the entry from the inactivated group. Then + # if it is still inactive we have to add it to the activated group + # which will override the group membership. + + res = "" + # First, check the entry status + entry = get_entry_by_dn(dn, ['dn', 'nsAccountlock']) + + if entry.get('nsaccountlock', 'false').lower() == "false": +# logging.debug("IPA: already active") + raise errors.AlreadyActiveError + + if has_nsaccountlock(dn): +# logging.debug("IPA: appears to have the nsaccountlock attribute") + raise errors.HasNSAccountLock + + group = get_entry_by_cn("inactivated", None) + try: + remove_member_from_group(entry.get('dn'), group.get('dn')) + except errors.NotGroupMember: + # Perhaps the user is there as a result of group membership + pass + + # Now they aren't a member of inactivated directly, what is the status + # now? + entry = get_entry_by_dn(dn, ['dn', 'nsAccountlock']) + + if entry.get('nsaccountlock', 'false').lower() == "false": + # great, we're done +# logging.debug("IPA: removing from inactivated did it.") + return res + + # So still inactive, add them to activated + group = get_entry_by_cn("activated", None) + res = add_member_to_group(dn, group.get('dn')) +# logging.debug("IPA: added to activated.") + + return res + +def mark_entry_inactive (dn): + """Mark an entry as inactive in LDAP.""" + + entry = get_entry_by_dn(dn, ['dn', 'nsAccountlock', 'memberOf']) + + if entry.get('nsaccountlock', 'false').lower() == "true": +# logging.debug("IPA: already marked as inactive") + raise errors.AlreadyInactiveError + + if has_nsaccountlock(dn): +# logging.debug("IPA: appears to have the nsaccountlock attribute") + raise errors.HasNSAccountLock + + # First see if they are in the activated group as this will override + # the our inactivation. + group = get_entry_by_cn("activated", None) + try: + remove_member_from_group(dn, group.get('dn')) + except errors.NotGroupMember: + # this is fine, they may not be explicitly in this group + pass + + # Now add them to inactivated + group = get_entry_by_cn("inactivated", None) + res = add_member_to_group(dn, group.get('dn')) + + return res + +def add_member_to_group(member_dn, group_dn): + """Add a member to an existing group.""" +# logging.info("IPA: add_member_to_group '%s' to '%s'" % (member_dn, group_dn)) + if member_dn.lower() == group_dn.lower(): + # You can't add a group to itself + raise errors.SameGroupError + + group = get_entry_by_dn(group_dn, None) + if group is None: + raise errors.NotFound + + # check to make sure member_dn exists + member_entry = get_base_entry(member_dn, "(objectClass=*)", ['dn','objectclass']) + if not member_entry: + raise errors.NotFound + + if group.get('member') is not None: + if isinstance(group.get('member'),basestring): + group['member'] = [group['member']] + group['member'].append(member_dn) + else: + group['member'] = member_dn + + try: + return update_entry(group) + except errors.EmptyModlist: + raise + +def remove_member_from_group(member_dn, group_dn=None): + """Remove a member_dn from an existing group.""" + + group = get_entry_by_dn(group_dn, None) + if group is None: + raise errors.NotFound + """ + if group.get('cn') == "admins": + member = get_entry_by_dn(member_dn, ['dn','uid']) + if member.get('uid') == "admin": + raise ipaerror.gen_exception(ipaerror.INPUT_ADMIN_REQUIRED_IN_ADMINS) + """ +# logging.info("IPA: remove_member_from_group '%s' from '%s'" % (member_dn, group_dn)) + + if group.get('member') is not None: + if isinstance(group.get('member'),basestring): + group['member'] = [group['member']] + for i in range(len(group['member'])): + group['member'][i] = ipaldap.IPAdmin.normalizeDN(group['member'][i]) + try: + group['member'].remove(member_dn) + except ValueError: + # member is not in the group + # FIXME: raise more specific error? + raise errors.NotGroupMember + else: + # Nothing to do if the group has no members + raise errors.NotGroupMember + + try: + return update_entry(group) + except errors.EmptyModlist: + raise diff --git a/ipalib/errors.py b/ipalib/errors.py index d0d917f6..f1c9e26e 100644 --- a/ipalib/errors.py +++ b/ipalib/errors.py @@ -286,57 +286,73 @@ class SameGroupError(InputError): """You can't add a group to itself""" faultCode = 1008 +class NotGroupMember(InputError): + """This entry is not a member of the group""" + faultCode = 1009 + class AdminsImmutable(InputError): """The admins group cannot be renamed""" - faultCode = 1009 + faultCode = 1010 class UsernameTooLong(InputError): """The requested username is too long""" - faultCode = 1010 + faultCode = 1011 class PrincipalError(GenericError): """There is a problem with the kerberos principal""" - faultCode = 1011 + faultCode = 1012 class MalformedServicePrincipal(PrincipalError): """The requested service principal is not of the form: service/fully-qualified host name""" - faultCode = 1012 + faultCode = 1013 class RealmMismatch(PrincipalError): """The realm for the principal does not match the realm for this IPA server""" - faultCode = 1013 + faultCode = 1014 class PrincipalRequired(PrincipalError): """You cannot remove IPA server service principals""" - faultCode = 1014 + faultCode = 1015 class InactivationError(GenericError): """This entry cannot be inactivated""" - faultCode = 1015 + faultCode = 1016 + +class AlreadyActiveError(InactivationError): + """This entry is already locked""" + faultCode = 1017 + +class AlreadyInactiveError(InactivationError): + """This entry is already unlocked""" + faultCode = 1018 + +class HasNSAccountLock(InactivationError): + """This entry appears to have the nsAccountLock attribute in it so the Class of Service activation/inactivation will not work. You will need to remove the attribute nsAccountLock for this to work.""" + faultCode = 1019 class ConnectionError(GenericError): """Connection to database failed""" - faultCode = 1016 + faultCode = 1020 class NoCCacheError(GenericError): """No Kerberos credentials cache is available. Connection cannot be made""" - faultCode = 1017 + faultCode = 1021 class GSSAPIError(GenericError): """GSSAPI Authorization error""" - faultCode = 1018 + faultCode = 1022 class ServerUnwilling(GenericError): """Account inactivated. Server is unwilling to perform""" - faultCode = 1018 + faultCode = 1023 class ConfigurationError(GenericError): """A configuration error occurred""" - faultCode = 1019 + faultCode = 1024 class DefaultGroup(ConfigurationError): """You cannot remove the default users group""" - faultCode = 1020 + faultCode = 1025 class FunctionDeprecated(GenericError): """Raised by a deprecated function""" diff --git a/ipalib/plugins/f_delegation.py b/ipalib/plugins/f_delegation.py index 762df1db..1fb2b4f9 100644 --- a/ipalib/plugins/f_delegation.py +++ b/ipalib/plugins/f_delegation.py @@ -40,7 +40,7 @@ class delegation(frontend.Object): 'target', Param('name', primary_key=True) ) -api.register(user) +api.register(delegation) class delegation_add(crud.Add): diff --git a/ipalib/plugins/f_pwpolicy.py b/ipalib/plugins/f_pwpolicy.py new file mode 100644 index 00000000..36e232dc --- /dev/null +++ b/ipalib/plugins/f_pwpolicy.py @@ -0,0 +1,100 @@ +# 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; version 2 only +# +# 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, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +""" +Frontend plugins for password policy. +""" + +from ipalib import frontend +from ipalib import crud +from ipalib.frontend import Param +from ipalib import api +from ipalib import errors +from ipalib import ipa_types +from ipa_server import servercore +from ipa_server import ipaldap +import ldap + + +class pwpolicy_mod(frontend.Command): + 'Edit existing password policy.' + # FIXME, switch to more human-readable names at some point + takes_options = ( + Param('krbmaxpwdlife?', type=ipa_types.Int(), doc='Max. Password Lifetime (days)'), + Param('krbminpwdlife?', type=ipa_types.Int(), doc='Min. Password Lifetime (hours)'), + Param('krbpwdhistorylength?', type=ipa_types.Int(), doc='Password History Size'), + Param('krbpwdmindiffchars?', type=ipa_types.Int(), doc='Min. Number of Character Classes'), + Param('krbpwdminlength?', type=ipa_types.Int(), doc='Min. Length of Password'), + ) + def execute(self, *args, **kw): + # Get the existing policy entry + oldpolicy = servercore.get_entry_by_cn("accounts", None) + + # Convert the existing policy into an entry object + dn = oldpolicy.get('dn') + del oldpolicy['dn'] + entry = ipaldap.Entry((dn, servercore.convert_scalar_values(oldpolicy))) + + # FIXME: if the user passed no options should we return something + # more than No modifications to be performed? + + policy = kw + + # The LDAP routines want strings, not ints, so convert a few + # things. Otherwise it sees a string -> int conversion as a change. + for k in policy.iterkeys(): + if k.startswith("krb", 0, 3): + policy[k] = str(policy[k]) + + # Convert hours and days to seconds + if policy.get('krbmaxpwdlife'): + policy['krbmaxpwdlife'] = str(int(policy.get('krbmaxpwdlife')) * 86400) + if policy.get('krbminpwdlife'): + policy['krbminpwdlife'] = str(int(policy.get('krbminpwdlife')) * 3600) + # Update the values passed-in + for p in policy: + # Values need to be strings, not integers + entry.setValues(p, str(policy[p])) + + result = servercore.update_entry(entry.toDict()) + + return result + def forward(self, *args, **kw): + result = super(pwpolicy_mod, self).forward(*args, **kw) + if result: + print "Policy modified" +api.register(pwpolicy_mod) + + +class pwpolicy_show(frontend.Command): + 'Retrieve current password policy' + def execute(self, *args, **kw): + policy = servercore.get_entry_by_cn("accounts", None) + + # convert some values for display purposes + policy['krbmaxpwdlife'] = str(int(policy.get('krbmaxpwdlife')) / 86400) + policy['krbminpwdlife'] = str(int(policy.get('krbminpwdlife')) / 3600) + + return policy + + def forward(self, *args, **kw): + result = super(pwpolicy_show, self).forward(*args, **kw) + if not result: return + print result +api.register(pwpolicy_show) diff --git a/ipalib/plugins/f_user.py b/ipalib/plugins/f_user.py index 9dbc93cb..ff459b3d 100644 --- a/ipalib/plugins/f_user.py +++ b/ipalib/plugins/f_user.py @@ -26,6 +26,7 @@ from ipalib import crud from ipalib.frontend import Param from ipalib import api from ipalib import errors +from ipalib import ipa_types from ipa_server import servercore from ipa_server import ipaldap import ldap @@ -136,7 +137,7 @@ class user_add(crud.Add): user['gidnumber'] = default_group.get('gidnumber') except errors.NotFound: # Fake an LDAP error so we can return something useful to the user - raise ipalib.NotFound, "The default group for new users, '%s', cannot be found." % config.get('ipadefaultprimarygroup') + raise errors.NotFound, "The default group for new users, '%s', cannot be found." % config.get('ipadefaultprimarygroup') except Exception, e: # catch everything else raise e @@ -203,7 +204,9 @@ class user_mod(crud.Mod): 'Edit an existing user.' def execute(self, *args, **kw): uid=args[0] - result = servercore.get_sub_entry(servercore.basedn, "uid=%s" % uid, ["*"]) + + # Get the existing user entry + result = servercore.get_sub_entry("cn=accounts," + servercore.basedn, "uid=%s" % uid, ["*"]) user = kw dn = result.get('dn') @@ -263,3 +266,34 @@ class user_show(crud.Get): except errors.NotFound: print "User %s not found" % args[0] api.register(user_show) + +class user_lock(frontend.Command): + 'Lock a user account.' + takes_args = ( + Param('uid', primary_key=True), + ) + def execute(self, *args, **kw): + uid = args[0] + user = servercore.get_user_by_uid(uid, ['dn', 'uid']) + return servercore.mark_entry_inactive(user['dn']) + def forward(self, *args, **kw): + result = super(user_lock, self).forward(*args, **kw) + if result: + print "User locked" +api.register(user_lock) + +class user_unlock(frontend.Command): + 'Unlock a user account.' + takes_args = ( + Param('uid', primary_key=True), + ) + def execute(self, *args, **kw): + uid = args[0] + user = servercore.get_user_by_uid(uid, ['dn', 'uid']) + return servercore.mark_entry_active(user['dn']) + def forward(self, *args, **kw): + result = super(user_unlock, self).forward(*args, **kw) + if result: + print "User unlocked" +api.register(user_unlock) + diff --git a/test_server b/test_server index 0ee250ad..d26fd596 100755 --- a/test_server +++ b/test_server @@ -143,9 +143,9 @@ XMLRPCServer.register_introspection_functions() # Get and register all the methods api.env.server_context = True api.finalize() -for cmd in api.Method: +for cmd in api.Command: logger.info("registering %s" % cmd) - XMLRPCServer.register_function(api.Method[cmd], cmd) + XMLRPCServer.register_function(api.Command[cmd], cmd) funcs = XMLRPCServer.funcs |