예제 #1
0
    def load_files(self, cmd, kw):
        """
        Load files from File parameters.

        This has to be done after all required parameters have been read
        (i.e. after prompt_interactively has or would have been called)
        AND before they are passed to the command. This is because:
        1) we need to be sure no more files are going to be added
        2) we load files from the machine where the command was executed
        3) the webUI will use a different way of loading files
        """
        for p in cmd.params():
            if isinstance(p, (File, BinaryFile)):
                # FIXME: this only reads the first file
                raw = None
                if p.name in kw:
                    if type(kw[p.name]) in (tuple, list):
                        fname = kw[p.name][0]
                    else:
                        fname = kw[p.name]
                    try:
                        with open(fname, p.open_mode) as f:
                            raw = f.read()
                    except IOError as e:
                        raise ValidationError(
                            name=to_cli(p.cli_name),
                            error='%s: %s:' % (fname, e.args[1])
                        )
                elif p.stdin_if_missing:
                    try:
                        if six.PY3 and p.type is bytes:
                            # pylint: disable=no-member
                            raw = sys.stdin.buffer.read()
                            # pylint: enable=no-member
                        else:
                            raw = sys.stdin.read()
                    except IOError as e:
                        raise ValidationError(
                            name=to_cli(p.cli_name), error=e.args[1]
                        )

                if raw:
                    if p.type is bytes:
                        kw[p.name] = raw
                    else:
                        kw[p.name] = self.Backend.textui.decode(raw)
                elif p.required:
                    raise ValidationError(
                        name=to_cli(p.cli_name), error=_('No file to read')
                    )
예제 #2
0
    def print_advice(self, keyword):
        advice = getattr(advise_api.Advice, keyword, None)

        # Ensure that Configuration class for given --setup option value exists
        if advice is None:
            raise ValidationError(
                name="advice",
                error="No instructions are available for '{con}'. "
                      "See the list of available configuration "
                      "by invoking the ipa-advise command with no argument."
                      .format(con=keyword.replace('_', '-')))

        # Check whether root privileges are needed
        if advice.require_root and os.getegid() != 0:
            raise admintool.ScriptError(
                'Must be root to get advice for {adv}'
                .format(adv=keyword.replace('_', '-')), 1)

        # Print out nicely formatted header
        self.print_header(advice.description, print_shell=True)

        # Set options so that plugin can use verbose/quiet options
        advice.set_options(self.options)

        # Print out the actual advice
        api.Backend.rpcclient.connect()
        advice.get_info()
        api.Backend.rpcclient.disconnect()
        for line in advice.log.content:
            print(line)
예제 #3
0
파일: otptoken.py 프로젝트: zz22394/freeipa
    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
예제 #4
0
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))
예제 #5
0
파일: otptoken.py 프로젝트: zz22394/freeipa
    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
예제 #6
0
def validate_attributename(ugettext, attr):
    if not LDAP_ATTRIBUTE.match(attr):
        raise ValidationError(name="ipatokenusermapattribute",
                              error=_('invalid attribute name'))
예제 #7
0
def validate_searchtimelimit(ugettext, limit):
    if limit == 0:
        raise ValidationError(name='ipasearchtimelimit',
                              error=_('searchtimelimit must be -1 or > 1.'))
    return None