Search in sources :

Example 91 with AccessControlContext

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

the class RequiredModelMBean method invoke.

/**
     * Invokes a method on or through a RequiredModelMBean and returns
     * the result of the method execution.
     * <P>
     * If the given method to be invoked, together with the provided
     * signature, matches one of RequiredModelMbean
     * accessible methods, this one will be call. Otherwise the call to
     * the given method will be tried on the managed resource.
     * <P>
     * The last value returned by an operation may be cached in
     * the operation's descriptor which
     * is in the ModelMBeanOperationInfo'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 operation method is invoked.
     *      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 operation method is invoked for the attribute.
     *      The 'lastUpdatedTimeStamp' field and `value' fields are set to
     *      the operation's return 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 operation
     *             method is invoked. 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>
     *
     * @param opName The name of the method to be invoked. The
     *     name can be the fully qualified method name including the
     *     classname, or just the method name if the classname is
     *     defined in the 'class' field of the operation descriptor.
     * @param opArgs An array containing the parameters to be set
     *     when the operation is invoked
     * @param sig An array containing the signature of the
     *     operation. The class objects will be loaded using the same
     *     class loader as the one used for loading the MBean on which
     *     the operation was invoked.
     *
     * @return  The object returned by the method, which represents the
     *     result of invoking the method on the specified managed resource.
     *
     * @exception MBeanException  Wraps one of the following Exceptions:
     * <UL>
     * <LI> An Exception thrown by the managed object's invoked method.</LI>
     * <LI> {@link ServiceNotFoundException}: No ModelMBeanOperationInfo or
     *      no descriptor defined for the specified operation or the managed
     *      resource is null.</LI>
     * <LI> {@link InvalidTargetObjectTypeException}: The 'targetType'
     *      field value is not 'objectReference'.</LI>
     * </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *      thrown while trying to invoke the method.
     * @exception RuntimeOperationsException Wraps an
     *      {@link IllegalArgumentException} Method name is null.
     *
     **/
/*
      The requirement to be able to invoke methods on the
      RequiredModelMBean class itself makes this method considerably
      more complicated than it might otherwise be.  Note that, unlike
      earlier versions, we do not allow you to invoke such methods if
      they are not explicitly mentioned in the ModelMBeanInfo.  Doing
      so was potentially a security problem, and certainly very
      surprising.

      We do not look for the method in the RequiredModelMBean class
      itself if:
      (a) there is a "targetObject" field in the Descriptor for the
      operation; or
      (b) there is a "class" field in the Descriptor for the operation
      and the named class is not RequiredModelMBean or one of its
      superinterfaces; or
      (c) the name of the operation is not the name of a method in
      RequiredModelMBean (this is just an optimization).

      In cases (a) and (b), if you have gone to the trouble of adding
      those fields specifically for this operation then presumably you
      do not want RequiredModelMBean's methods to be called.

      We have to pay attention to class loading issues.  If the
      "class" field is present, the named class has to be resolved
      relative to RequiredModelMBean's class loader to test the
      condition (b) above, and relative to the managed resource's
      class loader to ensure that the managed resource is in fact of
      the named class (or a subclass).  The class names in the sig
      array likewise have to be resolved, first against
      RequiredModelMBean's class loader, then against the managed
      resource's class loader.  There is no point in using any other
      loader because when we call Method.invoke we must call it on
      a Method that is implemented by the target object.
     */
public Object invoke(String opName, Object[] opArgs, String[] sig) throws MBeanException, ReflectionException {
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    final String mth = "invoke(String, Object[], String[])";
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Entry");
    }
    if (opName == null) {
        final RuntimeException x = new IllegalArgumentException("Method name must not be null");
        throw new RuntimeOperationsException(x, "An exception occurred while trying to " + "invoke a method on a RequiredModelMBean");
    }
    String opClassName = null;
    String opMethodName;
    // Parse for class name and method
    int opSplitter = opName.lastIndexOf(".");
    if (opSplitter > 0) {
        opClassName = opName.substring(0, opSplitter);
        opMethodName = opName.substring(opSplitter + 1);
    } else
        opMethodName = opName;
    /* Ignore anything after a left paren.  We keep this for
           compatibility but it isn't specified.  */
    opSplitter = opMethodName.indexOf("(");
    if (opSplitter > 0)
        opMethodName = opMethodName.substring(0, opSplitter);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Finding operation " + opName + " as " + opMethodName);
    }
    ModelMBeanOperationInfo opInfo = modelMBeanInfo.getOperation(opMethodName);
    if (opInfo == null) {
        final String msg = "Operation " + opName + " not in ModelMBeanInfo";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final Descriptor opDescr = opInfo.getDescriptor();
    if (opDescr == null) {
        final String msg = "Operation descriptor null";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final Object cached = resolveForCacheValue(opDescr);
    if (cached != null) {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Returning cached value");
        }
        return cached;
    }
    if (opClassName == null)
        opClassName = (String) opDescr.getFieldValue("class");
    // may still be null now
    opMethodName = (String) opDescr.getFieldValue("name");
    if (opMethodName == null) {
        final String msg = "Method descriptor must include `name' field";
        throw new MBeanException(new ServiceNotFoundException(msg), msg);
    }
    final String targetTypeField = (String) opDescr.getFieldValue("targetType");
    if (targetTypeField != null && !targetTypeField.equalsIgnoreCase("objectReference")) {
        final String msg = "Target type must be objectReference: " + targetTypeField;
        throw new MBeanException(new InvalidTargetObjectTypeException(msg), msg);
    }
    final Object targetObjectField = opDescr.getFieldValue("targetObject");
    if (tracing && targetObjectField != null)
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "Found target object in descriptor");
    /* Now look for the method, either in RequiredModelMBean itself
           or in the target object.  Set "method" and "targetObject"
           appropriately.  */
    Method method;
    Object targetObject;
    method = findRMMBMethod(opMethodName, targetObjectField, opClassName, sig);
    if (method != null)
        targetObject = this;
    else {
        if (tracing) {
            MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "looking for method in managedResource class");
        }
        if (targetObjectField != null)
            targetObject = targetObjectField;
        else {
            targetObject = managedResource;
            if (targetObject == null) {
                final String msg = "managedResource for invoke " + opName + " is null";
                Exception snfe = new ServiceNotFoundException(msg);
                throw new MBeanException(snfe);
            }
        }
        final Class<?> targetClass;
        if (opClassName != null) {
            try {
                AccessControlContext stack = AccessController.getContext();
                final Object obj = targetObject;
                final String className = opClassName;
                final ClassNotFoundException[] caughtException = new ClassNotFoundException[1];
                targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

                    @Override
                    public Class<?> run() {
                        try {
                            ReflectUtil.checkPackageAccess(className);
                            final ClassLoader targetClassLoader = obj.getClass().getClassLoader();
                            return Class.forName(className, false, targetClassLoader);
                        } catch (ClassNotFoundException e) {
                            caughtException[0] = e;
                        }
                        return null;
                    }
                }, stack, acc);
                if (caughtException[0] != null) {
                    throw caughtException[0];
                }
            } catch (ClassNotFoundException e) {
                final String msg = "class for invoke " + opName + " not found";
                throw new ReflectionException(e, msg);
            }
        } else
            targetClass = targetObject.getClass();
        method = resolveMethod(targetClass, opMethodName, sig);
    }
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "found " + opMethodName + ", now invoking");
    }
    final Object result = invokeMethod(opName, method, targetObject, opArgs);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), mth, "successfully invoked method");
    }
    if (result != null)
        cacheResult(opInfo, opDescr, result);
    return result;
}
Also used : ReflectionException(javax.management.ReflectionException) Method(java.lang.reflect.Method) 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) PrivilegedAction(java.security.PrivilegedAction) ServiceNotFoundException(javax.management.ServiceNotFoundException) MBeanException(javax.management.MBeanException) Descriptor(javax.management.Descriptor) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 92 with AccessControlContext

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

the class RequiredModelMBean method findRMMBMethod.

/* Find a method in RequiredModelMBean as determined by the given
       parameters.  Return null if there is none, or if the parameters
       exclude using it.  Called from invoke. */
private Method findRMMBMethod(String opMethodName, Object targetObjectField, String opClassName, String[] sig) {
    final boolean tracing = MODELMBEAN_LOGGER.isLoggable(Level.FINER);
    if (tracing) {
        MODELMBEAN_LOGGER.logp(Level.FINER, RequiredModelMBean.class.getName(), "invoke(String, Object[], String[])", "looking for method in RequiredModelMBean class");
    }
    if (!isRMMBMethodName(opMethodName))
        return null;
    if (targetObjectField != null)
        return null;
    final Class<RequiredModelMBean> rmmbClass = RequiredModelMBean.class;
    final Class<?> targetClass;
    if (opClassName == null)
        targetClass = rmmbClass;
    else {
        AccessControlContext stack = AccessController.getContext();
        final String className = opClassName;
        targetClass = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Class<?>>() {

            @Override
            public Class<?> run() {
                try {
                    ReflectUtil.checkPackageAccess(className);
                    final ClassLoader targetClassLoader = rmmbClass.getClassLoader();
                    Class clz = Class.forName(className, false, targetClassLoader);
                    if (!rmmbClass.isAssignableFrom(clz))
                        return null;
                    return clz;
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        }, stack, acc);
    }
    try {
        return targetClass != null ? resolveMethod(targetClass, opMethodName, sig) : null;
    } catch (ReflectionException e) {
        return null;
    }
}
Also used : ReflectionException(javax.management.ReflectionException) AccessControlContext(java.security.AccessControlContext) PrivilegedAction(java.security.PrivilegedAction)

Example 93 with AccessControlContext

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

the class RequiredModelMBean method invokeMethod.

/*
     * Invoke the given method, and throw the somewhat unpredictable
     * appropriate exception if the method itself gets an exception.
     */
private Object invokeMethod(String opName, final Method method, final Object targetObject, final Object[] opArgs) throws MBeanException, ReflectionException {
    try {
        final Throwable[] caughtException = new Throwable[1];
        AccessControlContext stack = AccessController.getContext();
        Object rslt = javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Object>() {

            @Override
            public Object run() {
                try {
                    ReflectUtil.checkPackageAccess(method.getDeclaringClass());
                    return MethodUtil.invoke(method, targetObject, opArgs);
                } catch (InvocationTargetException e) {
                    caughtException[0] = e;
                } catch (IllegalAccessException e) {
                    caughtException[0] = e;
                }
                return null;
            }
        }, stack, acc);
        if (caughtException[0] != null) {
            if (caughtException[0] instanceof Exception) {
                throw (Exception) caughtException[0];
            } else if (caughtException[0] instanceof Error) {
                throw (Error) caughtException[0];
            }
        }
        return rslt;
    } catch (RuntimeErrorException ree) {
        throw new RuntimeOperationsException(ree, "RuntimeException occurred in RequiredModelMBean " + "while trying to invoke operation " + opName);
    } catch (RuntimeException re) {
        throw new RuntimeOperationsException(re, "RuntimeException occurred in RequiredModelMBean " + "while trying to invoke operation " + opName);
    } catch (IllegalAccessException iae) {
        throw new ReflectionException(iae, "IllegalAccessException occurred in " + "RequiredModelMBean while trying to " + "invoke operation " + opName);
    } catch (InvocationTargetException ite) {
        Throwable mmbTargEx = ite.getTargetException();
        if (mmbTargEx instanceof RuntimeException) {
            throw new MBeanException((RuntimeException) mmbTargEx, "RuntimeException thrown in RequiredModelMBean " + "while trying to invoke operation " + opName);
        } else if (mmbTargEx instanceof Error) {
            throw new RuntimeErrorException((Error) mmbTargEx, "Error occurred in RequiredModelMBean while trying " + "to invoke operation " + opName);
        } else if (mmbTargEx instanceof ReflectionException) {
            throw (ReflectionException) mmbTargEx;
        } else {
            throw new MBeanException((Exception) mmbTargEx, "Exception thrown in RequiredModelMBean " + "while trying to invoke operation " + opName);
        }
    } catch (Error err) {
        throw new RuntimeErrorException(err, "Error occurred in RequiredModelMBean while trying " + "to invoke operation " + opName);
    } catch (Exception e) {
        throw new ReflectionException(e, "Exception occurred in RequiredModelMBean while " + "trying to invoke operation " + opName);
    }
}
Also used : ReflectionException(javax.management.ReflectionException) RuntimeErrorException(javax.management.RuntimeErrorException) InvocationTargetException(java.lang.reflect.InvocationTargetException) 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) MBeanException(javax.management.MBeanException) RuntimeOperationsException(javax.management.RuntimeOperationsException)

Example 94 with AccessControlContext

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

the class ServerNotifForwarder method checkMBeanPermission.

static void checkMBeanPermission(final MBeanServer mbs, final ObjectName name, final String actions) throws InstanceNotFoundException, SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        AccessControlContext acc = AccessController.getContext();
        ObjectInstance oi;
        try {
            oi = AccessController.doPrivileged(new PrivilegedExceptionAction<ObjectInstance>() {

                public ObjectInstance run() throws InstanceNotFoundException {
                    return mbs.getObjectInstance(name);
                }
            });
        } catch (PrivilegedActionException e) {
            throw (InstanceNotFoundException) extractException(e);
        }
        String classname = oi.getClassName();
        MBeanPermission perm = new MBeanPermission(classname, null, name, actions);
        sm.checkPermission(perm, acc);
    }
}
Also used : AccessControlContext(java.security.AccessControlContext) PrivilegedActionException(java.security.PrivilegedActionException) MBeanPermission(javax.management.MBeanPermission) ObjectInstance(javax.management.ObjectInstance) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction)

Example 95 with AccessControlContext

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

the class DocumentHandler method parse.

/**
     * Starts parsing of the specified input source.
     *
     * @param input  the input source to parse
     */
public void parse(final InputSource input) {
    if ((this.acc == null) && (null != System.getSecurityManager())) {
        throw new SecurityException("AccessControlContext is not set");
    }
    AccessControlContext stack = AccessController.getContext();
    SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Void>() {

        public Void run() {
            try {
                SAXParserFactory.newInstance().newSAXParser().parse(input, DocumentHandler.this);
            } catch (ParserConfigurationException exception) {
                handleException(exception);
            } catch (SAXException wrapper) {
                Exception exception = wrapper.getException();
                if (exception == null) {
                    exception = wrapper;
                }
                handleException(exception);
            } catch (IOException exception) {
                handleException(exception);
            }
            return null;
        }
    }, stack, this.acc);
}
Also used : AccessControlContext(java.security.AccessControlContext) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException)

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