def test_client_has_capability(): assert capabilities['messages'] == u'2.52' assert client_has_capability(u'2.52', 'messages') assert client_has_capability(u'2.60', 'messages') assert client_has_capability(u'3.0', 'messages') assert not client_has_capability(u'2.11', 'messages') assert not client_has_capability(u'0.1', 'messages')
def test_client_has_capability(): assert capabilities["messages"] == u"2.52" assert client_has_capability(u"2.52", "messages") assert client_has_capability(u"2.60", "messages") assert client_has_capability(u"3.0", "messages") assert not client_has_capability(u"2.11", "messages") assert not client_has_capability(u"0.1", "messages")
def xml_wrap(value, version): """ Wrap all ``str`` in ``xmlrpc.client.Binary``. Because ``xmlrpc.client.dumps()`` will itself convert all ``unicode`` instances into UTF-8 encoded ``str`` instances, we don't do it here. So in total, when encoding data for an XML-RPC packet, the following transformations occur: * All ``str`` instances are treated as binary data and are wrapped in an ``xmlrpc.client.Binary()`` instance. * Only ``unicode`` instances are treated as character data. They get converted to UTF-8 encoded ``str`` instances (although as mentioned, not by this function). Also see `xml_unwrap()`. :param value: The simple scalar or simple compound value to wrap. """ if type(value) in (list, tuple): return tuple(xml_wrap(v, version) for v in value) if isinstance(value, dict): return dict( (k, xml_wrap(v, version)) for (k, v) in value.items() ) if type(value) is bytes: return Binary(value) if type(value) is Decimal: # transfer Decimal as a string return unicode(value) if isinstance(value, six.integer_types) and (value < MININT or value > MAXINT): return unicode(value) if isinstance(value, DN): return str(value) # Encode datetime.datetime objects as xmlrpc.client.DateTime objects if isinstance(value, datetime.datetime): if capabilities.client_has_capability(version, 'datetime_values'): return DateTime(value) else: return value.strftime(LDAP_GENERALIZED_TIME_FORMAT) if isinstance(value, DNSName): if capabilities.client_has_capability(version, 'dns_name_values'): return {'__dns_name__': unicode(value)} else: return unicode(value) if isinstance(value, Principal): return unicode(value) if isinstance(value, crypto_x509.Certificate): return base64.b64encode( value.public_bytes(x509_Encoding.DER)).encode('ascii') assert type(value) in (unicode, float, bool, type(None)) + six.integer_types return value
def xml_wrap(value, version): """ Wrap all ``str`` in ``xmlrpc.client.Binary``. Because ``xmlrpc.client.dumps()`` will itself convert all ``unicode`` instances into UTF-8 encoded ``str`` instances, we don't do it here. So in total, when encoding data for an XML-RPC packet, the following transformations occur: * All ``str`` instances are treated as binary data and are wrapped in an ``xmlrpc.client.Binary()`` instance. * Only ``unicode`` instances are treated as character data. They get converted to UTF-8 encoded ``str`` instances (although as mentioned, not by this function). Also see `xml_unwrap()`. :param value: The simple scalar or simple compound value to wrap. """ if type(value) in (list, tuple): return tuple(xml_wrap(v, version) for v in value) if isinstance(value, dict): return dict((k, xml_wrap(v, version)) for (k, v) in value.items()) if type(value) is bytes: return Binary(value) if type(value) is Decimal: # transfer Decimal as a string return unicode(value) if isinstance(value, six.integer_types) and (value < MININT or value > MAXINT): return unicode(value) if isinstance(value, DN): return str(value) # Encode datetime.datetime objects as xmlrpc.client.DateTime objects if isinstance(value, datetime.datetime): if capabilities.client_has_capability(version, 'datetime_values'): return DateTime(value) else: return value.strftime(LDAP_GENERALIZED_TIME_FORMAT) if isinstance(value, DNSName): if capabilities.client_has_capability(version, 'dns_name_values'): return {'__dns_name__': unicode(value)} else: return unicode(value) if isinstance(value, Principal): return unicode(value) if isinstance(value, crypto_x509.Certificate): return base64.b64encode(value.public_bytes( x509_Encoding.DER)).decode('ascii') assert type(value) in (unicode, float, bool, type(None)) + six.integer_types return value
def json_encode_binary(val, version): """ JSON cannot encode binary values. We encode binary values in Python str objects and text in Python unicode objects. In order to allow a binary object to be passed through JSON we base64 encode it thus converting it to text which JSON can transport. To assure we recognize the value is a base64 encoded representation of the original binary value and not confuse it with other text we convert the binary value to a dict in this form: {'__base64__' : base64_encoding_of_binary_value} This modification of the original input value cannot be done "in place" as one might first assume (e.g. replacing any binary items in a container (e.g. list, tuple, dict) with the base64 dict because the container might be an immutable object (i.e. a tuple). Therefore this function returns a copy of any container objects it encounters with tuples replaced by lists. This is O.K. because the JSON encoding will map both lists and tuples to JSON arrays. """ if isinstance(val, dict): new_dict = {} for k, v in val.items(): new_dict[k] = json_encode_binary(v, version) return new_dict elif isinstance(val, (list, tuple)): new_list = [json_encode_binary(v, version) for v in val] return new_list elif isinstance(val, bytes): encoded = base64.b64encode(val) if not six.PY2: encoded = encoded.decode("ascii") return {"__base64__": encoded} elif isinstance(val, Decimal): return {"__base64__": base64.b64encode(str(val))} elif isinstance(val, DN): return str(val) elif isinstance(val, datetime.datetime): if capabilities.client_has_capability(version, "datetime_values"): return {"__datetime__": val.strftime(LDAP_GENERALIZED_TIME_FORMAT)} else: return val.strftime(LDAP_GENERALIZED_TIME_FORMAT) elif isinstance(val, DNSName): if capabilities.client_has_capability(version, "dns_name_values"): return {"__dns_name__": unicode(val)} else: return unicode(val) elif isinstance(val, Principal): return unicode(val) else: return val
def json_encode_binary(val, version): ''' JSON cannot encode binary values. We encode binary values in Python str objects and text in Python unicode objects. In order to allow a binary object to be passed through JSON we base64 encode it thus converting it to text which JSON can transport. To assure we recognize the value is a base64 encoded representation of the original binary value and not confuse it with other text we convert the binary value to a dict in this form: {'__base64__' : base64_encoding_of_binary_value} This modification of the original input value cannot be done "in place" as one might first assume (e.g. replacing any binary items in a container (e.g. list, tuple, dict) with the base64 dict because the container might be an immutable object (i.e. a tuple). Therefore this function returns a copy of any container objects it encounters with tuples replaced by lists. This is O.K. because the JSON encoding will map both lists and tuples to JSON arrays. ''' if isinstance(val, dict): new_dict = {} for k, v in val.items(): new_dict[k] = json_encode_binary(v, version) return new_dict elif isinstance(val, (list, tuple)): new_list = [json_encode_binary(v, version) for v in val] return new_list elif isinstance(val, bytes): encoded = base64.b64encode(val) if not six.PY2: encoded = encoded.decode('ascii') return {'__base64__': encoded} elif isinstance(val, Decimal): return {'__base64__': base64.b64encode(str(val))} elif isinstance(val, DN): return str(val) elif isinstance(val, datetime.datetime): if capabilities.client_has_capability(version, 'datetime_values'): return {'__datetime__': val.strftime(LDAP_GENERALIZED_TIME_FORMAT)} else: return val.strftime(LDAP_GENERALIZED_TIME_FORMAT) elif isinstance(val, DNSName): if capabilities.client_has_capability(version, 'dns_name_values'): return {'__dns_name__': unicode(val)} else: return unicode(val) elif isinstance(val, Principal): return unicode(val) else: return val
def _enc_dnsname(self, val): cap = self._cap_dnsname if cap is None: cap = capabilities.client_has_capability(self.version, 'dns_name_values') self._cap_dnsname = cap if cap: return {'__dns_name__': unicode(val)} else: return unicode(val)
def _enc_datetime(self, val): cap = self._cap_datetime if cap is None: cap = capabilities.client_has_capability(self.version, 'datetime_values') self._cap_datetime = cap if cap: return {'__datetime__': val.strftime(LDAP_GENERALIZED_TIME_FORMAT)} else: return val.strftime(LDAP_GENERALIZED_TIME_FORMAT)
def validate(self, cmd, values, version): if client_has_capability(version, 'primary_key_types'): types = (tuple, list) else: types = (unicode, ) if not isinstance(values, types): raise TypeError("%s.validate_output() => %s.validate():\n" " output[%r]: need %r; got %r: %r" % (cmd.name, self.__class__.__name__, self.name, types[0], type(values), values)) if client_has_capability(version, 'primary_key_types'): if hasattr(cmd, 'obj') and cmd.obj and cmd.obj.primary_key: types = cmd.obj.primary_key.allowed_types else: types = (unicode, ) for (i, value) in enumerate(values): if not isinstance(value, types): raise TypeError(emsg % (cmd.name, self.__class__.__name__, i, self.name, types[0], type(value), value))
def validate(self, cmd, values, version): if client_has_capability(version, 'primary_key_types'): types = (tuple, list) else: types = (unicode,) if not isinstance(values, types): raise TypeError( "%s.validate_output() => %s.validate():\n" " output[%r]: need %r; got %r: %r" % ( cmd.name, self.__class__.__name__, self.name, types[0], type(values), values)) if client_has_capability(version, 'primary_key_types'): if hasattr(cmd, 'obj') and cmd.obj and cmd.obj.primary_key: types = cmd.obj.primary_key.allowed_types else: types = (unicode,) for (i, value) in enumerate(values): if not isinstance(value, types): raise TypeError(emsg % ( cmd.name, self.__class__.__name__, i, self.name, types[0], type(value), value))
def validate(self, cmd, value, version): if client_has_capability(version, "primary_key_types"): if hasattr(cmd, "obj") and cmd.obj and cmd.obj.primary_key: types = cmd.obj.primary_key.allowed_types else: types = (unicode,) types = types + (NoneType,) else: types = (unicode,) if not isinstance(value, types): raise TypeError( "%s.validate_output() => %s.validate():\n" " output[%r]: need %r; got %r: %r" % (cmd.name, self.__class__.__name__, self.name, types[0], type(value), value) )
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', [paths.SH])[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(baseuser_pwdchars) # 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 return dn
def add_message(version, result, message): if client_has_capability(version, 'messages'): result.setdefault('messages', []).append(message.to_dict())
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 self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys, **options) return dn
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): 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', [paths.SH])[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') if 'ipauserauthtype' in entry_attrs and \ 'ipauserauthtypeclass' not in entry_attrs['objectclass']: entry_attrs['objectclass'].append('ipauserauthtypeclass') 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 self.pre_common_callback(ldap, dn, entry_attrs, attrs_list, *keys, **options) return dn
def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options): assert isinstance(dn, DN) if not options.get('noprivate', False): 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()[1] 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', ['/bin/sh'])[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', ['/home'])[0] # build user's home directory based on his uid entry_attrs['homedirectory'] = posixpath.join(homes_root, keys[-1]) entry_attrs.setdefault('krbpwdpolicyreference', DN(('cn', 'global_policy'), ('cn', api.env.realm), ('cn', 'kerberos'), api.env.basedn)) 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_dn, 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(user_pwdchars) # 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']) 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 return dn
def preprocess_options(self, options): """Preprocess options (in-place)""" 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: memberof = options.pop('memberof') if memberof: if 'ipapermtargetfilter' in options: raise errors.ValidationError( name='ipapermtargetfilter', error=_('filter and memberof are mutually exclusive')) try: groupdn = self.api.Object.group.get_dn_if_exists(memberof) except errors.NotFound: raise errors.NotFound( reason=_('%s: group not found') % memberof) options['ipapermtargetfilter'] = u'(memberOf=%s)' % groupdn else: if 'ipapermtargetfilter' not in options: options['ipapermtargetfilter'] = None # 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') if objtype: if 'ipapermlocation' in options: raise errors.ValidationError( name='ipapermlocation', error=_('subtree and type are mutually exclusive')) if 'ipapermtarget' in options: raise errors.ValidationError( name='ipapermtarget', error=_('target and type are mutually exclusive')) obj = self.api.Object[objtype.lower()] container_dn = DN(obj.container_dn, self.api.env.basedn) options['ipapermtarget'] = DN( (obj.rdn_attribute or obj.primary_key.name, '*'), container_dn) options['ipapermlocation'] = container_dn else: if 'ipapermtarget' not in options: options['ipapermtarget'] = None if 'ipapermlocation' not in options: options['ipapermlocation'] = None
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``. """ if not options.get('raw') and not options.get('pkey_only'): ipapermtargetfilter = entry.single_value.get('ipapermtargetfilter', '') ipapermtarget = entry.single_value.get('ipapermtarget') ipapermlocation = entry.single_value.get('ipapermlocation') # memberof match = re.match('^\(memberof=(.*)\)$', ipapermtargetfilter, re.I) if match: dn = DN(match.group(1)) if dn[1:] == DN(self.api.Object.group.container_dn, self.api.env.basedn)[:] and dn[0].attr == 'cn': entry.single_value['memberof'] = dn[0].value # 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 # type if ipapermtarget and ipapermlocation: for objname in VALID_OBJECT_TYPES: obj = self.api.Object[objname] wantdn = DN(obj.container_dn, self.api.env.basedn) if DN(ipapermlocation) == wantdn: targetdn = DN( (obj.rdn_attribute or obj.primary_key.name, '*'), obj.container_dn, self.api.env.basedn) if ipapermtarget == targetdn: entry.single_value['type'] = objname break # old output names if not client_has_capability(options['version'], 'permissions2'): 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: rights['memberof'] = rights['ipapermtargetfilter'] rights['targetgroup'] = rights['ipapermtarget'] type_rights = set(rights['ipapermtarget']) type_rights.intersection_update(rights['ipapermlocation']) rights['type'] = ''.join(sorted(type_rights, key=rights['ipapermtarget'].index)) if not client_has_capability(options['version'], 'permissions2'): for old_name, new_name in _DEPRECATED_OPTION_ALIASES.items(): if new_name in entry: 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 if not client_has_capability(options['version'], 'permissions2'): # Legacy clients expect some attributes as a single value for attr in 'type', 'targetgroup', 'memberof', 'aci': if attr in entry: entry[attr] = entry.single_value[attr] 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