Search in sources :

Example 86 with AccessControlContext

use of java.security.AccessControlContext in project karaf by apache.

the class JaasHelper method currentUserHasRole.

public static boolean currentUserHasRole(String requestedRole) {
    if (ROLE_WILDCARD.equals(requestedRole)) {
        return true;
    }
    AccessControlContext acc = AccessController.getContext();
    if (acc == null) {
        return false;
    }
    Subject subject = Subject.getSubject(acc);
    if (subject == null) {
        return false;
    }
    return currentUserHasRole(subject.getPrincipals(), requestedRole);
}
Also used : AccessControlContext(java.security.AccessControlContext) Subject(javax.security.auth.Subject)

Example 87 with AccessControlContext

use of java.security.AccessControlContext in project aries by apache.

the class AuthorizationInterceptor method preCall.

public Object preCall(ComponentMetadata cm, Method m, Object... parameters) throws Throwable {
    Annotation ann = new SecurityAnotationParser().getEffectiveAnnotation(beanClass, m);
    if (ann instanceof PermitAll) {
        return null;
    }
    // Also applies for @DenyAll
    String[] rolesAr = new String[] {};
    if (ann instanceof RolesAllowed) {
        rolesAr = ((RolesAllowed) ann).value();
    }
    Set<String> roles = new HashSet<String>(Arrays.asList(rolesAr));
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    if (subject == null) {
        throw new AccessControlException("Method call " + m.getDeclaringClass() + "." + m.getName() + " denied. No JAAS login present");
    }
    Set<Principal> principals = subject.getPrincipals();
    for (Principal principal : principals) {
        if (roles.contains(principal.getName())) {
            LOGGER.debug("Granting access to Method: {} for {}.", m, principal);
            return null;
        }
    }
    String msg = String.format("Method call %s.%s denied. Roles allowed are %s. Your principals are %s.", m.getDeclaringClass(), m.getName(), roles, getNames(principals));
    throw new AccessControlException(msg);
}
Also used : AccessControlException(java.security.AccessControlException) Annotation(java.lang.annotation.Annotation) Subject(javax.security.auth.Subject) RolesAllowed(javax.annotation.security.RolesAllowed) AccessControlContext(java.security.AccessControlContext) PermitAll(javax.annotation.security.PermitAll) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 88 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class MBS_Light method getAuthorizationId.

// The authorization Id
public String getAuthorizationId() {
    AccessControlContext acc = AccessController.getContext();
    Subject subject = Subject.getSubject(acc);
    Set<Principal> principals = subject.getPrincipals();
    Iterator<Principal> i = principals.iterator();
    StringBuffer buffer = new StringBuffer();
    while (i.hasNext()) {
        Principal p = i.next();
        buffer.append(p.getName());
        if (i.hasNext())
            buffer.append(" ");
    }
    return buffer.toString();
}
Also used : AccessControlContext(java.security.AccessControlContext) Subject(javax.security.auth.Subject) Principal(java.security.Principal)

Example 89 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class RequiredModelMBean method getAttribute.

/**
     * Returns the value of a specific attribute defined for this
     * ModelMBean.
     * The last value returned by an attribute may be cached in the
     * attribute's descriptor.
     * The valid value will be in the 'value' field if there is one.
     * If the 'currencyTimeLimit' field in the descriptor is:
     * <UL>
     * <LI>  <b>&lt;0</b> Then the value is not cached and is never valid.
     *       The getter method is invoked for the attribute.
     *       The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI>
     * <LI>  <b>=0</b> Then the value is always cached and always valid.
     *       The 'value' field is returned. If there is no'value' field
     *       then the getter method is invoked for the attribute.
     *       The 'lastUpdatedTimeStamp' field and `value' fields are set
     *       to the attribute's value and the current time stamp.</LI>
     * <LI>  <b>&gt;0</b> Represents the number of seconds that the 'value'
     *       field is valid.
     *       The 'value' field is no longer valid when
     *       'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.
     *   <UL>
     *        <LI>When 'value' is valid, 'value' is returned.</LI>
     *        <LI>When 'value' is no longer valid then the getter
     *            method is invoked for the attribute.
     *            The 'lastUpdatedTimeStamp' field and `value' fields
     *            are updated.</LI>
     *   </UL></LI>
     * </UL>
     *
     * <p><b>Note:</b> because of inconsistencies in previous versions of
     * this specification, it is recommended not to use negative or zero
     * values for <code>currencyTimeLimit</code>.  To indicate that a
     * cached value is never valid, omit the
     * <code>currencyTimeLimit</code> field.  To indicate that it is
     * always valid, use a very large number for this field.</p>
     *
     * <p>If the 'getMethod' field contains the name of a valid
     * operation descriptor, then the method described by the
     * operation descriptor is executed.  The response from the
     * method is returned as the value of the attribute.  If the
     * operation fails or the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     *
     * <p>If no 'getMethod' field is defined then the default value of the
     * attribute is returned. If the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     *
     * <p>The declared type of the attribute is the String returned by
     * {@link ModelMBeanAttributeInfo#getType()}.  A value is compatible
     * with this type if one of the following is true:
     * <ul>
     * <li>the value is null;</li>
     * <li>the declared name is a primitive type name (such as "int")
     *     and the value is an instance of the corresponding wrapper
     *     type (such as java.lang.Integer);</li>
     * <li>the name of the value's class is identical to the declared name;</li>
     * <li>the declared name can be loaded by the value's class loader and
     *     produces a class to which the value can be assigned.</li>
     * </ul>
     *
     * <p>In this implementation, in every case where the getMethod needs to
     * be called, because the method is invoked through the standard "invoke"
     * method and thus needs operationInfo, an operation must be specified
     * for that getMethod so that the invocation works correctly.</p>
     *
     * @param attrName A String specifying the name of the
     * attribute to be retrieved. It must match the name of a
     * ModelMBeanAttributeInfo.
     *
     * @return The value of the retrieved attribute from the
     * descriptor 'value' field or from the invocation of the
     * operation in the 'getMethod' field of the descriptor.
     *
     * @exception AttributeNotFoundException The specified attribute is
     *    not accessible in the MBean.
     *    The following cases may result in an AttributeNotFoundException:
     *    <UL>
     *      <LI> No ModelMBeanInfo was found for the Model MBean.</LI>
     *      <LI> No ModelMBeanAttributeInfo was found for the specified
     *           attribute name.</LI>
     *      <LI> The ModelMBeanAttributeInfo isReadable method returns
     *           'false'.</LI>
     *    </UL>
     * @exception MBeanException  Wraps one of the following Exceptions:
     *    <UL>
     *      <LI> {@link InvalidAttributeValueException}: A wrong value type
     *           was received from the attribute's getter method or
     *           no 'getMethod' field defined in the descriptor for
     *           the attribute and no default value exists.</LI>
     *      <LI> {@link ServiceNotFoundException}: No
     *           ModelMBeanOperationInfo defined for the attribute's
     *           getter method or no descriptor associated with the
     *           ModelMBeanOperationInfo or the managed resource is
     *           null.</LI>
     *      <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
     *           field value is not 'objectReference'.</LI>
     *      <LI> An Exception thrown by the managed object's getter.</LI>
     *    </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *    thrown while trying to invoke the getter.
     * @exception RuntimeOperationsException Wraps an
     *    {@link IllegalArgumentException}: The attribute name in
     *    parameter is null.
     *
     * @see #setAttribute(javax.management.Attribute)
     **/
public Object getAttribute(String attrName) throws AttributeNotFoundException, MBeanException, ReflectionException {
    if (attrName == null)
        throw new RuntimeOperationsException(new IllegalArgumentException("attributeName must not be null"), "Exception occurred trying to get attribute of a " + "RequiredModelMBean");
    final String mth = "getAttribute(String)";
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry with " + attrName);
    }
    /* Check attributeDescriptor for getMethod */
    Object response;
    try {
        if (modelMBeanInfo == null)
            throw new AttributeNotFoundException("getAttribute failed: ModelMBeanInfo not found for " + attrName);
        ModelMBeanAttributeInfo attrInfo = modelMBeanInfo.getAttribute(attrName);
        Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
        if (attrInfo == null)
            throw new AttributeNotFoundException("getAttribute failed:" + " ModelMBeanAttributeInfo not found for " + attrName);
        Descriptor attrDescr = attrInfo.getDescriptor();
        if (attrDescr != null) {
            if (!attrInfo.isReadable())
                throw new AttributeNotFoundException("getAttribute failed: " + attrName + " is not readable ");
            response = resolveForCacheValue(attrDescr);
            /* return current cached value */
            if (tracing) {
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "*** cached value is " + response);
            }
            if (response == null) {
                /* no cached value, run getMethod */
                if (tracing) {
                    MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "**** cached value is null - getting getMethod");
                }
                String attrGetMethod = (String) (attrDescr.getFieldValue("getMethod"));
                if (attrGetMethod != null) {
                    /* run method from operations descriptor */
                    if (tracing) {
                        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "invoking a getMethod for " + attrName);
                    }
                    Object getResponse = invoke(attrGetMethod, new Object[] {}, new String[] {});
                    if (getResponse != null) {
                        // error/validity check return value here
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a non-null response " + "from getMethod\n");
                        }
                        response = getResponse;
                        // change cached value in attribute descriptor
                        Object objctl = attrDescr.getFieldValue("currencyTimeLimit");
                        String ctl;
                        if (objctl != null)
                            ctl = objctl.toString();
                        else
                            ctl = null;
                        if ((ctl == null) && (mmbDesc != null)) {
                            objctl = mmbDesc.getFieldValue("currencyTimeLimit");
                            if (objctl != null)
                                ctl = objctl.toString();
                            else
                                ctl = null;
                        }
                        if ((ctl != null) && !(ctl.equals("-1"))) {
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "setting cached value and " + "lastUpdatedTime in descriptor");
                            }
                            attrDescr.setField("value", response);
                            final String stamp = String.valueOf((new Date()).getTime());
                            attrDescr.setField("lastUpdatedTimeStamp", stamp);
                            attrInfo.setDescriptor(attrDescr);
                            modelMBeanInfo.setDescriptor(attrDescr, "attribute");
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "new descriptor is " + attrDescr);
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "AttributeInfo descriptor is " + attrInfo.getDescriptor());
                                final String attStr = modelMBeanInfo.getDescriptor(attrName, "attribute").toString();
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "modelMBeanInfo: AttributeInfo " + "descriptor is " + attStr);
                            }
                        }
                    } else {
                        // response was invalid or really returned null
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "got a null response from getMethod\n");
                        }
                        response = null;
                    }
                } else {
                    // not getMethod so return descriptor (default) value
                    String qualifier = "";
                    response = attrDescr.getFieldValue("value");
                    if (response == null) {
                        qualifier = "default ";
                        response = attrDescr.getFieldValue("default");
                    }
                    if (tracing) {
                        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "could not find getMethod for " + attrName + ", returning descriptor " + qualifier + "value");
                    }
                // !! cast response to right class
                }
            }
            // make sure response class matches type field
            final String respType = attrInfo.getType();
            if (response != null) {
                String responseClass = response.getClass().getName();
                if (!respType.equals(responseClass)) {
                    boolean wrongType = false;
                    boolean primitiveType = false;
                    boolean correspondingTypes = false;
                    for (int i = 0; i < primitiveTypes.length; i++) {
                        if (respType.equals(primitiveTypes[i])) {
                            primitiveType = true;
                            if (responseClass.equals(primitiveWrappers[i]))
                                correspondingTypes = true;
                            break;
                        }
                    }
                    if (primitiveType) {
                        // inequality may come from primitive/wrapper class
                        if (!correspondingTypes)
                            wrongType = true;
                    } else {
                        // inequality may come from type subclassing
                        boolean subtype;
                        try {
                            final Class respClass = response.getClass();
                            final Exception[] caughException = new Exception[1];
                            AccessControlContext stack = AccessController.getContext();
                            Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

                                @Override
                                public Class<?> run() {
                                    try {
                                        ReflectUtil.checkPackageAccess(respType);
                                        ClassLoader cl = respClass.getClassLoader();
                                        return Class.forName(respType, true, cl);
                                    } catch (Exception e) {
                                        caughException[0] = e;
                                    }
                                    return null;
                                }
                            }, stack, acc);
                            if (caughException[0] != null) {
                                throw caughException[0];
                            }
                            subtype = c.isInstance(response);
                        } catch (Exception e) {
                            subtype = false;
                            if (tracing) {
                                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exception: ", e);
                            }
                        }
                        if (!subtype)
                            wrongType = true;
                    }
                    if (wrongType) {
                        if (tracing) {
                            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Wrong response type '" + respType + "'");
                        }
                        // back right attribute type
                        throw new MBeanException(new InvalidAttributeValueException("Wrong value type received for get attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
                    }
                }
            }
        } else {
            if (tracing) {
                MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed " + attrName + " not in attributeDescriptor\n");
            }
            throw new MBeanException(new InvalidAttributeValueException("Unable to resolve attribute value, " + "no getMethod defined in descriptor for attribute"), "An exception occurred while trying to get an " + "attribute value through a RequiredModelMBean");
        }
    } catch (MBeanException mbe) {
        throw mbe;
    } catch (AttributeNotFoundException t) {
        throw t;
    } catch (Exception e) {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "getMethod failed with " + e.getMessage() + " exception type " + (e.getClass()).toString());
        }
        throw new MBeanException(e, "An exception occurred while trying " + "to get an attribute value: " + e.getMessage());
    }
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Exit");
    }
    return response;
}
Also used : AttributeNotFoundException(javax.management.AttributeNotFoundException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) Date(java.util.Date) AttributeNotFoundException(javax.management.AttributeNotFoundException) ServiceNotFoundException(javax.management.ServiceNotFoundException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ReflectionException(javax.management.ReflectionException) RuntimeErrorException(javax.management.RuntimeErrorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvalidAttributeValueException(javax.management.InvalidAttributeValueException) MBeanException(javax.management.MBeanException) ListenerNotFoundException(javax.management.ListenerNotFoundException) RuntimeOperationsException(javax.management.RuntimeOperationsException) AccessControlContext(java.security.AccessControlContext) Descriptor(javax.management.Descriptor) MBeanException(javax.management.MBeanException) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 90 with AccessControlContext

use of java.security.AccessControlContext in project jdk8u_jdk by JetBrains.

the class RequiredModelMBean method loadClass.

private Class<?> loadClass(final String className) throws ClassNotFoundException {
    AccessControlContext stack = AccessController.getContext();
    final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
    Class c = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

        @Override
        public Class<?> run() {
            try {
                ReflectUtil.checkPackageAccess(className);
                return Class.forName(className);
            } catch (ClassNotFoundException e) {
                final ClassLoaderRepository clr = getClassLoaderRepository();
                try {
                    if (clr == null)
                        throw new ClassNotFoundException(className);
                    return clr.loadClass(className);
                } catch (ClassNotFoundException ex) {
                    caughtException[0] = ex;
                }
            }
            return null;
        }
    }, stack, acc);
    if (caughtException[0] != null) {
        throw caughtException[0];
    }
    return c;
}
Also used : ClassLoaderRepository(javax.management.loading.ClassLoaderRepository) AccessControlContext(java.security.AccessControlContext)

Aggregations

AccessControlContext (java.security.AccessControlContext)100 ProtectionDomain (java.security.ProtectionDomain)24 Subject (javax.security.auth.Subject)24 PrivilegedAction (java.security.PrivilegedAction)18 Permissions (java.security.Permissions)14 PrivilegedActionException (java.security.PrivilegedActionException)13 IOException (java.io.IOException)11 SocketPermission (java.net.SocketPermission)10 Test (org.testng.annotations.Test)8 Principal (java.security.Principal)7 CodeSource (java.security.CodeSource)6 Permission (java.security.Permission)6 DatagramSocket (java.net.DatagramSocket)5 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)5 MulticastSocket (java.net.MulticastSocket)4 Set (java.util.Set)4 ExecutorService (java.util.concurrent.ExecutorService)4 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)4 ReflectionException (javax.management.ReflectionException)4 Test (org.junit.Test)4