Enforce a dual approver policy for access.
17912
def CheckAccess(self, token):
    """"""
    namespace, _ = self.urn.Split(2)

    if namespace != "ACL":
      raise access_control.UnauthorizedAccess(
          "Approval object has invalid urn %s." % self.urn,
          subject=self.urn,
          requested_access=token.requested_access)

    user, subject_urn = self.InferUserAndSubjectFromUrn()
    if user != token.username:
      raise access_control.UnauthorizedAccess(
          "Approval object is not for user %s." % token.username,
          subject=self.urn,
          requested_access=token.requested_access)

    now = rdfvalue.RDFDatetime.Now()

    # Is this an emergency access?
    break_glass = self.Get(self.Schema.BREAK_GLASS)
    if break_glass and now < break_glass:
      # This tags the token as an emergency token.
      token.is_emergency = True
      return True

    # Check that there are enough approvers.
    approvers = self.GetNonExpiredApprovers()
    approvers_required = config.CONFIG["ACL.approvers_required"]
    if len(approvers) < approvers_required:
      missing = approvers_required - len(approvers)
      msg = ("Need at least %d additional approver%s for access." %
             (missing, "s" if missing > 1 else ""))

      raise access_control.UnauthorizedAccess(
          msg, subject=subject_urn, requested_access=token.requested_access)

    # Check User labels
    if self.checked_approvers_label:
      approvers_with_label = []

      # We need to check labels with high privilege since normal users can
      # inspect other user's labels.
      for approver in approvers:
        try:
          user = aff4.FACTORY.Open(
              "aff4:/users/%s" % approver,
              aff4_type=aff4_users.GRRUser,
              token=token.SetUID())
          if self.checked_approvers_label in user.GetLabelsNames():
            approvers_with_label.append(approver)
        except IOError:
          pass

      if len(approvers_with_label) < self.min_approvers_with_label:
        missing = self.min_approvers_with_label - len(approvers_with_label)
        raise access_control.UnauthorizedAccess(
            "Need at least 1 admin approver for access.",
            subject=subject_urn,
            requested_access=token.requested_access)

    return True
340503
def _attach_inline_policy(self, username, policy_document):
        """"""
        response = self.client.put_user_policy(
            UserName=username,
            PolicyName="threatresponse-temporal-key-revocation",
            PolicyDocument=policy_document
        )
        logger.info(
            'An inline policy has been attached for'
            ' {u} revoking sts tokens.'.format(u=username)
        )
        return response
934162
function (done) {
      user.authorizedScope(function (err, scopes) {
        if (err) { return done(err) }
        done(null, scopes)
      })
    }
773849
def allow(ip,
        port=None,
        proto='tcp',
        direction='in',
        port_origin='d',
        ip_origin='s',
        ttl=None,
        comment=''):
    '''
    
    '''
    return _access_rule('allow',
                        ip,
                        port=port,
                        proto=proto,
                        direction=direction,
                        port_origin=port_origin,
                        ip_origin=ip_origin,
                        comment=comment)
1029977
def can_approve(self, user, **data):
        
        is_external = data.get('service_type', self.service_type) == 'external'
        raise Return(user.is_admin() or is_external)
260387
def hold_policy(document, policy, server=False):
    
    old_policy = document._hold
    document._hold = policy
    try:
        yield
    finally:
        if server and not old_policy:
            document.unhold()
        else:
            document._hold = old_policy
178588
function checkPermissions(access, uid, gid, stat) {
  return (access & resolveOwnership(uid, gid, stat)) === access;
}
736075
def approveworker(ctx, workers, account):
    
    print_tx(ctx.bitshares.approveworker(workers, account=account))
537458
def deny(ip,
        port=None,
        proto='tcp',
        direction='in',
        port_origin='d',
        ip_origin='d',
        ttl=None,
        comment=''):
    '''
    
    '''
    return _access_rule('deny', ip, port, proto, direction, port_origin, ip_origin, comment)
530845
def default_policy(policy='deny', direction='incoming'):
    
    if policy not in ['allow', 'deny', 'reject']:
        raise UFWError(('Unknown policy %s, valid values: '
                        'allow, deny, reject') % policy)

    if direction not in ['incoming', 'outgoing', 'routed']:
        raise UFWError(('Unknown direction %s, valid values: '
                        'incoming, outgoing, routed') % direction)

    output = subprocess.check_output(['ufw', 'default', policy, direction],
                                     universal_newlines=True,
                                     env={'LANG': 'en_US',
                                          'PATH': os.environ['PATH']})
    hookenv.log(output, level='DEBUG')

    m = re.findall("^Default %s policy changed to '%s'\n" % (direction,
                                                             policy),
                   output, re.M)
    if len(m) == 0:
        hookenv.log("ufw couldn't change the default policy to %s for %s"
                    % (policy, direction), level='WARN')
        return False
    else:
        hookenv.log("ufw default policy for %s changed to %s"
                    % (direction, policy), level='INFO')
        return True
387814
def authorize_for(opts = {})
      authorize! opts[:action], opts[:resource] if opts[:resource].present?
      authorize! opts[:action], opts[:object] if opts[:object].present?
    end
1056108
def enforce(self, rule, target, creds, exc=None, *args, **kwargs):
        """"""

        self.load_rules()

        if isinstance(rule, checks.BaseCheck):
            result = rule(target, creds, self, rule)
        elif not self.rules:
            # No rules means we're going to fail closed.
            result = False
        else:
            try:
                # Evaluate the rule
                result = self.rules[rule](target, creds, self, rule)
            except KeyError:
                LOG.debug('Rule [%s] does not exist', rule)
                # If the rule doesn't exist, fail closed
                result = False

        if self.raise_error and not result:
            if exc:
                raise exc(*args, **kwargs)
            else:
                raise PolicyNotAuthorized(rule, target, creds)

        return result
56634
def approveproposal(ctx, proposal, account):
    
    pprint(ctx.peerplays.approveproposal(proposal, account=account))
1112769
def authorize(self):
        '''
        
        '''
        with salt.utils.files.fopen(self.path, 'w+') as fp_:
            fp_.write(str(int(time.time())))  # future lint: disable=blacklisted-function
        return True
992059
def apply_policy(self, policy):
        
        tenant_name = policy['tenant_name']
        fw_id = policy['fw_id']
        fw_name = policy['fw_name']
        LOG.info("asa_apply_policy: tenant=%(tenant)s fw_id=%(fw_id)s "
                 "fw_name=%(fw_name)s",
                 {'tenant': tenant_name, 'fw_id': fw_id, 'fw_name': fw_name})
        cmds = ["conf t", "changeto context " + tenant_name]

        for rule_id, rule in policy['rules'].items():
            acl = self.build_acl(tenant_name, rule)

            LOG.info("rule[%(rule_id)s]: name=%(name)s enabled=%(enabled)s"
                     " protocol=%(protocol)s dport=%(dport)s "
                     "sport=%(sport)s dip=%(dport)s "
                     "sip=%(sip)s action=%(dip)s",
                     {'rule_id': rule_id, 'name': rule.get('name'),
                      'enabled': rule.get('enabled'),
                      'protocol': rule.get('protocol'),
                      'dport': rule.get('dst_port'),
                      'sport': rule.get('src_port'),
                      'dip': rule.get('destination_ip_address'),
                      'sip': rule.get('source_ip_address'),
                      'action': rule.get('action')})

            # remove the old ace for this rule
            if rule_id in self.rule_tbl:
                cmds.append('no ' + self.rule_tbl[rule_id])

            self.rule_tbl[rule_id] = acl
            if tenant_name in self.tenant_rule:
                if rule_id not in self.tenant_rule[tenant_name]['rule_lst']:
                    self.tenant_rule[tenant_name]['rule_lst'].append(rule_id)
            cmds.append(acl)
        cmds.append("access-group " + tenant_name + " global")
        cmds.append("write memory")

        LOG.info("cmds sent is %s", cmds)
        data = {"commands": cmds}
        return self.rest_send_cli(data)
820531
def required_permission(f, level):
    """"""

    @functools.wraps(f)
    def wrapper(request, pid, *args, **kwargs):
        d1_gmn.app.auth.assert_allowed(request, level, pid)
        return f(request, pid, *args, **kwargs)

    return wrapper
621859
def permitted_to? (privilege, options = {}, &block)
      options = {
        :user =>  Authorization.current_user,
        :object => self
      }.merge(options)
      Authorization::Engine.instance.permit?(privilege,
          {:user => options[:user],
           :object => options[:object]},
          &block)
    end